08a468fb65fcc6772486169d2fa3f8a2000ccc67
[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.4.  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 ** 6527 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-10-15 11:26:48 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.784 2008/10/13 15:35:09 drh Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
50 ** Include the configuration header output by 'configure' if we're using the
51 ** autoconf-based build
52 */
53 #ifdef _HAVE_SQLITE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
58 /************** Begin file sqliteLimit.h *************************************/
59 /*
60 ** 2007 May 7
61 **
62 ** The author disclaims copyright to this source code.  In place of
63 ** a legal notice, here is a blessing:
64 **
65 **    May you do good and not evil.
66 **    May you find forgiveness for yourself and forgive others.
67 **    May you share freely, never taking more than you give.
68 **
69 *************************************************************************
70 ** 
71 ** This file defines various limits of what SQLite can process.
72 **
73 ** @(#) $Id: sqliteLimit.h,v 1.8 2008/03/26 15:56:22 drh Exp $
74 */
75
76 /*
77 ** The maximum length of a TEXT or BLOB in bytes.   This also
78 ** limits the size of a row in a table or index.
79 **
80 ** The hard limit is the ability of a 32-bit signed integer
81 ** to count the size: 2^31-1 or 2147483647.
82 */
83 #ifndef SQLITE_MAX_LENGTH
84 # define SQLITE_MAX_LENGTH 1000000000
85 #endif
86
87 /*
88 ** This is the maximum number of
89 **
90 **    * Columns in a table
91 **    * Columns in an index
92 **    * Columns in a view
93 **    * Terms in the SET clause of an UPDATE statement
94 **    * Terms in the result set of a SELECT statement
95 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
96 **    * Terms in the VALUES clause of an INSERT statement
97 **
98 ** The hard upper limit here is 32676.  Most database people will
99 ** tell you that in a well-normalized database, you usually should
100 ** not have more than a dozen or so columns in any table.  And if
101 ** that is the case, there is no point in having more than a few
102 ** dozen values in any of the other situations described above.
103 */
104 #ifndef SQLITE_MAX_COLUMN
105 # define SQLITE_MAX_COLUMN 2000
106 #endif
107
108 /*
109 ** The maximum length of a single SQL statement in bytes.
110 **
111 ** It used to be the case that setting this value to zero would
112 ** turn the limit off.  That is no longer true.  It is not possible
113 ** to turn this limit off.
114 */
115 #ifndef SQLITE_MAX_SQL_LENGTH
116 # define SQLITE_MAX_SQL_LENGTH 1000000000
117 #endif
118
119 /*
120 ** The maximum depth of an expression tree. This is limited to 
121 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
122 ** want to place more severe limits on the complexity of an 
123 ** expression.
124 **
125 ** A value of 0 used to mean that the limit was not enforced.
126 ** But that is no longer true.  The limit is now strictly enforced
127 ** at all times.
128 */
129 #ifndef SQLITE_MAX_EXPR_DEPTH
130 # define SQLITE_MAX_EXPR_DEPTH 1000
131 #endif
132
133 /*
134 ** The maximum number of terms in a compound SELECT statement.
135 ** The code generator for compound SELECT statements does one
136 ** level of recursion for each term.  A stack overflow can result
137 ** if the number of terms is too large.  In practice, most SQL
138 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
139 ** any limit on the number of terms in a compount SELECT.
140 */
141 #ifndef SQLITE_MAX_COMPOUND_SELECT
142 # define SQLITE_MAX_COMPOUND_SELECT 500
143 #endif
144
145 /*
146 ** The maximum number of opcodes in a VDBE program.
147 ** Not currently enforced.
148 */
149 #ifndef SQLITE_MAX_VDBE_OP
150 # define SQLITE_MAX_VDBE_OP 25000
151 #endif
152
153 /*
154 ** The maximum number of arguments to an SQL function.
155 */
156 #ifndef SQLITE_MAX_FUNCTION_ARG
157 # define SQLITE_MAX_FUNCTION_ARG 100
158 #endif
159
160 /*
161 ** The maximum number of in-memory pages to use for the main database
162 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
163 */
164 #ifndef SQLITE_DEFAULT_CACHE_SIZE
165 # define SQLITE_DEFAULT_CACHE_SIZE  2000
166 #endif
167 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
168 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
169 #endif
170
171 /*
172 ** The maximum number of attached databases.  This must be between 0
173 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
174 ** is used internally to track attached databases.
175 */
176 #ifndef SQLITE_MAX_ATTACHED
177 # define SQLITE_MAX_ATTACHED 10
178 #endif
179
180
181 /*
182 ** The maximum value of a ?nnn wildcard that the parser will accept.
183 */
184 #ifndef SQLITE_MAX_VARIABLE_NUMBER
185 # define SQLITE_MAX_VARIABLE_NUMBER 999
186 #endif
187
188 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
189 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
190 ** and the fact that the page size must be a power of 2.
191 */
192 #ifndef SQLITE_MAX_PAGE_SIZE
193 # define SQLITE_MAX_PAGE_SIZE 32768
194 #endif
195
196
197 /*
198 ** The default size of a database page.
199 */
200 #ifndef SQLITE_DEFAULT_PAGE_SIZE
201 # define SQLITE_DEFAULT_PAGE_SIZE 1024
202 #endif
203 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
204 # undef SQLITE_DEFAULT_PAGE_SIZE
205 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
206 #endif
207
208 /*
209 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
210 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
211 ** device characteristics (sector-size and atomic write() support),
212 ** SQLite may choose a larger value. This constant is the maximum value
213 ** SQLite will choose on its own.
214 */
215 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
216 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
217 #endif
218 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
219 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
220 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
221 #endif
222
223
224 /*
225 ** Maximum number of pages in one database file.
226 **
227 ** This is really just the default value for the max_page_count pragma.
228 ** This value can be lowered (or raised) at run-time using that the
229 ** max_page_count macro.
230 */
231 #ifndef SQLITE_MAX_PAGE_COUNT
232 # define SQLITE_MAX_PAGE_COUNT 1073741823
233 #endif
234
235 /*
236 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
237 ** operator.
238 */
239 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
240 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
241 #endif
242
243 /************** End of sqliteLimit.h *****************************************/
244 /************** Continuing where we left off in sqliteInt.h ******************/
245
246 /* Disable nuisance warnings on Borland compilers */
247 #if defined(__BORLANDC__)
248 #pragma warn -rch /* unreachable code */
249 #pragma warn -ccc /* Condition is always true or false */
250 #pragma warn -aus /* Assigned value is never used */
251 #pragma warn -csu /* Comparing signed and unsigned */
252 #pragma warn -spa /* Suspicous pointer arithmetic */
253 #endif
254
255 /* Needed for various definitions... */
256 #ifndef _GNU_SOURCE
257 # define _GNU_SOURCE
258 #endif
259
260 /*
261 ** Include standard header files as necessary
262 */
263 #ifdef HAVE_STDINT_H
264 #include <stdint.h>
265 #endif
266 #ifdef HAVE_INTTYPES_H
267 #include <inttypes.h>
268 #endif
269
270 /*
271 ** A macro used to aid in coverage testing.  When doing coverage
272 ** testing, the condition inside the argument must be evaluated 
273 ** both true and false in order to get full branch coverage.
274 ** This macro can be inserted to ensure adequate test coverage
275 ** in places where simple condition/decision coverage is inadequate.
276 */
277 #ifdef SQLITE_COVERAGE_TEST
278 SQLITE_PRIVATE   void sqlite3Coverage(int);
279 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
280 #else
281 # define testcase(X)
282 #endif
283
284 /*
285 ** The ALWAYS and NEVER macros surround boolean expressions which 
286 ** are intended to always be true or false, respectively.  Such
287 ** expressions could be omitted from the code completely.  But they
288 ** are included in a few cases in order to enhance the resilience
289 ** of SQLite to unexpected behavior - to make the code "self-healing"
290 ** or "ductile" rather than being "brittle" and crashing at the first
291 ** hint of unplanned behavior.
292 **
293 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
294 ** be true and false so that the unreachable code then specify will
295 ** not be counted as untested code.
296 */
297 #ifdef SQLITE_COVERAGE_TEST
298 # define ALWAYS(X)      (1)
299 # define NEVER(X)       (0)
300 #else
301 # define ALWAYS(X)      (X)
302 # define NEVER(X)       (X)
303 #endif
304
305 /*
306 ** The macro unlikely() is a hint that surrounds a boolean
307 ** expression that is usually false.  Macro likely() surrounds
308 ** a boolean expression that is usually true.  GCC is able to
309 ** use these hints to generate better code, sometimes.
310 */
311 #if defined(__GNUC__) && 0
312 # define likely(X)    __builtin_expect((X),1)
313 # define unlikely(X)  __builtin_expect((X),0)
314 #else
315 # define likely(X)    !!(X)
316 # define unlikely(X)  !!(X)
317 #endif
318
319 /*
320  * This macro is used to "hide" some ugliness in casting an int
321  * value to a ptr value under the MSVC 64-bit compiler.   Casting
322  * non 64-bit values to ptr types results in a "hard" error with 
323  * the MSVC 64-bit compiler which this attempts to avoid.  
324  *
325  * A simple compiler pragma or casting sequence could not be found
326  * to correct this in all situations, so this macro was introduced.
327  *
328  * It could be argued that the intptr_t type could be used in this
329  * case, but that type is not available on all compilers, or 
330  * requires the #include of specific headers which differs between
331  * platforms.
332  */
333 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
334 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
335
336 /*
337 ** These #defines should enable >2GB file support on Posix if the
338 ** underlying operating system supports it.  If the OS lacks
339 ** large file support, or if the OS is windows, these should be no-ops.
340 **
341 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
342 ** system #includes.  Hence, this block of code must be the very first
343 ** code in all source files.
344 **
345 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
346 ** on the compiler command line.  This is necessary if you are compiling
347 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
348 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
349 ** without this option, LFS is enable.  But LFS does not exist in the kernel
350 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
351 ** portability you should omit LFS.
352 **
353 ** Similar is true for MacOS.  LFS is only supported on MacOS 9 and later.
354 */
355 #ifndef SQLITE_DISABLE_LFS
356 # define _LARGE_FILE       1
357 # ifndef _FILE_OFFSET_BITS
358 #   define _FILE_OFFSET_BITS 64
359 # endif
360 # define _LARGEFILE_SOURCE 1
361 #endif
362
363
364 /*
365 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
366 ** Older versions of SQLite used an optional THREADSAFE macro.
367 ** We support that for legacy
368 */
369 #if !defined(SQLITE_THREADSAFE)
370 #if defined(THREADSAFE)
371 # define SQLITE_THREADSAFE THREADSAFE
372 #else
373 # define SQLITE_THREADSAFE 1
374 #endif
375 #endif
376
377 /*
378 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
379 ** It determines whether or not the features related to 
380 ** SQLITE_CONFIG_MEMSTATUS are availabe by default or not. This value can
381 ** be overridden at runtime using the sqlite3_config() API.
382 */
383 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
384 # define SQLITE_DEFAULT_MEMSTATUS 1
385 #endif
386
387 /*
388 ** Exactly one of the following macros must be defined in order to
389 ** specify which memory allocation subsystem to use.
390 **
391 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
392 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393 **     SQLITE_MEMORY_SIZE            // internal allocator #1
394 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
395 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
396 **
397 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
398 ** the default.
399 */
400 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
401     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
402     defined(SQLITE_POW2_MEMORY_SIZE)>1
403 # error "At most one of the following compile-time configuration options\
404  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
405  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
406 #endif
407 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
408     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
409     defined(SQLITE_POW2_MEMORY_SIZE)==0
410 # define SQLITE_SYSTEM_MALLOC 1
411 #endif
412
413 /*
414 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
415 ** sizes of memory allocations below this value where possible.
416 */
417 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
418 # define SQLITE_MALLOC_SOFT_LIMIT 1024
419 #endif
420
421 /*
422 ** We need to define _XOPEN_SOURCE as follows in order to enable
423 ** recursive mutexes on most unix systems.  But Mac OS X is different.
424 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425 ** so it is omitted there.  See ticket #2673.
426 **
427 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428 ** implemented on some systems.  So we avoid defining it at all
429 ** if it is already defined or if it is unneeded because we are
430 ** not doing a threadsafe build.  Ticket #2681.
431 **
432 ** See also ticket #2741.
433 */
434 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436 #endif
437
438 /*
439 ** The TCL headers are only needed when compiling the TCL bindings.
440 */
441 #if defined(SQLITE_TCL) || defined(TCLSH)
442 # include <tcl.h>
443 #endif
444
445 /*
446 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447 ** Setting NDEBUG makes the code smaller and run faster.  So the following
448 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450 ** feature.
451 */
452 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
453 # define NDEBUG 1
454 #endif
455
456 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
457 /************** Begin file sqlite3.h *****************************************/
458 /*
459 ** 2001 September 15
460 **
461 ** The author disclaims copyright to this source code.  In place of
462 ** a legal notice, here is a blessing:
463 **
464 **    May you do good and not evil.
465 **    May you find forgiveness for yourself and forgive others.
466 **    May you share freely, never taking more than you give.
467 **
468 *************************************************************************
469 ** This header file defines the interface that the SQLite library
470 ** presents to client programs.  If a C-function, structure, datatype,
471 ** or constant definition does not appear in this file, then it is
472 ** not a published API of SQLite, is subject to change without
473 ** notice, and should not be referenced by programs that use SQLite.
474 **
475 ** Some of the definitions that are in this file are marked as
476 ** "experimental".  Experimental interfaces are normally new
477 ** features recently added to SQLite.  We do not anticipate changes
478 ** to experimental interfaces but reserve to make minor changes if
479 ** experience from use "in the wild" suggest such changes are prudent.
480 **
481 ** The official C-language API documentation for SQLite is derived
482 ** from comments in this file.  This file is the authoritative source
483 ** on how SQLite interfaces are suppose to operate.
484 **
485 ** The name of this file under configuration management is "sqlite.h.in".
486 ** The makefile makes some minor changes to this file (such as inserting
487 ** the version number) and changes its name to "sqlite3.h" as
488 ** part of the build process.
489 **
490 ** @(#) $Id: sqlite.h.in,v 1.404 2008/10/12 00:27:54 shane 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.4"
568 #define SQLITE_VERSION_NUMBER  3006004
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_errmsg()], and [sqlite3_errmsg16()].
840 **
841 ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
842 **          empty string or contains nothing other than whitespace, comments,
843 **          and/or semicolons, then results of [sqlite3_errcode()],
844 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()]
845 **          shall reset to indicate no errors.
846 **
847 ** ASSUMPTIONS:
848 **
849 ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
850 **          [database connection].
851 **
852 ** {A12142} The database connection must not be closed while
853 **          [sqlite3_exec()] is running.
854 **
855 ** {A12143} The calling function should use [sqlite3_free()] to free
856 **          the memory that *errmsg is left pointing at once the error
857 **          message is no longer needed.
858 **
859 ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
860 **          must remain unchanged while [sqlite3_exec()] is running.
861 */
862 SQLITE_API int sqlite3_exec(
863   sqlite3*,                                  /* An open database */
864   const char *sql,                           /* SQL to be evaluated */
865   int (*callback)(void*,int,char**,char**),  /* Callback function */
866   void *,                                    /* 1st argument to callback */
867   char **errmsg                              /* Error msg written here */
868 );
869
870 /*
871 ** CAPI3REF: Result Codes {H10210} <S10700>
872 ** KEYWORDS: SQLITE_OK {error code} {error codes}
873 ** KEYWORDS: {result code} {result codes}
874 **
875 ** Many SQLite functions return an integer result code from the set shown
876 ** here in order to indicates success or failure.
877 **
878 ** New error codes may be added in future versions of SQLite.
879 **
880 ** See also: [SQLITE_IOERR_READ | extended result codes]
881 */
882 #define SQLITE_OK           0   /* Successful result */
883 /* beginning-of-error-codes */
884 #define SQLITE_ERROR        1   /* SQL error or missing database */
885 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
886 #define SQLITE_PERM         3   /* Access permission denied */
887 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
888 #define SQLITE_BUSY         5   /* The database file is locked */
889 #define SQLITE_LOCKED       6   /* A table in the database is locked */
890 #define SQLITE_NOMEM        7   /* A malloc() failed */
891 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
892 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
893 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
894 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
895 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
896 #define SQLITE_FULL        13   /* Insertion failed because database is full */
897 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
898 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
899 #define SQLITE_EMPTY       16   /* Database is empty */
900 #define SQLITE_SCHEMA      17   /* The database schema changed */
901 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
902 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
903 #define SQLITE_MISMATCH    20   /* Data type mismatch */
904 #define SQLITE_MISUSE      21   /* Library used incorrectly */
905 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
906 #define SQLITE_AUTH        23   /* Authorization denied */
907 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
908 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
909 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
910 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
911 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
912 /* end-of-error-codes */
913
914 /*
915 ** CAPI3REF: Extended Result Codes {H10220} <S10700>
916 ** KEYWORDS: {extended error code} {extended error codes}
917 ** KEYWORDS: {extended result code} {extended result codes}
918 **
919 ** In its default configuration, SQLite API routines return one of 26 integer
920 ** [SQLITE_OK | result codes].  However, experience has shown that many of
921 ** these result codes are too coarse-grained.  They do not provide as
922 ** much information about problems as programmers might like.  In an effort to
923 ** address this, newer versions of SQLite (version 3.3.8 and later) include
924 ** support for additional result codes that provide more detailed information
925 ** about errors. The extended result codes are enabled or disabled
926 ** on a per database connection basis using the
927 ** [sqlite3_extended_result_codes()] API.
928 **
929 ** Some of the available extended result codes are listed here.
930 ** One may expect the number of extended result codes will be expand
931 ** over time.  Software that uses extended result codes should expect
932 ** to see new result codes in future releases of SQLite.
933 **
934 ** The SQLITE_OK result code will never be extended.  It will always
935 ** be exactly zero.
936 **
937 ** INVARIANTS:
938 **
939 ** {H10223} The symbolic name for an extended result code shall contains
940 **          a related primary result code as a prefix.
941 **
942 ** {H10224} Primary result code names shall contain a single "_" character.
943 **
944 ** {H10225} Extended result code names shall contain two or more "_" characters.
945 **
946 ** {H10226} The numeric value of an extended result code shall contain the
947 **          numeric value of its corresponding primary result code in
948 **          its least significant 8 bits.
949 */
950 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
951 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
952 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
953 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
954 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
955 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
956 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
957 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
958 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
959 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
960 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
961 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
962 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
963 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
964 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
965
966 /*
967 ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
968 **
969 ** These bit values are intended for use in the
970 ** 3rd parameter to the [sqlite3_open_v2()] interface and
971 ** in the 4th parameter to the xOpen method of the
972 ** [sqlite3_vfs] object.
973 */
974 #define SQLITE_OPEN_READONLY         0x00000001
975 #define SQLITE_OPEN_READWRITE        0x00000002
976 #define SQLITE_OPEN_CREATE           0x00000004
977 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
978 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
979 #define SQLITE_OPEN_MAIN_DB          0x00000100
980 #define SQLITE_OPEN_TEMP_DB          0x00000200
981 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
982 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
983 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
984 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
985 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
986 #define SQLITE_OPEN_NOMUTEX          0x00008000
987 #define SQLITE_OPEN_FULLMUTEX        0x00010000
988
989 /*
990 ** CAPI3REF: Device Characteristics {H10240} <H11120>
991 **
992 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
993 ** object returns an integer which is a vector of the these
994 ** bit values expressing I/O characteristics of the mass storage
995 ** device that holds the file that the [sqlite3_io_methods]
996 ** refers to.
997 **
998 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
999 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1000 ** mean that writes of blocks that are nnn bytes in size and
1001 ** are aligned to an address which is an integer multiple of
1002 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1003 ** that when data is appended to a file, the data is appended
1004 ** first then the size of the file is extended, never the other
1005 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1006 ** information is written to disk in the same order as calls
1007 ** to xWrite().
1008 */
1009 #define SQLITE_IOCAP_ATOMIC          0x00000001
1010 #define SQLITE_IOCAP_ATOMIC512       0x00000002
1011 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
1012 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1013 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1014 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1015 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1016 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1017 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1018 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1019 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1020
1021 /*
1022 ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
1023 **
1024 ** SQLite uses one of these integer values as the second
1025 ** argument to calls it makes to the xLock() and xUnlock() methods
1026 ** of an [sqlite3_io_methods] object.
1027 */
1028 #define SQLITE_LOCK_NONE          0
1029 #define SQLITE_LOCK_SHARED        1
1030 #define SQLITE_LOCK_RESERVED      2
1031 #define SQLITE_LOCK_PENDING       3
1032 #define SQLITE_LOCK_EXCLUSIVE     4
1033
1034 /*
1035 ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
1036 **
1037 ** When SQLite invokes the xSync() method of an
1038 ** [sqlite3_io_methods] object it uses a combination of
1039 ** these integer values as the second argument.
1040 **
1041 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1042 ** sync operation only needs to flush data to mass storage.  Inode
1043 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
1044 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
1045 ** to use Mac OS-X style fullsync instead of fsync().
1046 */
1047 #define SQLITE_SYNC_NORMAL        0x00002
1048 #define SQLITE_SYNC_FULL          0x00003
1049 #define SQLITE_SYNC_DATAONLY      0x00010
1050
1051 /*
1052 ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
1053 **
1054 ** An [sqlite3_file] object represents an open file in the OS
1055 ** interface layer.  Individual OS interface implementations will
1056 ** want to subclass this object by appending additional fields
1057 ** for their own use.  The pMethods entry is a pointer to an
1058 ** [sqlite3_io_methods] object that defines methods for performing
1059 ** I/O operations on the open file.
1060 */
1061 typedef struct sqlite3_file sqlite3_file;
1062 struct sqlite3_file {
1063   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1064 };
1065
1066 /*
1067 ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
1068 **
1069 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1070 ** [sqlite3_file] object (or, more commonly, a subclass of the
1071 ** [sqlite3_file] object) with a pointer to an instance of this object.
1072 ** This object defines the methods used to perform various operations
1073 ** against the open file represented by the [sqlite3_file] object.
1074 **
1075 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1076 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1077 ** The second choice is a Mac OS-X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1078 ** flag may be ORed in to indicate that only the data of the file
1079 ** and not its inode needs to be synced.
1080 **
1081 ** The integer values to xLock() and xUnlock() are one of
1082 ** <ul>
1083 ** <li> [SQLITE_LOCK_NONE],
1084 ** <li> [SQLITE_LOCK_SHARED],
1085 ** <li> [SQLITE_LOCK_RESERVED],
1086 ** <li> [SQLITE_LOCK_PENDING], or
1087 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1088 ** </ul>
1089 ** xLock() increases the lock. xUnlock() decreases the lock.
1090 ** The xCheckReservedLock() method checks whether any database connection,
1091 ** either in this process or in some other process, is holding a RESERVED,
1092 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1093 ** if such a lock exists and false otherwise.
1094 **
1095 ** The xFileControl() method is a generic interface that allows custom
1096 ** VFS implementations to directly control an open file using the
1097 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1098 ** integer opcode.  The third argument is a generic pointer intended to
1099 ** point to a structure that may contain arguments or space in which to
1100 ** write return values.  Potential uses for xFileControl() might be
1101 ** functions to enable blocking locks with timeouts, to change the
1102 ** locking strategy (for example to use dot-file locks), to inquire
1103 ** about the status of a lock, or to break stale locks.  The SQLite
1104 ** core reserves all opcodes less than 100 for its own use.
1105 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1106 ** Applications that define a custom xFileControl method should use opcodes
1107 ** greater than 100 to avoid conflicts.
1108 **
1109 ** The xSectorSize() method returns the sector size of the
1110 ** device that underlies the file.  The sector size is the
1111 ** minimum write that can be performed without disturbing
1112 ** other bytes in the file.  The xDeviceCharacteristics()
1113 ** method returns a bit vector describing behaviors of the
1114 ** underlying device:
1115 **
1116 ** <ul>
1117 ** <li> [SQLITE_IOCAP_ATOMIC]
1118 ** <li> [SQLITE_IOCAP_ATOMIC512]
1119 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1120 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1121 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1122 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1123 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1124 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1125 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1126 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1127 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1128 ** </ul>
1129 **
1130 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1131 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1132 ** mean that writes of blocks that are nnn bytes in size and
1133 ** are aligned to an address which is an integer multiple of
1134 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1135 ** that when data is appended to a file, the data is appended
1136 ** first then the size of the file is extended, never the other
1137 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1138 ** information is written to disk in the same order as calls
1139 ** to xWrite().
1140 */
1141 typedef struct sqlite3_io_methods sqlite3_io_methods;
1142 struct sqlite3_io_methods {
1143   int iVersion;
1144   int (*xClose)(sqlite3_file*);
1145   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1146   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1147   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1148   int (*xSync)(sqlite3_file*, int flags);
1149   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1150   int (*xLock)(sqlite3_file*, int);
1151   int (*xUnlock)(sqlite3_file*, int);
1152   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1153   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1154   int (*xSectorSize)(sqlite3_file*);
1155   int (*xDeviceCharacteristics)(sqlite3_file*);
1156   /* Additional methods may be added in future releases */
1157 };
1158
1159 /*
1160 ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
1161 **
1162 ** These integer constants are opcodes for the xFileControl method
1163 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1164 ** interface.
1165 **
1166 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1167 ** opcode causes the xFileControl method to write the current state of
1168 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1169 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1170 ** into an integer that the pArg argument points to. This capability
1171 ** is used during testing and only needs to be supported when SQLITE_TEST
1172 ** is defined.
1173 */
1174 #define SQLITE_FCNTL_LOCKSTATE        1
1175
1176 /*
1177 ** CAPI3REF: Mutex Handle {H17110} <S20130>
1178 **
1179 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1180 ** abstract type for a mutex object.  The SQLite core never looks
1181 ** at the internal representation of an [sqlite3_mutex].  It only
1182 ** deals with pointers to the [sqlite3_mutex] object.
1183 **
1184 ** Mutexes are created using [sqlite3_mutex_alloc()].
1185 */
1186 typedef struct sqlite3_mutex sqlite3_mutex;
1187
1188 /*
1189 ** CAPI3REF: OS Interface Object {H11140} <S20100>
1190 **
1191 ** An instance of the sqlite3_vfs object defines the interface between
1192 ** the SQLite core and the underlying operating system.  The "vfs"
1193 ** in the name of the object stands for "virtual file system".
1194 **
1195 ** The value of the iVersion field is initially 1 but may be larger in
1196 ** future versions of SQLite.  Additional fields may be appended to this
1197 ** object when the iVersion value is increased.  Note that the structure
1198 ** of the sqlite3_vfs object changes in the transaction between
1199 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1200 ** modified.
1201 **
1202 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1203 ** structure used by this VFS.  mxPathname is the maximum length of
1204 ** a pathname in this VFS.
1205 **
1206 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1207 ** the pNext pointer.  The [sqlite3_vfs_register()]
1208 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1209 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1210 ** searches the list.  Neither the application code nor the VFS
1211 ** implementation should use the pNext pointer.
1212 **
1213 ** The pNext field is the only field in the sqlite3_vfs
1214 ** structure that SQLite will ever modify.  SQLite will only access
1215 ** or modify this field while holding a particular static mutex.
1216 ** The application should never modify anything within the sqlite3_vfs
1217 ** object once the object has been registered.
1218 **
1219 ** The zName field holds the name of the VFS module.  The name must
1220 ** be unique across all VFS modules.
1221 **
1222 ** {H11141} SQLite will guarantee that the zFilename parameter to xOpen
1223 ** is either a NULL pointer or string obtained
1224 ** from xFullPathname().  SQLite further guarantees that
1225 ** the string will be valid and unchanged until xClose() is
1226 ** called. {END}  Because of the previous sentense,
1227 ** the [sqlite3_file] can safely store a pointer to the
1228 ** filename if it needs to remember the filename for some reason.
1229 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1230 ** must invite its own temporary name for the file.  Whenever the 
1231 ** xFilename parameter is NULL it will also be the case that the
1232 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1233 **
1234 ** {H11142} The flags argument to xOpen() includes all bits set in
1235 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1236 ** or [sqlite3_open16()] is used, then flags includes at least
1237 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END}
1238 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1239 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1240 **
1241 ** {H11143} SQLite will also add one of the following flags to the xOpen()
1242 ** call, depending on the object being opened:
1243 **
1244 ** <ul>
1245 ** <li>  [SQLITE_OPEN_MAIN_DB]
1246 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1247 ** <li>  [SQLITE_OPEN_TEMP_DB]
1248 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1249 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1250 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1251 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1252 ** </ul> {END}
1253 **
1254 ** The file I/O implementation can use the object type flags to
1255 ** change the way it deals with files.  For example, an application
1256 ** that does not care about crash recovery or rollback might make
1257 ** the open of a journal file a no-op.  Writes to this journal would
1258 ** also be no-ops, and any attempt to read the journal would return
1259 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1260 ** file will be doing page-aligned sector reads and writes in a random
1261 ** order and set up its I/O subsystem accordingly.
1262 **
1263 ** SQLite might also add one of the following flags to the xOpen method:
1264 **
1265 ** <ul>
1266 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1267 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1268 ** </ul>
1269 **
1270 ** {H11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1271 ** deleted when it is closed.  {H11146} The [SQLITE_OPEN_DELETEONCLOSE]
1272 ** will be set for TEMP  databases, journals and for subjournals.
1273 **
1274 ** {H11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1275 ** for exclusive access.  This flag is set for all files except
1276 ** for the main database file.
1277 **
1278 ** {H11148} At least szOsFile bytes of memory are allocated by SQLite
1279 ** to hold the  [sqlite3_file] structure passed as the third
1280 ** argument to xOpen. {END}  The xOpen method does not have to
1281 ** allocate the structure; it should just fill it in.
1282 **
1283 ** {H11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1284 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1285 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1286 ** to test whether a file is at least readable. {END}  The file can be a
1287 ** directory.
1288 **
1289 ** {H11150} SQLite will always allocate at least mxPathname+1 bytes for the
1290 ** output buffer xFullPathname. {H11151} The exact size of the output buffer
1291 ** is also passed as a parameter to both  methods. {END}  If the output buffer
1292 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1293 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1294 ** to prevent this by setting mxPathname to a sufficiently large value.
1295 **
1296 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1297 ** are not strictly a part of the filesystem, but they are
1298 ** included in the VFS structure for completeness.
1299 ** The xRandomness() function attempts to return nBytes bytes
1300 ** of good-quality randomness into zOut.  The return value is
1301 ** the actual number of bytes of randomness obtained.
1302 ** The xSleep() method causes the calling thread to sleep for at
1303 ** least the number of microseconds given.  The xCurrentTime()
1304 ** method returns a Julian Day Number for the current date and time.
1305 */
1306 typedef struct sqlite3_vfs sqlite3_vfs;
1307 struct sqlite3_vfs {
1308   int iVersion;            /* Structure version number */
1309   int szOsFile;            /* Size of subclassed sqlite3_file */
1310   int mxPathname;          /* Maximum file pathname length */
1311   sqlite3_vfs *pNext;      /* Next registered VFS */
1312   const char *zName;       /* Name of this virtual file system */
1313   void *pAppData;          /* Pointer to application-specific data */
1314   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1315                int flags, int *pOutFlags);
1316   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1317   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1318   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1319   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1320   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1321   void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
1322   void (*xDlClose)(sqlite3_vfs*, void*);
1323   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1324   int (*xSleep)(sqlite3_vfs*, int microseconds);
1325   int (*xCurrentTime)(sqlite3_vfs*, double*);
1326   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1327   /* New fields may be appended in figure versions.  The iVersion
1328   ** value will increment whenever this happens. */
1329 };
1330
1331 /*
1332 ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
1333 **
1334 ** {H11191} These integer constants can be used as the third parameter to
1335 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1336 ** what kind of permissions the xAccess method is looking for.
1337 ** {H11192} With SQLITE_ACCESS_EXISTS, the xAccess method
1338 ** simply checks whether the file exists.
1339 ** {H11193} With SQLITE_ACCESS_READWRITE, the xAccess method
1340 ** checks whether the file is both readable and writable.
1341 ** {H11194} With SQLITE_ACCESS_READ, the xAccess method
1342 ** checks whether the file is readable.
1343 */
1344 #define SQLITE_ACCESS_EXISTS    0
1345 #define SQLITE_ACCESS_READWRITE 1
1346 #define SQLITE_ACCESS_READ      2
1347
1348 /*
1349 ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
1350 **
1351 ** The sqlite3_initialize() routine initializes the
1352 ** SQLite library.  The sqlite3_shutdown() routine
1353 ** deallocates any resources that were allocated by sqlite3_initialize().
1354 **
1355 ** A call to sqlite3_initialize() is an "effective" call if it is
1356 ** the first time sqlite3_initialize() is invoked during the lifetime of
1357 ** the process, or if it is the first time sqlite3_initialize() is invoked
1358 ** following a call to sqlite3_shutdown().  Only an effective call
1359 ** of sqlite3_initialize() does any initialization.  All other calls
1360 ** are harmless no-ops.
1361 **
1362 ** Among other things, sqlite3_initialize() shall invoke
1363 ** sqlite3_os_init().  Similarly, sqlite3_shutdown()
1364 ** shall invoke sqlite3_os_end().
1365 **
1366 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1367 ** If for some reason, sqlite3_initialize() is unable to initialize
1368 ** the library (perhaps it is unable to allocate a needed resource such
1369 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1370 **
1371 ** The sqlite3_initialize() routine is called internally by many other
1372 ** SQLite interfaces so that an application usually does not need to
1373 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1374 ** calls sqlite3_initialize() so the SQLite library will be automatically
1375 ** initialized when [sqlite3_open()] is called if it has not be initialized
1376 ** already.  However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1377 ** compile-time option, then the automatic calls to sqlite3_initialize()
1378 ** are omitted and the application must call sqlite3_initialize() directly
1379 ** prior to using any other SQLite interface.  For maximum portability,
1380 ** it is recommended that applications always invoke sqlite3_initialize()
1381 ** directly prior to using any other SQLite interface.  Future releases
1382 ** of SQLite may require this.  In other words, the behavior exhibited
1383 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1384 ** default behavior in some future release of SQLite.
1385 **
1386 ** The sqlite3_os_init() routine does operating-system specific
1387 ** initialization of the SQLite library.  The sqlite3_os_end()
1388 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1389 ** performed by these routines include allocation or deallocation
1390 ** of static resources, initialization of global variables,
1391 ** setting up a default [sqlite3_vfs] module, or setting up
1392 ** a default configuration using [sqlite3_config()].
1393 **
1394 ** The application should never invoke either sqlite3_os_init()
1395 ** or sqlite3_os_end() directly.  The application should only invoke
1396 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1397 ** interface is called automatically by sqlite3_initialize() and
1398 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1399 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1400 ** are built into SQLite when it is compiled for unix, windows, or os/2.
1401 ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time
1402 ** option) the application must supply a suitable implementation for
1403 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1404 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1405 ** must return [SQLITE_OK] on success and some other [error code] upon
1406 ** failure.
1407 */
1408 SQLITE_API int sqlite3_initialize(void);
1409 SQLITE_API int sqlite3_shutdown(void);
1410 SQLITE_API int sqlite3_os_init(void);
1411 SQLITE_API int sqlite3_os_end(void);
1412
1413 /*
1414 ** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
1415 ** EXPERIMENTAL
1416 **
1417 ** The sqlite3_config() interface is used to make global configuration
1418 ** changes to SQLite in order to tune SQLite to the specific needs of
1419 ** the application.  The default configuration is recommended for most
1420 ** applications and so this routine is usually not necessary.  It is
1421 ** provided to support rare applications with unusual needs.
1422 **
1423 ** The sqlite3_config() interface is not threadsafe.  The application
1424 ** must insure that no other SQLite interfaces are invoked by other
1425 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1426 ** may only be invoked prior to library initialization using
1427 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1428 ** Note, however, that sqlite3_config() can be called as part of the
1429 ** implementation of an application-defined [sqlite3_os_init()].
1430 **
1431 ** The first argument to sqlite3_config() is an integer
1432 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1433 ** what property of SQLite is to be configured.  Subsequent arguments
1434 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1435 ** in the first argument.
1436 **
1437 ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1438 ** If the option is unknown or SQLite is unable to set the option
1439 ** then this routine returns a non-zero [error code].
1440 **
1441 ** INVARIANTS:
1442 **
1443 ** {H14103} A successful invocation of [sqlite3_config()] shall return
1444 **          [SQLITE_OK].
1445 **
1446 ** {H14106} The [sqlite3_config()] interface shall return [SQLITE_MISUSE]
1447 **          if it is invoked in between calls to [sqlite3_initialize()] and
1448 **          [sqlite3_shutdown()].
1449 **
1450 ** {H14120} A successful call to [sqlite3_config]([SQLITE_CONFIG_SINGLETHREAD])
1451 **          shall set the default [threading mode] to Single-thread.
1452 **
1453 ** {H14123} A successful call to [sqlite3_config]([SQLITE_CONFIG_MULTITHREAD])
1454 **          shall set the default [threading mode] to Multi-thread.
1455 **
1456 ** {H14126} A successful call to [sqlite3_config]([SQLITE_CONFIG_SERIALIZED])
1457 **          shall set the default [threading mode] to Serialized.
1458 **
1459 ** {H14129} A successful call to [sqlite3_config]([SQLITE_CONFIG_MUTEX],X)
1460 **          where X is a pointer to an initialized [sqlite3_mutex_methods]
1461 **          object shall cause all subsequent mutex operations performed
1462 **          by SQLite to use the mutex methods that were present in X
1463 **          during the call to [sqlite3_config()].
1464 **
1465 ** {H14132} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMUTEX],X)
1466 **          where X is a pointer to an [sqlite3_mutex_methods] object 
1467 **          shall overwrite the content of [sqlite3_mutex_methods] object
1468 **          with the mutex methods currently in use by SQLite.
1469 **
1470 ** {H14135} A successful call to [sqlite3_config]([SQLITE_CONFIG_MALLOC],M)
1471 **          where M is a pointer to an initialized [sqlite3_mem_methods]
1472 **          object shall cause all subsequent memory allocation operations
1473 **          performed by SQLite to use the methods that were present in 
1474 **          M during the call to [sqlite3_config()].
1475 **
1476 ** {H14138} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMALLOC],M)
1477 **          where M is a pointer to an [sqlite3_mem_methods] object shall
1478 **          overwrite the content of [sqlite3_mem_methods] object with 
1479 **          the memory allocation methods currently in use by
1480 **          SQLite.
1481 **
1482 ** {H14141} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],1)
1483 **          shall enable the memory allocation status collection logic.
1484 **
1485 ** {H14144} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],0)
1486 **          shall disable the memory allocation status collection logic.
1487 **
1488 ** {H14147} The memory allocation status collection logic shall be
1489 **          enabled by default.
1490 **
1491 ** {H14150} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1492 **          where Z and N are non-negative integers and 
1493 **          S is a pointer to an aligned memory buffer not less than
1494 **          Z*N bytes in size shall cause S to be used by the
1495 **          [scratch memory allocator] for as many as N simulataneous
1496 **          allocations each of size Z.
1497 **
1498 ** {H14153} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1499 **          where S is a NULL pointer shall disable the
1500 **          [scratch memory allocator].
1501 **
1502 ** {H14156} A successful call to
1503 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1504 **          where Z and N are non-negative integers and 
1505 **          S is a pointer to an aligned memory buffer not less than
1506 **          Z*N bytes in size shall cause S to be used by the
1507 **          [pagecache memory allocator] for as many as N simulataneous
1508 **          allocations each of size Z.
1509 **
1510 ** {H14159} A successful call to
1511 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1512 **          where S is a NULL pointer shall disable the
1513 **          [pagecache memory allocator].
1514 **
1515 ** {H14162} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1516 **          where Z and N are non-negative integers and 
1517 **          H is a pointer to an aligned memory buffer not less than
1518 **          Z bytes in size shall enable the [memsys5] memory allocator
1519 **          and cause it to use buffer S as its memory source and to use
1520 **          a minimum allocation size of N.
1521 **
1522 ** {H14165} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1523 **          where H is a NULL pointer shall disable the
1524 **          [memsys5] memory allocator.
1525 **
1526 ** {H14168} A successful call to [sqlite3_config]([SQLITE_CONFIG_LOOKASIDE],Z,N)
1527 **          shall cause the default [lookaside memory allocator] configuration
1528 **          for new [database connections] to be N slots of Z bytes each.
1529 */
1530 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1531
1532 /*
1533 ** CAPI3REF: Configure database connections  {H14200} <S20000>
1534 ** EXPERIMENTAL
1535 **
1536 ** The sqlite3_db_config() interface is used to make configuration
1537 ** changes to a [database connection].  The interface is similar to
1538 ** [sqlite3_config()] except that the changes apply to a single
1539 ** [database connection] (specified in the first argument).  The
1540 ** sqlite3_db_config() interface can only be used immediately after
1541 ** the database connection is created using [sqlite3_open()],
1542 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1543 **
1544 ** The second argument to sqlite3_db_config(D,V,...)  is the
1545 ** configuration verb - an integer code that indicates what
1546 ** aspect of the [database connection] is being configured.
1547 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1548 ** New verbs are likely to be added in future releases of SQLite.
1549 ** Additional arguments depend on the verb.
1550 **
1551 ** INVARIANTS:
1552 **
1553 ** {H14203} A call to [sqlite3_db_config(D,V,...)] shall return [SQLITE_OK]
1554 **          if and only if the call is successful.
1555 **
1556 ** {H14206} If one or more slots of the [lookaside memory allocator] for
1557 **          [database connection] D are in use, then a call to
1558 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],...) shall
1559 **          fail with an [SQLITE_BUSY] return code.
1560 **
1561 ** {H14209} A successful call to 
1562 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1563 **          D is an open [database connection] and Z and N are positive
1564 **          integers and B is an aligned buffer at least Z*N bytes in size
1565 **          shall cause the [lookaside memory allocator] for D to use buffer B 
1566 **          with N slots of Z bytes each.
1567 **
1568 ** {H14212} A successful call to 
1569 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1570 **          D is an open [database connection] and Z and N are positive
1571 **          integers and B is NULL pointer shall cause the
1572 **          [lookaside memory allocator] for D to a obtain Z*N byte buffer
1573 **          from the primary memory allocator and use that buffer
1574 **          with N lookaside slots of Z bytes each.
1575 **
1576 ** {H14215} 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 zero shall
1579 **          disable the [lookaside memory allocator] for D.
1580 **
1581 **
1582 */
1583 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1584
1585 /*
1586 ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
1587 ** EXPERIMENTAL
1588 **
1589 ** An instance of this object defines the interface between SQLite
1590 ** and low-level memory allocation routines.
1591 **
1592 ** This object is used in only one place in the SQLite interface.
1593 ** A pointer to an instance of this object is the argument to
1594 ** [sqlite3_config()] when the configuration option is
1595 ** [SQLITE_CONFIG_MALLOC].  By creating an instance of this object
1596 ** and passing it to [sqlite3_config()] during configuration, an
1597 ** application can specify an alternative memory allocation subsystem
1598 ** for SQLite to use for all of its dynamic memory needs.
1599 **
1600 ** Note that SQLite comes with a built-in memory allocator that is
1601 ** perfectly adequate for the overwhelming majority of applications
1602 ** and that this object is only useful to a tiny minority of applications
1603 ** with specialized memory allocation requirements.  This object is
1604 ** also used during testing of SQLite in order to specify an alternative
1605 ** memory allocator that simulates memory out-of-memory conditions in
1606 ** order to verify that SQLite recovers gracefully from such
1607 ** conditions.
1608 **
1609 ** The xMalloc, xFree, and xRealloc methods must work like the
1610 ** malloc(), free(), and realloc() functions from the standard library.
1611 **
1612 ** xSize should return the allocated size of a memory allocation
1613 ** previously obtained from xMalloc or xRealloc.  The allocated size
1614 ** is always at least as big as the requested size but may be larger.
1615 **
1616 ** The xRoundup method returns what would be the allocated size of
1617 ** a memory allocation given a particular requested size.  Most memory
1618 ** allocators round up memory allocations at least to the next multiple
1619 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1620 **
1621 ** The xInit method initializes the memory allocator.  (For example,
1622 ** it might allocate any require mutexes or initialize internal data
1623 ** structures.  The xShutdown method is invoked (indirectly) by
1624 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1625 ** by xInit.  The pAppData pointer is used as the only parameter to
1626 ** xInit and xShutdown.
1627 */
1628 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1629 struct sqlite3_mem_methods {
1630   void *(*xMalloc)(int);         /* Memory allocation function */
1631   void (*xFree)(void*);          /* Free a prior allocation */
1632   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1633   int (*xSize)(void*);           /* Return the size of an allocation */
1634   int (*xRoundup)(int);          /* Round up request size to allocation size */
1635   int (*xInit)(void*);           /* Initialize the memory allocator */
1636   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1637   void *pAppData;                /* Argument to xInit() and xShutdown() */
1638 };
1639
1640 /*
1641 ** CAPI3REF: Configuration Options {H10160} <S20000>
1642 ** EXPERIMENTAL
1643 **
1644 ** These constants are the available integer configuration options that
1645 ** can be passed as the first argument to the [sqlite3_config()] interface.
1646 **
1647 ** New configuration options may be added in future releases of SQLite.
1648 ** Existing configuration options might be discontinued.  Applications
1649 ** should check the return code from [sqlite3_config()] to make sure that
1650 ** the call worked.  The [sqlite3_config()] interface will return a
1651 ** non-zero [error code] if a discontinued or unsupported configuration option
1652 ** is invoked.
1653 **
1654 ** <dl>
1655 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1656 ** <dd>There are no arguments to this option.  This option disables
1657 ** all mutexing and puts SQLite into a mode where it can only be used
1658 ** by a single thread.</dd>
1659 **
1660 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1661 ** <dd>There are no arguments to this option.  This option disables
1662 ** mutexing on [database connection] and [prepared statement] objects.
1663 ** The application is responsible for serializing access to
1664 ** [database connections] and [prepared statements].  But other mutexes
1665 ** are enabled so that SQLite will be safe to use in a multi-threaded
1666 ** environment as long as no two threads attempt to use the same
1667 ** [database connection] at the same time.  See the [threading mode]
1668 ** documentation for additional information.</dd>
1669 **
1670 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1671 ** <dd>There are no arguments to this option.  This option enables
1672 ** all mutexes including the recursive
1673 ** mutexes on [database connection] and [prepared statement] objects.
1674 ** In this mode (which is the default when SQLite is compiled with
1675 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1676 ** to [database connections] and [prepared statements] so that the
1677 ** application is free to use the same [database connection] or the
1678 ** same [prepared statement] in different threads at the same time.
1679 ** See the [threading mode] documentation for additional information.</dd>
1680 **
1681 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1682 ** <dd>This option takes a single argument which is a pointer to an
1683 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1684 ** alternative low-level memory allocation routines to be used in place of
1685 ** the memory allocation routines built into SQLite.</dd>
1686 **
1687 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1688 ** <dd>This option takes a single argument which is a pointer to an
1689 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1690 ** structure is filled with the currently defined memory allocation routines.
1691 ** This option can be used to overload the default memory allocation
1692 ** routines with a wrapper that simulations memory allocation failure or
1693 ** tracks memory usage, for example.</dd>
1694 **
1695 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1696 ** <dd>This option takes single argument of type int, interpreted as a 
1697 ** boolean, which enables or disables the collection of memory allocation 
1698 ** statistics. When disabled, the following SQLite interfaces become 
1699 ** non-operational:
1700 **   <ul>
1701 **   <li> [sqlite3_memory_used()]
1702 **   <li> [sqlite3_memory_highwater()]
1703 **   <li> [sqlite3_soft_heap_limit()]
1704 **   <li> [sqlite3_status()]
1705 **   </ul>
1706 ** </dd>
1707 **
1708 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1709 ** <dd>This option specifies a static memory buffer that SQLite can use for
1710 ** scratch memory.  There are three arguments:  A pointer to the memory, the
1711 ** size of each scratch buffer (sz), and the number of buffers (N).  The sz
1712 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1713 ** larger than the actual scratch space required due internal overhead.
1714 ** The first
1715 ** argument should point to an allocation of at least sz*N bytes of memory.
1716 ** SQLite will use no more than one scratch buffer at once per thread, so
1717 ** N should be set to the expected maximum number of threads.  The sz
1718 ** parameter should be 6 times the size of the largest database page size.
1719 ** Scratch buffers are used as part of the btree balance operation.  If
1720 ** The btree balancer needs additional memory beyond what is provided by
1721 ** scratch buffers or if no scratch buffer space is specified, then SQLite
1722 ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
1723 **
1724 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1725 ** <dd>This option specifies a static memory buffer that SQLite can use for
1726 ** the database page cache.  There are three arguments: A pointer to the
1727 ** memory, the size of each page buffer (sz), and the number of pages (N).
1728 ** The sz argument must be a power of two between 512 and 32768.  The first
1729 ** argument should point to an allocation of at least sz*N bytes of memory.
1730 ** SQLite will use the memory provided by the first argument to satisfy its
1731 ** memory needs for the first N pages that it adds to cache.  If additional
1732 ** page cache memory is needed beyond what is provided by this option, then
1733 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1734 ** The implementation might use one or more of the N buffers to hold 
1735 ** memory accounting information. </dd>
1736 **
1737 ** <dt>SQLITE_CONFIG_HEAP</dt>
1738 ** <dd>This option specifies a static memory buffer that SQLite will use
1739 ** for all of its dynamic memory allocation needs beyond those provided
1740 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1741 ** There are three arguments: A pointer to the memory, the number of
1742 ** bytes in the memory buffer, and the minimum allocation size.  If
1743 ** the first pointer (the memory pointer) is NULL, then SQLite reverts
1744 ** to using its default memory allocator (the system malloc() implementation),
1745 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
1746 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1747 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1748 ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
1749 **
1750 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1751 ** <dd>This option takes a single argument which is a pointer to an
1752 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1753 ** alternative low-level mutex routines to be used in place
1754 ** the mutex routines built into SQLite.</dd>
1755 **
1756 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1757 ** <dd>This option takes a single argument which is a pointer to an
1758 ** instance of the [sqlite3_mutex_methods] structure.  The
1759 ** [sqlite3_mutex_methods]
1760 ** structure is filled with the currently defined mutex routines.
1761 ** This option can be used to overload the default mutex allocation
1762 ** routines with a wrapper used to track mutex usage for performance
1763 ** profiling or testing, for example.</dd>
1764 **
1765 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1766 ** <dd>This option takes two arguments that determine the default
1767 ** memory allcation lookaside optimization.  The first argument is the
1768 ** size of each lookaside buffer slot and the second is the number of
1769 ** slots allocated to each database connection.</dd>
1770 **
1771 ** </dl>
1772 */
1773 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1774 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1775 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1776 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1777 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1778 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1779 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1780 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1781 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1782 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1783 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1784 #define SQLITE_CONFIG_CHUNKALLOC   12  /* int threshold */
1785 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1786
1787 /*
1788 ** CAPI3REF: Configuration Options {H10170} <S20000>
1789 ** EXPERIMENTAL
1790 **
1791 ** These constants are the available integer configuration options that
1792 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1793 **
1794 ** New configuration options may be added in future releases of SQLite.
1795 ** Existing configuration options might be discontinued.  Applications
1796 ** should check the return code from [sqlite3_db_config()] to make sure that
1797 ** the call worked.  The [sqlite3_db_config()] interface will return a
1798 ** non-zero [error code] if a discontinued or unsupported configuration option
1799 ** is invoked.
1800 **
1801 ** <dl>
1802 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1803 ** <dd>This option takes three additional arguments that determine the 
1804 ** [lookaside memory allocator] configuration for the [database connection].
1805 ** The first argument (the third parameter to [sqlite3_db_config()] is a
1806 ** pointer to a memory buffer to use for lookaside memory.  The first
1807 ** argument may be NULL in which case SQLite will allocate the lookaside
1808 ** buffer itself using [sqlite3_malloc()].  The second argument is the
1809 ** size of each lookaside buffer slot and the third argument is the number of
1810 ** slots.  The size of the buffer in the first argument must be greater than
1811 ** or equal to the product of the second and third arguments.</dd>
1812 **
1813 ** </dl>
1814 */
1815 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1816
1817
1818 /*
1819 ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
1820 **
1821 ** The sqlite3_extended_result_codes() routine enables or disables the
1822 ** [extended result codes] feature of SQLite. The extended result
1823 ** codes are disabled by default for historical compatibility considerations.
1824 **
1825 ** INVARIANTS:
1826 **
1827 ** {H12201} Each new [database connection] shall have the
1828 **          [extended result codes] feature disabled by default.
1829 **
1830 ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
1831 **          [extended result codes] for the  [database connection] D
1832 **          if the F parameter is true, or disable them if F is false.
1833 */
1834 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1835
1836 /*
1837 ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
1838 **
1839 ** Each entry in an SQLite table has a unique 64-bit signed
1840 ** integer key called the "rowid". The rowid is always available
1841 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1842 ** names are not also used by explicitly declared columns. If
1843 ** the table has a column of type INTEGER PRIMARY KEY then that column
1844 ** is another alias for the rowid.
1845 **
1846 ** This routine returns the rowid of the most recent
1847 ** successful [INSERT] into the database from the [database connection]
1848 ** in the first argument.  If no successful [INSERT]s
1849 ** have ever occurred on that database connection, zero is returned.
1850 **
1851 ** If an [INSERT] occurs within a trigger, then the rowid of the inserted
1852 ** row is returned by this routine as long as the trigger is running.
1853 ** But once the trigger terminates, the value returned by this routine
1854 ** reverts to the last value inserted before the trigger fired.
1855 **
1856 ** An [INSERT] that fails due to a constraint violation is not a
1857 ** successful [INSERT] and does not change the value returned by this
1858 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1859 ** and INSERT OR ABORT make no changes to the return value of this
1860 ** routine when their insertion fails.  When INSERT OR REPLACE
1861 ** encounters a constraint violation, it does not fail.  The
1862 ** INSERT continues to completion after deleting rows that caused
1863 ** the constraint problem so INSERT OR REPLACE will always change
1864 ** the return value of this interface.
1865 **
1866 ** For the purposes of this routine, an [INSERT] is considered to
1867 ** be successful even if it is subsequently rolled back.
1868 **
1869 ** INVARIANTS:
1870 **
1871 ** {H12221} The [sqlite3_last_insert_rowid()] function shall return the rowid
1872 **          of the most recent successful [INSERT] performed on the same
1873 **          [database connection] and within the same or higher level
1874 **          trigger context, or zero if there have been no qualifying
1875 **          [INSERT] statements.
1876 **
1877 ** {H12223} The [sqlite3_last_insert_rowid()] function shall return the
1878 **          same value when called from the same trigger context
1879 **          immediately before and after a [ROLLBACK].
1880 **
1881 ** ASSUMPTIONS:
1882 **
1883 ** {A12232} If a separate thread performs a new [INSERT] on the same
1884 **          database connection while the [sqlite3_last_insert_rowid()]
1885 **          function is running and thus changes the last insert rowid,
1886 **          then the value returned by [sqlite3_last_insert_rowid()] is
1887 **          unpredictable and might not equal either the old or the new
1888 **          last insert rowid.
1889 */
1890 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1891
1892 /*
1893 ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
1894 **
1895 ** This function returns the number of database rows that were changed
1896 ** or inserted or deleted by the most recently completed SQL statement
1897 ** on the [database connection] specified by the first parameter.
1898 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1899 ** or [DELETE] statement are counted.  Auxiliary changes caused by
1900 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1901 ** to find the total number of changes including changes caused by triggers.
1902 **
1903 ** A "row change" is a change to a single row of a single table
1904 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1905 ** are changed as side effects of REPLACE constraint resolution,
1906 ** rollback, ABORT processing, DROP TABLE, or by any other
1907 ** mechanisms do not count as direct row changes.
1908 **
1909 ** A "trigger context" is a scope of execution that begins and
1910 ** ends with the script of a trigger.  Most SQL statements are
1911 ** evaluated outside of any trigger.  This is the "top level"
1912 ** trigger context.  If a trigger fires from the top level, a
1913 ** new trigger context is entered for the duration of that one
1914 ** trigger.  Subtriggers create subcontexts for their duration.
1915 **
1916 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1917 ** not create a new trigger context.
1918 **
1919 ** This function returns the number of direct row changes in the
1920 ** most recent INSERT, UPDATE, or DELETE statement within the same
1921 ** trigger context.
1922 **
1923 ** Thus, when called from the top level, this function returns the
1924 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1925 ** that also occurred at the top level.  Within the body of a trigger,
1926 ** the sqlite3_changes() interface can be called to find the number of
1927 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1928 ** statement within the body of the same trigger.
1929 ** However, the number returned does not include changes
1930 ** caused by subtriggers since those have their own context.
1931 **
1932 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1933 ** by dropping and recreating the table.  Doing so is much faster than going
1934 ** through and deleting individual elements from the table.  Because of this
1935 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1936 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1937 ** functions, regardless of the number of elements that were originally
1938 ** in the table.  To get an accurate count of the number of rows deleted, use
1939 ** "DELETE FROM table WHERE 1" instead.  Or recompile using the
1940 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1941 ** optimization on all queries.
1942 **
1943 ** INVARIANTS:
1944 **
1945 ** {H12241} The [sqlite3_changes()] function shall return the number of
1946 **          row changes caused by the most recent INSERT, UPDATE,
1947 **          or DELETE statement on the same database connection and
1948 **          within the same or higher trigger context, or zero if there have
1949 **          not been any qualifying row changes.
1950 **
1951 ** {H12243} Statements of the form "DELETE FROM tablename" with no
1952 **          WHERE clause shall cause subsequent calls to
1953 **          [sqlite3_changes()] to return zero, regardless of the
1954 **          number of rows originally in the table.
1955 **
1956 ** ASSUMPTIONS:
1957 **
1958 ** {A12252} If a separate thread makes changes on the same database connection
1959 **          while [sqlite3_changes()] is running then the value returned
1960 **          is unpredictable and not meaningful.
1961 */
1962 SQLITE_API int sqlite3_changes(sqlite3*);
1963
1964 /*
1965 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1966 **
1967 ** This function returns the number of row changes caused by INSERT,
1968 ** UPDATE or DELETE statements since the [database connection] was opened.
1969 ** The count includes all changes from all trigger contexts.  However,
1970 ** the count does not include changes used to implement REPLACE constraints,
1971 ** do rollbacks or ABORT processing, or DROP table processing.
1972 ** The changes are counted as soon as the statement that makes them is
1973 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1974 ** [sqlite3_finalize()]).
1975 **
1976 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1977 ** by dropping and recreating the table.  (This is much faster than going
1978 ** through and deleting individual elements from the table.)  Because of this
1979 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1980 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1981 ** functions, regardless of the number of elements that were originally
1982 ** in the table.  To get an accurate count of the number of rows deleted, use
1983 ** "DELETE FROM table WHERE 1" instead.   Or recompile using the
1984 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1985 ** optimization on all queries.
1986 **
1987 ** See also the [sqlite3_changes()] interface.
1988 **
1989 ** INVARIANTS:
1990 **
1991 ** {H12261} The [sqlite3_total_changes()] returns the total number
1992 **          of row changes caused by INSERT, UPDATE, and/or DELETE
1993 **          statements on the same [database connection], in any
1994 **          trigger context, since the database connection was created.
1995 **
1996 ** {H12263} Statements of the form "DELETE FROM tablename" with no
1997 **          WHERE clause shall not change the value returned
1998 **          by [sqlite3_total_changes()].
1999 **
2000 ** ASSUMPTIONS:
2001 **
2002 ** {A12264} If a separate thread makes changes on the same database connection
2003 **          while [sqlite3_total_changes()] is running then the value
2004 **          returned is unpredictable and not meaningful.
2005 */
2006 SQLITE_API int sqlite3_total_changes(sqlite3*);
2007
2008 /*
2009 ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
2010 **
2011 ** This function causes any pending database operation to abort and
2012 ** return at its earliest opportunity. This routine is typically
2013 ** called in response to a user action such as pressing "Cancel"
2014 ** or Ctrl-C where the user wants a long query operation to halt
2015 ** immediately.
2016 **
2017 ** It is safe to call this routine from a thread different from the
2018 ** thread that is currently running the database operation.  But it
2019 ** is not safe to call this routine with a [database connection] that
2020 ** is closed or might close before sqlite3_interrupt() returns.
2021 **
2022 ** If an SQL operation is very nearly finished at the time when
2023 ** sqlite3_interrupt() is called, then it might not have an opportunity
2024 ** to be interrupted and might continue to completion.
2025 **
2026 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2027 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2028 ** that is inside an explicit transaction, then the entire transaction
2029 ** will be rolled back automatically.
2030 **
2031 ** A call to sqlite3_interrupt() has no effect on SQL statements
2032 ** that are started after sqlite3_interrupt() returns.
2033 **
2034 ** INVARIANTS:
2035 **
2036 ** {H12271} The [sqlite3_interrupt()] interface will force all running
2037 **          SQL statements associated with the same database connection
2038 **          to halt after processing at most one additional row of data.
2039 **
2040 ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
2041 **          will return [SQLITE_INTERRUPT].
2042 **
2043 ** ASSUMPTIONS:
2044 **
2045 ** {A12279} If the database connection closes while [sqlite3_interrupt()]
2046 **          is running then bad things will likely happen.
2047 */
2048 SQLITE_API void sqlite3_interrupt(sqlite3*);
2049
2050 /*
2051 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
2052 **
2053 ** These routines are useful for command-line input to determine if the
2054 ** currently entered text seems to form complete a SQL statement or
2055 ** if additional input is needed before sending the text into
2056 ** SQLite for parsing.  These routines return true if the input string
2057 ** appears to be a complete SQL statement.  A statement is judged to be
2058 ** complete if it ends with a semicolon token and is not a fragment of a
2059 ** CREATE TRIGGER statement.  Semicolons that are embedded within
2060 ** string literals or quoted identifier names or comments are not
2061 ** independent tokens (they are part of the token in which they are
2062 ** embedded) and thus do not count as a statement terminator.
2063 **
2064 ** These routines do not parse the SQL statements thus
2065 ** will not detect syntactically incorrect SQL.
2066 **
2067 ** INVARIANTS:
2068 **
2069 ** {H10511} A successful evaluation of [sqlite3_complete()] or
2070 **          [sqlite3_complete16()] functions shall
2071 **          return a numeric 1 if and only if the last non-whitespace
2072 **          token in their input is a semicolon that is not in between
2073 **          the BEGIN and END of a CREATE TRIGGER statement.
2074 **
2075 ** {H10512} If a memory allocation error occurs during an invocation
2076 **          of [sqlite3_complete()] or [sqlite3_complete16()] then the
2077 **          routine shall return [SQLITE_NOMEM].
2078 **
2079 ** ASSUMPTIONS:
2080 **
2081 ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
2082 **          UTF-8 string.
2083 **
2084 ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
2085 **          UTF-16 string in native byte order.
2086 */
2087 SQLITE_API int sqlite3_complete(const char *sql);
2088 SQLITE_API int sqlite3_complete16(const void *sql);
2089
2090 /*
2091 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
2092 **
2093 ** This routine sets a callback function that might be invoked whenever
2094 ** an attempt is made to open a database table that another thread
2095 ** or process has locked.
2096 **
2097 ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2098 ** is returned immediately upon encountering the lock. If the busy callback
2099 ** is not NULL, then the callback will be invoked with two arguments.
2100 **
2101 ** The first argument to the handler is a copy of the void* pointer which
2102 ** is the third argument to sqlite3_busy_handler().  The second argument to
2103 ** the handler callback is the number of times that the busy handler has
2104 ** been invoked for this locking event.  If the
2105 ** busy callback returns 0, then no additional attempts are made to
2106 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2107 ** If the callback returns non-zero, then another attempt
2108 ** is made to open the database for reading and the cycle repeats.
2109 **
2110 ** The presence of a busy handler does not guarantee that it will be invoked
2111 ** when there is lock contention. If SQLite determines that invoking the busy
2112 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2113 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2114 ** Consider a scenario where one process is holding a read lock that
2115 ** it is trying to promote to a reserved lock and
2116 ** a second process is holding a reserved lock that it is trying
2117 ** to promote to an exclusive lock.  The first process cannot proceed
2118 ** because it is blocked by the second and the second process cannot
2119 ** proceed because it is blocked by the first.  If both processes
2120 ** invoke the busy handlers, neither will make any progress.  Therefore,
2121 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2122 ** will induce the first process to release its read lock and allow
2123 ** the second process to proceed.
2124 **
2125 ** The default busy callback is NULL.
2126 **
2127 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2128 ** when SQLite is in the middle of a large transaction where all the
2129 ** changes will not fit into the in-memory cache.  SQLite will
2130 ** already hold a RESERVED lock on the database file, but it needs
2131 ** to promote this lock to EXCLUSIVE so that it can spill cache
2132 ** pages into the database file without harm to concurrent
2133 ** readers.  If it is unable to promote the lock, then the in-memory
2134 ** cache will be left in an inconsistent state and so the error
2135 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2136 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
2137 ** forces an automatic rollback of the changes.  See the
2138 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2139 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2140 ** this is important.
2141 **
2142 ** There can only be a single busy handler defined for each
2143 ** [database connection].  Setting a new busy handler clears any
2144 ** previously set handler.  Note that calling [sqlite3_busy_timeout()]
2145 ** will also set or clear the busy handler.
2146 **
2147 ** The busy callback should not take any actions which modify the
2148 ** database connection that invoked the busy handler.  Any such actions
2149 ** result in undefined behavior.
2150 ** 
2151 ** INVARIANTS:
2152 **
2153 ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
2154 **          busy callback in the [database connection] D with a new
2155 **          a new busy handler C and application data pointer A.
2156 **
2157 ** {H12312} Newly created [database connections] shall have a busy
2158 **          handler of NULL.
2159 **
2160 ** {H12314} When two or more [database connections] share a
2161 **          [sqlite3_enable_shared_cache | common cache],
2162 **          the busy handler for the database connection currently using
2163 **          the cache shall be invoked when the cache encounters a lock.
2164 **
2165 ** {H12316} If a busy handler callback returns zero, then the SQLite interface
2166 **          that provoked the locking event shall return [SQLITE_BUSY].
2167 **
2168 ** {H12318} SQLite shall invokes the busy handler with two arguments which
2169 **          are a copy of the pointer supplied by the 3rd parameter to
2170 **          [sqlite3_busy_handler()] and a count of the number of prior
2171 **          invocations of the busy handler for the same locking event.
2172 **
2173 ** ASSUMPTIONS:
2174 **
2175 ** {A12319} A busy handler must not close the database connection
2176 **          or [prepared statement] that invoked the busy handler.
2177 */
2178 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2179
2180 /*
2181 ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
2182 **
2183 ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2184 ** for a specified amount of time when a table is locked.  The handler
2185 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2186 ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
2187 ** the handler returns 0 which causes [sqlite3_step()] to return
2188 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2189 **
2190 ** Calling this routine with an argument less than or equal to zero
2191 ** turns off all busy handlers.
2192 **
2193 ** There can only be a single busy handler for a particular
2194 ** [database connection] any any given moment.  If another busy handler
2195 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2196 ** this routine, that other busy handler is cleared.
2197 **
2198 ** INVARIANTS:
2199 **
2200 ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
2201 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
2202 **          on the same [database connection].
2203 **
2204 ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
2205 **          or equal to zero, then the busy handler shall be cleared so that
2206 **          all subsequent locking events immediately return [SQLITE_BUSY].
2207 **
2208 ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
2209 **          number N, then a busy handler shall be set that repeatedly calls
2210 **          the xSleep() method in the [sqlite3_vfs | VFS interface] until
2211 **          either the lock clears or until the cumulative sleep time
2212 **          reported back by xSleep() exceeds N milliseconds.
2213 */
2214 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2215
2216 /*
2217 ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
2218 **
2219 ** Definition: A <b>result table</b> is memory data structure created by the
2220 ** [sqlite3_get_table()] interface.  A result table records the
2221 ** complete query results from one or more queries.
2222 **
2223 ** The table conceptually has a number of rows and columns.  But
2224 ** these numbers are not part of the result table itself.  These
2225 ** numbers are obtained separately.  Let N be the number of rows
2226 ** and M be the number of columns.
2227 **
2228 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2229 ** There are (N+1)*M elements in the array.  The first M pointers point
2230 ** to zero-terminated strings that  contain the names of the columns.
2231 ** The remaining entries all point to query results.  NULL values result
2232 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2233 ** string representation as returned by [sqlite3_column_text()].
2234 **
2235 ** A result table might consist of one or more memory allocations.
2236 ** It is not safe to pass a result table directly to [sqlite3_free()].
2237 ** A result table should be deallocated using [sqlite3_free_table()].
2238 **
2239 ** As an example of the result table format, suppose a query result
2240 ** is as follows:
2241 **
2242 ** <blockquote><pre>
2243 **        Name        | Age
2244 **        -----------------------
2245 **        Alice       | 43
2246 **        Bob         | 28
2247 **        Cindy       | 21
2248 ** </pre></blockquote>
2249 **
2250 ** There are two column (M==2) and three rows (N==3).  Thus the
2251 ** result table has 8 entries.  Suppose the result table is stored
2252 ** in an array names azResult.  Then azResult holds this content:
2253 **
2254 ** <blockquote><pre>
2255 **        azResult&#91;0] = "Name";
2256 **        azResult&#91;1] = "Age";
2257 **        azResult&#91;2] = "Alice";
2258 **        azResult&#91;3] = "43";
2259 **        azResult&#91;4] = "Bob";
2260 **        azResult&#91;5] = "28";
2261 **        azResult&#91;6] = "Cindy";
2262 **        azResult&#91;7] = "21";
2263 ** </pre></blockquote>
2264 **
2265 ** The sqlite3_get_table() function evaluates one or more
2266 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2267 ** string of its 2nd parameter.  It returns a result table to the
2268 ** pointer given in its 3rd parameter.
2269 **
2270 ** After the calling function has finished using the result, it should
2271 ** pass the pointer to the result table to sqlite3_free_table() in order to
2272 ** release the memory that was malloced.  Because of the way the
2273 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2274 ** function must not try to call [sqlite3_free()] directly.  Only
2275 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2276 **
2277 ** The sqlite3_get_table() interface is implemented as a wrapper around
2278 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2279 ** to any internal data structures of SQLite.  It uses only the public
2280 ** interface defined here.  As a consequence, errors that occur in the
2281 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2282 ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
2283 **
2284 ** INVARIANTS:
2285 **
2286 ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
2287 **          it shall free the result table under construction, abort the
2288 **          query in process, skip any subsequent queries, set the
2289 **          *pazResult output pointer to NULL and return [SQLITE_NOMEM].
2290 **
2291 ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
2292 **          then a successful invocation of [sqlite3_get_table()] shall
2293 **          write the number of columns in the
2294 **          result set of the query into *pnColumn.
2295 **
2296 ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
2297 **          then a successful invocation of [sqlite3_get_table()] shall
2298 **          writes the number of rows in the
2299 **          result set of the query into *pnRow.
2300 **
2301 ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
2302 **          N rows of result with C columns per row shall make *pazResult
2303 **          point to an array of pointers to (N+1)*C strings where the first
2304 **          C strings are column names as obtained from
2305 **          [sqlite3_column_name()] and the rest are column result values
2306 **          obtained from [sqlite3_column_text()].
2307 **
2308 ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
2309 **          shall remain valid until cleared by [sqlite3_free_table()].
2310 **
2311 ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
2312 **          the function shall set *pazResult to NULL, write an error message
2313 **          into memory obtained from [sqlite3_malloc()], make
2314 **          **pzErrmsg point to that error message, and return a
2315 **          appropriate [error code].
2316 */
2317 SQLITE_API int sqlite3_get_table(
2318   sqlite3 *db,          /* An open database */
2319   const char *zSql,     /* SQL to be evaluated */
2320   char ***pazResult,    /* Results of the query */
2321   int *pnRow,           /* Number of result rows written here */
2322   int *pnColumn,        /* Number of result columns written here */
2323   char **pzErrmsg       /* Error msg written here */
2324 );
2325 SQLITE_API void sqlite3_free_table(char **result);
2326
2327 /*
2328 ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
2329 **
2330 ** These routines are workalikes of the "printf()" family of functions
2331 ** from the standard C library.
2332 **
2333 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2334 ** results into memory obtained from [sqlite3_malloc()].
2335 ** The strings returned by these two routines should be
2336 ** released by [sqlite3_free()].  Both routines return a
2337 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2338 ** memory to hold the resulting string.
2339 **
2340 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
2341 ** the standard C library.  The result is written into the
2342 ** buffer supplied as the second parameter whose size is given by
2343 ** the first parameter. Note that the order of the
2344 ** first two parameters is reversed from snprintf().  This is an
2345 ** historical accident that cannot be fixed without breaking
2346 ** backwards compatibility.  Note also that sqlite3_snprintf()
2347 ** returns a pointer to its buffer instead of the number of
2348 ** characters actually written into the buffer.  We admit that
2349 ** the number of characters written would be a more useful return
2350 ** value but we cannot change the implementation of sqlite3_snprintf()
2351 ** now without breaking compatibility.
2352 **
2353 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
2354 ** guarantees that the buffer is always zero-terminated.  The first
2355 ** parameter "n" is the total size of the buffer, including space for
2356 ** the zero terminator.  So the longest string that can be completely
2357 ** written will be n-1 characters.
2358 **
2359 ** These routines all implement some additional formatting
2360 ** options that are useful for constructing SQL statements.
2361 ** All of the usual printf() formatting options apply.  In addition, there
2362 ** is are "%q", "%Q", and "%z" options.
2363 **
2364 ** The %q option works like %s in that it substitutes a null-terminated
2365 ** string from the argument list.  But %q also doubles every '\'' character.
2366 ** %q is designed for use inside a string literal.  By doubling each '\''
2367 ** character it escapes that character and allows it to be inserted into
2368 ** the string.
2369 **
2370 ** For example, assume the string variable zText contains text as follows:
2371 **
2372 ** <blockquote><pre>
2373 **  char *zText = "It's a happy day!";
2374 ** </pre></blockquote>
2375 **
2376 ** One can use this text in an SQL statement as follows:
2377 **
2378 ** <blockquote><pre>
2379 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2380 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2381 **  sqlite3_free(zSQL);
2382 ** </pre></blockquote>
2383 **
2384 ** Because the %q format string is used, the '\'' character in zText
2385 ** is escaped and the SQL generated is as follows:
2386 **
2387 ** <blockquote><pre>
2388 **  INSERT INTO table1 VALUES('It''s a happy day!')
2389 ** </pre></blockquote>
2390 **
2391 ** This is correct.  Had we used %s instead of %q, the generated SQL
2392 ** would have looked like this:
2393 **
2394 ** <blockquote><pre>
2395 **  INSERT INTO table1 VALUES('It's a happy day!');
2396 ** </pre></blockquote>
2397 **
2398 ** This second example is an SQL syntax error.  As a general rule you should
2399 ** always use %q instead of %s when inserting text into a string literal.
2400 **
2401 ** The %Q option works like %q except it also adds single quotes around
2402 ** the outside of the total string.  Additionally, if the parameter in the
2403 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2404 ** single quotes) in place of the %Q option.  So, for example, one could say:
2405 **
2406 ** <blockquote><pre>
2407 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2408 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2409 **  sqlite3_free(zSQL);
2410 ** </pre></blockquote>
2411 **
2412 ** The code above will render a correct SQL statement in the zSQL
2413 ** variable even if the zText variable is a NULL pointer.
2414 **
2415 ** The "%z" formatting option works exactly like "%s" with the
2416 ** addition that after the string has been read and copied into
2417 ** the result, [sqlite3_free()] is called on the input string. {END}
2418 **
2419 ** INVARIANTS:
2420 **
2421 ** {H17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
2422 **           return either pointers to zero-terminated UTF-8 strings held in
2423 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
2424 **           a call to [sqlite3_malloc()] fails.
2425 **
2426 ** {H17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
2427 **           UTF-8 string into the buffer pointed to by the second parameter
2428 **           provided that the first parameter is greater than zero.
2429 **
2430 ** {H17407}  The [sqlite3_snprintf()] interface does not write slots of
2431 **           its output buffer (the second parameter) outside the range
2432 **           of 0 through N-1 (where N is the first parameter)
2433 **           regardless of the length of the string
2434 **           requested by the format specification.
2435 */
2436 SQLITE_API char *sqlite3_mprintf(const char*,...);
2437 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2438 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2439
2440 /*
2441 ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
2442 **
2443 ** The SQLite core  uses these three routines for all of its own
2444 ** internal memory allocation needs. "Core" in the previous sentence
2445 ** does not include operating-system specific VFS implementation.  The
2446 ** Windows VFS uses native malloc() and free() for some operations.
2447 **
2448 ** The sqlite3_malloc() routine returns a pointer to a block
2449 ** of memory at least N bytes in length, where N is the parameter.
2450 ** If sqlite3_malloc() is unable to obtain sufficient free
2451 ** memory, it returns a NULL pointer.  If the parameter N to
2452 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2453 ** a NULL pointer.
2454 **
2455 ** Calling sqlite3_free() with a pointer previously returned
2456 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2457 ** that it might be reused.  The sqlite3_free() routine is
2458 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2459 ** to sqlite3_free() is harmless.  After being freed, memory
2460 ** should neither be read nor written.  Even reading previously freed
2461 ** memory might result in a segmentation fault or other severe error.
2462 ** Memory corruption, a segmentation fault, or other severe error
2463 ** might result if sqlite3_free() is called with a non-NULL pointer that
2464 ** was not obtained from sqlite3_malloc() or sqlite3_free().
2465 **
2466 ** The sqlite3_realloc() interface attempts to resize a
2467 ** prior memory allocation to be at least N bytes, where N is the
2468 ** second parameter.  The memory allocation to be resized is the first
2469 ** parameter.  If the first parameter to sqlite3_realloc()
2470 ** is a NULL pointer then its behavior is identical to calling
2471 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2472 ** If the second parameter to sqlite3_realloc() is zero or
2473 ** negative then the behavior is exactly the same as calling
2474 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2475 ** sqlite3_realloc() returns a pointer to a memory allocation
2476 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2477 ** If M is the size of the prior allocation, then min(N,M) bytes
2478 ** of the prior allocation are copied into the beginning of buffer returned
2479 ** by sqlite3_realloc() and the prior allocation is freed.
2480 ** If sqlite3_realloc() returns NULL, then the prior allocation
2481 ** is not freed.
2482 **
2483 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
2484 ** is always aligned to at least an 8 byte boundary. {END}
2485 **
2486 ** The default implementation of the memory allocation subsystem uses
2487 ** the malloc(), realloc() and free() provided by the standard C library.
2488 ** {H17382} However, if SQLite is compiled with the
2489 ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
2490 ** is an integer), then SQLite create a static array of at least
2491 ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
2492 ** memory allocation needs. {END}  Additional memory allocator options
2493 ** may be added in future releases.
2494 **
2495 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2496 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2497 ** implementation of these routines to be omitted.  That capability
2498 ** is no longer provided.  Only built-in memory allocators can be used.
2499 **
2500 ** The Windows OS interface layer calls
2501 ** the system malloc() and free() directly when converting
2502 ** filenames between the UTF-8 encoding used by SQLite
2503 ** and whatever filename encoding is used by the particular Windows
2504 ** installation.  Memory allocation errors are detected, but
2505 ** they are reported back as [SQLITE_CANTOPEN] or
2506 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2507 **
2508 ** INVARIANTS:
2509 **
2510 ** {H17303}  The [sqlite3_malloc(N)] interface returns either a pointer to
2511 **           a newly checked-out block of at least N bytes of memory
2512 **           that is 8-byte aligned, or it returns NULL if it is unable
2513 **           to fulfill the request.
2514 **
2515 ** {H17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
2516 **           N is less than or equal to zero.
2517 **
2518 ** {H17305}  The [sqlite3_free(P)] interface releases memory previously
2519 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
2520 **           making it available for reuse.
2521 **
2522 ** {H17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
2523 **
2524 ** {H17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
2525 **           to [sqlite3_malloc(N)].
2526 **
2527 ** {H17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
2528 **           to [sqlite3_free(P)].
2529 **
2530 ** {H17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
2531 **           and [sqlite3_free()] for all of its memory allocation and
2532 **           deallocation needs.
2533 **
2534 ** {H17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
2535 **           to a block of checked-out memory of at least N bytes in size
2536 **           that is 8-byte aligned, or a NULL pointer.
2537 **
2538 ** {H17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2539 **           copies the first K bytes of content from P into the newly
2540 **           allocated block, where K is the lesser of N and the size of
2541 **           the buffer P.
2542 **
2543 ** {H17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2544 **           releases the buffer P.
2545 **
2546 ** {H17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2547 **           not modified or released.
2548 **
2549 ** ASSUMPTIONS:
2550 **
2551 ** {A17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2552 **           must be either NULL or else pointers obtained from a prior
2553 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2554 **           not yet been released.
2555 **
2556 ** {A17351}  The application must not read or write any part of
2557 **           a block of memory after it has been released using
2558 **           [sqlite3_free()] or [sqlite3_realloc()].
2559 */
2560 SQLITE_API void *sqlite3_malloc(int);
2561 SQLITE_API void *sqlite3_realloc(void*, int);
2562 SQLITE_API void sqlite3_free(void*);
2563
2564 /*
2565 ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
2566 **
2567 ** SQLite provides these two interfaces for reporting on the status
2568 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2569 ** routines, which form the built-in memory allocation subsystem.
2570 **
2571 ** INVARIANTS:
2572 **
2573 ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
2574 **          of memory currently outstanding (malloced but not freed).
2575 **
2576 ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
2577 **          value of [sqlite3_memory_used()] since the high-water mark
2578 **          was last reset.
2579 **
2580 ** {H17374} The values returned by [sqlite3_memory_used()] and
2581 **          [sqlite3_memory_highwater()] include any overhead
2582 **          added by SQLite in its implementation of [sqlite3_malloc()],
2583 **          but not overhead added by the any underlying system library
2584 **          routines that [sqlite3_malloc()] may call.
2585 **
2586 ** {H17375} The memory high-water mark is reset to the current value of
2587 **          [sqlite3_memory_used()] if and only if the parameter to
2588 **          [sqlite3_memory_highwater()] is true.  The value returned
2589 **          by [sqlite3_memory_highwater(1)] is the high-water mark
2590 **          prior to the reset.
2591 */
2592 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2593 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2594
2595 /*
2596 ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
2597 **
2598 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2599 ** select random ROWIDs when inserting new records into a table that
2600 ** already uses the largest possible ROWID.  The PRNG is also used for
2601 ** the build-in random() and randomblob() SQL functions.  This interface allows
2602 ** applications to access the same PRNG for other purposes.
2603 **
2604 ** A call to this routine stores N bytes of randomness into buffer P.
2605 **
2606 ** The first time this routine is invoked (either internally or by
2607 ** the application) the PRNG is seeded using randomness obtained
2608 ** from the xRandomness method of the default [sqlite3_vfs] object.
2609 ** On all subsequent invocations, the pseudo-randomness is generated
2610 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2611 ** method.
2612 **
2613 ** INVARIANTS:
2614 **
2615 ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2616 **          high-quality pseudo-randomness into buffer P.
2617 */
2618 SQLITE_API void sqlite3_randomness(int N, void *P);
2619
2620 /*
2621 ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
2622 **
2623 ** This routine registers a authorizer callback with a particular
2624 ** [database connection], supplied in the first argument.
2625 ** The authorizer callback is invoked as SQL statements are being compiled
2626 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2627 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2628 ** points during the compilation process, as logic is being created
2629 ** to perform various actions, the authorizer callback is invoked to
2630 ** see if those actions are allowed.  The authorizer callback should
2631 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2632 ** specific action but allow the SQL statement to continue to be
2633 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2634 ** rejected with an error.  If the authorizer callback returns
2635 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2636 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2637 ** the authorizer will fail with an error message.
2638 **
2639 ** When the callback returns [SQLITE_OK], that means the operation
2640 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2641 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2642 ** authorizer will fail with an error message explaining that
2643 ** access is denied.  If the authorizer code is [SQLITE_READ]
2644 ** and the callback returns [SQLITE_IGNORE] then the
2645 ** [prepared statement] statement is constructed to substitute
2646 ** a NULL value in place of the table column that would have
2647 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2648 ** return can be used to deny an untrusted user access to individual
2649 ** columns of a table.
2650 **
2651 ** The first parameter to the authorizer callback is a copy of the third
2652 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2653 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2654 ** the particular action to be authorized. The third through sixth parameters
2655 ** to the callback are zero-terminated strings that contain additional
2656 ** details about the action to be authorized.
2657 **
2658 ** An authorizer is used when [sqlite3_prepare | preparing]
2659 ** SQL statements from an untrusted source, to ensure that the SQL statements
2660 ** do not try to access data they are not allowed to see, or that they do not
2661 ** try to execute malicious statements that damage the database.  For
2662 ** example, an application may allow a user to enter arbitrary
2663 ** SQL queries for evaluation by a database.  But the application does
2664 ** not want the user to be able to make arbitrary changes to the
2665 ** database.  An authorizer could then be put in place while the
2666 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2667 ** disallows everything except [SELECT] statements.
2668 **
2669 ** Applications that need to process SQL from untrusted sources
2670 ** might also consider lowering resource limits using [sqlite3_limit()]
2671 ** and limiting database size using the [max_page_count] [PRAGMA]
2672 ** in addition to using an authorizer.
2673 **
2674 ** Only a single authorizer can be in place on a database connection
2675 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2676 ** previous call.  Disable the authorizer by installing a NULL callback.
2677 ** The authorizer is disabled by default.
2678 **
2679 ** The authorizer callback must not do anything that will modify
2680 ** the database connection that invoked the authorizer callback.
2681 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2682 ** database connections for the meaning of "modify" in this paragraph.
2683 **
2684 ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
2685 ** statement might be reprepared during [sqlite3_step()] due to a 
2686 ** schema change.  Hence, the application should ensure that the
2687 ** correct authorizer callback remains in place during the [sqlite3_step()].
2688 **
2689 ** Note that the authorizer callback is invoked only during
2690 ** [sqlite3_prepare()] or its variants.  Authorization is not
2691 ** performed during statement evaluation in [sqlite3_step()].
2692 **
2693 ** INVARIANTS:
2694 **
2695 ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2696 **          authorizer callback with database connection D.
2697 **
2698 ** {H12502} The authorizer callback is invoked as SQL statements are
2699 **          being parseed and compiled.
2700 **
2701 ** {H12503} If the authorizer callback returns any value other than
2702 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
2703 **          the application interface call that caused
2704 **          the authorizer callback to run shall fail with an
2705 **          [SQLITE_ERROR] error code and an appropriate error message.
2706 **
2707 ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
2708 **          described is processed normally.
2709 **
2710 ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
2711 **          application interface call that caused the
2712 **          authorizer callback to run shall fail
2713 **          with an [SQLITE_ERROR] error code and an error message
2714 **          explaining that access is denied.
2715 **
2716 ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
2717 **          callback) is [SQLITE_READ] and the authorizer callback returns
2718 **          [SQLITE_IGNORE], then the prepared statement is constructed to
2719 **          insert a NULL value in place of the table column that would have
2720 **          been read if [SQLITE_OK] had been returned.
2721 **
2722 ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
2723 **          callback) is anything other than [SQLITE_READ], then
2724 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
2725 **
2726 ** {H12510} The first parameter to the authorizer callback is a copy of
2727 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2728 **
2729 ** {H12511} The second parameter to the callback is an integer
2730 **          [SQLITE_COPY | action code] that specifies the particular action
2731 **          to be authorized.
2732 **
2733 ** {H12512} The third through sixth parameters to the callback are
2734 **          zero-terminated strings that contain
2735 **          additional details about the action to be authorized.
2736 **
2737 ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
2738 **          any previously installed authorizer.
2739 **
2740 ** {H12521} A NULL authorizer means that no authorization
2741 **          callback is invoked.
2742 **
2743 ** {H12522} The default authorizer is NULL.
2744 */
2745 SQLITE_API int sqlite3_set_authorizer(
2746   sqlite3*,
2747   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2748   void *pUserData
2749 );
2750
2751 /*
2752 ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
2753 **
2754 ** The [sqlite3_set_authorizer | authorizer callback function] must
2755 ** return either [SQLITE_OK] or one of these two constants in order
2756 ** to signal SQLite whether or not the action is permitted.  See the
2757 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2758 ** information.
2759 */
2760 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2761 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2762
2763 /*
2764 ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
2765 **
2766 ** The [sqlite3_set_authorizer()] interface registers a callback function
2767 ** that is invoked to authorize certain SQL statement actions.  The
2768 ** second parameter to the callback is an integer code that specifies
2769 ** what action is being authorized.  These are the integer action codes that
2770 ** the authorizer callback may be passed.
2771 **
2772 ** These action code values signify what kind of operation is to be
2773 ** authorized.  The 3rd and 4th parameters to the authorization
2774 ** callback function will be parameters or NULL depending on which of these
2775 ** codes is used as the second parameter.  The 5th parameter to the
2776 ** authorizer callback is the name of the database ("main", "temp",
2777 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2778 ** is the name of the inner-most trigger or view that is responsible for
2779 ** the access attempt or NULL if this access attempt is directly from
2780 ** top-level SQL code.
2781 **
2782 ** INVARIANTS:
2783 **
2784 ** {H12551} The second parameter to an
2785 **          [sqlite3_set_authorizer | authorizer callback] shall be an integer
2786 **          [SQLITE_COPY | authorizer code] that specifies what action
2787 **          is being authorized.
2788 **
2789 ** {H12552} The 3rd and 4th parameters to the
2790 **          [sqlite3_set_authorizer | authorization callback]
2791 **          shall be parameters or NULL depending on which
2792 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2793 **
2794 ** {H12553} The 5th parameter to the
2795 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2796 **          of the database (example: "main", "temp", etc.) if applicable.
2797 **
2798 ** {H12554} The 6th parameter to the
2799 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2800 **          of the inner-most trigger or view that is responsible for
2801 **          the access attempt or NULL if this access attempt is directly from
2802 **          top-level SQL code.
2803 */
2804 /******************************************* 3rd ************ 4th ***********/
2805 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2806 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2807 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2808 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2809 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2810 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2811 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2812 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2813 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2814 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2815 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2816 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2817 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2818 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2819 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2820 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2821 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2822 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2823 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2824 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2825 #define SQLITE_SELECT               21   /* NULL            NULL            */
2826 #define SQLITE_TRANSACTION          22   /* NULL            NULL            */
2827 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2828 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2829 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2830 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2831 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2832 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2833 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2834 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2835 #define SQLITE_FUNCTION             31   /* Function Name   NULL            */
2836 #define SQLITE_COPY                  0   /* No longer used */
2837
2838 /*
2839 ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
2840 ** EXPERIMENTAL
2841 **
2842 ** These routines register callback functions that can be used for
2843 ** tracing and profiling the execution of SQL statements.
2844 **
2845 ** The callback function registered by sqlite3_trace() is invoked at
2846 ** various times when an SQL statement is being run by [sqlite3_step()].
2847 ** The callback returns a UTF-8 rendering of the SQL statement text
2848 ** as the statement first begins executing.  Additional callbacks occur
2849 ** as each triggered subprogram is entered.  The callbacks for triggers
2850 ** contain a UTF-8 SQL comment that identifies the trigger.
2851 **
2852 ** The callback function registered by sqlite3_profile() is invoked
2853 ** as each SQL statement finishes.  The profile callback contains
2854 ** the original statement text and an estimate of wall-clock time
2855 ** of how long that statement took to run.
2856 **
2857 ** INVARIANTS:
2858 **
2859 ** {H12281} The callback function registered by [sqlite3_trace()] 
2860 **          shall be invoked
2861 **          whenever an SQL statement first begins to execute and
2862 **          whenever a trigger subprogram first begins to run.
2863 **
2864 ** {H12282} Each call to [sqlite3_trace()] shall override the previously
2865 **          registered trace callback.
2866 **
2867 ** {H12283} A NULL trace callback shall disable tracing.
2868 **
2869 ** {H12284} The first argument to the trace callback shall be a copy of
2870 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2871 **
2872 ** {H12285} The second argument to the trace callback is a
2873 **          zero-terminated UTF-8 string containing the original text
2874 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2875 **          or the equivalent, or an SQL comment indicating the beginning
2876 **          of a trigger subprogram.
2877 **
2878 ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
2879 **          as each SQL statement finishes.
2880 **
2881 ** {H12288} The first parameter to the profile callback is a copy of
2882 **          the 3rd parameter to [sqlite3_profile()].
2883 **
2884 ** {H12289} The second parameter to the profile callback is a
2885 **          zero-terminated UTF-8 string that contains the complete text of
2886 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2887 **          or the equivalent.
2888 **
2889 ** {H12290} The third parameter to the profile callback is an estimate
2890 **          of the number of nanoseconds of wall-clock time required to
2891 **          run the SQL statement from start to finish.
2892 */
2893 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2894 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2895    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2896
2897 /*
2898 ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
2899 **
2900 ** This routine configures a callback function - the
2901 ** progress callback - that is invoked periodically during long
2902 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2903 ** [sqlite3_get_table()].  An example use for this
2904 ** interface is to keep a GUI updated during a large query.
2905 **
2906 ** If the progress callback returns non-zero, the operation is
2907 ** interrupted.  This feature can be used to implement a
2908 ** "Cancel" button on a GUI progress dialog box.
2909 **
2910 ** The progress handler must not do anything that will modify
2911 ** the database connection that invoked the progress handler.
2912 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2913 ** database connections for the meaning of "modify" in this paragraph.
2914 **
2915 ** INVARIANTS:
2916 **
2917 ** {H12911} The callback function registered by sqlite3_progress_handler()
2918 **          is invoked periodically during long running calls to
2919 **          [sqlite3_step()].
2920 **
2921 ** {H12912} The progress callback is invoked once for every N virtual
2922 **          machine opcodes, where N is the second argument to
2923 **          the [sqlite3_progress_handler()] call that registered
2924 **          the callback.  If N is less than 1, sqlite3_progress_handler()
2925 **          acts as if a NULL progress handler had been specified.
2926 **
2927 ** {H12913} The progress callback itself is identified by the third
2928 **          argument to sqlite3_progress_handler().
2929 **
2930 ** {H12914} The fourth argument to sqlite3_progress_handler() is a
2931 **          void pointer passed to the progress callback
2932 **          function each time it is invoked.
2933 **
2934 ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
2935 **          being executed, then the progress callback is never invoked.
2936 **
2937 ** {H12916} Every call to [sqlite3_progress_handler()]
2938 **          overwrites any previously registered progress handler.
2939 **
2940 ** {H12917} If the progress handler callback is NULL then no progress
2941 **          handler is invoked.
2942 **
2943 ** {H12918} If the progress callback returns a result other than 0, then
2944 **          the behavior is a if [sqlite3_interrupt()] had been called.
2945 **          <S30500>
2946 */
2947 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2948
2949 /*
2950 ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
2951 **
2952 ** These routines open an SQLite database file whose name is given by the
2953 ** filename argument. The filename argument is interpreted as UTF-8 for
2954 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2955 ** order for sqlite3_open16(). A [database connection] handle is usually
2956 ** returned in *ppDb, even if an error occurs.  The only exception is that
2957 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2958 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2959 ** object. If the database is opened (and/or created) successfully, then
2960 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
2961 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2962 ** an English language description of the error.
2963 **
2964 ** The default encoding for the database will be UTF-8 if
2965 ** sqlite3_open() or sqlite3_open_v2() is called and
2966 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2967 **
2968 ** Whether or not an error occurs when it is opened, resources
2969 ** associated with the [database connection] handle should be released by
2970 ** passing it to [sqlite3_close()] when it is no longer required.
2971 **
2972 ** The sqlite3_open_v2() interface works like sqlite3_open()
2973 ** except that it accepts two additional parameters for additional control
2974 ** over the new database connection.  The flags parameter can take one of
2975 ** the following three values, optionally combined with the 
2976 ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
2977 **
2978 ** <dl>
2979 ** <dt>[SQLITE_OPEN_READONLY]</dt>
2980 ** <dd>The database is opened in read-only mode.  If the database does not
2981 ** already exist, an error is returned.</dd>
2982 **
2983 ** <dt>[SQLITE_OPEN_READWRITE]</dt>
2984 ** <dd>The database is opened for reading and writing if possible, or reading
2985 ** only if the file is write protected by the operating system.  In either
2986 ** case the database must already exist, otherwise an error is returned.</dd>
2987 **
2988 ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2989 ** <dd>The database is opened for reading and writing, and is creates it if
2990 ** it does not already exist. This is the behavior that is always used for
2991 ** sqlite3_open() and sqlite3_open16().</dd>
2992 ** </dl>
2993 **
2994 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2995 ** combinations shown above or one of the combinations shown above combined
2996 ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
2997 ** then the behavior is undefined.
2998 **
2999 ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3000 ** opens in the multi-thread [threading mode] as long as the single-thread
3001 ** mode has not been set at compile-time or start-time.  If the
3002 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3003 ** in the serialized [threading mode] unless single-thread was
3004 ** previously selected at compile-time or start-time.
3005 **
3006 ** If the filename is ":memory:", then a private, temporary in-memory database
3007 ** is created for the connection.  This in-memory database will vanish when
3008 ** the database connection is closed.  Future versions of SQLite might
3009 ** make use of additional special filenames that begin with the ":" character.
3010 ** It is recommended that when a database filename actually does begin with
3011 ** a ":" character you should prefix the filename with a pathname such as
3012 ** "./" to avoid ambiguity.
3013 **
3014 ** If the filename is an empty string, then a private, temporary
3015 ** on-disk database will be created.  This private database will be
3016 ** automatically deleted as soon as the database connection is closed.
3017 **
3018 ** The fourth parameter to sqlite3_open_v2() is the name of the
3019 ** [sqlite3_vfs] object that defines the operating system interface that
3020 ** the new database connection should use.  If the fourth parameter is
3021 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3022 **
3023 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3024 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3025 ** codepage is currently defined.  Filenames containing international
3026 ** characters must be converted to UTF-8 prior to passing them into
3027 ** sqlite3_open() or sqlite3_open_v2().
3028 **
3029 ** INVARIANTS:
3030 **
3031 ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
3032 **          [sqlite3_open_v2()] interfaces create a new
3033 **          [database connection] associated with
3034 **          the database file given in their first parameter.
3035 **
3036 ** {H12702} The filename argument is interpreted as UTF-8
3037 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
3038 **          in the native byte order for [sqlite3_open16()].
3039 **
3040 ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
3041 **          or [sqlite3_open_v2()] writes a pointer to a new
3042 **          [database connection] into *ppDb.
3043 **
3044 ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
3045 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
3046 **          or an appropriate [error code] on failure.
3047 **
3048 ** {H12706} The default text encoding for a new database created using
3049 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
3050 **
3051 ** {H12707} The default text encoding for a new database created using
3052 **          [sqlite3_open16()] will be UTF-16.
3053 **
3054 ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
3055 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
3056 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
3057 **
3058 ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3059 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
3060 **          for reading only.
3061 **
3062 ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3063 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
3064 **          reading and writing if possible, or for reading only if the
3065 **          file is write protected by the operating system.
3066 **
3067 ** {H12713} If the G parameter to [sqlite3_open_v2(F,D,G,V)] omits the
3068 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3069 **          previously exist, an error is returned.
3070 **
3071 ** {H12714} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3072 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3073 **          previously exist, then an attempt is made to create and
3074 **          initialize the database.
3075 **
3076 ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
3077 **          or [sqlite3_open_v2()] is ":memory:", then an private,
3078 **          ephemeral, in-memory database is created for the connection.
3079 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3080 **          in sqlite3_open_v2()?</todo>
3081 **
3082 ** {H12719} If the filename is NULL or an empty string, then a private,
3083 **          ephemeral on-disk database will be created.
3084 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3085 **          in sqlite3_open_v2()?</todo>
3086 **
3087 ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
3088 **          will use the [sqlite3_vfs] object identified by the V parameter,
3089 **          or the default [sqlite3_vfs] object if V is a NULL pointer.
3090 **
3091 ** {H12723} Two [database connections] will share a common cache if both were
3092 **          opened with the same VFS while [shared cache mode] was enabled and
3093 **          if both filenames compare equal using memcmp() after having been
3094 **          processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
3095 */
3096 SQLITE_API int sqlite3_open(
3097   const char *filename,   /* Database filename (UTF-8) */
3098   sqlite3 **ppDb          /* OUT: SQLite db handle */
3099 );
3100 SQLITE_API int sqlite3_open16(
3101   const void *filename,   /* Database filename (UTF-16) */
3102   sqlite3 **ppDb          /* OUT: SQLite db handle */
3103 );
3104 SQLITE_API int sqlite3_open_v2(
3105   const char *filename,   /* Database filename (UTF-8) */
3106   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3107   int flags,              /* Flags */
3108   const char *zVfs        /* Name of VFS module to use */
3109 );
3110
3111 /*
3112 ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
3113 **
3114 ** The sqlite3_errcode() interface returns the numeric [result code] or
3115 ** [extended result code] for the most recent failed sqlite3_* API call
3116 ** associated with a [database connection]. If a prior API call failed
3117 ** but the most recent API call succeeded, the return value from
3118 ** sqlite3_errcode() is undefined.
3119 **
3120 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3121 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3122 ** Memory to hold the error message string is managed internally.
3123 ** The application does not need to worry about freeing the result.
3124 ** However, the error string might be overwritten or deallocated by
3125 ** subsequent calls to other SQLite interface functions.
3126 **
3127 ** If an interface fails with SQLITE_MISUSE, that means the interface
3128 ** was invoked incorrectly by the application.  In that case, the
3129 ** error code and message may or may not be set.
3130 **
3131 ** INVARIANTS:
3132 **
3133 ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
3134 **          [result code] or [extended result code] for the most recently
3135 **          failed interface call associated with the [database connection] D.
3136 **
3137 ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
3138 **          interfaces return English-language text that describes
3139 **          the error in the mostly recently failed interface call,
3140 **          encoded as either UTF-8 or UTF-16 respectively.
3141 **
3142 ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
3143 **          are valid until the next SQLite interface call.
3144 **
3145 ** {H12808} Calls to API routines that do not return an error code
3146 **          (example: [sqlite3_data_count()]) do not
3147 **          change the error code or message returned by
3148 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3149 **
3150 ** {H12809} Interfaces that are not associated with a specific
3151 **          [database connection] (examples:
3152 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
3153 **          do not change the values returned by
3154 **          [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3155 */
3156 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3157 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3158 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3159
3160 /*
3161 ** CAPI3REF: SQL Statement Object {H13000} <H13010>
3162 ** KEYWORDS: {prepared statement} {prepared statements}
3163 **
3164 ** An instance of this object represents a single SQL statement.
3165 ** This object is variously known as a "prepared statement" or a
3166 ** "compiled SQL statement" or simply as a "statement".
3167 **
3168 ** The life of a statement object goes something like this:
3169 **
3170 ** <ol>
3171 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3172 **      function.
3173 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3174 **      interfaces.
3175 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3176 ** <li> Reset the statement using [sqlite3_reset()] then go back
3177 **      to step 2.  Do this zero or more times.
3178 ** <li> Destroy the object using [sqlite3_finalize()].
3179 ** </ol>
3180 **
3181 ** Refer to documentation on individual methods above for additional
3182 ** information.
3183 */
3184 typedef struct sqlite3_stmt sqlite3_stmt;
3185
3186 /*
3187 ** CAPI3REF: Run-time Limits {H12760} <S20600>
3188 **
3189 ** This interface allows the size of various constructs to be limited
3190 ** on a connection by connection basis.  The first parameter is the
3191 ** [database connection] whose limit is to be set or queried.  The
3192 ** second parameter is one of the [limit categories] that define a
3193 ** class of constructs to be size limited.  The third parameter is the
3194 ** new limit for that construct.  The function returns the old limit.
3195 **
3196 ** If the new limit is a negative number, the limit is unchanged.
3197 ** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper
3198 ** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ.
3199 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
3200 ** Attempts to increase a limit above its hard upper bound are
3201 ** silently truncated to the hard upper limit.
3202 **
3203 ** Run time limits are intended for use in applications that manage
3204 ** both their own internal database and also databases that are controlled
3205 ** by untrusted external sources.  An example application might be a
3206 ** webbrowser that has its own databases for storing history and
3207 ** separate databases controlled by JavaScript applications downloaded
3208 ** off the Internet.  The internal databases can be given the
3209 ** large, default limits.  Databases managed by external sources can
3210 ** be given much smaller limits designed to prevent a denial of service
3211 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3212 ** interface to further control untrusted SQL.  The size of the database
3213 ** created by an untrusted script can be contained using the
3214 ** [max_page_count] [PRAGMA].
3215 **
3216 ** New run-time limit categories may be added in future releases.
3217 **
3218 ** INVARIANTS:
3219 **
3220 ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
3221 **          positive changes the limit on the size of construct C in the
3222 **          [database connection] D to the lesser of V and the hard upper
3223 **          bound on the size of C that is set at compile-time.
3224 **
3225 ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
3226 **          leaves the state of the [database connection] D unchanged.
3227 **
3228 ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
3229 **          value of the limit on the size of construct C in the
3230 **          [database connection] D as it was prior to the call.
3231 */
3232 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3233
3234 /*
3235 ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
3236 ** KEYWORDS: {limit category} {limit categories}
3237 **
3238 ** These constants define various aspects of a [database connection]
3239 ** that can be limited in size by calls to [sqlite3_limit()].
3240 ** The meanings of the various limits are as follows:
3241 **
3242 ** <dl>
3243 ** <dt>SQLITE_LIMIT_LENGTH</dt>
3244 ** <dd>The maximum size of any string or BLOB or table row.<dd>
3245 **
3246 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3247 ** <dd>The maximum length of an SQL statement.</dd>
3248 **
3249 ** <dt>SQLITE_LIMIT_COLUMN</dt>
3250 ** <dd>The maximum number of columns in a table definition or in the
3251 ** result set of a SELECT or the maximum number of columns in an index
3252 ** or in an ORDER BY or GROUP BY clause.</dd>
3253 **
3254 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3255 ** <dd>The maximum depth of the parse tree on any expression.</dd>
3256 **
3257 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3258 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
3259 **
3260 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
3261 ** <dd>The maximum number of instructions in a virtual machine program
3262 ** used to implement an SQL statement.</dd>
3263 **
3264 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3265 ** <dd>The maximum number of arguments on a function.</dd>
3266 **
3267 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
3268 ** <dd>The maximum number of attached databases.</dd>
3269 **
3270 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3271 ** <dd>The maximum length of the pattern argument to the LIKE or
3272 ** GLOB operators.</dd>
3273 **
3274 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3275 ** <dd>The maximum number of variables in an SQL statement that can
3276 ** be bound.</dd>
3277 ** </dl>
3278 */
3279 #define SQLITE_LIMIT_LENGTH                    0
3280 #define SQLITE_LIMIT_SQL_LENGTH                1
3281 #define SQLITE_LIMIT_COLUMN                    2
3282 #define SQLITE_LIMIT_EXPR_DEPTH                3
3283 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3284 #define SQLITE_LIMIT_VDBE_OP                   5
3285 #define SQLITE_LIMIT_FUNCTION_ARG              6
3286 #define SQLITE_LIMIT_ATTACHED                  7
3287 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3288 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3289
3290 /*
3291 ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
3292 ** KEYWORDS: {SQL statement compiler}
3293 **
3294 ** To execute an SQL query, it must first be compiled into a byte-code
3295 ** program using one of these routines.
3296 **
3297 ** The first argument, "db", is a [database connection] obtained from a
3298 ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
3299 **
3300 ** The second argument, "zSql", is the statement to be compiled, encoded
3301 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3302 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3303 ** use UTF-16.
3304 **
3305 ** If the nByte argument is less than zero, then zSql is read up to the
3306 ** first zero terminator. If nByte is non-negative, then it is the maximum
3307 ** number of  bytes read from zSql.  When nByte is non-negative, the
3308 ** zSql string ends at either the first '\000' or '\u0000' character or
3309 ** the nByte-th byte, whichever comes first. If the caller knows
3310 ** that the supplied string is nul-terminated, then there is a small
3311 ** performance advantage to be gained by passing an nByte parameter that
3312 ** is equal to the number of bytes in the input string <i>including</i>
3313 ** the nul-terminator bytes.
3314 **
3315 ** *pzTail is made to point to the first byte past the end of the
3316 ** first SQL statement in zSql.  These routines only compile the first
3317 ** statement in zSql, so *pzTail is left pointing to what remains
3318 ** uncompiled.
3319 **
3320 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
3321 ** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
3322 ** to NULL.  If the input text contains no SQL (if the input is an empty
3323 ** string or a comment) then *ppStmt is set to NULL.
3324 ** {A13018} The calling procedure is responsible for deleting the compiled
3325 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3326 **
3327 ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
3328 **
3329 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3330 ** recommended for all new programs. The two older interfaces are retained
3331 ** for backwards compatibility, but their use is discouraged.
3332 ** In the "v2" interfaces, the prepared statement
3333 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3334 ** original SQL text. This causes the [sqlite3_step()] interface to
3335 ** behave a differently in two ways:
3336 **
3337 ** <ol>
3338 ** <li>
3339 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3340 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3341 ** statement and try to run it again.  If the schema has changed in
3342 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3343 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3344 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3345 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3346 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3347 ** </li>
3348 **
3349 ** <li>
3350 ** When an error occurs, [sqlite3_step()] will return one of the detailed
3351 ** [error codes] or [extended error codes].  The legacy behavior was that
3352 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3353 ** and you would have to make a second call to [sqlite3_reset()] in order
3354 ** to find the underlying cause of the problem. With the "v2" prepare
3355 ** interfaces, the underlying reason for the error is returned immediately.
3356 ** </li>
3357 ** </ol>
3358 **
3359 ** INVARIANTS:
3360 **
3361 ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
3362 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
3363 **          text in their zSql parameter as UTF-8.
3364 **
3365 ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
3366 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
3367 **          text in their zSql parameter as UTF-16 in the native byte order.
3368 **
3369 ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3370 **          and its variants is less than zero, the SQL text is
3371 **          read from zSql is read up to the first zero terminator.
3372 **
3373 ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3374 **          and its variants is non-negative, then at most nBytes bytes of
3375 **          SQL text is read from zSql.
3376 **
3377 ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
3378 **          if the zSql input text contains more than one SQL statement
3379 **          and pzTail is not NULL, then *pzTail is made to point to the
3380 **          first byte past the end of the first SQL statement in zSql.
3381 **          <todo>What does *pzTail point to if there is one statement?</todo>
3382 **
3383 ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
3384 **          or one of its variants writes into *ppStmt a pointer to a new
3385 **          [prepared statement] or a pointer to NULL if zSql contains
3386 **          nothing other than whitespace or comments.
3387 **
3388 ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
3389 **          [SQLITE_OK] or an appropriate [error code] upon failure.
3390 **
3391 ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
3392 **          variants returns an error (any value other than [SQLITE_OK]),
3393 **          they first set *ppStmt to NULL.
3394 */
3395 SQLITE_API int sqlite3_prepare(
3396   sqlite3 *db,            /* Database handle */
3397   const char *zSql,       /* SQL statement, UTF-8 encoded */
3398   int nByte,              /* Maximum length of zSql in bytes. */
3399   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3400   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3401 );
3402 SQLITE_API int sqlite3_prepare_v2(
3403   sqlite3 *db,            /* Database handle */
3404   const char *zSql,       /* SQL statement, UTF-8 encoded */
3405   int nByte,              /* Maximum length of zSql in bytes. */
3406   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3407   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3408 );
3409 SQLITE_API int sqlite3_prepare16(
3410   sqlite3 *db,            /* Database handle */
3411   const void *zSql,       /* SQL statement, UTF-16 encoded */
3412   int nByte,              /* Maximum length of zSql in bytes. */
3413   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3414   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3415 );
3416 SQLITE_API int sqlite3_prepare16_v2(
3417   sqlite3 *db,            /* Database handle */
3418   const void *zSql,       /* SQL statement, UTF-16 encoded */
3419   int nByte,              /* Maximum length of zSql in bytes. */
3420   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3421   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3422 );
3423
3424 /*
3425 ** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
3426 **
3427 ** This interface can be used to retrieve a saved copy of the original
3428 ** SQL text used to create a [prepared statement] if that statement was
3429 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3430 **
3431 ** INVARIANTS:
3432 **
3433 ** {H13101} If the [prepared statement] passed as the argument to
3434 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
3435 **          [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
3436 **          a pointer to a zero-terminated string containing a UTF-8 rendering
3437 **          of the original SQL statement.
3438 **
3439 ** {H13102} If the [prepared statement] passed as the argument to
3440 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
3441 **          [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
3442 **
3443 ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
3444 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
3445 */
3446 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3447
3448 /*
3449 ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
3450 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3451 **
3452 ** SQLite uses the sqlite3_value object to represent all values
3453 ** that can be stored in a database table. SQLite uses dynamic typing
3454 ** for the values it stores. Values stored in sqlite3_value objects
3455 ** can be integers, floating point values, strings, BLOBs, or NULL.
3456 **
3457 ** An sqlite3_value object may be either "protected" or "unprotected".
3458 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3459 ** will accept either a protected or an unprotected sqlite3_value.
3460 ** Every interface that accepts sqlite3_value arguments specifies
3461 ** whether or not it requires a protected sqlite3_value.
3462 **
3463 ** The terms "protected" and "unprotected" refer to whether or not
3464 ** a mutex is held.  A internal mutex is held for a protected
3465 ** sqlite3_value object but no mutex is held for an unprotected
3466 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3467 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3468 ** or if SQLite is run in one of reduced mutex modes 
3469 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3470 ** then there is no distinction between protected and unprotected
3471 ** sqlite3_value objects and they can be used interchangeably.  However,
3472 ** for maximum code portability it is recommended that applications
3473 ** still make the distinction between between protected and unprotected
3474 ** sqlite3_value objects even when not strictly required.
3475 **
3476 ** The sqlite3_value objects that are passed as parameters into the
3477 ** implementation of [application-defined SQL functions] are protected.
3478 ** The sqlite3_value object returned by
3479 ** [sqlite3_column_value()] is unprotected.
3480 ** Unprotected sqlite3_value objects may only be used with
3481 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3482 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3483 ** interfaces require protected sqlite3_value objects.
3484 */
3485 typedef struct Mem sqlite3_value;
3486
3487 /*
3488 ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
3489 **
3490 ** The context in which an SQL function executes is stored in an
3491 ** sqlite3_context object.  A pointer to an sqlite3_context object
3492 ** is always first parameter to [application-defined SQL functions].
3493 ** The application-defined SQL function implementation will pass this
3494 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3495 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3496 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3497 ** and/or [sqlite3_set_auxdata()].
3498 */
3499 typedef struct sqlite3_context sqlite3_context;
3500
3501 /*
3502 ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
3503 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3504 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3505 **
3506 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
3507 ** literals may be replaced by a parameter in one of these forms:
3508 **
3509 ** <ul>
3510 ** <li>  ?
3511 ** <li>  ?NNN
3512 ** <li>  :VVV
3513 ** <li>  @VVV
3514 ** <li>  $VVV
3515 ** </ul>
3516 **
3517 ** In the parameter forms shown above NNN is an integer literal,
3518 ** and VVV is an alpha-numeric parameter name. The values of these
3519 ** parameters (also called "host parameter names" or "SQL parameters")
3520 ** can be set using the sqlite3_bind_*() routines defined here.
3521 **
3522 ** The first argument to the sqlite3_bind_*() routines is always
3523 ** a pointer to the [sqlite3_stmt] object returned from
3524 ** [sqlite3_prepare_v2()] or its variants.
3525 **
3526 ** The second argument is the index of the SQL parameter to be set.
3527 ** The leftmost SQL parameter has an index of 1.  When the same named
3528 ** SQL parameter is used more than once, second and subsequent
3529 ** occurrences have the same index as the first occurrence.
3530 ** The index for named parameters can be looked up using the
3531 ** [sqlite3_bind_parameter_index()] API if desired.  The index
3532 ** for "?NNN" parameters is the value of NNN.
3533 ** The NNN value must be between 1 and the [sqlite3_limit()]
3534 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3535 **
3536 ** The third argument is the value to bind to the parameter.
3537 **
3538 ** In those routines that have a fourth argument, its value is the
3539 ** number of bytes in the parameter.  To be clear: the value is the
3540 ** number of <u>bytes</u> in the value, not the number of characters.
3541 ** If the fourth parameter is negative, the length of the string is
3542 ** the number of bytes up to the first zero terminator.
3543 **
3544 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3545 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3546 ** string after SQLite has finished with it. If the fifth argument is
3547 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3548 ** information is in static, unmanaged space and does not need to be freed.
3549 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
3550 ** SQLite makes its own private copy of the data immediately, before
3551 ** the sqlite3_bind_*() routine returns.
3552 **
3553 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3554 ** is filled with zeroes.  A zeroblob uses a fixed amount of memory
3555 ** (just an integer to hold its size) while it is being processed.
3556 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3557 ** content is later written using
3558 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3559 ** A negative value for the zeroblob results in a zero-length BLOB.
3560 **
3561 ** The sqlite3_bind_*() routines must be called after
3562 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
3563 ** before [sqlite3_step()].
3564 ** Bindings are not cleared by the [sqlite3_reset()] routine.
3565 ** Unbound parameters are interpreted as NULL.
3566 **
3567 ** These routines return [SQLITE_OK] on success or an error code if
3568 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
3569 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
3570 ** [SQLITE_MISUSE] might be returned if these routines are called on a
3571 ** virtual machine that is the wrong state or which has already been finalized.
3572 ** Detection of misuse is unreliable.  Applications should not depend
3573 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
3574 ** a logic error in the application.  Future versions of SQLite might
3575 ** panic rather than return SQLITE_MISUSE.
3576 **
3577 ** See also: [sqlite3_bind_parameter_count()],
3578 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3579 **
3580 ** INVARIANTS:
3581 **
3582 ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
3583 **          "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
3584 **          where NNN is any sequence of one or more digits
3585 **          and where VVV is any sequence of one or more alphanumeric
3586 **          characters or "::" optionally followed by a string containing
3587 **          no spaces and contained within parentheses.
3588 **
3589 ** {H13509} The initial value of an SQL parameter is NULL.
3590 **
3591 ** {H13512} The index of an "?" SQL parameter is one larger than the
3592 **          largest index of SQL parameter to the left, or 1 if
3593 **          the "?" is the leftmost SQL parameter.
3594 **
3595 ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
3596 **
3597 ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
3598 **          the same as the index of leftmost occurrences of the same
3599 **          parameter, or one more than the largest index over all
3600 **          parameters to the left if this is the first occurrence
3601 **          of this parameter, or 1 if this is the leftmost parameter.
3602 **
3603 ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
3604 **          error if the index of an SQL parameter is less than 1
3605 **          or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
3606 **          parameter.
3607 **
3608 ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3609 **          associate the value V with all SQL parameters having an
3610 **          index of N in the [prepared statement] S.
3611 **
3612 ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3613 **          override prior calls with the same values of S and N.
3614 **
3615 ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3616 **          persist across calls to [sqlite3_reset(S)].
3617 **
3618 ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3619 **          [sqlite3_bind_text(S,N,V,L,D)], or
3620 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3621 **          bytes of the BLOB or string pointed to by V, when L
3622 **          is non-negative.
3623 **
3624 ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3625 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3626 **          from V through the first zero character when L is negative.
3627 **
3628 ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3629 **          [sqlite3_bind_text(S,N,V,L,D)], or
3630 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3631 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3632 **          is held in static unmanaged space that will not change
3633 **          during the lifetime of the binding.
3634 **
3635 ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3636 **          [sqlite3_bind_text(S,N,V,L,D)], or
3637 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3638 **          constant [SQLITE_TRANSIENT], the routine makes a
3639 **          private copy of the value V before it returns.
3640 **
3641 ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3642 **          [sqlite3_bind_text(S,N,V,L,D)], or
3643 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3644 **          a function, SQLite invokes that function to destroy the
3645 **          value V after it has finished using the value V.
3646 **
3647 ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3648 **          is a BLOB of L bytes, or a zero-length BLOB if L is negative.
3649 **
3650 ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3651 **          be either a [protected sqlite3_value] object or an
3652 **          [unprotected sqlite3_value] object.
3653 */
3654 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3655 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3656 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3657 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3658 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3659 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3660 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3661 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3662 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3663
3664 /*
3665 ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
3666 **
3667 ** This routine can be used to find the number of [SQL parameters]
3668 ** in a [prepared statement].  SQL parameters are tokens of the
3669 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3670 ** placeholders for values that are [sqlite3_bind_blob | bound]
3671 ** to the parameters at a later time.
3672 **
3673 ** This routine actually returns the index of the largest (rightmost)
3674 ** parameter. For all forms except ?NNN, this will correspond to the
3675 ** number of unique parameters.  If parameters of the ?NNN are used,
3676 ** there may be gaps in the list.
3677 **
3678 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3679 ** [sqlite3_bind_parameter_name()], and
3680 ** [sqlite3_bind_parameter_index()].
3681 **
3682 ** INVARIANTS:
3683 **
3684 ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
3685 **          the largest index of all SQL parameters in the
3686 **          [prepared statement] S, or 0 if S contains no SQL parameters.
3687 */
3688 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3689
3690 /*
3691 ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
3692 **
3693 ** This routine returns a pointer to the name of the n-th
3694 ** [SQL parameter] in a [prepared statement].
3695 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3696 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3697 ** respectively.
3698 ** In other words, the initial ":" or "$" or "@" or "?"
3699 ** is included as part of the name.
3700 ** Parameters of the form "?" without a following integer have no name
3701 ** and are also referred to as "anonymous parameters".
3702 **
3703 ** The first host parameter has an index of 1, not 0.
3704 **
3705 ** If the value n is out of range or if the n-th parameter is
3706 ** nameless, then NULL is returned.  The returned string is
3707 ** always in UTF-8 encoding even if the named parameter was
3708 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3709 ** [sqlite3_prepare16_v2()].
3710 **
3711 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3712 ** [sqlite3_bind_parameter_count()], and
3713 ** [sqlite3_bind_parameter_index()].
3714 **
3715 ** INVARIANTS:
3716 **
3717 ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3718 **          a UTF-8 rendering of the name of the SQL parameter in
3719 **          the [prepared statement] S having index N, or
3720 **          NULL if there is no SQL parameter with index N or if the
3721 **          parameter with index N is an anonymous parameter "?".
3722 */
3723 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3724
3725 /*
3726 ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
3727 **
3728 ** Return the index of an SQL parameter given its name.  The
3729 ** index value returned is suitable for use as the second
3730 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3731 ** is returned if no matching parameter is found.  The parameter
3732 ** name must be given in UTF-8 even if the original statement
3733 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3734 **
3735 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3736 ** [sqlite3_bind_parameter_count()], and
3737 ** [sqlite3_bind_parameter_index()].
3738 **
3739 ** INVARIANTS:
3740 **
3741 ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3742 **          the index of SQL parameter in the [prepared statement]
3743 **          S whose name matches the UTF-8 string N, or 0 if there is
3744 **          no match.
3745 */
3746 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3747
3748 /*
3749 ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
3750 **
3751 ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
3752 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3753 ** Use this routine to reset all host parameters to NULL.
3754 **
3755 ** INVARIANTS:
3756 **
3757 ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
3758 **          parameter bindings in the [prepared statement] S back to NULL.
3759 */
3760 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3761
3762 /*
3763 ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
3764 **
3765 ** Return the number of columns in the result set returned by the
3766 ** [prepared statement]. This routine returns 0 if pStmt is an SQL
3767 ** statement that does not return data (for example an [UPDATE]).
3768 **
3769 ** INVARIANTS:
3770 **
3771 ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
3772 **          columns in the result set generated by the [prepared statement] S,
3773 **          or 0 if S does not generate a result set.
3774 */
3775 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3776
3777 /*
3778 ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
3779 **
3780 ** These routines return the name assigned to a particular column
3781 ** in the result set of a [SELECT] statement.  The sqlite3_column_name()
3782 ** interface returns a pointer to a zero-terminated UTF-8 string
3783 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3784 ** UTF-16 string.  The first parameter is the [prepared statement]
3785 ** that implements the [SELECT] statement. The second parameter is the
3786 ** column number.  The leftmost column is number 0.
3787 **
3788 ** The returned string pointer is valid until either the [prepared statement]
3789 ** is destroyed by [sqlite3_finalize()] or until the next call to
3790 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3791 **
3792 ** If sqlite3_malloc() fails during the processing of either routine
3793 ** (for example during a conversion from UTF-8 to UTF-16) then a
3794 ** NULL pointer is returned.
3795 **
3796 ** The name of a result column is the value of the "AS" clause for
3797 ** that column, if there is an AS clause.  If there is no AS clause
3798 ** then the name of the column is unspecified and may change from
3799 ** one release of SQLite to the next.
3800 **
3801 ** INVARIANTS:
3802 **
3803 ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
3804 **          interface returns the name of the Nth column (where 0 is
3805 **          the leftmost column) for the result set of the
3806 **          [prepared statement] S as a zero-terminated UTF-8 string.
3807 **
3808 ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3809 **          interface returns the name of the Nth column (where 0 is
3810 **          the leftmost column) for the result set of the
3811 **          [prepared statement] S as a zero-terminated UTF-16 string
3812 **          in the native byte order.
3813 **
3814 ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3815 **          interfaces return a NULL pointer if they are unable to
3816 **          allocate memory to hold their normal return strings.
3817 **
3818 ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
3819 **          [sqlite3_column_name16(S,N)] is out of range, then the
3820 **          interfaces return a NULL pointer.
3821 **
3822 ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
3823 **          [sqlite3_column_name16(S,N)] are valid until the next
3824 **          call to either routine with the same S and N parameters
3825 **          or until [sqlite3_finalize(S)] is called.
3826 **
3827 ** {H13727} When a result column of a [SELECT] statement contains
3828 **          an AS clause, the name of that column is the identifier
3829 **          to the right of the AS keyword.
3830 */
3831 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3832 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3833
3834 /*
3835 ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
3836 **
3837 ** These routines provide a means to determine what column of what
3838 ** table in which database a result of a [SELECT] statement comes from.
3839 ** The name of the database or table or column can be returned as
3840 ** either a UTF-8 or UTF-16 string.  The _database_ routines return
3841 ** the database name, the _table_ routines return the table name, and
3842 ** the origin_ routines return the column name.
3843 ** The returned string is valid until the [prepared statement] is destroyed
3844 ** using [sqlite3_finalize()] or until the same information is requested
3845 ** again in a different encoding.
3846 **
3847 ** The names returned are the original un-aliased names of the
3848 ** database, table, and column.
3849 **
3850 ** The first argument to the following calls is a [prepared statement].
3851 ** These functions return information about the Nth column returned by
3852 ** the statement, where N is the second function argument.
3853 **
3854 ** If the Nth column returned by the statement is an expression or
3855 ** subquery and is not a column value, then all of these functions return
3856 ** NULL.  These routine might also return NULL if a memory allocation error
3857 ** occurs.  Otherwise, they return the name of the attached database, table
3858 ** and column that query result column was extracted from.
3859 **
3860 ** As with all other SQLite APIs, those postfixed with "16" return
3861 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3862 **
3863 ** These APIs are only available if the library was compiled with the
3864 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
3865 **
3866 ** {A13751}
3867 ** If two or more threads call one or more of these routines against the same
3868 ** prepared statement and column at the same time then the results are
3869 ** undefined.
3870 **
3871 ** INVARIANTS:
3872 **
3873 ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
3874 **          the UTF-8 zero-terminated name of the database from which the
3875 **          Nth result column of the [prepared statement] S is extracted,
3876 **          or NULL if the Nth column of S is a general expression
3877 **          or if unable to allocate memory to store the name.
3878 **
3879 ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3880 **          the UTF-16 native byte order zero-terminated name of the database
3881 **          from which the Nth result column of the [prepared statement] S is
3882 **          extracted, or NULL if the Nth column of S is a general expression
3883 **          or if unable to allocate memory to store the name.
3884 **
3885 ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
3886 **          the UTF-8 zero-terminated name of the table from which the
3887 **          Nth result column of the [prepared statement] S is extracted,
3888 **          or NULL if the Nth column of S is a general expression
3889 **          or if unable to allocate memory to store the name.
3890 **
3891 ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3892 **          the UTF-16 native byte order zero-terminated name of the table
3893 **          from which the Nth result column of the [prepared statement] S is
3894 **          extracted, or NULL if the Nth column of S is a general expression
3895 **          or if unable to allocate memory to store the name.
3896 **
3897 ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3898 **          the UTF-8 zero-terminated name of the table column from which the
3899 **          Nth result column of the [prepared statement] S is extracted,
3900 **          or NULL if the Nth column of S is a general expression
3901 **          or if unable to allocate memory to store the name.
3902 **
3903 ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
3904 **          the UTF-16 native byte order zero-terminated name of the table
3905 **          column from which the Nth result column of the
3906 **          [prepared statement] S is extracted, or NULL if the Nth column
3907 **          of S is a general expression or if unable to allocate memory
3908 **          to store the name.
3909 **
3910 ** {H13748} The return values from
3911 **          [sqlite3_column_database_name | column metadata interfaces]
3912 **          are valid for the lifetime of the [prepared statement]
3913 **          or until the encoding is changed by another metadata
3914 **          interface call for the same prepared statement and column.
3915 **
3916 ** ASSUMPTIONS:
3917 **
3918 ** {A13751} If two or more threads call one or more
3919 **          [sqlite3_column_database_name | column metadata interfaces]
3920 **          for the same [prepared statement] and result column
3921 **          at the same time then the results are undefined.
3922 */
3923 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3924 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3925 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3926 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3927 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3928 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3929
3930 /*
3931 ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
3932 **
3933 ** The first parameter is a [prepared statement].
3934 ** If this statement is a [SELECT] statement and the Nth column of the
3935 ** returned result set of that [SELECT] is a table column (not an
3936 ** expression or subquery) then the declared type of the table
3937 ** column is returned.  If the Nth column of the result set is an
3938 ** expression or subquery, then a NULL pointer is returned.
3939 ** The returned string is always UTF-8 encoded. {END}
3940 **
3941 ** For example, given the database schema:
3942 **
3943 ** CREATE TABLE t1(c1 VARIANT);
3944 **
3945 ** and the following statement to be compiled:
3946 **
3947 ** SELECT c1 + 1, c1 FROM t1;
3948 **
3949 ** this routine would return the string "VARIANT" for the second result
3950 ** column (i==1), and a NULL pointer for the first result column (i==0).
3951 **
3952 ** SQLite uses dynamic run-time typing.  So just because a column
3953 ** is declared to contain a particular type does not mean that the
3954 ** data stored in that column is of the declared type.  SQLite is
3955 ** strongly typed, but the typing is dynamic not static.  Type
3956 ** is associated with individual values, not with the containers
3957 ** used to hold those values.
3958 **
3959 ** INVARIANTS:
3960 **
3961 ** {H13761}  A successful call to [sqlite3_column_decltype(S,N)] returns a
3962 **           zero-terminated UTF-8 string containing the declared datatype
3963 **           of the table column that appears as the Nth column (numbered
3964 **           from 0) of the result set to the [prepared statement] S.
3965 **
3966 ** {H13762}  A successful call to [sqlite3_column_decltype16(S,N)]
3967 **           returns a zero-terminated UTF-16 native byte order string
3968 **           containing the declared datatype of the table column that appears
3969 **           as the Nth column (numbered from 0) of the result set to the
3970 **           [prepared statement] S.
3971 **
3972 ** {H13763}  If N is less than 0 or N is greater than or equal to
3973 **           the number of columns in the [prepared statement] S,
3974 **           or if the Nth column of S is an expression or subquery rather
3975 **           than a table column, or if a memory allocation failure
3976 **           occurs during encoding conversions, then
3977 **           calls to [sqlite3_column_decltype(S,N)] or
3978 **           [sqlite3_column_decltype16(S,N)] return NULL.
3979 */
3980 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3981 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3982
3983 /*
3984 ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
3985 **
3986 ** After a [prepared statement] has been prepared using either
3987 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3988 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3989 ** must be called one or more times to evaluate the statement.
3990 **
3991 ** The details of the behavior of the sqlite3_step() interface depend
3992 ** on whether the statement was prepared using the newer "v2" interface
3993 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3994 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3995 ** new "v2" interface is recommended for new applications but the legacy
3996 ** interface will continue to be supported.
3997 **
3998 ** In the legacy interface, the return value will be either [SQLITE_BUSY],
3999 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4000 ** With the "v2" interface, any of the other [result codes] or
4001 ** [extended result codes] might be returned as well.
4002 **
4003 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
4004 ** database locks it needs to do its job.  If the statement is a [COMMIT]
4005 ** or occurs outside of an explicit transaction, then you can retry the
4006 ** statement.  If the statement is not a [COMMIT] and occurs within a
4007 ** explicit transaction then you should rollback the transaction before
4008 ** continuing.
4009 **
4010 ** [SQLITE_DONE] means that the statement has finished executing
4011 ** successfully.  sqlite3_step() should not be called again on this virtual
4012 ** machine without first calling [sqlite3_reset()] to reset the virtual
4013 ** machine back to its initial state.
4014 **
4015 ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
4016 ** is returned each time a new row of data is ready for processing by the
4017 ** caller. The values may be accessed using the [column access functions].
4018 ** sqlite3_step() is called again to retrieve the next row of data.
4019 **
4020 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
4021 ** violation) has occurred.  sqlite3_step() should not be called again on
4022 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4023 ** With the legacy interface, a more specific error code (for example,
4024 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4025 ** can be obtained by calling [sqlite3_reset()] on the
4026 ** [prepared statement].  In the "v2" interface,
4027 ** the more specific error code is returned directly by sqlite3_step().
4028 **
4029 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4030 ** Perhaps it was called on a [prepared statement] that has
4031 ** already been [sqlite3_finalize | finalized] or on one that had
4032 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4033 ** be the case that the same database connection is being used by two or
4034 ** more threads at the same moment in time.
4035 **
4036 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4037 ** API always returns a generic error code, [SQLITE_ERROR], following any
4038 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4039 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4040 ** specific [error codes] that better describes the error.
4041 ** We admit that this is a goofy design.  The problem has been fixed
4042 ** with the "v2" interface.  If you prepare all of your SQL statements
4043 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4044 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4045 ** then the more specific [error codes] are returned directly
4046 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4047 **
4048 ** INVARIANTS:
4049 **
4050 ** {H13202}  If the [prepared statement] S is ready to be run, then
4051 **           [sqlite3_step(S)] advances that prepared statement until
4052 **           completion or until it is ready to return another row of the
4053 **           result set, or until an [sqlite3_interrupt | interrupt]
4054 **           or a run-time error occurs.
4055 **
4056 ** {H15304}  When a call to [sqlite3_step(S)] causes the [prepared statement]
4057 **           S to run to completion, the function returns [SQLITE_DONE].
4058 **
4059 ** {H15306}  When a call to [sqlite3_step(S)] stops because it is ready to
4060 **           return another row of the result set, it returns [SQLITE_ROW].
4061 **
4062 ** {H15308}  If a call to [sqlite3_step(S)] encounters an
4063 **           [sqlite3_interrupt | interrupt] or a run-time error,
4064 **           it returns an appropriate error code that is not one of
4065 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
4066 **
4067 ** {H15310}  If an [sqlite3_interrupt | interrupt] or a run-time error
4068 **           occurs during a call to [sqlite3_step(S)]
4069 **           for a [prepared statement] S created using
4070 **           legacy interfaces [sqlite3_prepare()] or
4071 **           [sqlite3_prepare16()], then the function returns either
4072 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
4073 */
4074 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4075
4076 /*
4077 ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
4078 **
4079 ** Returns the number of values in the current row of the result set.
4080 **
4081 ** INVARIANTS:
4082 **
4083 ** {H13771}  After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
4084 **           the [sqlite3_data_count(S)] routine will return the same value
4085 **           as the [sqlite3_column_count(S)] function.
4086 **
4087 ** {H13772}  After [sqlite3_step(S)] has returned any value other than
4088 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
4089 **           [prepared statement] for the first time since it was
4090 **           [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
4091 **           the [sqlite3_data_count(S)] routine returns zero.
4092 */
4093 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4094
4095 /*
4096 ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
4097 ** KEYWORDS: SQLITE_TEXT
4098 **
4099 ** {H10266} Every value in SQLite has one of five fundamental datatypes:
4100 **
4101 ** <ul>
4102 ** <li> 64-bit signed integer
4103 ** <li> 64-bit IEEE floating point number
4104 ** <li> string
4105 ** <li> BLOB
4106 ** <li> NULL
4107 ** </ul> {END}
4108 **
4109 ** These constants are codes for each of those types.
4110 **
4111 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4112 ** for a completely different meaning.  Software that links against both
4113 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4114 ** SQLITE_TEXT.
4115 */
4116 #define SQLITE_INTEGER  1
4117 #define SQLITE_FLOAT    2
4118 #define SQLITE_BLOB     4
4119 #define SQLITE_NULL     5
4120 #ifdef SQLITE_TEXT
4121 # undef SQLITE_TEXT
4122 #else
4123 # define SQLITE_TEXT     3
4124 #endif
4125 #define SQLITE3_TEXT     3
4126
4127 /*
4128 ** CAPI3REF: Result Values From A Query {H13800} <S10700>
4129 ** KEYWORDS: {column access functions}
4130 **
4131 ** These routines form the "result set query" interface.
4132 **
4133 ** These routines return information about a single column of the current
4134 ** result row of a query.  In every case the first argument is a pointer
4135 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4136 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4137 ** and the second argument is the index of the column for which information
4138 ** should be returned.  The leftmost column of the result set has the index 0.
4139 **
4140 ** If the SQL statement does not currently point to a valid row, or if the
4141 ** column index is out of range, the result is undefined.
4142 ** These routines may only be called when the most recent call to
4143 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4144 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4145 ** If any of these routines are called after [sqlite3_reset()] or
4146 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4147 ** something other than [SQLITE_ROW], the results are undefined.
4148 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4149 ** are called from a different thread while any of these routines
4150 ** are pending, then the results are undefined.
4151 **
4152 ** The sqlite3_column_type() routine returns the
4153 ** [SQLITE_INTEGER | datatype code] for the initial data type
4154 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
4155 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4156 ** returned by sqlite3_column_type() is only meaningful if no type
4157 ** conversions have occurred as described below.  After a type conversion,
4158 ** the value returned by sqlite3_column_type() is undefined.  Future
4159 ** versions of SQLite may change the behavior of sqlite3_column_type()
4160 ** following a type conversion.
4161 **
4162 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4163 ** routine returns the number of bytes in that BLOB or string.
4164 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4165 ** the string to UTF-8 and then returns the number of bytes.
4166 ** If the result is a numeric value then sqlite3_column_bytes() uses
4167 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4168 ** the number of bytes in that string.
4169 ** The value returned does not include the zero terminator at the end
4170 ** of the string.  For clarity: the value returned is the number of
4171 ** bytes in the string, not the number of characters.
4172 **
4173 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4174 ** even empty strings, are always zero terminated.  The return
4175 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
4176 ** pointer, possibly even a NULL pointer.
4177 **
4178 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
4179 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
4180 ** The zero terminator is not included in this count.
4181 **
4182 ** The object returned by [sqlite3_column_value()] is an
4183 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4184 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4185 ** If the [unprotected sqlite3_value] object returned by
4186 ** [sqlite3_column_value()] is used in any other way, including calls
4187 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4188 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4189 **
4190 ** These routines attempt to convert the value where appropriate.  For
4191 ** example, if the internal representation is FLOAT and a text result
4192 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4193 ** conversion automatically.  The following table details the conversions
4194 ** that are applied:
4195 **
4196 ** <blockquote>
4197 ** <table border="1">
4198 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4199 **
4200 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4201 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4202 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4203 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4204 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4205 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4206 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4207 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4208 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4209 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4210 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4211 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4212 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4213 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4214 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4215 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4216 ** </table>
4217 ** </blockquote>
4218 **
4219 ** The table above makes reference to standard C library functions atoi()
4220 ** and atof().  SQLite does not really use these functions.  It has its
4221 ** own equivalent internal routines.  The atoi() and atof() names are
4222 ** used in the table for brevity and because they are familiar to most
4223 ** C programmers.
4224 **
4225 ** Note that when type conversions occur, pointers returned by prior
4226 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4227 ** sqlite3_column_text16() may be invalidated.
4228 ** Type conversions and pointer invalidations might occur
4229 ** in the following cases:
4230 **
4231 ** <ul>
4232 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4233 **      sqlite3_column_text16() is called.  A zero-terminator might
4234 **      need to be added to the string.</li>
4235 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4236 **      sqlite3_column_text16() is called.  The content must be converted
4237 **      to UTF-16.</li>
4238 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4239 **      sqlite3_column_text() is called.  The content must be converted
4240 **      to UTF-8.</li>
4241 ** </ul>
4242 **
4243 ** Conversions between UTF-16be and UTF-16le are always done in place and do
4244 ** not invalidate a prior pointer, though of course the content of the buffer
4245 ** that the prior pointer points to will have been modified.  Other kinds
4246 ** of conversion are done in place when it is possible, but sometimes they
4247 ** are not possible and in those cases prior pointers are invalidated.
4248 **
4249 ** The safest and easiest to remember policy is to invoke these routines
4250 ** in one of the following ways:
4251 **
4252 ** <ul>
4253 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4254 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4255 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4256 ** </ul>
4257 **
4258 ** In other words, you should call sqlite3_column_text(),
4259 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4260 ** into the desired format, then invoke sqlite3_column_bytes() or
4261 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4262 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4263 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4264 ** with calls to sqlite3_column_bytes().
4265 **
4266 ** The pointers returned are valid until a type conversion occurs as
4267 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4268 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
4269 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4270 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4271 ** [sqlite3_free()].
4272 **
4273 ** If a memory allocation error occurs during the evaluation of any
4274 ** of these routines, a default value is returned.  The default value
4275 ** is either the integer 0, the floating point number 0.0, or a NULL
4276 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4277 ** [SQLITE_NOMEM].
4278 **
4279 ** INVARIANTS:
4280 **
4281 ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
4282 **          Nth column in the current row of the result set for
4283 **          the [prepared statement] S into a BLOB and then returns a
4284 **          pointer to the converted value.
4285 **
4286 ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
4287 **          number of bytes in the BLOB or string (exclusive of the
4288 **          zero terminator on the string) that was returned by the
4289 **          most recent call to [sqlite3_column_blob(S,N)] or
4290 **          [sqlite3_column_text(S,N)].
4291 **
4292 ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
4293 **          number of bytes in the string (exclusive of the
4294 **          zero terminator on the string) that was returned by the
4295 **          most recent call to [sqlite3_column_text16(S,N)].
4296 **
4297 ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
4298 **          Nth column in the current row of the result set for the
4299 **          [prepared statement] S into a floating point value and
4300 **          returns a copy of that value.
4301 **
4302 ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
4303 **          Nth column in the current row of the result set for the
4304 **          [prepared statement] S into a 64-bit signed integer and
4305 **          returns the lower 32 bits of that integer.
4306 **
4307 ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
4308 **          Nth column in the current row of the result set for the
4309 **          [prepared statement] S into a 64-bit signed integer and
4310 **          returns a copy of that integer.
4311 **
4312 ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
4313 **          Nth column in the current row of the result set for
4314 **          the [prepared statement] S into a zero-terminated UTF-8
4315 **          string and returns a pointer to that string.
4316 **
4317 ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
4318 **          Nth column in the current row of the result set for the
4319 **          [prepared statement] S into a zero-terminated 2-byte
4320 **          aligned UTF-16 native byte order string and returns
4321 **          a pointer to that string.
4322 **
4323 ** {H13827} The [sqlite3_column_type(S,N)] interface returns
4324 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4325 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4326 **          the Nth column in the current row of the result set for
4327 **          the [prepared statement] S.
4328 **
4329 ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
4330 **          pointer to an [unprotected sqlite3_value] object for the
4331 **          Nth column in the current row of the result set for
4332 **          the [prepared statement] S.
4333 */
4334 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4335 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4336 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4337 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4338 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4339 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4340 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4341 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4342 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4343 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4344
4345 /*
4346 ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
4347 **
4348 ** The sqlite3_finalize() function is called to delete a [prepared statement].
4349 ** If the statement was executed successfully or not executed at all, then
4350 ** SQLITE_OK is returned. If execution of the statement failed then an
4351 ** [error code] or [extended error code] is returned.
4352 **
4353 ** This routine can be called at any point during the execution of the
4354 ** [prepared statement].  If the virtual machine has not
4355 ** completed execution when this routine is called, that is like
4356 ** encountering an error or an [sqlite3_interrupt | interrupt].
4357 ** Incomplete updates may be rolled back and transactions canceled,
4358 ** depending on the circumstances, and the
4359 ** [error code] returned will be [SQLITE_ABORT].
4360 **
4361 ** INVARIANTS:
4362 **
4363 ** {H11302} The [sqlite3_finalize(S)] interface destroys the
4364 **          [prepared statement] S and releases all
4365 **          memory and file resources held by that object.
4366 **
4367 ** {H11304} If the most recent call to [sqlite3_step(S)] for the
4368 **          [prepared statement] S returned an error,
4369 **          then [sqlite3_finalize(S)] returns that same error.
4370 */
4371 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4372
4373 /*
4374 ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
4375 **
4376 ** The sqlite3_reset() function is called to reset a [prepared statement]
4377 ** object back to its initial state, ready to be re-executed.
4378 ** Any SQL statement variables that had values bound to them using
4379 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4380 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4381 **
4382 ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
4383 **          back to the beginning of its program.
4384 **
4385 ** {H11334} If the most recent call to [sqlite3_step(S)] for the
4386 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4387 **          or if [sqlite3_step(S)] has never before been called on S,
4388 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
4389 **
4390 ** {H11336} If the most recent call to [sqlite3_step(S)] for the
4391 **          [prepared statement] S indicated an error, then
4392 **          [sqlite3_reset(S)] returns an appropriate [error code].
4393 **
4394 ** {H11338} The [sqlite3_reset(S)] interface does not change the values
4395 **          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4396 */
4397 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4398
4399 /*
4400 ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
4401 ** KEYWORDS: {function creation routines}
4402 ** KEYWORDS: {application-defined SQL function}
4403 ** KEYWORDS: {application-defined SQL functions}
4404 **
4405 ** These two functions (collectively known as "function creation routines")
4406 ** are used to add SQL functions or aggregates or to redefine the behavior
4407 ** of existing SQL functions or aggregates.  The only difference between the
4408 ** two is that the second parameter, the name of the (scalar) function or
4409 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
4410 ** for sqlite3_create_function16().
4411 **
4412 ** The first parameter is the [database connection] to which the SQL
4413 ** function is to be added.  If a single program uses more than one database
4414 ** connection internally, then SQL functions must be added individually to
4415 ** each database connection.
4416 **
4417 ** The second parameter is the name of the SQL function to be created or
4418 ** redefined.  The length of the name is limited to 255 bytes, exclusive of
4419 ** the zero-terminator.  Note that the name length limit is in bytes, not
4420 ** characters.  Any attempt to create a function with a longer name
4421 ** will result in [SQLITE_ERROR] being returned.
4422 **
4423 ** The third parameter (nArg)
4424 ** is the number of arguments that the SQL function or
4425 ** aggregate takes. If this parameter is negative, then the SQL function or
4426 ** aggregate may take any number of arguments.
4427 **
4428 ** The fourth parameter, eTextRep, specifies what
4429 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4430 ** its parameters.  Any SQL function implementation should be able to work
4431 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4432 ** more efficient with one encoding than another.  It is allowed to
4433 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4434 ** times with the same function but with different values of eTextRep.
4435 ** When multiple implementations of the same function are available, SQLite
4436 ** will pick the one that involves the least amount of data conversion.
4437 ** If there is only a single implementation which does not care what text
4438 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4439 **
4440 ** The fifth parameter is an arbitrary pointer.  The implementation of the
4441 ** function can gain access to this pointer using [sqlite3_user_data()].
4442 **
4443 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
4444 ** pointers to C-language functions that implement the SQL function or
4445 ** aggregate. A scalar SQL function requires an implementation of the xFunc
4446 ** callback only, NULL pointers should be passed as the xStep and xFinal
4447 ** parameters. An aggregate SQL function requires an implementation of xStep
4448 ** and xFinal and NULL should be passed for xFunc. To delete an existing
4449 ** SQL function or aggregate, pass NULL for all three function callbacks.
4450 **
4451 ** It is permitted to register multiple implementations of the same
4452 ** functions with the same name but with either differing numbers of
4453 ** arguments or differing preferred text encodings.  SQLite will use
4454 ** the implementation most closely matches the way in which the
4455 ** SQL function is used.  A function implementation with a non-negative
4456 ** nArg parameter is a better match than a function implementation with
4457 ** a negative nArg.  A function where the preferred text encoding
4458 ** matches the database encoding is a better
4459 ** match than a function where the encoding is different.  
4460 ** A function where the encoding difference is between UTF16le and UTF16be
4461 ** is a closer match than a function where the encoding difference is
4462 ** between UTF8 and UTF16.
4463 **
4464 ** Built-in functions may be overloaded by new application-defined functions.
4465 ** The first application-defined function with a given name overrides all
4466 ** built-in functions in the same [database connection] with the same name.
4467 ** Subsequent application-defined functions of the same name only override 
4468 ** prior application-defined functions that are an exact match for the
4469 ** number of parameters and preferred encoding.
4470 **
4471 ** An application-defined function is permitted to call other
4472 ** SQLite interfaces.  However, such calls must not
4473 ** close the database connection nor finalize or reset the prepared
4474 ** statement in which the function is running.
4475 **
4476 ** INVARIANTS:
4477 **
4478 ** {H16103} The [sqlite3_create_function16(D,X,...)] interface shall behave
4479 **          as [sqlite3_create_function(D,X,...)] in every way except that it
4480 **          interprets the X argument as zero-terminated UTF-16
4481 **          native byte order instead of as zero-terminated UTF-8.
4482 **
4483 ** {H16106} A successful invocation of the
4484 **          [sqlite3_create_function(D,X,N,E,...)] interface shall register
4485 **          or replaces callback functions in the [database connection] D
4486 **          used to implement the SQL function named X with N parameters
4487 **          and having a preferred text encoding of E.
4488 **
4489 ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4490 **          shall replace the P, F, S, and L values from any prior calls with
4491 **          the same D, X, N, and E values.
4492 **
4493 ** {H16112} The [sqlite3_create_function(D,X,...)] interface shall fail
4494 **          if the SQL function name X is
4495 **          longer than 255 bytes exclusive of the zero terminator.
4496 **
4497 ** {H16118} The [sqlite3_create_function(D,X,N,E,P,F,S,L)] interface
4498 **          shall fail unless either F is NULL and S and L are non-NULL or
4499 ***         F is non-NULL and S and L are NULL.
4500 **
4501 ** {H16121} The [sqlite3_create_function(D,...)] interface shall fails with an
4502 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
4503 **          associated with the [database connection] D.
4504 **
4505 ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface shall fail with
4506 **          an error code of [SQLITE_ERROR] if parameter N is less
4507 **          than -1 or greater than 127.
4508 **
4509 ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
4510 **          interface shall register callbacks to be invoked for the
4511 **          SQL function
4512 **          named X when the number of arguments to the SQL function is
4513 **          exactly N.
4514 **
4515 ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
4516 **          interface shall register callbacks to be invoked for the SQL
4517 **          function named X with any number of arguments.
4518 **
4519 ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
4520 **          specify multiple implementations of the same function X
4521 **          and when one implementation has N>=0 and the other has N=(-1)
4522 **          the implementation with a non-zero N shall be preferred.
4523 **
4524 ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
4525 **          specify multiple implementations of the same function X with
4526 **          the same number of arguments N but with different
4527 **          encodings E, then the implementation where E matches the
4528 **          database encoding shall preferred.
4529 **
4530 ** {H16139} For an aggregate SQL function created using
4531 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
4532 **          function L shall always be invoked exactly once if the
4533 **          step function S is called one or more times.
4534 **
4535 ** {H16142} When SQLite invokes either the xFunc or xStep function of
4536 **          an application-defined SQL function or aggregate created
4537 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
4538 **          then the array of [sqlite3_value] objects passed as the
4539 **          third parameter shall be [protected sqlite3_value] objects.
4540 */
4541 SQLITE_API int sqlite3_create_function(
4542   sqlite3 *db,
4543   const char *zFunctionName,
4544   int nArg,
4545   int eTextRep,
4546   void *pApp,
4547   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4548   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4549   void (*xFinal)(sqlite3_context*)
4550 );
4551 SQLITE_API int sqlite3_create_function16(
4552   sqlite3 *db,
4553   const void *zFunctionName,
4554   int nArg,
4555   int eTextRep,
4556   void *pApp,
4557   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4558   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4559   void (*xFinal)(sqlite3_context*)
4560 );
4561
4562 /*
4563 ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
4564 **
4565 ** These constant define integer codes that represent the various
4566 ** text encodings supported by SQLite.
4567 */
4568 #define SQLITE_UTF8           1
4569 #define SQLITE_UTF16LE        2
4570 #define SQLITE_UTF16BE        3
4571 #define SQLITE_UTF16          4    /* Use native byte order */
4572 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4573 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4574
4575 /*
4576 ** CAPI3REF: Deprecated Functions
4577 ** DEPRECATED
4578 **
4579 ** These functions are [deprecated].  In order to maintain
4580 ** backwards compatibility with older code, these functions continue 
4581 ** to be supported.  However, new applications should avoid
4582 ** the use of these functions.  To help encourage people to avoid
4583 ** using these functions, we are not going to tell you want they do.
4584 */
4585 #ifndef SQLITE_OMIT_DEPRECATED
4586 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4587 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4588 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4589 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4590 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4591 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4592 #endif
4593
4594 /*
4595 ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
4596 **
4597 ** The C-language implementation of SQL functions and aggregates uses
4598 ** this set of interface routines to access the parameter values on
4599 ** the function or aggregate.
4600 **
4601 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4602 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4603 ** define callbacks that implement the SQL functions and aggregates.
4604 ** The 4th parameter to these callbacks is an array of pointers to
4605 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4606 ** each parameter to the SQL function.  These routines are used to
4607 ** extract values from the [sqlite3_value] objects.
4608 **
4609 ** These routines work only with [protected sqlite3_value] objects.
4610 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4611 ** object results in undefined behavior.
4612 **
4613 ** These routines work just like the corresponding [column access functions]
4614 ** except that  these routines take a single [protected sqlite3_value] object
4615 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4616 **
4617 ** The sqlite3_value_text16() interface extracts a UTF-16 string
4618 ** in the native byte-order of the host machine.  The
4619 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4620 ** extract UTF-16 strings as big-endian and little-endian respectively.
4621 **
4622 ** The sqlite3_value_numeric_type() interface attempts to apply
4623 ** numeric affinity to the value.  This means that an attempt is
4624 ** made to convert the value to an integer or floating point.  If
4625 ** such a conversion is possible without loss of information (in other
4626 ** words, if the value is a string that looks like a number)
4627 ** then the conversion is performed.  Otherwise no conversion occurs.
4628 ** The [SQLITE_INTEGER | datatype] after conversion is returned.
4629 **
4630 ** Please pay particular attention to the fact that the pointer returned
4631 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4632 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4633 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4634 ** or [sqlite3_value_text16()].
4635 **
4636 ** These routines must be called from the same thread as
4637 ** the SQL function that supplied the [sqlite3_value*] parameters.
4638 **
4639 ** INVARIANTS:
4640 **
4641 ** {H15103} The [sqlite3_value_blob(V)] interface converts the
4642 **          [protected sqlite3_value] object V into a BLOB and then
4643 **          returns a pointer to the converted value.
4644 **
4645 ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
4646 **          number of bytes in the BLOB or string (exclusive of the
4647 **          zero terminator on the string) that was returned by the
4648 **          most recent call to [sqlite3_value_blob(V)] or
4649 **          [sqlite3_value_text(V)].
4650 **
4651 ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
4652 **          number of bytes in the string (exclusive of the
4653 **          zero terminator on the string) that was returned by the
4654 **          most recent call to [sqlite3_value_text16(V)],
4655 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4656 **
4657 ** {H15112} The [sqlite3_value_double(V)] interface converts the
4658 **          [protected sqlite3_value] object V into a floating point value and
4659 **          returns a copy of that value.
4660 **
4661 ** {H15115} The [sqlite3_value_int(V)] interface converts the
4662 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4663 **          returns the lower 32 bits of that integer.
4664 **
4665 ** {H15118} The [sqlite3_value_int64(V)] interface converts the
4666 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4667 **          returns a copy of that integer.
4668 **
4669 ** {H15121} The [sqlite3_value_text(V)] interface converts the
4670 **          [protected sqlite3_value] object V into a zero-terminated UTF-8
4671 **          string and returns a pointer to that string.
4672 **
4673 ** {H15124} The [sqlite3_value_text16(V)] interface converts the
4674 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4675 **          aligned UTF-16 native byte order
4676 **          string and returns a pointer to that string.
4677 **
4678 ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
4679 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4680 **          aligned UTF-16 big-endian
4681 **          string and returns a pointer to that string.
4682 **
4683 ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
4684 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4685 **          aligned UTF-16 little-endian
4686 **          string and returns a pointer to that string.
4687 **
4688 ** {H15133} The [sqlite3_value_type(V)] interface returns
4689 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4690 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4691 **          the [sqlite3_value] object V.
4692 **
4693 ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
4694 **          the [protected sqlite3_value] object V into either an integer or
4695 **          a floating point value if it can do so without loss of
4696 **          information, and returns one of [SQLITE_NULL],
4697 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4698 **          [SQLITE_BLOB] as appropriate for the
4699 **          [protected sqlite3_value] object V after the conversion attempt.
4700 */
4701 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4702 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4703 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4704 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4705 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4706 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4707 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4708 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4709 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4710 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4711 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4712 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4713
4714 /*
4715 ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
4716 **
4717 ** The implementation of aggregate SQL functions use this routine to allocate
4718 ** a structure for storing their state.
4719 **
4720 ** The first time the sqlite3_aggregate_context() routine is called for a
4721 ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
4722 ** memory, and returns a pointer to it. On second and subsequent calls to
4723 ** sqlite3_aggregate_context() for the same aggregate function index,
4724 ** the same buffer is returned. The implementation of the aggregate can use
4725 ** the returned buffer to accumulate data.
4726 **
4727 ** SQLite automatically frees the allocated buffer when the aggregate
4728 ** query concludes.
4729 **
4730 ** The first parameter should be a copy of the
4731 ** [sqlite3_context | SQL function context] that is the first parameter
4732 ** to the callback routine that implements the aggregate function.
4733 **
4734 ** This routine must be called from the same thread in which
4735 ** the aggregate SQL function is running.
4736 **
4737 ** INVARIANTS:
4738 **
4739 ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4740 **          a particular instance of an aggregate function (for a particular
4741 **          context C) causes SQLite to allocate N bytes of memory,
4742 **          zero that memory, and return a pointer to the allocated memory.
4743 **
4744 ** {H16213} If a memory allocation error occurs during
4745 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4746 **
4747 ** {H16215} Second and subsequent invocations of
4748 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4749 **          ignore the N parameter and return a pointer to the same
4750 **          block of memory returned by the first invocation.
4751 **
4752 ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4753 **          automatically freed on the next call to [sqlite3_reset()]
4754 **          or [sqlite3_finalize()] for the [prepared statement] containing
4755 **          the aggregate function associated with context C.
4756 */
4757 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4758
4759 /*
4760 ** CAPI3REF: User Data For Functions {H16240} <S20200>
4761 **
4762 ** The sqlite3_user_data() interface returns a copy of
4763 ** the pointer that was the pUserData parameter (the 5th parameter)
4764 ** of the [sqlite3_create_function()]
4765 ** and [sqlite3_create_function16()] routines that originally
4766 ** registered the application defined function. {END}
4767 **
4768 ** This routine must be called from the same thread in which
4769 ** the application-defined function is running.
4770 **
4771 ** INVARIANTS:
4772 **
4773 ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
4774 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4775 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4776 **          registered the SQL function associated with [sqlite3_context] C.
4777 */
4778 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4779
4780 /*
4781 ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
4782 **
4783 ** The sqlite3_context_db_handle() interface returns a copy of
4784 ** the pointer to the [database connection] (the 1st parameter)
4785 ** of the [sqlite3_create_function()]
4786 ** and [sqlite3_create_function16()] routines that originally
4787 ** registered the application defined function.
4788 **
4789 ** INVARIANTS:
4790 **
4791 ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4792 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4793 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4794 **          registered the SQL function associated with [sqlite3_context] C.
4795 */
4796 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4797
4798 /*
4799 ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
4800 **
4801 ** The following two functions may be used by scalar SQL functions to
4802 ** associate metadata with argument values. If the same value is passed to
4803 ** multiple invocations of the same SQL function during query execution, under
4804 ** some circumstances the associated metadata may be preserved. This may
4805 ** be used, for example, to add a regular-expression matching scalar
4806 ** function. The compiled version of the regular expression is stored as
4807 ** metadata associated with the SQL value passed as the regular expression
4808 ** pattern.  The compiled regular expression can be reused on multiple
4809 ** invocations of the same function so that the original pattern string
4810 ** does not need to be recompiled on each invocation.
4811 **
4812 ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
4813 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4814 ** value to the application-defined function. If no metadata has been ever
4815 ** been set for the Nth argument of the function, or if the corresponding
4816 ** function parameter has changed since the meta-data was set,
4817 ** then sqlite3_get_auxdata() returns a NULL pointer.
4818 **
4819 ** The sqlite3_set_auxdata() interface saves the metadata
4820 ** pointed to by its 3rd parameter as the metadata for the N-th
4821 ** argument of the application-defined function.  Subsequent
4822 ** calls to sqlite3_get_auxdata() might return this data, if it has
4823 ** not been destroyed.
4824 ** If it is not NULL, SQLite will invoke the destructor
4825 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4826 ** the metadata when the corresponding function parameter changes
4827 ** or when the SQL statement completes, whichever comes first.
4828 **
4829 ** SQLite is free to call the destructor and drop metadata on any
4830 ** parameter of any function at any time.  The only guarantee is that
4831 ** the destructor will be called before the metadata is dropped.
4832 **
4833 ** In practice, metadata is preserved between function calls for
4834 ** expressions that are constant at compile time. This includes literal
4835 ** values and SQL variables.
4836 **
4837 ** These routines must be called from the same thread in which
4838 ** the SQL function is running.
4839 **
4840 ** INVARIANTS:
4841 **
4842 ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4843 **          to metadata associated with the Nth parameter of the SQL function
4844 **          whose context is C, or NULL if there is no metadata associated
4845 **          with that parameter.
4846 **
4847 ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4848 **          pointer P to the Nth parameter of the SQL function with context C.
4849 **
4850 ** {H16276} SQLite will invoke the destructor D with a single argument
4851 **          which is the metadata pointer P following a call to
4852 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4853 **          the metadata.
4854 **
4855 ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
4856 **          when the value of that parameter changes.
4857 **
4858 ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4859 **          is called for any prior metadata associated with the same function
4860 **          context C and parameter N.
4861 **
4862 ** {H16279} SQLite will call destructors for any metadata it is holding
4863 **          in a particular [prepared statement] S when either
4864 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4865 */
4866 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4867 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4868
4869
4870 /*
4871 ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
4872 **
4873 ** These are special values for the destructor that is passed in as the
4874 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4875 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4876 ** and will never change.  It does not need to be destroyed.  The
4877 ** SQLITE_TRANSIENT value means that the content will likely change in
4878 ** the near future and that SQLite should make its own private copy of
4879 ** the content before returning.
4880 **
4881 ** The typedef is necessary to work around problems in certain
4882 ** C++ compilers.  See ticket #2191.
4883 */
4884 typedef void (*sqlite3_destructor_type)(void*);
4885 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4886 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4887
4888 /*
4889 ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
4890 **
4891 ** These routines are used by the xFunc or xFinal callbacks that
4892 ** implement SQL functions and aggregates.  See
4893 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4894 ** for additional information.
4895 **
4896 ** These functions work very much like the [parameter binding] family of
4897 ** functions used to bind values to host parameters in prepared statements.
4898 ** Refer to the [SQL parameter] documentation for additional information.
4899 **
4900 ** The sqlite3_result_blob() interface sets the result from
4901 ** an application-defined function to be the BLOB whose content is pointed
4902 ** to by the second parameter and which is N bytes long where N is the
4903 ** third parameter.
4904 **
4905 ** The sqlite3_result_zeroblob() interfaces set the result of
4906 ** the application-defined function to be a BLOB containing all zero
4907 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4908 **
4909 ** The sqlite3_result_double() interface sets the result from
4910 ** an application-defined function to be a floating point value specified
4911 ** by its 2nd argument.
4912 **
4913 ** The sqlite3_result_error() and sqlite3_result_error16() functions
4914 ** cause the implemented SQL function to throw an exception.
4915 ** SQLite uses the string pointed to by the
4916 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4917 ** as the text of an error message.  SQLite interprets the error
4918 ** message string from sqlite3_result_error() as UTF-8. SQLite
4919 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4920 ** byte order.  If the third parameter to sqlite3_result_error()
4921 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4922 ** message all text up through the first zero character.
4923 ** If the third parameter to sqlite3_result_error() or
4924 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4925 ** bytes (not characters) from the 2nd parameter as the error message.
4926 ** The sqlite3_result_error() and sqlite3_result_error16()
4927 ** routines make a private copy of the error message text before
4928 ** they return.  Hence, the calling function can deallocate or
4929 ** modify the text after they return without harm.
4930 ** The sqlite3_result_error_code() function changes the error code
4931 ** returned by SQLite as a result of an error in a function.  By default,
4932 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
4933 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4934 **
4935 ** The sqlite3_result_toobig() interface causes SQLite to throw an error
4936 ** indicating that a string or BLOB is to long to represent.
4937 **
4938 ** The sqlite3_result_nomem() interface causes SQLite to throw an error
4939 ** indicating that a memory allocation failed.
4940 **
4941 ** The sqlite3_result_int() interface sets the return value
4942 ** of the application-defined function to be the 32-bit signed integer
4943 ** value given in the 2nd argument.
4944 ** The sqlite3_result_int64() interface sets the return value
4945 ** of the application-defined function to be the 64-bit signed integer
4946 ** value given in the 2nd argument.
4947 **
4948 ** The sqlite3_result_null() interface sets the return value
4949 ** of the application-defined function to be NULL.
4950 **
4951 ** The sqlite3_result_text(), sqlite3_result_text16(),
4952 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4953 ** set the return value of the application-defined function to be
4954 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4955 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4956 ** SQLite takes the text result from the application from
4957 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4958 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4959 ** is negative, then SQLite takes result text from the 2nd parameter
4960 ** through the first zero character.
4961 ** If the 3rd parameter to the sqlite3_result_text* interfaces
4962 ** is non-negative, then as many bytes (not characters) of the text
4963 ** pointed to by the 2nd parameter are taken as the application-defined
4964 ** function result.
4965 ** If the 4th parameter to the sqlite3_result_text* interfaces
4966 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4967 ** function as the destructor on the text or BLOB result when it has
4968 ** finished using that result.
4969 ** If the 4th parameter to the sqlite3_result_text* interfaces or
4970 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4971 ** assumes that the text or BLOB result is in constant space and does not
4972 ** copy the it or call a destructor when it has finished using that result.
4973 ** If the 4th parameter to the sqlite3_result_text* interfaces
4974 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4975 ** then SQLite makes a copy of the result into space obtained from
4976 ** from [sqlite3_malloc()] before it returns.
4977 **
4978 ** The sqlite3_result_value() interface sets the result of
4979 ** the application-defined function to be a copy the
4980 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
4981 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4982 ** so that the [sqlite3_value] specified in the parameter may change or
4983 ** be deallocated after sqlite3_result_value() returns without harm.
4984 ** A [protected sqlite3_value] object may always be used where an
4985 ** [unprotected sqlite3_value] object is required, so either
4986 ** kind of [sqlite3_value] object can be used with this interface.
4987 **
4988 ** If these routines are called from within the different thread
4989 ** than the one containing the application-defined function that received
4990 ** the [sqlite3_context] pointer, the results are undefined.
4991 **
4992 ** INVARIANTS:
4993 **
4994 ** {H16403} The default return value from any SQL function is NULL.
4995 **
4996 ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
4997 **          return value of function C to be a BLOB that is N bytes
4998 **          in length and with content pointed to by V.
4999 **
5000 ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
5001 **          return value of function C to be the floating point value V.
5002 **
5003 ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
5004 **          value of function C to be an exception with error code
5005 **          [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
5006 **          first zero byte or until N bytes are read if N is positive.
5007 **
5008 ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
5009 **          value of function C to be an exception with error code
5010 **          [SQLITE_ERROR] and a UTF-16 native byte order error message
5011 **          copied from V up to the first zero terminator or until N bytes
5012 **          are read if N is positive.
5013 **
5014 ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
5015 **          value of the function C to be an exception with error code
5016 **          [SQLITE_TOOBIG] and an appropriate error message.
5017 **
5018 ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
5019 **          value of the function C to be an exception with error code
5020 **          [SQLITE_NOMEM] and an appropriate error message.
5021 **
5022 ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
5023 **          value of the function C to be an exception with error code E.
5024 **          The error message text is unchanged.
5025 **
5026 ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
5027 **          return value of function C to be the 32-bit integer value V.
5028 **
5029 ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
5030 **          return value of function C to be the 64-bit integer value V.
5031 **
5032 ** {H16433} The [sqlite3_result_null(C)] interface changes the
5033 **          return value of function C to be NULL.
5034 **
5035 ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
5036 **          return value of function C to be the UTF-8 string
5037 **          V up to the first zero if N is negative
5038 **          or the first N bytes of V if N is non-negative.
5039 **
5040 ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
5041 **          return value of function C to be the UTF-16 native byte order
5042 **          string V up to the first zero if N is negative
5043 **          or the first N bytes of V if N is non-negative.
5044 **
5045 ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
5046 **          return value of function C to be the UTF-16 big-endian
5047 **          string V up to the first zero if N is negative
5048 **          or the first N bytes or V if N is non-negative.
5049 **
5050 ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
5051 **          return value of function C to be the UTF-16 little-endian
5052 **          string V up to the first zero if N is negative
5053 **          or the first N bytes of V if N is non-negative.
5054 **
5055 ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
5056 **          return value of function C to be the [unprotected sqlite3_value]
5057 **          object V.
5058 **
5059 ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
5060 **          return value of function C to be an N-byte BLOB of all zeros.
5061 **
5062 ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
5063 **          interfaces make a copy of their error message strings before
5064 **          returning.
5065 **
5066 ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5067 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5068 **          [sqlite3_result_text16be(C,V,N,D)], or
5069 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
5070 **          then no destructor is ever called on the pointer V and SQLite
5071 **          assumes that V is immutable.
5072 **
5073 ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5074 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5075 **          [sqlite3_result_text16be(C,V,N,D)], or
5076 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
5077 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
5078 **          content of V and retains the copy.
5079 **
5080 ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5081 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5082 **          [sqlite3_result_text16be(C,V,N,D)], or
5083 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
5084 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
5085 **          SQLite will invoke the destructor D with V as its only argument
5086 **          when it has finished with the V value.
5087 */
5088 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5089 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
5090 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5091 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5092 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
5093 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
5094 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
5095 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
5096 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5097 SQLITE_API void sqlite3_result_null(sqlite3_context*);
5098 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5099 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5100 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5101 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5102 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5103 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
5104
5105 /*
5106 ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
5107 **
5108 ** These functions are used to add new collation sequences to the
5109 ** [database connection] specified as the first argument.
5110 **
5111 ** The name of the new collation sequence is specified as a UTF-8 string
5112 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5113 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
5114 ** the name is passed as the second function argument.
5115 **
5116 ** The third argument may be one of the constants [SQLITE_UTF8],
5117 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
5118 ** routine expects to be passed pointers to strings encoded using UTF-8,
5119 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
5120 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
5121 ** the routine expects pointers to 16-bit word aligned strings
5122 ** of UTF-16 in the native byte order of the host computer.
5123 **
5124 ** A pointer to the user supplied routine must be passed as the fifth
5125 ** argument.  If it is NULL, this is the same as deleting the collation
5126 ** sequence (so that SQLite cannot call it anymore).
5127 ** Each time the application supplied function is invoked, it is passed
5128 ** as its first parameter a copy of the void* passed as the fourth argument
5129 ** to sqlite3_create_collation() or sqlite3_create_collation16().
5130 **
5131 ** The remaining arguments to the application-supplied routine are two strings,
5132 ** each represented by a (length, data) pair and encoded in the encoding
5133 ** that was passed as the third argument when the collation sequence was
5134 ** registered. {END}  The application defined collation routine should
5135 ** return negative, zero or positive if the first string is less than,
5136 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
5137 **
5138 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5139 ** except that it takes an extra argument which is a destructor for
5140 ** the collation.  The destructor is called when the collation is
5141 ** destroyed and is passed a copy of the fourth parameter void* pointer
5142 ** of the sqlite3_create_collation_v2().
5143 ** Collations are destroyed when they are overridden by later calls to the
5144 ** collation creation functions or when the [database connection] is closed
5145 ** using [sqlite3_close()].
5146 **
5147 ** INVARIANTS:
5148 **
5149 ** {H16603} A successful call to the
5150 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
5151 **          registers function F as the comparison function used to
5152 **          implement collation X on the [database connection] B for
5153 **          databases having encoding E.
5154 **
5155 ** {H16604} SQLite understands the X parameter to
5156 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
5157 **          UTF-8 string in which case is ignored for ASCII characters and
5158 **          is significant for non-ASCII characters.
5159 **
5160 ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5161 **          with the same values for B, X, and E, override prior values
5162 **          of P, F, and D.
5163 **
5164 ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5165 **          is not NULL then it is called with argument P when the
5166 **          collating function is dropped by SQLite.
5167 **
5168 ** {H16612} A collating function is dropped when it is overloaded.
5169 **
5170 ** {H16615} A collating function is dropped when the database connection
5171 **          is closed using [sqlite3_close()].
5172 **
5173 ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5174 **          is passed through as the first parameter to the comparison
5175 **          function F for all subsequent invocations of F.
5176 **
5177 ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
5178 **          the same as a call to [sqlite3_create_collation_v2()] with
5179 **          the same parameters and a NULL destructor.
5180 **
5181 ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
5182 **          SQLite uses the comparison function F for all text comparison
5183 **          operations on the [database connection] B on text values that
5184 **          use the collating sequence named X.
5185 **
5186 ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
5187 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
5188 **          collation name X is understood as UTF-16 in native byte order
5189 **          instead of UTF-8.
5190 **
5191 ** {H16630} When multiple comparison functions are available for the same
5192 **          collating sequence, SQLite chooses the one whose text encoding
5193 **          requires the least amount of conversion from the default
5194 **          text encoding of the database.
5195 */
5196 SQLITE_API int sqlite3_create_collation(
5197   sqlite3*, 
5198   const char *zName, 
5199   int eTextRep, 
5200   void*,
5201   int(*xCompare)(void*,int,const void*,int,const void*)
5202 );
5203 SQLITE_API int sqlite3_create_collation_v2(
5204   sqlite3*, 
5205   const char *zName, 
5206   int eTextRep, 
5207   void*,
5208   int(*xCompare)(void*,int,const void*,int,const void*),
5209   void(*xDestroy)(void*)
5210 );
5211 SQLITE_API int sqlite3_create_collation16(
5212   sqlite3*, 
5213   const void *zName,
5214   int eTextRep, 
5215   void*,
5216   int(*xCompare)(void*,int,const void*,int,const void*)
5217 );
5218
5219 /*
5220 ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
5221 **
5222 ** To avoid having to register all collation sequences before a database
5223 ** can be used, a single callback function may be registered with the
5224 ** [database connection] to be called whenever an undefined collation
5225 ** sequence is required.
5226 **
5227 ** If the function is registered using the sqlite3_collation_needed() API,
5228 ** then it is passed the names of undefined collation sequences as strings
5229 ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
5230 ** the names are passed as UTF-16 in machine native byte order.
5231 ** A call to either function replaces any existing callback.
5232 **
5233 ** When the callback is invoked, the first argument passed is a copy
5234 ** of the second argument to sqlite3_collation_needed() or
5235 ** sqlite3_collation_needed16().  The second argument is the database
5236 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5237 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5238 ** sequence function required.  The fourth parameter is the name of the
5239 ** required collation sequence.
5240 **
5241 ** The callback function should register the desired collation using
5242 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5243 ** [sqlite3_create_collation_v2()].
5244 **
5245 ** INVARIANTS:
5246 **
5247 ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
5248 **          or [sqlite3_collation_needed16(D,P,F)] causes
5249 **          the [database connection] D to invoke callback F with first
5250 **          parameter P whenever it needs a comparison function for a
5251 **          collating sequence that it does not know about.
5252 **
5253 ** {H16704} Each successful call to [sqlite3_collation_needed()] or
5254 **          [sqlite3_collation_needed16()] overrides the callback registered
5255 **          on the same [database connection] by prior calls to either
5256 **          interface.
5257 **
5258 ** {H16706} The name of the requested collating function passed in the
5259 **          4th parameter to the callback is in UTF-8 if the callback
5260 **          was registered using [sqlite3_collation_needed()] and
5261 **          is in UTF-16 native byte order if the callback was
5262 **          registered using [sqlite3_collation_needed16()].
5263 */
5264 SQLITE_API int sqlite3_collation_needed(
5265   sqlite3*, 
5266   void*, 
5267   void(*)(void*,sqlite3*,int eTextRep,const char*)
5268 );
5269 SQLITE_API int sqlite3_collation_needed16(
5270   sqlite3*, 
5271   void*,
5272   void(*)(void*,sqlite3*,int eTextRep,const void*)
5273 );
5274
5275 /*
5276 ** Specify the key for an encrypted database.  This routine should be
5277 ** called right after sqlite3_open().
5278 **
5279 ** The code to implement this API is not available in the public release
5280 ** of SQLite.
5281 */
5282 SQLITE_API int sqlite3_key(
5283   sqlite3 *db,                   /* Database to be rekeyed */
5284   const void *pKey, int nKey     /* The key */
5285 );
5286
5287 /*
5288 ** Change the key on an open database.  If the current database is not
5289 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5290 ** database is decrypted.
5291 **
5292 ** The code to implement this API is not available in the public release
5293 ** of SQLite.
5294 */
5295 SQLITE_API int sqlite3_rekey(
5296   sqlite3 *db,                   /* Database to be rekeyed */
5297   const void *pKey, int nKey     /* The new key */
5298 );
5299
5300 /*
5301 ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
5302 **
5303 ** The sqlite3_sleep() function causes the current thread to suspend execution
5304 ** for at least a number of milliseconds specified in its parameter.
5305 **
5306 ** If the operating system does not support sleep requests with
5307 ** millisecond time resolution, then the time will be rounded up to
5308 ** the nearest second. The number of milliseconds of sleep actually
5309 ** requested from the operating system is returned.
5310 **
5311 ** SQLite implements this interface by calling the xSleep()
5312 ** method of the default [sqlite3_vfs] object.
5313 **
5314 ** INVARIANTS:
5315 **
5316 ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
5317 **          method of the default [sqlite3_vfs|VFS] in order to
5318 **          suspend execution of the current thread for at least
5319 **          M milliseconds.
5320 **
5321 ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
5322 **          milliseconds of sleep actually requested of the operating
5323 **          system, which might be larger than the parameter M.
5324 */
5325 SQLITE_API int sqlite3_sleep(int);
5326
5327 /*
5328 ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
5329 **
5330 ** If this global variable is made to point to a string which is
5331 ** the name of a folder (a.k.a. directory), then all temporary files
5332 ** created by SQLite will be placed in that directory.  If this variable
5333 ** is a NULL pointer, then SQLite performs a search for an appropriate
5334 ** temporary file directory.
5335 **
5336 ** It is not safe to modify this variable once a [database connection]
5337 ** has been opened.  It is intended that this variable be set once
5338 ** as part of process initialization and before any SQLite interface
5339 ** routines have been call and remain unchanged thereafter.
5340 */
5341 SQLITE_API char *sqlite3_temp_directory;
5342
5343 /*
5344 ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
5345 ** KEYWORDS: {autocommit mode}
5346 **
5347 ** The sqlite3_get_autocommit() interface returns non-zero or
5348 ** zero if the given database connection is or is not in autocommit mode,
5349 ** respectively.  Autocommit mode is on by default.
5350 ** Autocommit mode is disabled by a [BEGIN] statement.
5351 ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5352 **
5353 ** If certain kinds of errors occur on a statement within a multi-statement
5354 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5355 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5356 ** transaction might be rolled back automatically.  The only way to
5357 ** find out whether SQLite automatically rolled back the transaction after
5358 ** an error is to use this function.
5359 **
5360 ** INVARIANTS:
5361 **
5362 ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
5363 **          zero if the [database connection] D is or is not in autocommit
5364 **          mode, respectively.
5365 **
5366 ** {H12932} Autocommit mode is on by default.
5367 **
5368 ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
5369 **
5370 ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
5371 **          statement.
5372 **
5373 ** ASSUMPTIONS:
5374 **
5375 ** {A12936} If another thread changes the autocommit status of the database
5376 **          connection while this routine is running, then the return value
5377 **          is undefined.
5378 */
5379 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5380
5381 /*
5382 ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
5383 **
5384 ** The sqlite3_db_handle interface returns the [database connection] handle
5385 ** to which a [prepared statement] belongs.  The database handle returned by
5386 ** sqlite3_db_handle is the same database handle that was the first argument
5387 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5388 ** create the statement in the first place.
5389 **
5390 ** INVARIANTS:
5391 **
5392 ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
5393 **          to the [database connection] associated with the
5394 **          [prepared statement] S.
5395 */
5396 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5397
5398 /*
5399 ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
5400 **
5401 ** This interface returns a pointer to the next [prepared statement] after
5402 ** pStmt associated with the [database connection] pDb.  If pStmt is NULL
5403 ** then this interface returns a pointer to the first prepared statement
5404 ** associated with the database connection pDb.  If no prepared statement
5405 ** satisfies the conditions of this routine, it returns NULL.
5406 **
5407 ** INVARIANTS:
5408 **
5409 ** {H13143} If D is a [database connection] that holds one or more
5410 **          unfinalized [prepared statements] and S is a NULL pointer,
5411 **          then [sqlite3_next_stmt(D, S)] routine shall return a pointer
5412 **          to one of the prepared statements associated with D.
5413 **
5414 ** {H13146} If D is a [database connection] that holds no unfinalized
5415 **          [prepared statements] and S is a NULL pointer, then
5416 **          [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
5417 **
5418 ** {H13149} If S is a [prepared statement] in the [database connection] D
5419 **          and S is not the last prepared statement in D, then
5420 **          [sqlite3_next_stmt(D, S)] routine shall return a pointer
5421 **          to the next prepared statement in D after S.
5422 **
5423 ** {H13152} If S is the last [prepared statement] in the
5424 **          [database connection] D then the [sqlite3_next_stmt(D, S)]
5425 **          routine shall return a NULL pointer.
5426 **
5427 ** ASSUMPTIONS:
5428 **
5429 ** {A13154} The [database connection] pointer D in a call to
5430 **          [sqlite3_next_stmt(D,S)] must refer to an open database
5431 **          connection and in particular must not be a NULL pointer.
5432 */
5433 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5434
5435 /*
5436 ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
5437 **
5438 ** The sqlite3_commit_hook() interface registers a callback
5439 ** function to be invoked whenever a transaction is committed.
5440 ** Any callback set by a previous call to sqlite3_commit_hook()
5441 ** for the same database connection is overridden.
5442 ** The sqlite3_rollback_hook() interface registers a callback
5443 ** function to be invoked whenever a transaction is committed.
5444 ** Any callback set by a previous call to sqlite3_commit_hook()
5445 ** for the same database connection is overridden.
5446 ** The pArg argument is passed through to the callback.
5447 ** If the callback on a commit hook function returns non-zero,
5448 ** then the commit is converted into a rollback.
5449 **
5450 ** If another function was previously registered, its
5451 ** pArg value is returned.  Otherwise NULL is returned.
5452 **
5453 ** The callback implementation must not do anything that will modify
5454 ** the database connection that invoked the callback.  Any actions
5455 ** to modify the database connection must be deferred until after the
5456 ** completion of the [sqlite3_step()] call that triggered the commit
5457 ** or rollback hook in the first place.
5458 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5459 ** database connections for the meaning of "modify" in this paragraph.
5460 **
5461 ** Registering a NULL function disables the callback.
5462 **
5463 ** For the purposes of this API, a transaction is said to have been
5464 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5465 ** an error or constraint causes an implicit rollback to occur.
5466 ** The rollback callback is not invoked if a transaction is
5467 ** automatically rolled back because the database connection is closed.
5468 ** The rollback callback is not invoked if a transaction is
5469 ** rolled back because a commit callback returned non-zero.
5470 ** <todo> Check on this </todo>
5471 **
5472 ** INVARIANTS:
5473 **
5474 ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
5475 **          callback function F to be invoked with argument P whenever
5476 **          a transaction commits on the [database connection] D.
5477 **
5478 ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
5479 **          from the previous call with the same [database connection] D,
5480 **          or NULL on the first call for a particular database connection D.
5481 **
5482 ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
5483 **          registered by prior calls.
5484 **
5485 ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
5486 **          then the commit hook callback is canceled and no callback
5487 **          is invoked when a transaction commits.
5488 **
5489 ** {H12955} If the commit callback returns non-zero then the commit is
5490 **          converted into a rollback.
5491 **
5492 ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
5493 **          callback function F to be invoked with argument P whenever
5494 **          a transaction rolls back on the [database connection] D.
5495 **
5496 ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
5497 **          argument from the previous call with the same
5498 **          [database connection] D, or NULL on the first call
5499 **          for a particular database connection D.
5500 **
5501 ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
5502 **          registered by prior calls.
5503 **
5504 ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
5505 **          then the rollback hook callback is canceled and no callback
5506 **          is invoked when a transaction rolls back.
5507 */
5508 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5509 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5510
5511 /*
5512 ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
5513 **
5514 ** The sqlite3_update_hook() interface registers a callback function
5515 ** with the [database connection] identified by the first argument
5516 ** to be invoked whenever a row is updated, inserted or deleted.
5517 ** Any callback set by a previous call to this function
5518 ** for the same database connection is overridden.
5519 **
5520 ** The second argument is a pointer to the function to invoke when a
5521 ** row is updated, inserted or deleted.
5522 ** The first argument to the callback is a copy of the third argument
5523 ** to sqlite3_update_hook().
5524 ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5525 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5526 ** to be invoked.
5527 ** The third and fourth arguments to the callback contain pointers to the
5528 ** database and table name containing the affected row.
5529 ** The final callback parameter is the rowid of the row. In the case of
5530 ** an update, this is the rowid after the update takes place.
5531 **
5532 ** The update hook is not invoked when internal system tables are
5533 ** modified (i.e. sqlite_master and sqlite_sequence).
5534 **
5535 ** The update hook implementation must not do anything that will modify
5536 ** the database connection that invoked the update hook.  Any actions
5537 ** to modify the database connection must be deferred until after the
5538 ** completion of the [sqlite3_step()] call that triggered the update hook.
5539 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5540 ** database connections for the meaning of "modify" in this paragraph.
5541 **
5542 ** If another function was previously registered, its pArg value
5543 ** is returned.  Otherwise NULL is returned.
5544 **
5545 ** INVARIANTS:
5546 **
5547 ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
5548 **          function F to be invoked with first parameter P whenever
5549 **          a table row is modified, inserted, or deleted on
5550 **          the [database connection] D.
5551 **
5552 ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
5553 **          of P for the previous call on the same [database connection] D,
5554 **          or NULL for the first call.
5555 **
5556 ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
5557 **          is NULL then the no update callbacks are made.
5558 **
5559 ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
5560 **          to the same interface on the same [database connection] D.
5561 **
5562 ** {H12979} The update hook callback is not invoked when internal system
5563 **          tables such as sqlite_master and sqlite_sequence are modified.
5564 **
5565 ** {H12981} The second parameter to the update callback
5566 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
5567 **          depending on the operation that caused the callback to be invoked.
5568 **
5569 ** {H12983} The third and fourth arguments to the callback contain pointers
5570 **          to zero-terminated UTF-8 strings which are the names of the
5571 **          database and table that is being updated.
5572
5573 ** {H12985} The final callback parameter is the rowid of the row after
5574 **          the change occurs.
5575 */
5576 SQLITE_API void *sqlite3_update_hook(
5577   sqlite3*, 
5578   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5579   void*
5580 );
5581
5582 /*
5583 ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
5584 ** KEYWORDS: {shared cache} {shared cache mode}
5585 **
5586 ** This routine enables or disables the sharing of the database cache
5587 ** and schema data structures between [database connection | connections]
5588 ** to the same database. Sharing is enabled if the argument is true
5589 ** and disabled if the argument is false.
5590 **
5591 ** Cache sharing is enabled and disabled for an entire process. {END}
5592 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5593 ** sharing was enabled or disabled for each thread separately.
5594 **
5595 ** The cache sharing mode set by this interface effects all subsequent
5596 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5597 ** Existing database connections continue use the sharing mode
5598 ** that was in effect at the time they were opened.
5599 **
5600 ** Virtual tables cannot be used with a shared cache.  When shared
5601 ** cache is enabled, the [sqlite3_create_module()] API used to register
5602 ** virtual tables will always return an error.
5603 **
5604 ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5605 ** successfully.  An [error code] is returned otherwise.
5606 **
5607 ** Shared cache is disabled by default. But this might change in
5608 ** future releases of SQLite.  Applications that care about shared
5609 ** cache setting should set it explicitly.
5610 **
5611 ** INVARIANTS:
5612 **
5613 ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
5614 **          will enable or disable shared cache mode for any subsequently
5615 **          created [database connection] in the same process.
5616 **
5617 ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
5618 **          interface will always return an error.
5619 **
5620 ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
5621 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5622 **
5623 ** {H10339} Shared cache is disabled by default.
5624 */
5625 SQLITE_API int sqlite3_enable_shared_cache(int);
5626
5627 /*
5628 ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
5629 **
5630 ** The sqlite3_release_memory() interface attempts to free N bytes
5631 ** of heap memory by deallocating non-essential memory allocations
5632 ** held by the database library. {END}  Memory used to cache database
5633 ** pages to improve performance is an example of non-essential memory.
5634 ** sqlite3_release_memory() returns the number of bytes actually freed,
5635 ** which might be more or less than the amount requested.
5636 **
5637 ** INVARIANTS:
5638 **
5639 ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
5640 **          free N bytes of heap memory by deallocating non-essential
5641 **          memory allocations held by the database library.
5642 **
5643 ** {H16342} The [sqlite3_release_memory(N)] returns the number
5644 **          of bytes actually freed, which might be more or less
5645 **          than the amount requested.
5646 */
5647 SQLITE_API int sqlite3_release_memory(int);
5648
5649 /*
5650 ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
5651 **
5652 ** The sqlite3_soft_heap_limit() interface places a "soft" limit
5653 ** on the amount of heap memory that may be allocated by SQLite.
5654 ** If an internal allocation is requested that would exceed the
5655 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
5656 ** more times to free up some space before the allocation is performed.
5657 **
5658 ** The limit is called "soft", because if [sqlite3_release_memory()]
5659 ** cannot free sufficient memory to prevent the limit from being exceeded,
5660 ** the memory is allocated anyway and the current operation proceeds.
5661 **
5662 ** A negative or zero value for N means that there is no soft heap limit and
5663 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5664 ** The default value for the soft heap limit is zero.
5665 **
5666 ** SQLite makes a best effort to honor the soft heap limit.
5667 ** But if the soft heap limit cannot be honored, execution will
5668 ** continue without error or notification.  This is why the limit is
5669 ** called a "soft" limit.  It is advisory only.
5670 **
5671 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5672 ** allocated by a single thread - the same thread in which this routine
5673 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5674 ** applied to all threads. The value specified for the soft heap limit
5675 ** is an upper bound on the total memory allocation for all threads. In
5676 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5677 ** individual threads.
5678 **
5679 ** INVARIANTS:
5680 **
5681 ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5682 **          of N bytes on the amount of heap memory that may be allocated
5683 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5684 **          in time.
5685 **
5686 ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5687 **          cause the total amount of allocated memory to exceed the
5688 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5689 **          in an attempt to reduce the memory usage prior to proceeding
5690 **          with the memory allocation attempt.
5691 **
5692 ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5693 **          attempts to reduce memory usage through the soft heap limit
5694 **          mechanism continue even if the attempt to reduce memory
5695 **          usage is unsuccessful.
5696 **
5697 ** {H16354} A negative or zero value for N in a call to
5698 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5699 **          heap limit and [sqlite3_release_memory()] will only be
5700 **          called when memory is completely exhausted.
5701 **
5702 ** {H16355} The default value for the soft heap limit is zero.
5703 **
5704 ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5705 **          values set by all prior calls.
5706 */
5707 SQLITE_API void sqlite3_soft_heap_limit(int);
5708
5709 /*
5710 ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
5711 **
5712 ** This routine returns metadata about a specific column of a specific
5713 ** database table accessible using the [database connection] handle
5714 ** passed as the first function argument.
5715 **
5716 ** The column is identified by the second, third and fourth parameters to
5717 ** this function. The second parameter is either the name of the database
5718 ** (i.e. "main", "temp" or an attached database) containing the specified
5719 ** table or NULL. If it is NULL, then all attached databases are searched
5720 ** for the table using the same algorithm used by the database engine to
5721 ** resolve unqualified table references.
5722 **
5723 ** The third and fourth parameters to this function are the table and column
5724 ** name of the desired column, respectively. Neither of these parameters
5725 ** may be NULL.
5726 **
5727 ** Metadata is returned by writing to the memory locations passed as the 5th
5728 ** and subsequent parameters to this function. Any of these arguments may be
5729 ** NULL, in which case the corresponding element of metadata is omitted.
5730 **
5731 ** <blockquote>
5732 ** <table border="1">
5733 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5734 **
5735 ** <tr><td> 5th <td> const char* <td> Data type
5736 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5737 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5738 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5739 ** <tr><td> 9th <td> int         <td> True if column is AUTOINCREMENT
5740 ** </table>
5741 ** </blockquote>
5742 **
5743 ** The memory pointed to by the character pointers returned for the
5744 ** declaration type and collation sequence is valid only until the next
5745 ** call to any SQLite API function.
5746 **
5747 ** If the specified table is actually a view, an [error code] is returned.
5748 **
5749 ** If the specified column is "rowid", "oid" or "_rowid_" and an
5750 ** INTEGER PRIMARY KEY column has been explicitly declared, then the output
5751 ** parameters are set for the explicitly declared column. If there is no
5752 ** explicitly declared INTEGER PRIMARY KEY column, then the output
5753 ** parameters are set as follows:
5754 **
5755 ** <pre>
5756 **     data type: "INTEGER"
5757 **     collation sequence: "BINARY"
5758 **     not null: 0
5759 **     primary key: 1
5760 **     auto increment: 0
5761 ** </pre>
5762 **
5763 ** This function may load one or more schemas from database files. If an
5764 ** error occurs during this process, or if the requested table or column
5765 ** cannot be found, an [error code] is returned and an error message left
5766 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
5767 **
5768 ** This API is only available if the library was compiled with the
5769 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5770 */
5771 SQLITE_API int sqlite3_table_column_metadata(
5772   sqlite3 *db,                /* Connection handle */
5773   const char *zDbName,        /* Database name or NULL */
5774   const char *zTableName,     /* Table name */
5775   const char *zColumnName,    /* Column name */
5776   char const **pzDataType,    /* OUTPUT: Declared data type */
5777   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5778   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5779   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5780   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5781 );
5782
5783 /*
5784 ** CAPI3REF: Load An Extension {H12600} <S20500>
5785 **
5786 ** This interface loads an SQLite extension library from the named file.
5787 **
5788 ** {H12601} The sqlite3_load_extension() interface attempts to load an
5789 **          SQLite extension library contained in the file zFile.
5790 **
5791 ** {H12602} The entry point is zProc.
5792 **
5793 ** {H12603} zProc may be 0, in which case the name of the entry point
5794 **          defaults to "sqlite3_extension_init".
5795 **
5796 ** {H12604} The sqlite3_load_extension() interface shall return
5797 **          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5798 **
5799 ** {H12605} If an error occurs and pzErrMsg is not 0, then the
5800 **          [sqlite3_load_extension()] interface shall attempt to
5801 **          fill *pzErrMsg with error message text stored in memory
5802 **          obtained from [sqlite3_malloc()]. {END}  The calling function
5803 **          should free this memory by calling [sqlite3_free()].
5804 **
5805 ** {H12606} Extension loading must be enabled using
5806 **          [sqlite3_enable_load_extension()] prior to calling this API,
5807 **          otherwise an error will be returned.
5808 */
5809 SQLITE_API int sqlite3_load_extension(
5810   sqlite3 *db,          /* Load the extension into this database connection */
5811   const char *zFile,    /* Name of the shared library containing extension */
5812   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5813   char **pzErrMsg       /* Put error message here if not 0 */
5814 );
5815
5816 /*
5817 ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
5818 **
5819 ** So as not to open security holes in older applications that are
5820 ** unprepared to deal with extension loading, and as a means of disabling
5821 ** extension loading while evaluating user-entered SQL, the following API
5822 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5823 **
5824 ** Extension loading is off by default. See ticket #1863.
5825 **
5826 ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
5827 **          to turn extension loading on and call it with onoff==0 to turn
5828 **          it back off again.
5829 **
5830 ** {H12622} Extension loading is off by default.
5831 */
5832 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5833
5834 /*
5835 ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
5836 **
5837 ** This API can be invoked at program startup in order to register
5838 ** one or more statically linked extensions that will be available
5839 ** to all new [database connections]. {END}
5840 **
5841 ** This routine stores a pointer to the extension in an array that is
5842 ** obtained from [sqlite3_malloc()].  If you run a memory leak checker
5843 ** on your program and it reports a leak because of this array, invoke
5844 ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
5845 **
5846 ** {H12641} This function registers an extension entry point that is
5847 **          automatically invoked whenever a new [database connection]
5848 **          is opened using [sqlite3_open()], [sqlite3_open16()],
5849 **          or [sqlite3_open_v2()].
5850 **
5851 ** {H12642} Duplicate extensions are detected so calling this routine
5852 **          multiple times with the same extension is harmless.
5853 **
5854 ** {H12643} This routine stores a pointer to the extension in an array
5855 **          that is obtained from [sqlite3_malloc()].
5856 **
5857 ** {H12644} Automatic extensions apply across all threads.
5858 */
5859 SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
5860
5861 /*
5862 ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
5863 **
5864 ** This function disables all previously registered automatic
5865 ** extensions. {END}  It undoes the effect of all prior
5866 ** [sqlite3_auto_extension()] calls.
5867 **
5868 ** {H12661} This function disables all previously registered
5869 **          automatic extensions.
5870 **
5871 ** {H12662} This function disables automatic extensions in all threads.
5872 */
5873 SQLITE_API void sqlite3_reset_auto_extension(void);
5874
5875 /*
5876 ****** EXPERIMENTAL - subject to change without notice **************
5877 **
5878 ** The interface to the virtual-table mechanism is currently considered
5879 ** to be experimental.  The interface might change in incompatible ways.
5880 ** If this is a problem for you, do not use the interface at this time.
5881 **
5882 ** When the virtual-table mechanism stabilizes, we will declare the
5883 ** interface fixed, support it indefinitely, and remove this comment.
5884 */
5885
5886 /*
5887 ** Structures used by the virtual table interface
5888 */
5889 typedef struct sqlite3_vtab sqlite3_vtab;
5890 typedef struct sqlite3_index_info sqlite3_index_info;
5891 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5892 typedef struct sqlite3_module sqlite3_module;
5893
5894 /*
5895 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
5896 ** KEYWORDS: sqlite3_module
5897 ** EXPERIMENTAL
5898 **
5899 ** A module is a class of virtual tables.  Each module is defined
5900 ** by an instance of the following structure.  This structure consists
5901 ** mostly of methods for the module.
5902 **
5903 ** This interface is experimental and is subject to change or
5904 ** removal in future releases of SQLite.
5905 */
5906 struct sqlite3_module {
5907   int iVersion;
5908   int (*xCreate)(sqlite3*, void *pAux,
5909                int argc, const char *const*argv,
5910                sqlite3_vtab **ppVTab, char**);
5911   int (*xConnect)(sqlite3*, void *pAux,
5912                int argc, const char *const*argv,
5913                sqlite3_vtab **ppVTab, char**);
5914   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5915   int (*xDisconnect)(sqlite3_vtab *pVTab);
5916   int (*xDestroy)(sqlite3_vtab *pVTab);
5917   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5918   int (*xClose)(sqlite3_vtab_cursor*);
5919   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5920                 int argc, sqlite3_value **argv);
5921   int (*xNext)(sqlite3_vtab_cursor*);
5922   int (*xEof)(sqlite3_vtab_cursor*);
5923   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5924   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5925   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5926   int (*xBegin)(sqlite3_vtab *pVTab);
5927   int (*xSync)(sqlite3_vtab *pVTab);
5928   int (*xCommit)(sqlite3_vtab *pVTab);
5929   int (*xRollback)(sqlite3_vtab *pVTab);
5930   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5931                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5932                        void **ppArg);
5933   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5934 };
5935
5936 /*
5937 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
5938 ** KEYWORDS: sqlite3_index_info
5939 ** EXPERIMENTAL
5940 **
5941 ** The sqlite3_index_info structure and its substructures is used to
5942 ** pass information into and receive the reply from the xBestIndex
5943 ** method of an sqlite3_module.  The fields under **Inputs** are the
5944 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5945 ** results into the **Outputs** fields.
5946 **
5947 ** The aConstraint[] array records WHERE clause constraints of the form:
5948 **
5949 ** <pre>column OP expr</pre>
5950 **
5951 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
5952 ** stored in aConstraint[].op.  The index of the column is stored in
5953 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
5954 ** expr on the right-hand side can be evaluated (and thus the constraint
5955 ** is usable) and false if it cannot.
5956 **
5957 ** The optimizer automatically inverts terms of the form "expr OP column"
5958 ** and makes other simplifications to the WHERE clause in an attempt to
5959 ** get as many WHERE clause terms into the form shown above as possible.
5960 ** The aConstraint[] array only reports WHERE clause terms in the correct
5961 ** form that refer to the particular virtual table being queried.
5962 **
5963 ** Information about the ORDER BY clause is stored in aOrderBy[].
5964 ** Each term of aOrderBy records a column of the ORDER BY clause.
5965 **
5966 ** The xBestIndex method must fill aConstraintUsage[] with information
5967 ** about what parameters to pass to xFilter.  If argvIndex>0 then
5968 ** the right-hand side of the corresponding aConstraint[] is evaluated
5969 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
5970 ** is true, then the constraint is assumed to be fully handled by the
5971 ** virtual table and is not checked again by SQLite.
5972 **
5973 ** The idxNum and idxPtr values are recorded and passed into xFilter.
5974 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
5975 **
5976 ** The orderByConsumed means that output from xFilter will occur in
5977 ** the correct order to satisfy the ORDER BY clause so that no separate
5978 ** sorting step is required.
5979 **
5980 ** The estimatedCost value is an estimate of the cost of doing the
5981 ** particular lookup.  A full scan of a table with N entries should have
5982 ** a cost of N.  A binary search of a table of N entries should have a
5983 ** cost of approximately log(N).
5984 **
5985 ** This interface is experimental and is subject to change or
5986 ** removal in future releases of SQLite.
5987 */
5988 struct sqlite3_index_info {
5989   /* Inputs */
5990   int nConstraint;           /* Number of entries in aConstraint */
5991   struct sqlite3_index_constraint {
5992      int iColumn;              /* Column on left-hand side of constraint */
5993      unsigned char op;         /* Constraint operator */
5994      unsigned char usable;     /* True if this constraint is usable */
5995      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5996   } *aConstraint;            /* Table of WHERE clause constraints */
5997   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5998   struct sqlite3_index_orderby {
5999      int iColumn;              /* Column number */
6000      unsigned char desc;       /* True for DESC.  False for ASC. */
6001   } *aOrderBy;               /* The ORDER BY clause */
6002   /* Outputs */
6003   struct sqlite3_index_constraint_usage {
6004     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
6005     unsigned char omit;      /* Do not code a test for this constraint */
6006   } *aConstraintUsage;
6007   int idxNum;                /* Number used to identify the index */
6008   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
6009   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
6010   int orderByConsumed;       /* True if output is already ordered */
6011   double estimatedCost;      /* Estimated cost of using this index */
6012 };
6013 #define SQLITE_INDEX_CONSTRAINT_EQ    2
6014 #define SQLITE_INDEX_CONSTRAINT_GT    4
6015 #define SQLITE_INDEX_CONSTRAINT_LE    8
6016 #define SQLITE_INDEX_CONSTRAINT_LT    16
6017 #define SQLITE_INDEX_CONSTRAINT_GE    32
6018 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6019
6020 /*
6021 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
6022 ** EXPERIMENTAL
6023 **
6024 ** This routine is used to register a new module name with a
6025 ** [database connection].  Module names must be registered before
6026 ** creating new virtual tables on the module, or before using
6027 ** preexisting virtual tables of the module.
6028 **
6029 ** This interface is experimental and is subject to change or
6030 ** removal in future releases of SQLite.
6031 */
6032 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
6033   sqlite3 *db,               /* SQLite connection to register module with */
6034   const char *zName,         /* Name of the module */
6035   const sqlite3_module *,    /* Methods for the module */
6036   void *                     /* Client data for xCreate/xConnect */
6037 );
6038
6039 /*
6040 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
6041 ** EXPERIMENTAL
6042 **
6043 ** This routine is identical to the [sqlite3_create_module()] method above,
6044 ** except that it allows a destructor function to be specified. It is
6045 ** even more experimental than the rest of the virtual tables API.
6046 */
6047 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
6048   sqlite3 *db,               /* SQLite connection to register module with */
6049   const char *zName,         /* Name of the module */
6050   const sqlite3_module *,    /* Methods for the module */
6051   void *,                    /* Client data for xCreate/xConnect */
6052   void(*xDestroy)(void*)     /* Module destructor function */
6053 );
6054
6055 /*
6056 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
6057 ** KEYWORDS: sqlite3_vtab
6058 ** EXPERIMENTAL
6059 **
6060 ** Every module implementation uses a subclass of the following structure
6061 ** to describe a particular instance of the module.  Each subclass will
6062 ** be tailored to the specific needs of the module implementation.
6063 ** The purpose of this superclass is to define certain fields that are
6064 ** common to all module implementations.
6065 **
6066 ** Virtual tables methods can set an error message by assigning a
6067 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
6068 ** take care that any prior string is freed by a call to [sqlite3_free()]
6069 ** prior to assigning a new string to zErrMsg.  After the error message
6070 ** is delivered up to the client application, the string will be automatically
6071 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
6072 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
6073 ** since virtual tables are commonly implemented in loadable extensions which
6074 ** do not have access to sqlite3MPrintf() or sqlite3Free().
6075 **
6076 ** This interface is experimental and is subject to change or
6077 ** removal in future releases of SQLite.
6078 */
6079 struct sqlite3_vtab {
6080   const sqlite3_module *pModule;  /* The module for this virtual table */
6081   int nRef;                       /* Used internally */
6082   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
6083   /* Virtual table implementations will typically add additional fields */
6084 };
6085
6086 /*
6087 ** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
6088 ** KEYWORDS: sqlite3_vtab_cursor
6089 ** EXPERIMENTAL
6090 **
6091 ** Every module implementation uses a subclass of the following structure
6092 ** to describe cursors that point into the virtual table and are used
6093 ** to loop through the virtual table.  Cursors are created using the
6094 ** xOpen method of the module.  Each module implementation will define
6095 ** the content of a cursor structure to suit its own needs.
6096 **
6097 ** This superclass exists in order to define fields of the cursor that
6098 ** are common to all implementations.
6099 **
6100 ** This interface is experimental and is subject to change or
6101 ** removal in future releases of SQLite.
6102 */
6103 struct sqlite3_vtab_cursor {
6104   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6105   /* Virtual table implementations will typically add additional fields */
6106 };
6107
6108 /*
6109 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
6110 ** EXPERIMENTAL
6111 **
6112 ** The xCreate and xConnect methods of a module use the following API
6113 ** to declare the format (the names and datatypes of the columns) of
6114 ** the virtual tables they implement.
6115 **
6116 ** This interface is experimental and is subject to change or
6117 ** removal in future releases of SQLite.
6118 */
6119 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
6120
6121 /*
6122 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
6123 ** EXPERIMENTAL
6124 **
6125 ** Virtual tables can provide alternative implementations of functions
6126 ** using the xFindFunction method.  But global versions of those functions
6127 ** must exist in order to be overloaded.
6128 **
6129 ** This API makes sure a global version of a function with a particular
6130 ** name and number of parameters exists.  If no such function exists
6131 ** before this API is called, a new function is created.  The implementation
6132 ** of the new function always causes an exception to be thrown.  So
6133 ** the new function is not good for anything by itself.  Its only
6134 ** purpose is to be a placeholder function that can be overloaded
6135 ** by virtual tables.
6136 **
6137 ** This API should be considered part of the virtual table interface,
6138 ** which is experimental and subject to change.
6139 */
6140 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6141
6142 /*
6143 ** The interface to the virtual-table mechanism defined above (back up
6144 ** to a comment remarkably similar to this one) is currently considered
6145 ** to be experimental.  The interface might change in incompatible ways.
6146 ** If this is a problem for you, do not use the interface at this time.
6147 **
6148 ** When the virtual-table mechanism stabilizes, we will declare the
6149 ** interface fixed, support it indefinitely, and remove this comment.
6150 **
6151 ****** EXPERIMENTAL - subject to change without notice **************
6152 */
6153
6154 /*
6155 ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
6156 ** KEYWORDS: {BLOB handle} {BLOB handles}
6157 **
6158 ** An instance of this object represents an open BLOB on which
6159 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6160 ** Objects of this type are created by [sqlite3_blob_open()]
6161 ** and destroyed by [sqlite3_blob_close()].
6162 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6163 ** can be used to read or write small subsections of the BLOB.
6164 ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6165 */
6166 typedef struct sqlite3_blob sqlite3_blob;
6167
6168 /*
6169 ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
6170 **
6171 ** This interfaces opens a [BLOB handle | handle] to the BLOB located
6172 ** in row iRow, column zColumn, table zTable in database zDb;
6173 ** in other words, the same BLOB that would be selected by:
6174 **
6175 ** <pre>
6176 **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
6177 ** </pre> {END}
6178 **
6179 ** If the flags parameter is non-zero, the the BLOB is opened for read
6180 ** and write access. If it is zero, the BLOB is opened for read access.
6181 **
6182 ** Note that the database name is not the filename that contains
6183 ** the database but rather the symbolic name of the database that
6184 ** is assigned when the database is connected using [ATTACH].
6185 ** For the main database file, the database name is "main".
6186 ** For TEMP tables, the database name is "temp".
6187 **
6188 ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6189 ** to *ppBlob. Otherwise an [error code] is returned and any value written
6190 ** to *ppBlob should not be used by the caller.
6191 ** This function sets the [database connection] error code and message
6192 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
6193 **
6194 ** If the row that a BLOB handle points to is modified by an
6195 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6196 ** then the BLOB handle is marked as "expired".
6197 ** This is true if any column of the row is changed, even a column
6198 ** other than the one the BLOB handle is open on.
6199 ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6200 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
6201 ** Changes written into a BLOB prior to the BLOB expiring are not
6202 ** rollback by the expiration of the BLOB.  Such changes will eventually
6203 ** commit if the transaction continues to completion.
6204 **
6205 ** INVARIANTS:
6206 **
6207 ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
6208 **          interface shall open an [sqlite3_blob] object P on the BLOB
6209 **          in column C of the table T in the database B on
6210 **          the [database connection] D.
6211 **
6212 ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
6213 **          a new transaction on the [database connection] D if that
6214 **          connection is not already in a transaction.
6215 **
6216 ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
6217 **          the BLOB for read and write access if and only if the F
6218 **          parameter is non-zero.
6219 **
6220 ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
6221 **          success and an appropriate [error code] on failure.
6222 **
6223 ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
6224 **          then subsequent calls to [sqlite3_errcode(D)],
6225 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6226 **          information appropriate for that error.
6227 **
6228 ** {H17824} If any column in the row that a [sqlite3_blob] has open is
6229 **          changed by a separate [UPDATE] or [DELETE] statement or by
6230 **          an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
6231 **          be marked as invalid.
6232 */
6233 SQLITE_API int sqlite3_blob_open(
6234   sqlite3*,
6235   const char *zDb,
6236   const char *zTable,
6237   const char *zColumn,
6238   sqlite3_int64 iRow,
6239   int flags,
6240   sqlite3_blob **ppBlob
6241 );
6242
6243 /*
6244 ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
6245 **
6246 ** Closes an open [BLOB handle].
6247 **
6248 ** Closing a BLOB shall cause the current transaction to commit
6249 ** if there are no other BLOBs, no pending prepared statements, and the
6250 ** database connection is in [autocommit mode].
6251 ** If any writes were made to the BLOB, they might be held in cache
6252 ** until the close operation if they will fit. {END}
6253 **
6254 ** Closing the BLOB often forces the changes
6255 ** out to disk and so if any I/O errors occur, they will likely occur
6256 ** at the time when the BLOB is closed.  {H17833} Any errors that occur during
6257 ** closing are reported as a non-zero return value.
6258 **
6259 ** The BLOB is closed unconditionally.  Even if this routine returns
6260 ** an error code, the BLOB is still closed.
6261 **
6262 ** INVARIANTS:
6263 **
6264 ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
6265 **          object P previously opened using [sqlite3_blob_open()].
6266 **
6267 ** {H17836} Closing an [sqlite3_blob] object using
6268 **          [sqlite3_blob_close()] shall cause the current transaction to
6269 **          commit if there are no other open [sqlite3_blob] objects
6270 **          or [prepared statements] on the same [database connection] and
6271 **          the database connection is in [autocommit mode].
6272 **
6273 ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
6274 **          [sqlite3_blob] object P unconditionally, even if
6275 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
6276 */
6277 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6278
6279 /*
6280 ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
6281 **
6282 ** Returns the size in bytes of the BLOB accessible via the open
6283 ** []BLOB handle] in its only argument.
6284 **
6285 ** INVARIANTS:
6286 **
6287 ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
6288 **          in bytes of the BLOB that the [sqlite3_blob] object P
6289 **          refers to.
6290 */
6291 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6292
6293 /*
6294 ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
6295 **
6296 ** This function is used to read data from an open [BLOB handle] into a
6297 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6298 ** from the open BLOB, starting at offset iOffset.
6299 **
6300 ** If offset iOffset is less than N bytes from the end of the BLOB,
6301 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
6302 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6303 **
6304 ** An attempt to read from an expired [BLOB handle] fails with an
6305 ** error code of [SQLITE_ABORT].
6306 **
6307 ** On success, SQLITE_OK is returned.
6308 ** Otherwise, an [error code] or an [extended error code] is returned.
6309 **
6310 ** INVARIANTS:
6311 **
6312 ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] 
6313 **          shall reads N bytes of data out of the BLOB referenced by
6314 **          [BLOB handle] P beginning at offset X and store those bytes
6315 **          into buffer Z.
6316 **
6317 ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
6318 **          is less than N+X bytes, then the function shall leave the
6319 **          Z buffer unchanged and return [SQLITE_ERROR].
6320 **
6321 ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
6322 **          then the function shall leave the Z buffer unchanged
6323 **          and return [SQLITE_ERROR].
6324 **
6325 ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
6326 **          if N bytes are successfully read into buffer Z.
6327 **
6328 ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
6329 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
6330 **          unchanged and return [SQLITE_ABORT].
6331 **
6332 ** {H17865} If the requested read could not be completed,
6333 **          the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
6334 **          appropriate [error code] or [extended error code].
6335 **
6336 ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
6337 **          then subsequent calls to [sqlite3_errcode(D)],
6338 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6339 **          information appropriate for that error, where D is the
6340 **          [database connection] that was used to open the [BLOB handle] P.
6341 */
6342 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6343
6344 /*
6345 ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
6346 **
6347 ** This function is used to write data into an open [BLOB handle] from a
6348 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6349 ** into the open BLOB, starting at offset iOffset.
6350 **
6351 ** If the [BLOB handle] passed as the first argument was not opened for
6352 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6353 ** this function returns [SQLITE_READONLY].
6354 **
6355 ** This function may only modify the contents of the BLOB; it is
6356 ** not possible to increase the size of a BLOB using this API.
6357 ** If offset iOffset is less than N bytes from the end of the BLOB,
6358 ** [SQLITE_ERROR] is returned and no data is written.  If N is
6359 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6360 **
6361 ** An attempt to write to an expired [BLOB handle] fails with an
6362 ** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
6363 ** before the [BLOB handle] expired are not rolled back by the
6364 ** expiration of the handle, though of course those changes might
6365 ** have been overwritten by the statement that expired the BLOB handle
6366 ** or by other independent statements.
6367 **
6368 ** On success, SQLITE_OK is returned.
6369 ** Otherwise, an  [error code] or an [extended error code] is returned.
6370 **
6371 ** INVARIANTS:
6372 **
6373 ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
6374 **          shall write N bytes of data from buffer Z into the BLOB 
6375 **          referenced by [BLOB handle] P beginning at offset X into
6376 **          the BLOB.
6377 **
6378 ** {H17874} In the absence of other overridding changes, the changes
6379 **          written to a BLOB by [sqlite3_blob_write()] shall
6380 **          remain in effect after the associated [BLOB handle] expires.
6381 **
6382 ** {H17875} If the [BLOB handle] P was opened for reading only then
6383 **          an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
6384 **          the referenced BLOB unchanged and return [SQLITE_READONLY].
6385 **
6386 ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
6387 **          less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
6388 **          leave the BLOB unchanged and return [SQLITE_ERROR].
6389 **
6390 ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
6391 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
6392 **          unchanged and return [SQLITE_ABORT].
6393 **
6394 ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
6395 **          shall leave the BLOB referenced by [BLOB handle] P unchanged
6396 **          and return [SQLITE_ERROR].
6397 **
6398 ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
6399 **          [SQLITE_OK] if N bytes where successfully written into the BLOB.
6400 **
6401 ** {H17885} If the requested write could not be completed,
6402 **          the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
6403 **          appropriate [error code] or [extended error code].
6404 **
6405 ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
6406 **          then subsequent calls to [sqlite3_errcode(D)],
6407 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6408 **          information appropriate for that error.
6409 */
6410 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6411
6412 /*
6413 ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
6414 **
6415 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6416 ** that SQLite uses to interact
6417 ** with the underlying operating system.  Most SQLite builds come with a
6418 ** single default VFS that is appropriate for the host computer.
6419 ** New VFSes can be registered and existing VFSes can be unregistered.
6420 ** The following interfaces are provided.
6421 **
6422 ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6423 ** Names are case sensitive.
6424 ** Names are zero-terminated UTF-8 strings.
6425 ** If there is no match, a NULL pointer is returned.
6426 ** If zVfsName is NULL then the default VFS is returned.
6427 **
6428 ** New VFSes are registered with sqlite3_vfs_register().
6429 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
6430 ** The same VFS can be registered multiple times without injury.
6431 ** To make an existing VFS into the default VFS, register it again
6432 ** with the makeDflt flag set.  If two different VFSes with the
6433 ** same name are registered, the behavior is undefined.  If a
6434 ** VFS is registered with a name that is NULL or an empty string,
6435 ** then the behavior is undefined.
6436 **
6437 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
6438 ** If the default VFS is unregistered, another VFS is chosen as
6439 ** the default.  The choice for the new VFS is arbitrary.
6440 **
6441 ** INVARIANTS:
6442 **
6443 ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
6444 **          registered [sqlite3_vfs] object whose name exactly matches
6445 **          the zero-terminated UTF-8 string N, or it returns NULL if
6446 **          there is no match.
6447 **
6448 ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
6449 **          the function returns a pointer to the default [sqlite3_vfs]
6450 **          object if there is one, or NULL if there is no default
6451 **          [sqlite3_vfs] object.
6452 **
6453 ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
6454 **          well-formed [sqlite3_vfs] object P using the name given
6455 **          by the zName field of the object.
6456 **
6457 ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
6458 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
6459 **
6460 ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
6461 **          object P the default [sqlite3_vfs] object if F is non-zero.
6462 **
6463 ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
6464 **          [sqlite3_vfs] object P so that it is no longer returned by
6465 **          subsequent calls to [sqlite3_vfs_find()].
6466 */
6467 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6468 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6469 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6470
6471 /*
6472 ** CAPI3REF: Mutexes {H17000} <S20000>
6473 **
6474 ** The SQLite core uses these routines for thread
6475 ** synchronization. Though they are intended for internal
6476 ** use by SQLite, code that links against SQLite is
6477 ** permitted to use any of these routines.
6478 **
6479 ** The SQLite source code contains multiple implementations
6480 ** of these mutex routines.  An appropriate implementation
6481 ** is selected automatically at compile-time.  The following
6482 ** implementations are available in the SQLite core:
6483 **
6484 ** <ul>
6485 ** <li>   SQLITE_MUTEX_OS2
6486 ** <li>   SQLITE_MUTEX_PTHREAD
6487 ** <li>   SQLITE_MUTEX_W32
6488 ** <li>   SQLITE_MUTEX_NOOP
6489 ** </ul>
6490 **
6491 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6492 ** that does no real locking and is appropriate for use in
6493 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
6494 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
6495 ** are appropriate for use on OS/2, Unix, and Windows.
6496 **
6497 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6498 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6499 ** implementation is included with the library. In this case the
6500 ** application must supply a custom mutex implementation using the
6501 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6502 ** before calling sqlite3_initialize() or any other public sqlite3_
6503 ** function that calls sqlite3_initialize().
6504 **
6505 ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
6506 ** mutex and returns a pointer to it. {H17012} If it returns NULL
6507 ** that means that a mutex could not be allocated. {H17013} SQLite
6508 ** will unwind its stack and return an error. {H17014} The argument
6509 ** to sqlite3_mutex_alloc() is one of these integer constants:
6510 **
6511 ** <ul>
6512 ** <li>  SQLITE_MUTEX_FAST
6513 ** <li>  SQLITE_MUTEX_RECURSIVE
6514 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6515 ** <li>  SQLITE_MUTEX_STATIC_MEM
6516 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6517 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6518 ** <li>  SQLITE_MUTEX_STATIC_LRU
6519 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6520 ** </ul>
6521 **
6522 ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
6523 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6524 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
6525 ** The mutex implementation does not need to make a distinction
6526 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6527 ** not want to.  {H17016} But SQLite will only request a recursive mutex in
6528 ** cases where it really needs one.  {END} If a faster non-recursive mutex
6529 ** implementation is available on the host platform, the mutex subsystem
6530 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6531 **
6532 ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
6533 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
6534 ** used by the current version of SQLite.  Future versions of SQLite
6535 ** may add additional static mutexes.  Static mutexes are for internal
6536 ** use by SQLite only.  Applications that use SQLite mutexes should
6537 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6538 ** SQLITE_MUTEX_RECURSIVE.
6539 **
6540 ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6541 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6542 ** returns a different mutex on every call.  {H17034} But for the static
6543 ** mutex types, the same mutex is returned on every call that has
6544 ** the same type number.
6545 **
6546 ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
6547 ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
6548 ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
6549 ** use when they are deallocated. {A17022} Attempting to deallocate a static
6550 ** mutex results in undefined behavior. {H17023} SQLite never deallocates
6551 ** a static mutex. {END}
6552 **
6553 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6554 ** to enter a mutex. {H17024} If another thread is already within the mutex,
6555 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6556 ** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
6557 ** upon successful entry.  {H17026} Mutexes created using
6558 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6559 ** {H17027} In such cases the,
6560 ** mutex must be exited an equal number of times before another thread
6561 ** can enter.  {A17028} If the same thread tries to enter any other
6562 ** kind of mutex more than once, the behavior is undefined.
6563 ** {H17029} SQLite will never exhibit
6564 ** such behavior in its own use of mutexes.
6565 **
6566 ** Some systems (for example, Windows 95) do not support the operation
6567 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6568 ** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
6569 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
6570 **
6571 ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
6572 ** previously entered by the same thread.  {A17032} The behavior
6573 ** is undefined if the mutex is not currently entered by the
6574 ** calling thread or is not currently allocated.  {H17033} SQLite will
6575 ** never do either. {END}
6576 **
6577 ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6578 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6579 ** behave as no-ops.
6580 **
6581 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6582 */
6583 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6584 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6585 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6586 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6587 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6588
6589 /*
6590 ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
6591 ** EXPERIMENTAL
6592 **
6593 ** An instance of this structure defines the low-level routines
6594 ** used to allocate and use mutexes.
6595 **
6596 ** Usually, the default mutex implementations provided by SQLite are
6597 ** sufficient, however the user has the option of substituting a custom
6598 ** implementation for specialized deployments or systems for which SQLite
6599 ** does not provide a suitable implementation. In this case, the user
6600 ** creates and populates an instance of this structure to pass
6601 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6602 ** Additionally, an instance of this structure can be used as an
6603 ** output variable when querying the system for the current mutex
6604 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6605 **
6606 ** The xMutexInit method defined by this structure is invoked as
6607 ** part of system initialization by the sqlite3_initialize() function.
6608 ** {H17001} The xMutexInit routine shall be called by SQLite once for each
6609 ** effective call to [sqlite3_initialize()].
6610 **
6611 ** The xMutexEnd method defined by this structure is invoked as
6612 ** part of system shutdown by the sqlite3_shutdown() function. The
6613 ** implementation of this method is expected to release all outstanding
6614 ** resources obtained by the mutex methods implementation, especially
6615 ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
6616 ** interface shall be invoked once for each call to [sqlite3_shutdown()].
6617 **
6618 ** The remaining seven methods defined by this structure (xMutexAlloc,
6619 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6620 ** xMutexNotheld) implement the following interfaces (respectively):
6621 **
6622 ** <ul>
6623 **   <li>  [sqlite3_mutex_alloc()] </li>
6624 **   <li>  [sqlite3_mutex_free()] </li>
6625 **   <li>  [sqlite3_mutex_enter()] </li>
6626 **   <li>  [sqlite3_mutex_try()] </li>
6627 **   <li>  [sqlite3_mutex_leave()] </li>
6628 **   <li>  [sqlite3_mutex_held()] </li>
6629 **   <li>  [sqlite3_mutex_notheld()] </li>
6630 ** </ul>
6631 **
6632 ** The only difference is that the public sqlite3_XXX functions enumerated
6633 ** above silently ignore any invocations that pass a NULL pointer instead
6634 ** of a valid mutex handle. The implementations of the methods defined
6635 ** by this structure are not required to handle this case, the results
6636 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6637 ** (i.e. it is acceptable to provide an implementation that segfaults if
6638 ** it is passed a NULL pointer).
6639 */
6640 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6641 struct sqlite3_mutex_methods {
6642   int (*xMutexInit)(void);
6643   int (*xMutexEnd)(void);
6644   sqlite3_mutex *(*xMutexAlloc)(int);
6645   void (*xMutexFree)(sqlite3_mutex *);
6646   void (*xMutexEnter)(sqlite3_mutex *);
6647   int (*xMutexTry)(sqlite3_mutex *);
6648   void (*xMutexLeave)(sqlite3_mutex *);
6649   int (*xMutexHeld)(sqlite3_mutex *);
6650   int (*xMutexNotheld)(sqlite3_mutex *);
6651 };
6652
6653 /*
6654 ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
6655 **
6656 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6657 ** are intended for use inside assert() statements. {H17081} The SQLite core
6658 ** never uses these routines except inside an assert() and applications
6659 ** are advised to follow the lead of the core.  {H17082} The core only
6660 ** provides implementations for these routines when it is compiled
6661 ** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
6662 ** are only required to provide these routines if SQLITE_DEBUG is
6663 ** defined and if NDEBUG is not defined.
6664 **
6665 ** {H17083} These routines should return true if the mutex in their argument
6666 ** is held or not held, respectively, by the calling thread.
6667 **
6668 ** {X17084} The implementation is not required to provided versions of these
6669 ** routines that actually work. If the implementation does not provide working
6670 ** versions of these routines, it should at least provide stubs that always
6671 ** return true so that one does not get spurious assertion failures.
6672 **
6673 ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
6674 ** the routine should return 1.  {END} This seems counter-intuitive since
6675 ** clearly the mutex cannot be held if it does not exist.  But the
6676 ** the reason the mutex does not exist is because the build is not
6677 ** using mutexes.  And we do not want the assert() containing the
6678 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6679 ** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
6680 ** interface should also return 1 when given a NULL pointer.
6681 */
6682 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6683 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6684
6685 /*
6686 ** CAPI3REF: Mutex Types {H17001} <H17000>
6687 **
6688 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6689 ** which is one of these integer constants.
6690 **
6691 ** The set of static mutexes may change from one SQLite release to the
6692 ** next.  Applications that override the built-in mutex logic must be
6693 ** prepared to accommodate additional static mutexes.
6694 */
6695 #define SQLITE_MUTEX_FAST             0
6696 #define SQLITE_MUTEX_RECURSIVE        1
6697 #define SQLITE_MUTEX_STATIC_MASTER    2
6698 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6699 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
6700 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6701 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6702 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
6703
6704 /*
6705 ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
6706 **
6707 ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
6708 ** xFileControl method for the [sqlite3_io_methods] object associated
6709 ** with a particular database identified by the second argument. {H11302} The
6710 ** name of the database is the name assigned to the database by the
6711 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
6712 ** database. {H11303} To control the main database file, use the name "main"
6713 ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
6714 ** are passed directly through to the second and third parameters of
6715 ** the xFileControl method.  {H11305} The return value of the xFileControl
6716 ** method becomes the return value of this routine.
6717 **
6718 ** {H11306} If the second parameter (zDbName) does not match the name of any
6719 ** open database file, then SQLITE_ERROR is returned. {H11307} This error
6720 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6721 ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
6722 ** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
6723 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6724 ** xFileControl method. {END}
6725 **
6726 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6727 */
6728 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6729
6730 /*
6731 ** CAPI3REF: Testing Interface {H11400} <S30800>
6732 **
6733 ** The sqlite3_test_control() interface is used to read out internal
6734 ** state of SQLite and to inject faults into SQLite for testing
6735 ** purposes.  The first parameter is an operation code that determines
6736 ** the number, meaning, and operation of all subsequent parameters.
6737 **
6738 ** This interface is not for use by applications.  It exists solely
6739 ** for verifying the correct operation of the SQLite library.  Depending
6740 ** on how the SQLite library is compiled, this interface might not exist.
6741 **
6742 ** The details of the operation codes, their meanings, the parameters
6743 ** they take, and what they do are all subject to change without notice.
6744 ** Unlike most of the SQLite API, this function is not guaranteed to
6745 ** operate consistently from one release to the next.
6746 */
6747 SQLITE_API int sqlite3_test_control(int op, ...);
6748
6749 /*
6750 ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
6751 **
6752 ** These constants are the valid operation code parameters used
6753 ** as the first argument to [sqlite3_test_control()].
6754 **
6755 ** These parameters and their meanings are subject to change
6756 ** without notice.  These values are for testing purposes only.
6757 ** Applications should not use any of these parameters or the
6758 ** [sqlite3_test_control()] interface.
6759 */
6760 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6761 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6762 #define SQLITE_TESTCTRL_PRNG_RESET               7
6763 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6764 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6765 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6766
6767 /*
6768 ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
6769 ** EXPERIMENTAL
6770 **
6771 ** This interface is used to retrieve runtime status information
6772 ** about the preformance of SQLite, and optionally to reset various
6773 ** highwater marks.  The first argument is an integer code for
6774 ** the specific parameter to measure.  Recognized integer codes
6775 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
6776 ** The current value of the parameter is returned into *pCurrent.
6777 ** The highest recorded value is returned in *pHighwater.  If the
6778 ** resetFlag is true, then the highest record value is reset after
6779 ** *pHighwater is written. Some parameters do not record the highest
6780 ** value.  For those parameters
6781 ** nothing is written into *pHighwater and the resetFlag is ignored.
6782 ** Other parameters record only the highwater mark and not the current
6783 ** value.  For these latter parameters nothing is written into *pCurrent.
6784 **
6785 ** This routine returns SQLITE_OK on success and a non-zero
6786 ** [error code] on failure.
6787 **
6788 ** This routine is threadsafe but is not atomic.  This routine can
6789 ** called while other threads are running the same or different SQLite
6790 ** interfaces.  However the values returned in *pCurrent and
6791 ** *pHighwater reflect the status of SQLite at different points in time
6792 ** and it is possible that another thread might change the parameter
6793 ** in between the times when *pCurrent and *pHighwater are written.
6794 **
6795 ** See also: [sqlite3_db_status()]
6796 */
6797 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6798
6799
6800 /*
6801 ** CAPI3REF: Status Parameters {H17250} <H17200>
6802 ** EXPERIMENTAL
6803 **
6804 ** These integer constants designate various run-time status parameters
6805 ** that can be returned by [sqlite3_status()].
6806 **
6807 ** <dl>
6808 ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
6809 ** <dd>This parameter is the current amount of memory checked out
6810 ** using [sqlite3_malloc()], either directly or indirectly.  The
6811 ** figure includes calls made to [sqlite3_malloc()] by the application
6812 ** and internal memory usage by the SQLite library.  Scratch memory
6813 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6814 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6815 ** this parameter.  The amount returned is the sum of the allocation
6816 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
6817 **
6818 ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6819 ** <dd>This parameter records the largest memory allocation request
6820 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6821 ** internal equivalents).  Only the value returned in the
6822 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6823 ** The value written into the *pCurrent parameter is undefined.</dd>
6824 **
6825 ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6826 ** <dd>This parameter returns the number of pages used out of the
6827 ** [pagecache memory allocator] that was configured using 
6828 ** [SQLITE_CONFIG_PAGECACHE].  The
6829 ** value returned is in pages, not in bytes.</dd>
6830 **
6831 ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6832 ** <dd>This parameter returns the number of bytes of page cache
6833 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
6834 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6835 ** returned value includes allocations that overflowed because they
6836 ** where too large (they were larger than the "sz" parameter to
6837 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6838 ** no space was left in the page cache.</dd>
6839 **
6840 ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6841 ** <dd>This parameter records the largest memory allocation request
6842 ** handed to [pagecache memory allocator].  Only the value returned in the
6843 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6844 ** The value written into the *pCurrent parameter is undefined.</dd>
6845 **
6846 ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
6847 ** <dd>This parameter returns the number of allocations used out of the
6848 ** [scratch memory allocator] configured using
6849 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6850 ** in bytes.  Since a single thread may only have one scratch allocation
6851 ** outstanding at time, this parameter also reports the number of threads
6852 ** using scratch memory at the same time.</dd>
6853 **
6854 ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6855 ** <dd>This parameter returns the number of bytes of scratch memory
6856 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
6857 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6858 ** returned include overflows because the requested allocation was too
6859 ** larger (that is, because the requested allocation was larger than the
6860 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6861 ** slots were available.
6862 ** </dd>
6863 **
6864 ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6865 ** <dd>This parameter records the largest memory allocation request
6866 ** handed to [scratch memory allocator].  Only the value returned in the
6867 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6868 ** The value written into the *pCurrent parameter is undefined.</dd>
6869 **
6870 ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
6871 ** <dd>This parameter records the deepest parser stack.  It is only
6872 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
6873 ** </dl>
6874 **
6875 ** New status parameters may be added from time to time.
6876 */
6877 #define SQLITE_STATUS_MEMORY_USED          0
6878 #define SQLITE_STATUS_PAGECACHE_USED       1
6879 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6880 #define SQLITE_STATUS_SCRATCH_USED         3
6881 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6882 #define SQLITE_STATUS_MALLOC_SIZE          5
6883 #define SQLITE_STATUS_PARSER_STACK         6
6884 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6885 #define SQLITE_STATUS_SCRATCH_SIZE         8
6886
6887 /*
6888 ** CAPI3REF: Database Connection Status {H17500} <S60200>
6889 ** EXPERIMENTAL
6890 **
6891 ** This interface is used to retrieve runtime status information 
6892 ** about a single [database connection].  The first argument is the
6893 ** database connection object to be interrogated.  The second argument
6894 ** is the parameter to interrogate.  Currently, the only allowed value
6895 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
6896 ** Additional options will likely appear in future releases of SQLite.
6897 **
6898 ** The current value of the requested parameter is written into *pCur
6899 ** and the highest instantaneous value is written into *pHiwtr.  If
6900 ** the resetFlg is true, then the highest instantaneous value is
6901 ** reset back down to the current value.
6902 **
6903 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6904 */
6905 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6906
6907 /*
6908 ** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
6909 ** EXPERIMENTAL
6910 **
6911 ** Status verbs for [sqlite3_db_status()].
6912 **
6913 ** <dl>
6914 ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6915 ** <dd>This parameter returns the number of lookaside memory slots currently
6916 ** checked out.</dd>
6917 ** </dl>
6918 */
6919 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
6920
6921
6922 /*
6923 ** CAPI3REF: Prepared Statement Status {H17550} <S60200>
6924 ** EXPERIMENTAL
6925 **
6926 ** Each prepared statement maintains various
6927 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6928 ** of times it has performed specific operations.  These counters can
6929 ** be used to monitor the performance characteristics of the prepared
6930 ** statements.  For example, if the number of table steps greatly exceeds
6931 ** the number of table searches or result rows, that would tend to indicate
6932 ** that the prepared statement is using a full table scan rather than
6933 ** an index.  
6934 **
6935 ** This interface is used to retrieve and reset counter values from
6936 ** a [prepared statement].  The first argument is the prepared statement
6937 ** object to be interrogated.  The second argument
6938 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6939 ** to be interrogated. 
6940 ** The current value of the requested counter is returned.
6941 ** If the resetFlg is true, then the counter is reset to zero after this
6942 ** interface call returns.
6943 **
6944 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6945 */
6946 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6947
6948 /*
6949 ** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
6950 ** EXPERIMENTAL
6951 **
6952 ** These preprocessor macros define integer codes that name counter
6953 ** values associated with the [sqlite3_stmt_status()] interface.
6954 ** The meanings of the various counters are as follows:
6955 **
6956 ** <dl>
6957 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6958 ** <dd>This is the number of times that SQLite has stepped forward in
6959 ** a table as part of a full table scan.  Large numbers for this counter
6960 ** may indicate opportunities for performance improvement through 
6961 ** careful use of indices.</dd>
6962 **
6963 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6964 ** <dd>This is the number of sort operations that have occurred.
6965 ** A non-zero value in this counter may indicate an opportunity to
6966 ** improvement performance through careful use of indices.</dd>
6967 **
6968 ** </dl>
6969 */
6970 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6971 #define SQLITE_STMTSTATUS_SORT              2
6972
6973 /*
6974 ** Undo the hack that converts floating point types to integer for
6975 ** builds on processors without floating point support.
6976 */
6977 #ifdef SQLITE_OMIT_FLOATING_POINT
6978 # undef double
6979 #endif
6980
6981 #if 0
6982 }  /* End of the 'extern "C"' block */
6983 #endif
6984 #endif
6985
6986 /************** End of sqlite3.h *********************************************/
6987 /************** Continuing where we left off in sqliteInt.h ******************/
6988 /************** Include hash.h in the middle of sqliteInt.h ******************/
6989 /************** Begin file hash.h ********************************************/
6990 /*
6991 ** 2001 September 22
6992 **
6993 ** The author disclaims copyright to this source code.  In place of
6994 ** a legal notice, here is a blessing:
6995 **
6996 **    May you do good and not evil.
6997 **    May you find forgiveness for yourself and forgive others.
6998 **    May you share freely, never taking more than you give.
6999 **
7000 *************************************************************************
7001 ** This is the header file for the generic hash-table implemenation
7002 ** used in SQLite.
7003 **
7004 ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
7005 */
7006 #ifndef _SQLITE_HASH_H_
7007 #define _SQLITE_HASH_H_
7008
7009 /* Forward declarations of structures. */
7010 typedef struct Hash Hash;
7011 typedef struct HashElem HashElem;
7012
7013 /* A complete hash table is an instance of the following structure.
7014 ** The internals of this structure are intended to be opaque -- client
7015 ** code should not attempt to access or modify the fields of this structure
7016 ** directly.  Change this structure only by using the routines below.
7017 ** However, many of the "procedures" and "functions" for modifying and
7018 ** accessing this structure are really macros, so we can't really make
7019 ** this structure opaque.
7020 */
7021 struct Hash {
7022   unsigned int copyKey: 1;  /* True if copy of key made on insert */
7023   unsigned int htsize : 31; /* Number of buckets in the hash table */
7024   unsigned int count;       /* Number of entries in this table */
7025   HashElem *first;          /* The first element of the array */
7026   struct _ht {              /* the hash table */
7027     int count;                 /* Number of entries with this hash */
7028     HashElem *chain;           /* Pointer to first entry with this hash */
7029   } *ht;
7030 };
7031
7032 /* Each element in the hash table is an instance of the following 
7033 ** structure.  All elements are stored on a single doubly-linked list.
7034 **
7035 ** Again, this structure is intended to be opaque, but it can't really
7036 ** be opaque because it is used by macros.
7037 */
7038 struct HashElem {
7039   HashElem *next, *prev;   /* Next and previous elements in the table */
7040   void *data;              /* Data associated with this element */
7041   void *pKey; int nKey;    /* Key associated with this element */
7042 };
7043
7044 /*
7045 ** Access routines.  To delete, insert a NULL pointer.
7046 */
7047 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
7048 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
7049 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
7050 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
7051 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7052
7053 /*
7054 ** Macros for looping over all elements of a hash table.  The idiom is
7055 ** like this:
7056 **
7057 **   Hash h;
7058 **   HashElem *p;
7059 **   ...
7060 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7061 **     SomeStructure *pData = sqliteHashData(p);
7062 **     // do something with pData
7063 **   }
7064 */
7065 #define sqliteHashFirst(H)  ((H)->first)
7066 #define sqliteHashNext(E)   ((E)->next)
7067 #define sqliteHashData(E)   ((E)->data)
7068 #define sqliteHashKey(E)    ((E)->pKey)
7069 #define sqliteHashKeysize(E) ((E)->nKey)
7070
7071 /*
7072 ** Number of entries in a hash table
7073 */
7074 #define sqliteHashCount(H)  ((H)->count)
7075
7076 #endif /* _SQLITE_HASH_H_ */
7077
7078 /************** End of hash.h ************************************************/
7079 /************** Continuing where we left off in sqliteInt.h ******************/
7080 /************** Include parse.h in the middle of sqliteInt.h *****************/
7081 /************** Begin file parse.h *******************************************/
7082 #define TK_SEMI                            1
7083 #define TK_EXPLAIN                         2
7084 #define TK_QUERY                           3
7085 #define TK_PLAN                            4
7086 #define TK_BEGIN                           5
7087 #define TK_TRANSACTION                     6
7088 #define TK_DEFERRED                        7
7089 #define TK_IMMEDIATE                       8
7090 #define TK_EXCLUSIVE                       9
7091 #define TK_COMMIT                         10
7092 #define TK_END                            11
7093 #define TK_ROLLBACK                       12
7094 #define TK_CREATE                         13
7095 #define TK_TABLE                          14
7096 #define TK_IF                             15
7097 #define TK_NOT                            16
7098 #define TK_EXISTS                         17
7099 #define TK_TEMP                           18
7100 #define TK_LP                             19
7101 #define TK_RP                             20
7102 #define TK_AS                             21
7103 #define TK_COMMA                          22
7104 #define TK_ID                             23
7105 #define TK_ABORT                          24
7106 #define TK_AFTER                          25
7107 #define TK_ANALYZE                        26
7108 #define TK_ASC                            27
7109 #define TK_ATTACH                         28
7110 #define TK_BEFORE                         29
7111 #define TK_CASCADE                        30
7112 #define TK_CAST                           31
7113 #define TK_CONFLICT                       32
7114 #define TK_DATABASE                       33
7115 #define TK_DESC                           34
7116 #define TK_DETACH                         35
7117 #define TK_EACH                           36
7118 #define TK_FAIL                           37
7119 #define TK_FOR                            38
7120 #define TK_IGNORE                         39
7121 #define TK_INITIALLY                      40
7122 #define TK_INSTEAD                        41
7123 #define TK_LIKE_KW                        42
7124 #define TK_MATCH                          43
7125 #define TK_KEY                            44
7126 #define TK_OF                             45
7127 #define TK_OFFSET                         46
7128 #define TK_PRAGMA                         47
7129 #define TK_RAISE                          48
7130 #define TK_REPLACE                        49
7131 #define TK_RESTRICT                       50
7132 #define TK_ROW                            51
7133 #define TK_TRIGGER                        52
7134 #define TK_VACUUM                         53
7135 #define TK_VIEW                           54
7136 #define TK_VIRTUAL                        55
7137 #define TK_REINDEX                        56
7138 #define TK_RENAME                         57
7139 #define TK_CTIME_KW                       58
7140 #define TK_ANY                            59
7141 #define TK_OR                             60
7142 #define TK_AND                            61
7143 #define TK_IS                             62
7144 #define TK_BETWEEN                        63
7145 #define TK_IN                             64
7146 #define TK_ISNULL                         65
7147 #define TK_NOTNULL                        66
7148 #define TK_NE                             67
7149 #define TK_EQ                             68
7150 #define TK_GT                             69
7151 #define TK_LE                             70
7152 #define TK_LT                             71
7153 #define TK_GE                             72
7154 #define TK_ESCAPE                         73
7155 #define TK_BITAND                         74
7156 #define TK_BITOR                          75
7157 #define TK_LSHIFT                         76
7158 #define TK_RSHIFT                         77
7159 #define TK_PLUS                           78
7160 #define TK_MINUS                          79
7161 #define TK_STAR                           80
7162 #define TK_SLASH                          81
7163 #define TK_REM                            82
7164 #define TK_CONCAT                         83
7165 #define TK_COLLATE                        84
7166 #define TK_UMINUS                         85
7167 #define TK_UPLUS                          86
7168 #define TK_BITNOT                         87
7169 #define TK_STRING                         88
7170 #define TK_JOIN_KW                        89
7171 #define TK_CONSTRAINT                     90
7172 #define TK_DEFAULT                        91
7173 #define TK_NULL                           92
7174 #define TK_PRIMARY                        93
7175 #define TK_UNIQUE                         94
7176 #define TK_CHECK                          95
7177 #define TK_REFERENCES                     96
7178 #define TK_AUTOINCR                       97
7179 #define TK_ON                             98
7180 #define TK_DELETE                         99
7181 #define TK_UPDATE                         100
7182 #define TK_INSERT                         101
7183 #define TK_SET                            102
7184 #define TK_DEFERRABLE                     103
7185 #define TK_FOREIGN                        104
7186 #define TK_DROP                           105
7187 #define TK_UNION                          106
7188 #define TK_ALL                            107
7189 #define TK_EXCEPT                         108
7190 #define TK_INTERSECT                      109
7191 #define TK_SELECT                         110
7192 #define TK_DISTINCT                       111
7193 #define TK_DOT                            112
7194 #define TK_FROM                           113
7195 #define TK_JOIN                           114
7196 #define TK_INDEXED                        115
7197 #define TK_BY                             116
7198 #define TK_USING                          117
7199 #define TK_ORDER                          118
7200 #define TK_GROUP                          119
7201 #define TK_HAVING                         120
7202 #define TK_LIMIT                          121
7203 #define TK_WHERE                          122
7204 #define TK_INTO                           123
7205 #define TK_VALUES                         124
7206 #define TK_INTEGER                        125
7207 #define TK_FLOAT                          126
7208 #define TK_BLOB                           127
7209 #define TK_REGISTER                       128
7210 #define TK_VARIABLE                       129
7211 #define TK_CASE                           130
7212 #define TK_WHEN                           131
7213 #define TK_THEN                           132
7214 #define TK_ELSE                           133
7215 #define TK_INDEX                          134
7216 #define TK_ALTER                          135
7217 #define TK_TO                             136
7218 #define TK_ADD                            137
7219 #define TK_COLUMNKW                       138
7220 #define TK_TO_TEXT                        139
7221 #define TK_TO_BLOB                        140
7222 #define TK_TO_NUMERIC                     141
7223 #define TK_TO_INT                         142
7224 #define TK_TO_REAL                        143
7225 #define TK_END_OF_FILE                    144
7226 #define TK_ILLEGAL                        145
7227 #define TK_SPACE                          146
7228 #define TK_UNCLOSED_STRING                147
7229 #define TK_FUNCTION                       148
7230 #define TK_COLUMN                         149
7231 #define TK_AGG_FUNCTION                   150
7232 #define TK_AGG_COLUMN                     151
7233 #define TK_CONST_FUNC                     152
7234
7235 /************** End of parse.h ***********************************************/
7236 /************** Continuing where we left off in sqliteInt.h ******************/
7237 #include <stdio.h>
7238 #include <stdlib.h>
7239 #include <string.h>
7240 #include <assert.h>
7241 #include <stddef.h>
7242
7243 /*
7244 ** If compiling for a processor that lacks floating point support,
7245 ** substitute integer for floating-point
7246 */
7247 #ifdef SQLITE_OMIT_FLOATING_POINT
7248 # define double sqlite_int64
7249 # define LONGDOUBLE_TYPE sqlite_int64
7250 # ifndef SQLITE_BIG_DBL
7251 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
7252 # endif
7253 # define SQLITE_OMIT_DATETIME_FUNCS 1
7254 # define SQLITE_OMIT_TRACE 1
7255 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7256 #endif
7257 #ifndef SQLITE_BIG_DBL
7258 # define SQLITE_BIG_DBL (1e99)
7259 #endif
7260
7261 /*
7262 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7263 ** afterward. Having this macro allows us to cause the C compiler 
7264 ** to omit code used by TEMP tables without messy #ifndef statements.
7265 */
7266 #ifdef SQLITE_OMIT_TEMPDB
7267 #define OMIT_TEMPDB 1
7268 #else
7269 #define OMIT_TEMPDB 0
7270 #endif
7271
7272 /*
7273 ** If the following macro is set to 1, then NULL values are considered
7274 ** distinct when determining whether or not two entries are the same
7275 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
7276 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
7277 ** is the way things are suppose to work.
7278 **
7279 ** If the following macro is set to 0, the NULLs are indistinct for
7280 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
7281 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
7282 ** work.
7283 */
7284 #define NULL_DISTINCT_FOR_UNIQUE 1
7285
7286 /*
7287 ** The "file format" number is an integer that is incremented whenever
7288 ** the VDBE-level file format changes.  The following macros define the
7289 ** the default file format for new databases and the maximum file format
7290 ** that the library can read.
7291 */
7292 #define SQLITE_MAX_FILE_FORMAT 4
7293 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7294 # define SQLITE_DEFAULT_FILE_FORMAT 1
7295 #endif
7296
7297 /*
7298 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7299 ** on the command-line
7300 */
7301 #ifndef SQLITE_TEMP_STORE
7302 # define SQLITE_TEMP_STORE 1
7303 #endif
7304
7305 /*
7306 ** GCC does not define the offsetof() macro so we'll have to do it
7307 ** ourselves.
7308 */
7309 #ifndef offsetof
7310 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7311 #endif
7312
7313 /*
7314 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7315 ** not, there are still machines out there that use EBCDIC.)
7316 */
7317 #if 'A' == '\301'
7318 # define SQLITE_EBCDIC 1
7319 #else
7320 # define SQLITE_ASCII 1
7321 #endif
7322
7323 /*
7324 ** Integers of known sizes.  These typedefs might change for architectures
7325 ** where the sizes very.  Preprocessor macros are available so that the
7326 ** types can be conveniently redefined at compile-type.  Like this:
7327 **
7328 **         cc '-DUINTPTR_TYPE=long long int' ...
7329 */
7330 #ifndef UINT32_TYPE
7331 # ifdef HAVE_UINT32_T
7332 #  define UINT32_TYPE uint32_t
7333 # else
7334 #  define UINT32_TYPE unsigned int
7335 # endif
7336 #endif
7337 #ifndef UINT16_TYPE
7338 # ifdef HAVE_UINT16_T
7339 #  define UINT16_TYPE uint16_t
7340 # else
7341 #  define UINT16_TYPE unsigned short int
7342 # endif
7343 #endif
7344 #ifndef INT16_TYPE
7345 # ifdef HAVE_INT16_T
7346 #  define INT16_TYPE int16_t
7347 # else
7348 #  define INT16_TYPE short int
7349 # endif
7350 #endif
7351 #ifndef UINT8_TYPE
7352 # ifdef HAVE_UINT8_T
7353 #  define UINT8_TYPE uint8_t
7354 # else
7355 #  define UINT8_TYPE unsigned char
7356 # endif
7357 #endif
7358 #ifndef INT8_TYPE
7359 # ifdef HAVE_INT8_T
7360 #  define INT8_TYPE int8_t
7361 # else
7362 #  define INT8_TYPE signed char
7363 # endif
7364 #endif
7365 #ifndef LONGDOUBLE_TYPE
7366 # define LONGDOUBLE_TYPE long double
7367 #endif
7368 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7369 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7370 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7371 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7372 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7373 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7374 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7375
7376 /*
7377 ** Macros to determine whether the machine is big or little endian,
7378 ** evaluated at runtime.
7379 */
7380 #ifdef SQLITE_AMALGAMATION
7381 SQLITE_PRIVATE const int sqlite3one;
7382 #else
7383 SQLITE_PRIVATE const int sqlite3one;
7384 #endif
7385 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7386                              || defined(__x86_64) || defined(__x86_64__)
7387 # define SQLITE_BIGENDIAN    0
7388 # define SQLITE_LITTLEENDIAN 1
7389 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7390 #else
7391 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7392 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7393 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7394 #endif
7395
7396 /*
7397 ** Constants for the largest and smallest possible 64-bit signed integers.
7398 ** These macros are designed to work correctly on both 32-bit and 64-bit
7399 ** compilers.
7400 */
7401 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7402 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7403
7404 /*
7405 ** An instance of the following structure is used to store the busy-handler
7406 ** callback for a given sqlite handle. 
7407 **
7408 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7409 ** callback for the database handle. Each pager opened via the sqlite
7410 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7411 ** callback is currently invoked only from within pager.c.
7412 */
7413 typedef struct BusyHandler BusyHandler;
7414 struct BusyHandler {
7415   int (*xFunc)(void *,int);  /* The busy callback */
7416   void *pArg;                /* First arg to busy callback */
7417   int nBusy;                 /* Incremented with each busy call */
7418 };
7419
7420 /*
7421 ** Name of the master database table.  The master database table
7422 ** is a special table that holds the names and attributes of all
7423 ** user tables and indices.
7424 */
7425 #define MASTER_NAME       "sqlite_master"
7426 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7427
7428 /*
7429 ** The root-page of the master database table.
7430 */
7431 #define MASTER_ROOT       1
7432
7433 /*
7434 ** The name of the schema table.
7435 */
7436 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7437
7438 /*
7439 ** A convenience macro that returns the number of elements in
7440 ** an array.
7441 */
7442 #define ArraySize(X)    (sizeof(X)/sizeof(X[0]))
7443
7444 /*
7445 ** The following value as a destructor means to use sqlite3DbFree().
7446 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7447 */
7448 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7449
7450 /*
7451 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7452 ** not support Writable Static Data (WSD) such as global and static variables.
7453 ** All variables must either be on the stack or dynamically allocated from
7454 ** the heap.  When WSD is unsupported, the variable declarations scattered
7455 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7456 ** macro is used for this purpose.  And instead of referencing the variable
7457 ** directly, we use its constant as a key to lookup the run-time allocated
7458 ** buffer that holds real variable.  The constant is also the initializer
7459 ** for the run-time allocated buffer.
7460 **
7461 ** In the usually case where WSD is supported, the SQLITE_WSD and GLOBAL
7462 ** macros become no-ops and have zero performance impact.
7463 */
7464 #ifdef SQLITE_OMIT_WSD
7465   #define SQLITE_WSD const
7466   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7467   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7468 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7469 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7470 #else
7471   #define SQLITE_WSD 
7472   #define GLOBAL(t,v) v
7473   #define sqlite3GlobalConfig sqlite3Config
7474 #endif
7475
7476 /*
7477 ** Forward references to structures
7478 */
7479 typedef struct AggInfo AggInfo;
7480 typedef struct AuthContext AuthContext;
7481 typedef struct Bitvec Bitvec;
7482 typedef struct CollSeq CollSeq;
7483 typedef struct Column Column;
7484 typedef struct Db Db;
7485 typedef struct Schema Schema;
7486 typedef struct Expr Expr;
7487 typedef struct ExprList ExprList;
7488 typedef struct FKey FKey;
7489 typedef struct FuncDef FuncDef;
7490 typedef struct FuncDefHash FuncDefHash;
7491 typedef struct IdList IdList;
7492 typedef struct Index Index;
7493 typedef struct KeyClass KeyClass;
7494 typedef struct KeyInfo KeyInfo;
7495 typedef struct Lookaside Lookaside;
7496 typedef struct LookasideSlot LookasideSlot;
7497 typedef struct Module Module;
7498 typedef struct NameContext NameContext;
7499 typedef struct Parse Parse;
7500 typedef struct Select Select;
7501 typedef struct SrcList SrcList;
7502 typedef struct StrAccum StrAccum;
7503 typedef struct Table Table;
7504 typedef struct TableLock TableLock;
7505 typedef struct Token Token;
7506 typedef struct TriggerStack TriggerStack;
7507 typedef struct TriggerStep TriggerStep;
7508 typedef struct Trigger Trigger;
7509 typedef struct UnpackedRecord UnpackedRecord;
7510 typedef struct Walker Walker;
7511 typedef struct WhereInfo WhereInfo;
7512 typedef struct WhereLevel WhereLevel;
7513
7514 /*
7515 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7516 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7517 ** pointer types (i.e. FuncDef) defined above.
7518 */
7519 /************** Include btree.h in the middle of sqliteInt.h *****************/
7520 /************** Begin file btree.h *******************************************/
7521 /*
7522 ** 2001 September 15
7523 **
7524 ** The author disclaims copyright to this source code.  In place of
7525 ** a legal notice, here is a blessing:
7526 **
7527 **    May you do good and not evil.
7528 **    May you find forgiveness for yourself and forgive others.
7529 **    May you share freely, never taking more than you give.
7530 **
7531 *************************************************************************
7532 ** This header file defines the interface that the sqlite B-Tree file
7533 ** subsystem.  See comments in the source code for a detailed description
7534 ** of what each interface routine does.
7535 **
7536 ** @(#) $Id: btree.h,v 1.104 2008/10/08 17:58:49 danielk1977 Exp $
7537 */
7538 #ifndef _BTREE_H_
7539 #define _BTREE_H_
7540
7541 /* TODO: This definition is just included so other modules compile. It
7542 ** needs to be revisited.
7543 */
7544 #define SQLITE_N_BTREE_META 10
7545
7546 /*
7547 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7548 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7549 */
7550 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7551   #define SQLITE_DEFAULT_AUTOVACUUM 0
7552 #endif
7553
7554 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7555 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7556 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7557
7558 /*
7559 ** Forward declarations of structure
7560 */
7561 typedef struct Btree Btree;
7562 typedef struct BtCursor BtCursor;
7563 typedef struct BtShared BtShared;
7564 typedef struct BtreeMutexArray BtreeMutexArray;
7565
7566 /*
7567 ** This structure records all of the Btrees that need to hold
7568 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7569 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7570 ** we can always lock and unlock them all quickly.
7571 */
7572 struct BtreeMutexArray {
7573   int nMutex;
7574   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7575 };
7576
7577
7578 SQLITE_PRIVATE int sqlite3BtreeOpen(
7579   const char *zFilename,   /* Name of database file to open */
7580   sqlite3 *db,             /* Associated database connection */
7581   Btree **,                /* Return open Btree* here */
7582   int flags,               /* Flags */
7583   int vfsFlags             /* Flags passed through to VFS open */
7584 );
7585
7586 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7587 ** following values.
7588 **
7589 ** NOTE:  These values must match the corresponding PAGER_ values in
7590 ** pager.h.
7591 */
7592 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7593 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7594 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7595 #define BTREE_READONLY      8  /* Open the database in read-only mode */
7596 #define BTREE_READWRITE    16  /* Open for both reading and writing */
7597 #define BTREE_CREATE       32  /* Create the database if it does not exist */
7598
7599 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7600 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7601 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7602 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7603 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
7604 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7605 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7606 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7607 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7608 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7609 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7610 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7611 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7612 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7613 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7614 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
7615 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
7616 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
7617 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7618 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7619 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
7620 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7621 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7622 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
7623 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
7624
7625 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7626 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
7627 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7628 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7629
7630 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7631
7632 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7633 ** of the following flags:
7634 */
7635 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7636 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
7637 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7638
7639 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7640 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
7641 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
7642 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7643 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7644
7645 SQLITE_PRIVATE int sqlite3BtreeCursor(
7646   Btree*,                              /* BTree containing table to open */
7647   int iTable,                          /* Index of root page */
7648   int wrFlag,                          /* 1 for writing.  0 for read-only */
7649   struct KeyInfo*,                     /* First argument to compare function */
7650   BtCursor *pCursor                    /* Space to write cursor structure */
7651 );
7652 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7653
7654 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7655 SQLITE_PRIVATE int sqlite3BtreeMoveto(
7656   BtCursor*,
7657   const void *pKey,
7658   i64 nKey,
7659   int bias,
7660   int *pRes
7661 );
7662 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7663   BtCursor*,
7664   UnpackedRecord *pUnKey,
7665   i64 intKey,
7666   int bias,
7667   int *pRes
7668 );
7669 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7670 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7671 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7672                                   const void *pData, int nData,
7673                                   int nZero, int bias);
7674 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7675 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7676 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7677 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7678 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
7679 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7680 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7681 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7682 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
7683 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7684 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7685 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7686 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7687
7688 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7689 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7690
7691 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7692 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7693 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7694
7695 #ifdef SQLITE_TEST
7696 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7697 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7698 #endif
7699
7700 /*
7701 ** If we are not using shared cache, then there is no need to
7702 ** use mutexes to access the BtShared structures.  So make the
7703 ** Enter and Leave procedures no-ops.
7704 */
7705 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7706 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7707 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7708 #ifndef NDEBUG
7709   /* This routine is used inside assert() statements only. */
7710 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7711 #endif
7712 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7713 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7714 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7715 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7716 #ifndef NDEBUG
7717   /* This routine is used inside assert() statements only. */
7718 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7719 #endif
7720 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7721 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7722 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7723 #else
7724 # define sqlite3BtreeEnter(X)
7725 # define sqlite3BtreeLeave(X)
7726 #ifndef NDEBUG
7727   /* This routine is used inside assert() statements only. */
7728 # define sqlite3BtreeHoldsMutex(X) 1
7729 #endif
7730 # define sqlite3BtreeEnterCursor(X)
7731 # define sqlite3BtreeLeaveCursor(X)
7732 # define sqlite3BtreeEnterAll(X)
7733 # define sqlite3BtreeLeaveAll(X)
7734 #ifndef NDEBUG
7735   /* This routine is used inside assert() statements only. */
7736 # define sqlite3BtreeHoldsAllMutexes(X) 1
7737 #endif
7738 # define sqlite3BtreeMutexArrayEnter(X)
7739 # define sqlite3BtreeMutexArrayLeave(X)
7740 # define sqlite3BtreeMutexArrayInsert(X,Y)
7741 #endif
7742
7743
7744 #endif /* _BTREE_H_ */
7745
7746 /************** End of btree.h ***********************************************/
7747 /************** Continuing where we left off in sqliteInt.h ******************/
7748 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7749 /************** Begin file vdbe.h ********************************************/
7750 /*
7751 ** 2001 September 15
7752 **
7753 ** The author disclaims copyright to this source code.  In place of
7754 ** a legal notice, here is a blessing:
7755 **
7756 **    May you do good and not evil.
7757 **    May you find forgiveness for yourself and forgive others.
7758 **    May you share freely, never taking more than you give.
7759 **
7760 *************************************************************************
7761 ** Header file for the Virtual DataBase Engine (VDBE)
7762 **
7763 ** This header defines the interface to the virtual database engine
7764 ** or VDBE.  The VDBE implements an abstract machine that runs a
7765 ** simple program to access and modify the underlying database.
7766 **
7767 ** $Id: vdbe.h,v 1.138 2008/08/20 22:06:48 drh Exp $
7768 */
7769 #ifndef _SQLITE_VDBE_H_
7770 #define _SQLITE_VDBE_H_
7771
7772 /*
7773 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7774 ** in the source file sqliteVdbe.c are allowed to see the insides
7775 ** of this structure.
7776 */
7777 typedef struct Vdbe Vdbe;
7778
7779 /*
7780 ** The names of the following types declared in vdbeInt.h are required
7781 ** for the VdbeOp definition.
7782 */
7783 typedef struct VdbeFunc VdbeFunc;
7784 typedef struct Mem Mem;
7785
7786 /*
7787 ** A single instruction of the virtual machine has an opcode
7788 ** and as many as three operands.  The instruction is recorded
7789 ** as an instance of the following structure:
7790 */
7791 struct VdbeOp {
7792   u8 opcode;          /* What operation to perform */
7793   signed char p4type; /* One of the P4_xxx constants for p4 */
7794   u8 opflags;         /* Not currently used */
7795   u8 p5;              /* Fifth parameter is an unsigned character */
7796   int p1;             /* First operand */
7797   int p2;             /* Second parameter (often the jump destination) */
7798   int p3;             /* The third parameter */
7799   union {             /* forth parameter */
7800     int i;                 /* Integer value if p4type==P4_INT32 */
7801     void *p;               /* Generic pointer */
7802     char *z;               /* Pointer to data for string (char array) types */
7803     i64 *pI64;             /* Used when p4type is P4_INT64 */
7804     double *pReal;         /* Used when p4type is P4_REAL */
7805     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7806     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7807     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7808     Mem *pMem;             /* Used when p4type is P4_MEM */
7809     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
7810     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7811     int *ai;               /* Used when p4type is P4_INTARRAY */
7812   } p4;
7813 #ifdef SQLITE_DEBUG
7814   char *zComment;          /* Comment to improve readability */
7815 #endif
7816 #ifdef VDBE_PROFILE
7817   int cnt;                 /* Number of times this instruction was executed */
7818   u64 cycles;              /* Total time spent executing this instruction */
7819 #endif
7820 };
7821 typedef struct VdbeOp VdbeOp;
7822
7823 /*
7824 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7825 ** it takes up less space.
7826 */
7827 struct VdbeOpList {
7828   u8 opcode;          /* What operation to perform */
7829   signed char p1;     /* First operand */
7830   signed char p2;     /* Second parameter (often the jump destination) */
7831   signed char p3;     /* Third parameter */
7832 };
7833 typedef struct VdbeOpList VdbeOpList;
7834
7835 /*
7836 ** Allowed values of VdbeOp.p3type
7837 */
7838 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7839 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7840 #define P4_STATIC   (-2)  /* Pointer to a static string */
7841 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7842 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7843 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7844 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7845 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7846 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7847 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7848 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7849 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7850 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7851 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7852 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7853
7854 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7855 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7856 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7857 ** gets freed when the Vdbe is finalized so it still should be obtained
7858 ** from a single sqliteMalloc().  But no copy is made and the calling
7859 ** function should *not* try to free the KeyInfo.
7860 */
7861 #define P4_KEYINFO_HANDOFF (-16)
7862 #define P4_KEYINFO_STATIC  (-17)
7863
7864 /*
7865 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7866 ** number of columns of data returned by the statement.
7867 */
7868 #define COLNAME_NAME     0
7869 #define COLNAME_DECLTYPE 1
7870 #define COLNAME_DATABASE 2
7871 #define COLNAME_TABLE    3
7872 #define COLNAME_COLUMN   4
7873 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7874 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7875 #else
7876 # ifdef SQLITE_OMIT_DECLTYPE
7877 #   define COLNAME_N      1      /* Store only the name */
7878 # else
7879 #   define COLNAME_N      2      /* Store the name and decltype */
7880 # endif
7881 #endif
7882
7883 /*
7884 ** The following macro converts a relative address in the p2 field
7885 ** of a VdbeOp structure into a negative number so that 
7886 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7887 ** the macro again restores the address.
7888 */
7889 #define ADDR(X)  (-1-(X))
7890
7891 /*
7892 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7893 ** header file that defines a number for each opcode used by the VDBE.
7894 */
7895 /************** Include opcodes.h in the middle of vdbe.h ********************/
7896 /************** Begin file opcodes.h *****************************************/
7897 /* Automatically generated.  Do not edit */
7898 /* See the mkopcodeh.awk script for details */
7899 #define OP_VNext                                1
7900 #define OP_Affinity                             2
7901 #define OP_Column                               3
7902 #define OP_SetCookie                            4
7903 #define OP_Real                               126   /* same as TK_FLOAT    */
7904 #define OP_Sequence                             5
7905 #define OP_MoveGt                               6
7906 #define OP_Ge                                  72   /* same as TK_GE       */
7907 #define OP_RowKey                               7
7908 #define OP_SCopy                                8
7909 #define OP_Eq                                  68   /* same as TK_EQ       */
7910 #define OP_OpenWrite                            9
7911 #define OP_NotNull                             66   /* same as TK_NOTNULL  */
7912 #define OP_If                                  10
7913 #define OP_ToInt                              142   /* same as TK_TO_INT   */
7914 #define OP_String8                             88   /* same as TK_STRING   */
7915 #define OP_VRowid                              11
7916 #define OP_CollSeq                             12
7917 #define OP_OpenRead                            13
7918 #define OP_Expire                              14
7919 #define OP_AutoCommit                          15
7920 #define OP_Gt                                  69   /* same as TK_GT       */
7921 #define OP_Pagecount                           17
7922 #define OP_IntegrityCk                         18
7923 #define OP_Sort                                19
7924 #define OP_Copy                                20
7925 #define OP_Trace                               21
7926 #define OP_Function                            22
7927 #define OP_IfNeg                               23
7928 #define OP_And                                 61   /* same as TK_AND      */
7929 #define OP_Subtract                            79   /* same as TK_MINUS    */
7930 #define OP_Noop                                24
7931 #define OP_Return                              25
7932 #define OP_Remainder                           82   /* same as TK_REM      */
7933 #define OP_NewRowid                            26
7934 #define OP_Multiply                            80   /* same as TK_STAR     */
7935 #define OP_Variable                            27
7936 #define OP_String                              28
7937 #define OP_RealAffinity                        29
7938 #define OP_VRename                             30
7939 #define OP_ParseSchema                         31
7940 #define OP_VOpen                               32
7941 #define OP_Close                               33
7942 #define OP_CreateIndex                         34
7943 #define OP_IsUnique                            35
7944 #define OP_NotFound                            36
7945 #define OP_Int64                               37
7946 #define OP_MustBeInt                           38
7947 #define OP_Halt                                39
7948 #define OP_Rowid                               40
7949 #define OP_IdxLT                               41
7950 #define OP_AddImm                              42
7951 #define OP_Statement                           43
7952 #define OP_RowData                             44
7953 #define OP_MemMax                              45
7954 #define OP_Or                                  60   /* same as TK_OR       */
7955 #define OP_NotExists                           46
7956 #define OP_Gosub                               47
7957 #define OP_Divide                              81   /* same as TK_SLASH    */
7958 #define OP_Integer                             48
7959 #define OP_ToNumeric                          141   /* same as TK_TO_NUMERIC*/
7960 #define OP_Prev                                49
7961 #define OP_Concat                              83   /* same as TK_CONCAT   */
7962 #define OP_BitAnd                              74   /* same as TK_BITAND   */
7963 #define OP_VColumn                             50
7964 #define OP_CreateTable                         51
7965 #define OP_Last                                52
7966 #define OP_IsNull                              65   /* same as TK_ISNULL   */
7967 #define OP_IncrVacuum                          53
7968 #define OP_IdxRowid                            54
7969 #define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
7970 #define OP_ResetCount                          55
7971 #define OP_FifoWrite                           56
7972 #define OP_ContextPush                         57
7973 #define OP_Yield                               58
7974 #define OP_DropTrigger                         59
7975 #define OP_DropIndex                           62
7976 #define OP_IdxGE                               63
7977 #define OP_IdxDelete                           64
7978 #define OP_Vacuum                              73
7979 #define OP_MoveLe                              84
7980 #define OP_IfNot                               85
7981 #define OP_DropTable                           86
7982 #define OP_MakeRecord                          89
7983 #define OP_ToBlob                             140   /* same as TK_TO_BLOB  */
7984 #define OP_ResultRow                           90
7985 #define OP_Delete                              91
7986 #define OP_AggFinal                            92
7987 #define OP_Compare                             93
7988 #define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
7989 #define OP_Goto                                94
7990 #define OP_TableLock                           95
7991 #define OP_FifoRead                            96
7992 #define OP_Clear                               97
7993 #define OP_MoveLt                              98
7994 #define OP_Le                                  70   /* same as TK_LE       */
7995 #define OP_VerifyCookie                        99
7996 #define OP_AggStep                            100
7997 #define OP_ToText                             139   /* same as TK_TO_TEXT  */
7998 #define OP_Not                                 16   /* same as TK_NOT      */
7999 #define OP_ToReal                             143   /* same as TK_TO_REAL  */
8000 #define OP_SetNumColumns                      101
8001 #define OP_Transaction                        102
8002 #define OP_VFilter                            103
8003 #define OP_Ne                                  67   /* same as TK_NE       */
8004 #define OP_VDestroy                           104
8005 #define OP_ContextPop                         105
8006 #define OP_BitOr                               75   /* same as TK_BITOR    */
8007 #define OP_Next                               106
8008 #define OP_IdxInsert                          107
8009 #define OP_Lt                                  71   /* same as TK_LT       */
8010 #define OP_Insert                             108
8011 #define OP_Destroy                            109
8012 #define OP_ReadCookie                         110
8013 #define OP_ForceInt                           111
8014 #define OP_LoadAnalysis                       112
8015 #define OP_Explain                            113
8016 #define OP_OpenPseudo                         114
8017 #define OP_OpenEphemeral                      115
8018 #define OP_Null                               116
8019 #define OP_Move                               117
8020 #define OP_Blob                               118
8021 #define OP_Add                                 78   /* same as TK_PLUS     */
8022 #define OP_Rewind                             119
8023 #define OP_MoveGe                             120
8024 #define OP_VBegin                             121
8025 #define OP_VUpdate                            122
8026 #define OP_IfZero                             123
8027 #define OP_BitNot                              87   /* same as TK_BITNOT   */
8028 #define OP_VCreate                            124
8029 #define OP_Found                              125
8030 #define OP_IfPos                              127
8031 #define OP_NullRow                            128
8032 #define OP_Jump                               129
8033 #define OP_Permutation                        130
8034
8035 /* The following opcode values are never used */
8036 #define OP_NotUsed_131                        131
8037 #define OP_NotUsed_132                        132
8038 #define OP_NotUsed_133                        133
8039 #define OP_NotUsed_134                        134
8040 #define OP_NotUsed_135                        135
8041 #define OP_NotUsed_136                        136
8042 #define OP_NotUsed_137                        137
8043 #define OP_NotUsed_138                        138
8044
8045
8046 /* Properties such as "out2" or "jump" that are specified in
8047 ** comments following the "case" for each opcode in the vdbe.c
8048 ** are encoded into bitvectors as follows:
8049 */
8050 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8051 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8052 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8053 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8054 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8055 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
8056 #define OPFLG_INITIALIZER {\
8057 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\
8058 /*   8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\
8059 /*  16 */ 0x04, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,\
8060 /*  24 */ 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00,\
8061 /*  32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
8062 /*  40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
8063 /*  48 */ 0x02, 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8064 /*  56 */ 0x04, 0x00, 0x00, 0x00, 0x2c, 0x2c, 0x00, 0x11,\
8065 /*  64 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8066 /*  72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
8067 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x11, 0x05, 0x00, 0x04,\
8068 /*  88 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,\
8069 /*  96 */ 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01,\
8070 /* 104 */ 0x00, 0x00, 0x01, 0x08, 0x00, 0x02, 0x02, 0x05,\
8071 /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x01,\
8072 /* 120 */ 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x02, 0x05,\
8073 /* 128 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8074 /* 136 */ 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,\
8075 }
8076
8077 /************** End of opcodes.h *********************************************/
8078 /************** Continuing where we left off in vdbe.h ***********************/
8079
8080 /*
8081 ** Prototypes for the VDBE interface.  See comments on the implementation
8082 ** for a description of what each of these routines does.
8083 */
8084 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8085 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8086 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8087 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8088 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8089 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8090 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8091 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8092 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8093 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8094 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8095 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8096 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8097 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8098 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8099 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8100 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8101 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8102 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
8103 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8104 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8105 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8106 #ifdef SQLITE_DEBUG
8107 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8108 #endif
8109 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8110 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8111 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8112 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
8113 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8114 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8115 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
8116 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8117
8118 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8119 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
8120 #endif
8121 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,
8122                                         UnpackedRecord*,int);
8123 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8124 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8125
8126
8127 #ifndef NDEBUG
8128 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8129 # define VdbeComment(X)  sqlite3VdbeComment X
8130 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8131 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8132 #else
8133 # define VdbeComment(X)
8134 # define VdbeNoopComment(X)
8135 #endif
8136
8137 #endif
8138
8139 /************** End of vdbe.h ************************************************/
8140 /************** Continuing where we left off in sqliteInt.h ******************/
8141 /************** Include pager.h in the middle of sqliteInt.h *****************/
8142 /************** Begin file pager.h *******************************************/
8143 /*
8144 ** 2001 September 15
8145 **
8146 ** The author disclaims copyright to this source code.  In place of
8147 ** a legal notice, here is a blessing:
8148 **
8149 **    May you do good and not evil.
8150 **    May you find forgiveness for yourself and forgive others.
8151 **    May you share freely, never taking more than you give.
8152 **
8153 *************************************************************************
8154 ** This header file defines the interface that the sqlite page cache
8155 ** subsystem.  The page cache subsystem reads and writes a file a page
8156 ** at a time and provides a journal for rollback.
8157 **
8158 ** @(#) $Id: pager.h,v 1.85 2008/09/29 11:49:48 danielk1977 Exp $
8159 */
8160
8161 #ifndef _PAGER_H_
8162 #define _PAGER_H_
8163
8164 /*
8165 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8166 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8167 */
8168 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8169   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8170 #endif
8171
8172 /*
8173 ** The type used to represent a page number.  The first page in a file
8174 ** is called page 1.  0 is used to represent "not a page".
8175 */
8176 typedef u32 Pgno;
8177
8178 /*
8179 ** Each open file is managed by a separate instance of the "Pager" structure.
8180 */
8181 typedef struct Pager Pager;
8182
8183 /*
8184 ** Handle type for pages.
8185 */
8186 typedef struct PgHdr DbPage;
8187
8188 /*
8189 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8190 **
8191 ** NOTE: This values must match the corresponding BTREE_ values in btree.h.
8192 */
8193 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8194 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8195
8196 /*
8197 ** Valid values for the second argument to sqlite3PagerLockingMode().
8198 */
8199 #define PAGER_LOCKINGMODE_QUERY      -1
8200 #define PAGER_LOCKINGMODE_NORMAL      0
8201 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8202
8203 /*
8204 ** Valid values for the second argument to sqlite3PagerJournalMode().
8205 */
8206 #define PAGER_JOURNALMODE_QUERY      -1
8207 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8208 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8209 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8210 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8211
8212 /*
8213 ** See source code comments for a detailed description of the following
8214 ** routines:
8215 */
8216 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
8217 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
8218 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
8219 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
8220 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8221 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8222 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8223 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8224 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8225 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8226 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8227 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8228 SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
8229 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
8230 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8231 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
8232 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
8233 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
8234 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int);
8235 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8236 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8237 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
8238 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
8239 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
8240 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
8241 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
8242 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage*);
8243 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8244 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
8245 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8246 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8247 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8248 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
8249 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8250 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8251 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8252 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8253 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8254 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8255 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
8256 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8257 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8258 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8259
8260 #ifdef SQLITE_HAS_CODEC
8261 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
8262 #endif
8263
8264 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8265 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8266 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8267 #endif
8268
8269 #ifdef SQLITE_TEST
8270 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8271 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8272 SQLITE_PRIVATE   int sqlite3PagerIsMemdb(Pager*);
8273 #endif
8274
8275 #ifdef SQLITE_TEST
8276 void disable_simulated_io_errors(void);
8277 void enable_simulated_io_errors(void);
8278 #else
8279 # define disable_simulated_io_errors()
8280 # define enable_simulated_io_errors()
8281 #endif
8282
8283 #endif /* _PAGER_H_ */
8284
8285 /************** End of pager.h ***********************************************/
8286 /************** Continuing where we left off in sqliteInt.h ******************/
8287 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8288 /************** Begin file pcache.h ******************************************/
8289 /*
8290 ** 2008 August 05
8291 **
8292 ** The author disclaims copyright to this source code.  In place of
8293 ** a legal notice, here is a blessing:
8294 **
8295 **    May you do good and not evil.
8296 **    May you find forgiveness for yourself and forgive others.
8297 **    May you share freely, never taking more than you give.
8298 **
8299 *************************************************************************
8300 ** This header file defines the interface that the sqlite page cache
8301 ** subsystem. 
8302 **
8303 ** @(#) $Id: pcache.h,v 1.13 2008/10/11 17:42:29 drh Exp $
8304 */
8305
8306 #ifndef _PCACHE_H_
8307
8308 typedef struct PgHdr PgHdr;
8309 typedef struct PCache PCache;
8310
8311 /*
8312 ** Every page in the cache is controlled by an instance of the following
8313 ** structure.
8314 */
8315 struct PgHdr {
8316   void *pData;                   /* Content of this page */
8317   void *pExtra;                  /* Extra content */
8318   PgHdr *pDirty;                 /* Transient list of dirty pages */
8319   Pgno pgno;                     /* Page number for this page */
8320   Pager *pPager;                 /* The pager this page is part of */
8321 #ifdef SQLITE_CHECK_PAGES
8322   u32 pageHash;                  /* Hash of page content */
8323 #endif
8324   u16 flags;                     /* PGHDR flags defined below */
8325   /**********************************************************************
8326   ** Elements above are public.  All that follows is private to pcache.c
8327   ** and should not be accessed by other modules.
8328   */
8329   i16 nRef;                      /* Number of users of this page */
8330   PCache *pCache;                /* Cache that owns this page */
8331   void *apSave[2];               /* Journal entries for in-memory databases */
8332   /**********************************************************************
8333   ** Elements above are accessible at any time by the owner of the cache
8334   ** without the need for a mutex.  The elements that follow can only be
8335   ** accessed while holding the SQLITE_MUTEX_STATIC_LRU mutex.
8336   */
8337   PgHdr *pNextHash, *pPrevHash;  /* Hash collision chain for PgHdr.pgno */
8338   PgHdr *pNext, *pPrev;          /* List of clean or dirty pages */
8339   PgHdr *pNextLru, *pPrevLru;    /* Part of global LRU list */
8340 };
8341
8342 /* Bit values for PgHdr.flags */
8343 #define PGHDR_IN_JOURNAL        0x001  /* Page is in rollback journal */
8344 #define PGHDR_DIRTY             0x002  /* Page has changed */
8345 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8346                                        ** writing this page to the database */
8347 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8348 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8349 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8350
8351 /* Initialize and shutdown the page cache subsystem */
8352 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8353 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8354
8355 /* Page cache buffer management:
8356 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8357 */
8358 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8359 SQLITE_PRIVATE void *sqlite3PCacheMalloc(int sz);
8360 SQLITE_PRIVATE void sqlite3PCacheFree(void*);
8361
8362 /* Create a new pager cache.
8363 ** Under memory stress, invoke xStress to try to make pages clean.
8364 ** Only clean and unpinned pages can be reclaimed.
8365 */
8366 SQLITE_PRIVATE void sqlite3PcacheOpen(
8367   int szPage,                    /* Size of every page */
8368   int szExtra,                   /* Extra space associated with each page */
8369   int bPurgeable,                /* True if pages are on backing store */
8370   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8371   void *pStress,                 /* Argument to xStress */
8372   PCache *pToInit                /* Preallocated space for the PCache */
8373 );
8374
8375 /* Modify the page-size after the cache has been created. */
8376 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8377
8378 /* Return the size in bytes of a PCache object.  Used to preallocate
8379 ** storage space.
8380 */
8381 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8382
8383 /* One release per successful fetch.  Page is pinned until released.
8384 ** Reference counted. 
8385 */
8386 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8387 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8388
8389 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8390 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8391 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8392 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8393
8394 /* Change a page number.  Used by incr-vacuum. */
8395 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8396
8397 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8398 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8399
8400 /* Routines used to implement transactions on memory-only databases. */
8401 SQLITE_PRIVATE int sqlite3PcachePreserve(PgHdr*, int);    /* Preserve current page content */
8402 SQLITE_PRIVATE void sqlite3PcacheCommit(PCache*, int);    /* Drop preserved copy */
8403 SQLITE_PRIVATE void sqlite3PcacheRollback(PCache*, int, void (*xReiniter)(PgHdr*));
8404
8405 /* Get a list of all dirty pages in the cache, sorted by page number */
8406 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8407
8408 /* Reset and close the cache object */
8409 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8410
8411 /* Clear flags from pages of the page cache */
8412 SQLITE_PRIVATE void sqlite3PcacheClearFlags(PCache*, int mask);
8413
8414 /* Assert flags settings on all pages.  Debugging only */
8415 #ifndef NDEBUG
8416 SQLITE_PRIVATE   void sqlite3PcacheAssertFlags(PCache*, int trueMask, int falseMask);
8417 #else
8418 # define sqlite3PcacheAssertFlags(A,B,C)
8419 #endif
8420
8421 /* Return true if the number of dirty pages is 0 or 1 */
8422 SQLITE_PRIVATE int sqlite3PcacheZeroOrOneDirtyPages(PCache*);
8423
8424 /* Discard the contents of the cache */
8425 SQLITE_PRIVATE int sqlite3PcacheClear(PCache*);
8426
8427 /* Return the total number of outstanding page references */
8428 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8429
8430 /* Increment the reference count of an existing page */
8431 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8432
8433 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8434
8435 /* Return the total number of pages stored in the cache */
8436 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8437
8438 #ifdef SQLITE_CHECK_PAGES
8439 /* Iterate through all pages currently stored in the cache. This interface
8440 ** is only available if SQLITE_CHECK_PAGES is defined when the library is 
8441 ** built.
8442 */
8443 SQLITE_PRIVATE void sqlite3PcacheIterate(PCache *pCache, void (*xIter)(PgHdr *));
8444 #endif
8445
8446 /* Set and get the suggested cache-size for the specified pager-cache.
8447 **
8448 ** If no global maximum is configured, then the system attempts to limit
8449 ** the total number of pages cached by purgeable pager-caches to the sum
8450 ** of the suggested cache-sizes.
8451 */
8452 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8453 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8454
8455 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8456 /* Try to return memory used by the pcache module to the main memory heap */
8457 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8458 #endif
8459
8460 #ifdef SQLITE_TEST
8461 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8462 #endif
8463
8464 #endif /* _PCACHE_H_ */
8465
8466 /************** End of pcache.h **********************************************/
8467 /************** Continuing where we left off in sqliteInt.h ******************/
8468
8469 /************** Include os.h in the middle of sqliteInt.h ********************/
8470 /************** Begin file os.h **********************************************/
8471 /*
8472 ** 2001 September 16
8473 **
8474 ** The author disclaims copyright to this source code.  In place of
8475 ** a legal notice, here is a blessing:
8476 **
8477 **    May you do good and not evil.
8478 **    May you find forgiveness for yourself and forgive others.
8479 **    May you share freely, never taking more than you give.
8480 **
8481 ******************************************************************************
8482 **
8483 ** This header file (together with is companion C source-code file
8484 ** "os.c") attempt to abstract the underlying operating system so that
8485 ** the SQLite library will work on both POSIX and windows systems.
8486 **
8487 ** This header file is #include-ed by sqliteInt.h and thus ends up
8488 ** being included by every source file.
8489 **
8490 ** $Id: os.h,v 1.105 2008/06/26 10:41:19 danielk1977 Exp $
8491 */
8492 #ifndef _SQLITE_OS_H_
8493 #define _SQLITE_OS_H_
8494
8495 /*
8496 ** Figure out if we are dealing with Unix, Windows, or some other
8497 ** operating system.  After the following block of preprocess macros,
8498 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8499 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8500 ** three will be 0.
8501 */
8502 #if defined(SQLITE_OS_OTHER)
8503 # if SQLITE_OS_OTHER==1
8504 #   undef SQLITE_OS_UNIX
8505 #   define SQLITE_OS_UNIX 0
8506 #   undef SQLITE_OS_WIN
8507 #   define SQLITE_OS_WIN 0
8508 #   undef SQLITE_OS_OS2
8509 #   define SQLITE_OS_OS2 0
8510 # else
8511 #   undef SQLITE_OS_OTHER
8512 # endif
8513 #endif
8514 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8515 # define SQLITE_OS_OTHER 0
8516 # ifndef SQLITE_OS_WIN
8517 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8518 #     define SQLITE_OS_WIN 1
8519 #     define SQLITE_OS_UNIX 0
8520 #     define SQLITE_OS_OS2 0
8521 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8522 #     define SQLITE_OS_WIN 0
8523 #     define SQLITE_OS_UNIX 0
8524 #     define SQLITE_OS_OS2 1
8525 #   else
8526 #     define SQLITE_OS_WIN 0
8527 #     define SQLITE_OS_UNIX 1
8528 #     define SQLITE_OS_OS2 0
8529 #  endif
8530 # else
8531 #  define SQLITE_OS_UNIX 0
8532 #  define SQLITE_OS_OS2 0
8533 # endif
8534 #else
8535 # ifndef SQLITE_OS_WIN
8536 #  define SQLITE_OS_WIN 0
8537 # endif
8538 #endif
8539
8540 /*
8541 ** Determine if we are dealing with WindowsCE - which has a much
8542 ** reduced API.
8543 */
8544 #if defined(_WIN32_WCE)
8545 # define SQLITE_OS_WINCE 1
8546 #else
8547 # define SQLITE_OS_WINCE 0
8548 #endif
8549
8550
8551 /*
8552 ** Define the maximum size of a temporary filename
8553 */
8554 #if SQLITE_OS_WIN
8555 # include <windows.h>
8556 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8557 #elif SQLITE_OS_OS2
8558 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8559 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8560 # endif
8561 # define INCL_DOSDATETIME
8562 # define INCL_DOSFILEMGR
8563 # define INCL_DOSERRORS
8564 # define INCL_DOSMISC
8565 # define INCL_DOSPROCESS
8566 # define INCL_DOSMODULEMGR
8567 # define INCL_DOSSEMAPHORES
8568 # include <os2.h>
8569 # include <uconv.h>
8570 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8571 #else
8572 # define SQLITE_TEMPNAME_SIZE 200
8573 #endif
8574
8575 /* If the SET_FULLSYNC macro is not defined above, then make it
8576 ** a no-op
8577 */
8578 #ifndef SET_FULLSYNC
8579 # define SET_FULLSYNC(x,y)
8580 #endif
8581
8582 /*
8583 ** The default size of a disk sector
8584 */
8585 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8586 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8587 #endif
8588
8589 /*
8590 ** Temporary files are named starting with this prefix followed by 16 random
8591 ** alphanumeric characters, and no file extension. They are stored in the
8592 ** OS's standard temporary file directory, and are deleted prior to exit.
8593 ** If sqlite is being embedded in another program, you may wish to change the
8594 ** prefix to reflect your program's name, so that if your program exits
8595 ** prematurely, old temporary files can be easily identified. This can be done
8596 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8597 **
8598 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8599 ** Mcafee started using SQLite in their anti-virus product and it
8600 ** started putting files with the "sqlite" name in the c:/temp folder.
8601 ** This annoyed many windows users.  Those users would then do a 
8602 ** Google search for "sqlite", find the telephone numbers of the
8603 ** developers and call to wake them up at night and complain.
8604 ** For this reason, the default name prefix is changed to be "sqlite" 
8605 ** spelled backwards.  So the temp files are still identified, but
8606 ** anybody smart enough to figure out the code is also likely smart
8607 ** enough to know that calling the developer will not help get rid
8608 ** of the file.
8609 */
8610 #ifndef SQLITE_TEMP_FILE_PREFIX
8611 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8612 #endif
8613
8614 /*
8615 ** The following values may be passed as the second argument to
8616 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8617 **
8618 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8619 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8620 **            any time. Other processes may hold and obtain new SHARED locks.
8621 ** PENDING:   A single process may hold a PENDING lock on a file at
8622 **            any one time. Existing SHARED locks may persist, but no new
8623 **            SHARED locks may be obtained by other processes.
8624 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8625 **
8626 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8627 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8628 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8629 ** sqlite3OsLock().
8630 */
8631 #define NO_LOCK         0
8632 #define SHARED_LOCK     1
8633 #define RESERVED_LOCK   2
8634 #define PENDING_LOCK    3
8635 #define EXCLUSIVE_LOCK  4
8636
8637 /*
8638 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8639 **
8640 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8641 ** those functions are not available.  So we use only LockFile() and
8642 ** UnlockFile().
8643 **
8644 ** LockFile() prevents not just writing but also reading by other processes.
8645 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8646 ** byte out of a specific range of bytes. The lock byte is obtained at 
8647 ** random so two separate readers can probably access the file at the 
8648 ** same time, unless they are unlucky and choose the same lock byte.
8649 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8650 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8651 ** a single byte of the file that is designated as the reserved lock byte.
8652 ** A PENDING_LOCK is obtained by locking a designated byte different from
8653 ** the RESERVED_LOCK byte.
8654 **
8655 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8656 ** which means we can use reader/writer locks.  When reader/writer locks
8657 ** are used, the lock is placed on the same range of bytes that is used
8658 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8659 ** will support two or more Win95 readers or two or more WinNT readers.
8660 ** But a single Win95 reader will lock out all WinNT readers and a single
8661 ** WinNT reader will lock out all other Win95 readers.
8662 **
8663 ** The following #defines specify the range of bytes used for locking.
8664 ** SHARED_SIZE is the number of bytes available in the pool from which
8665 ** a random byte is selected for a shared lock.  The pool of bytes for
8666 ** shared locks begins at SHARED_FIRST. 
8667 **
8668 ** These #defines are available in sqlite_aux.h so that adaptors for
8669 ** connecting SQLite to other operating systems can use the same byte
8670 ** ranges for locking.  In particular, the same locking strategy and
8671 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8672 ** clients on win95, winNT, and unix all talking to the same shared file
8673 ** and all locking correctly.  To do so would require that samba (or whatever
8674 ** tool is being used for file sharing) implements locks correctly between
8675 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8676 ** using the same locking range we are at least open to the possibility.
8677 **
8678 ** Locking in windows is manditory.  For this reason, we cannot store
8679 ** actual data in the bytes used for locking.  The pager never allocates
8680 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8681 ** that all locks will fit on a single page even at the minimum page size.
8682 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8683 ** is set high so that we don't have to allocate an unused page except
8684 ** for very large databases.  But one should test the page skipping logic 
8685 ** by setting PENDING_BYTE low and running the entire regression suite.
8686 **
8687 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8688 ** file format.  Depending on how it is changed, you might not notice
8689 ** the incompatibility right away, even running a full regression test.
8690 ** The default location of PENDING_BYTE is the first byte past the
8691 ** 1GB boundary.
8692 **
8693 */
8694 #ifndef SQLITE_TEST
8695 #define PENDING_BYTE      0x40000000  /* First byte past the 1GB boundary */
8696 #else
8697 SQLITE_API extern unsigned int sqlite3_pending_byte;
8698 #define PENDING_BYTE sqlite3_pending_byte
8699 #endif
8700
8701 #define RESERVED_BYTE     (PENDING_BYTE+1)
8702 #define SHARED_FIRST      (PENDING_BYTE+2)
8703 #define SHARED_SIZE       510
8704
8705 /* 
8706 ** Functions for accessing sqlite3_file methods 
8707 */
8708 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8709 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8710 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8711 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8712 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8713 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8714 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8715 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8716 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8717 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8718 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8719 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8720
8721 /* 
8722 ** Functions for accessing sqlite3_vfs methods 
8723 */
8724 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8725 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8726 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8727 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8728 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8729 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8730 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8731 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *);
8732 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8733 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8734 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8735 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8736 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8737
8738 /*
8739 ** Convenience functions for opening and closing files using 
8740 ** sqlite3_malloc() to obtain space for the file-handle structure.
8741 */
8742 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8743 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8744
8745 #endif /* _SQLITE_OS_H_ */
8746
8747 /************** End of os.h **************************************************/
8748 /************** Continuing where we left off in sqliteInt.h ******************/
8749 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8750 /************** Begin file mutex.h *******************************************/
8751 /*
8752 ** 2007 August 28
8753 **
8754 ** The author disclaims copyright to this source code.  In place of
8755 ** a legal notice, here is a blessing:
8756 **
8757 **    May you do good and not evil.
8758 **    May you find forgiveness for yourself and forgive others.
8759 **    May you share freely, never taking more than you give.
8760 **
8761 *************************************************************************
8762 **
8763 ** This file contains the common header for all mutex implementations.
8764 ** The sqliteInt.h header #includes this file so that it is available
8765 ** to all source files.  We break it out in an effort to keep the code
8766 ** better organized.
8767 **
8768 ** NOTE:  source files should *not* #include this header file directly.
8769 ** Source files should #include the sqliteInt.h file and let that file
8770 ** include this one indirectly.
8771 **
8772 ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
8773 */
8774
8775
8776 /*
8777 ** Figure out what version of the code to use.  The choices are
8778 **
8779 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8780 **                             mutexes implemention cannot be overridden
8781 **                             at start-time.
8782 **
8783 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8784 **                             mutual exclusion is provided.  But this
8785 **                             implementation can be overridden at
8786 **                             start-time.
8787 **
8788 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8789 **
8790 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8791 **
8792 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8793 */
8794 #if !SQLITE_THREADSAFE
8795 # define SQLITE_MUTEX_OMIT
8796 #endif
8797 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8798 #  if SQLITE_OS_UNIX
8799 #    define SQLITE_MUTEX_PTHREADS
8800 #  elif SQLITE_OS_WIN
8801 #    define SQLITE_MUTEX_W32
8802 #  elif SQLITE_OS_OS2
8803 #    define SQLITE_MUTEX_OS2
8804 #  else
8805 #    define SQLITE_MUTEX_NOOP
8806 #  endif
8807 #endif
8808
8809 #ifdef SQLITE_MUTEX_OMIT
8810 /*
8811 ** If this is a no-op implementation, implement everything as macros.
8812 */
8813 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8814 #define sqlite3_mutex_free(X)
8815 #define sqlite3_mutex_enter(X)
8816 #define sqlite3_mutex_try(X)      SQLITE_OK
8817 #define sqlite3_mutex_leave(X)
8818 #define sqlite3_mutex_held(X)     1
8819 #define sqlite3_mutex_notheld(X)  1
8820 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8821 #define sqlite3MutexInit()        SQLITE_OK
8822 #define sqlite3MutexEnd()
8823 #endif /* defined(SQLITE_OMIT_MUTEX) */
8824
8825 /************** End of mutex.h ***********************************************/
8826 /************** Continuing where we left off in sqliteInt.h ******************/
8827
8828
8829 /*
8830 ** Each database file to be accessed by the system is an instance
8831 ** of the following structure.  There are normally two of these structures
8832 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8833 ** aDb[1] is the database file used to hold temporary tables.  Additional
8834 ** databases may be attached.
8835 */
8836 struct Db {
8837   char *zName;         /* Name of this database */
8838   Btree *pBt;          /* The B*Tree structure for this database file */
8839   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8840   u8 safety_level;     /* How aggressive at synching data to disk */
8841   void *pAux;               /* Auxiliary data.  Usually NULL */
8842   void (*xFreeAux)(void*);  /* Routine to free pAux */
8843   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8844 };
8845
8846 /*
8847 ** An instance of the following structure stores a database schema.
8848 **
8849 ** If there are no virtual tables configured in this schema, the
8850 ** Schema.db variable is set to NULL. After the first virtual table
8851 ** has been added, it is set to point to the database connection 
8852 ** used to create the connection. Once a virtual table has been
8853 ** added to the Schema structure and the Schema.db variable populated, 
8854 ** only that database connection may use the Schema to prepare 
8855 ** statements.
8856 */
8857 struct Schema {
8858   int schema_cookie;   /* Database schema version number for this file */
8859   Hash tblHash;        /* All tables indexed by name */
8860   Hash idxHash;        /* All (named) indices indexed by name */
8861   Hash trigHash;       /* All triggers indexed by name */
8862   Hash aFKey;          /* Foreign keys indexed by to-table */
8863   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8864   u8 file_format;      /* Schema format version for this file */
8865   u8 enc;              /* Text encoding used by this database */
8866   u16 flags;           /* Flags associated with this schema */
8867   int cache_size;      /* Number of pages to use in the cache */
8868 #ifndef SQLITE_OMIT_VIRTUALTABLE
8869   sqlite3 *db;         /* "Owner" connection. See comment above */
8870 #endif
8871 };
8872
8873 /*
8874 ** These macros can be used to test, set, or clear bits in the 
8875 ** Db.flags field.
8876 */
8877 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8878 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8879 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8880 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8881
8882 /*
8883 ** Allowed values for the DB.flags field.
8884 **
8885 ** The DB_SchemaLoaded flag is set after the database schema has been
8886 ** read into internal hash tables.
8887 **
8888 ** DB_UnresetViews means that one or more views have column names that
8889 ** have been filled out.  If the schema changes, these column names might
8890 ** changes and so the view will need to be reset.
8891 */
8892 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8893 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8894 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8895
8896 /*
8897 ** The number of different kinds of things that can be limited
8898 ** using the sqlite3_limit() interface.
8899 */
8900 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
8901
8902 /*
8903 ** Lookaside malloc is a set of fixed-size buffers that can be used
8904 ** to satisify small transient memory allocation requests for objects
8905 ** associated with a particular database connection.  The use of
8906 ** lookaside malloc provides a significant performance enhancement
8907 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8908 ** SQL statements.
8909 **
8910 ** The Lookaside structure holds configuration information about the
8911 ** lookaside malloc subsystem.  Each available memory allocation in
8912 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8913 ** objects.
8914 */
8915 struct Lookaside {
8916   u16 sz;                 /* Size of each buffer in bytes */
8917   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
8918   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8919   int nOut;               /* Number of buffers currently checked out */
8920   int mxOut;              /* Highwater mark for nOut */
8921   LookasideSlot *pFree;   /* List of available buffers */
8922   void *pStart;           /* First byte of available memory space */
8923   void *pEnd;             /* First byte past end of available space */
8924 };
8925 struct LookasideSlot {
8926   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8927 };
8928
8929 /*
8930 ** A hash table for function definitions.
8931 **
8932 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8933 ** Collisions are on the FuncDef.pHash chain.
8934 */
8935 struct FuncDefHash {
8936   FuncDef *a[23];       /* Hash table for functions */
8937 };
8938
8939 /*
8940 ** Each database is an instance of the following structure.
8941 **
8942 ** The sqlite.lastRowid records the last insert rowid generated by an
8943 ** insert statement.  Inserts on views do not affect its value.  Each
8944 ** trigger has its own context, so that lastRowid can be updated inside
8945 ** triggers as usual.  The previous value will be restored once the trigger
8946 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8947 ** longer (since after version 2.8.12) reset to -1.
8948 **
8949 ** The sqlite.nChange does not count changes within triggers and keeps no
8950 ** context.  It is reset at start of sqlite3_exec.
8951 ** The sqlite.lsChange represents the number of changes made by the last
8952 ** insert, update, or delete statement.  It remains constant throughout the
8953 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8954 ** context stack just like lastRowid so that the count of changes
8955 ** within a trigger is not seen outside the trigger.  Changes to views do not
8956 ** affect the value of lsChange.
8957 ** The sqlite.csChange keeps track of the number of current changes (since
8958 ** the last statement) and is used to update sqlite_lsChange.
8959 **
8960 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8961 ** store the most recent error code and, if applicable, string. The
8962 ** internal function sqlite3Error() is used to set these variables
8963 ** consistently.
8964 */
8965 struct sqlite3 {
8966   sqlite3_vfs *pVfs;            /* OS Interface */
8967   int nDb;                      /* Number of backends currently in use */
8968   Db *aDb;                      /* All backends */
8969   int flags;                    /* Miscellanous flags. See below */
8970   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8971   int errCode;                  /* Most recent error code (SQLITE_*) */
8972   int errMask;                  /* & result codes with this before returning */
8973   u8 autoCommit;                /* The auto-commit flag. */
8974   u8 temp_store;                /* 1: file 2: memory 0: default */
8975   u8 mallocFailed;              /* True if we have seen a malloc failure */
8976   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8977   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8978   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8979   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8980   int nTable;                   /* Number of tables in the database */
8981   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8982   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8983   i64 priorNewRowid;            /* Last randomly generated ROWID */
8984   int magic;                    /* Magic number for detect library misuse */
8985   int nChange;                  /* Value returned by sqlite3_changes() */
8986   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8987   sqlite3_mutex *mutex;         /* Connection mutex */
8988   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8989   struct sqlite3InitInfo {      /* Information used during initialization */
8990     int iDb;                    /* When back is being initialized */
8991     int newTnum;                /* Rootpage of table being initialized */
8992     u8 busy;                    /* TRUE if currently initializing */
8993   } init;
8994   int nExtension;               /* Number of loaded extensions */
8995   void **aExtension;            /* Array of shared libraray handles */
8996   struct Vdbe *pVdbe;           /* List of active virtual machines */
8997   int activeVdbeCnt;            /* Number of vdbes currently executing */
8998   void (*xTrace)(void*,const char*);        /* Trace function */
8999   void *pTraceArg;                          /* Argument to the trace function */
9000   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9001   void *pProfileArg;                        /* Argument to profile function */
9002   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9003   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9004   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9005   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9006   void *pUpdateArg;
9007   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9008   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9009   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9010   void *pCollNeededArg;
9011   sqlite3_value *pErr;          /* Most recent error message */
9012   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9013   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9014   union {
9015     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9016     double notUsed1;            /* Spacer */
9017   } u1;
9018   Lookaside lookaside;          /* Lookaside malloc configuration */
9019 #ifndef SQLITE_OMIT_AUTHORIZATION
9020   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9021                                 /* Access authorization function */
9022   void *pAuthArg;               /* 1st argument to the access auth function */
9023 #endif
9024 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9025   int (*xProgress)(void *);     /* The progress callback */
9026   void *pProgressArg;           /* Argument to the progress callback */
9027   int nProgressOps;             /* Number of opcodes for progress callback */
9028 #endif
9029 #ifndef SQLITE_OMIT_VIRTUALTABLE
9030   Hash aModule;                 /* populated by sqlite3_create_module() */
9031   Table *pVTab;                 /* vtab with active Connect/Create method */
9032   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
9033   int nVTrans;                  /* Allocated size of aVTrans */
9034 #endif
9035   FuncDefHash aFunc;            /* Hash table of connection functions */
9036   Hash aCollSeq;                /* All collating sequences */
9037   BusyHandler busyHandler;      /* Busy callback */
9038   int busyTimeout;              /* Busy handler timeout, in msec */
9039   Db aDbStatic[2];              /* Static space for the 2 default backends */
9040 #ifdef SQLITE_SSE
9041   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
9042 #endif
9043 };
9044
9045 /*
9046 ** A macro to discover the encoding of a database.
9047 */
9048 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9049
9050 /*
9051 ** Possible values for the sqlite.flags and or Db.flags fields.
9052 **
9053 ** On sqlite.flags, the SQLITE_InTrans value means that we have
9054 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
9055 ** transaction is active on that particular database file.
9056 */
9057 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
9058 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
9059 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
9060 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
9061 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
9062 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
9063                                           /*   DELETE, or UPDATE and return */
9064                                           /*   the count using a callback. */
9065 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
9066                                           /*   result set is empty */
9067 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
9068 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
9069 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
9070 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
9071                                           ** accessing read-only databases */
9072 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
9073 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
9074 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
9075 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
9076 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
9077
9078 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
9079 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
9080 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
9081
9082 /*
9083 ** Possible values for the sqlite.magic field.
9084 ** The numbers are obtained at random and have no special meaning, other
9085 ** than being distinct from one another.
9086 */
9087 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9088 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9089 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9090 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9091 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9092
9093 /*
9094 ** Each SQL function is defined by an instance of the following
9095 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9096 ** hash table.  When multiple functions have the same name, the hash table
9097 ** points to a linked list of these structures.
9098 */
9099 struct FuncDef {
9100   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9101   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9102   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9103   void *pUserData;     /* User data parameter */
9104   FuncDef *pNext;      /* Next function with same name */
9105   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9106   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9107   void (*xFinalize)(sqlite3_context*);                /* Aggregate finializer */
9108   char *zName;         /* SQL name of the function. */
9109   FuncDef *pHash;      /* Next with a different name but the same hash */
9110 };
9111
9112 /*
9113 ** Possible values for FuncDef.flags
9114 */
9115 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9116 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9117 #define SQLITE_FUNC_EPHEM    0x04 /* Ephermeral.  Delete with VDBE */
9118 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9119
9120 /*
9121 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9122 ** used to create the initializers for the FuncDef structures.
9123 **
9124 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9125 **     Used to create a scalar function definition of a function zName 
9126 **     implemented by C function xFunc that accepts nArg arguments. The
9127 **     value passed as iArg is cast to a (void*) and made available
9128 **     as the user-data (sqlite3_user_data()) for the function. If 
9129 **     argument bNC is true, then the FuncDef.needCollate flag is set.
9130 **
9131 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9132 **     Used to create an aggregate function definition implemented by
9133 **     the C functions xStep and xFinal. The first four parameters
9134 **     are interpreted in the same way as the first 4 parameters to
9135 **     FUNCTION().
9136 **
9137 **   LIKEFUNC(zName, nArg, pArg, flags)
9138 **     Used to create a scalar function definition of a function zName 
9139 **     that accepts nArg arguments and is implemented by a call to C 
9140 **     function likeFunc. Argument pArg is cast to a (void *) and made
9141 **     available as the function user-data (sqlite3_user_data()). The
9142 **     FuncDef.flags variable is set to the value passed as the flags
9143 **     parameter.
9144 */
9145 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9146   {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName}
9147 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9148   {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName}
9149 #define LIKEFUNC(zName, nArg, arg, flags) \
9150   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName}
9151 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9152   {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal, #zName}
9153
9154
9155 /*
9156 ** Each SQLite module (virtual table definition) is defined by an
9157 ** instance of the following structure, stored in the sqlite3.aModule
9158 ** hash table.
9159 */
9160 struct Module {
9161   const sqlite3_module *pModule;       /* Callback pointers */
9162   const char *zName;                   /* Name passed to create_module() */
9163   void *pAux;                          /* pAux passed to create_module() */
9164   void (*xDestroy)(void *);            /* Module destructor function */
9165 };
9166
9167 /*
9168 ** information about each column of an SQL table is held in an instance
9169 ** of this structure.
9170 */
9171 struct Column {
9172   char *zName;     /* Name of this column */
9173   Expr *pDflt;     /* Default value of this column */
9174   char *zType;     /* Data type for this column */
9175   char *zColl;     /* Collating sequence.  If NULL, use the default */
9176   u8 notNull;      /* True if there is a NOT NULL constraint */
9177   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9178   char affinity;   /* One of the SQLITE_AFF_... values */
9179 #ifndef SQLITE_OMIT_VIRTUALTABLE
9180   u8 isHidden;     /* True if this column is 'hidden' */
9181 #endif
9182 };
9183
9184 /*
9185 ** A "Collating Sequence" is defined by an instance of the following
9186 ** structure. Conceptually, a collating sequence consists of a name and
9187 ** a comparison routine that defines the order of that sequence.
9188 **
9189 ** There may two seperate implementations of the collation function, one
9190 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9191 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9192 ** native byte order. When a collation sequence is invoked, SQLite selects
9193 ** the version that will require the least expensive encoding
9194 ** translations, if any.
9195 **
9196 ** The CollSeq.pUser member variable is an extra parameter that passed in
9197 ** as the first argument to the UTF-8 comparison function, xCmp.
9198 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9199 ** xCmp16.
9200 **
9201 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9202 ** collating sequence is undefined.  Indices built on an undefined
9203 ** collating sequence may not be read or written.
9204 */
9205 struct CollSeq {
9206   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9207   u8 enc;               /* Text encoding handled by xCmp() */
9208   u8 type;              /* One of the SQLITE_COLL_... values below */
9209   void *pUser;          /* First argument to xCmp() */
9210   int (*xCmp)(void*,int, const void*, int, const void*);
9211   void (*xDel)(void*);  /* Destructor for pUser */
9212 };
9213
9214 /*
9215 ** Allowed values of CollSeq.type:
9216 */
9217 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9218 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9219 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9220 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9221
9222 /*
9223 ** A sort order can be either ASC or DESC.
9224 */
9225 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9226 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9227
9228 /*
9229 ** Column affinity types.
9230 **
9231 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9232 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9233 ** the speed a little by numbering the values consecutively.  
9234 **
9235 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9236 ** when multiple affinity types are concatenated into a string and
9237 ** used as the P4 operand, they will be more readable.
9238 **
9239 ** Note also that the numeric types are grouped together so that testing
9240 ** for a numeric type is a single comparison.
9241 */
9242 #define SQLITE_AFF_TEXT     'a'
9243 #define SQLITE_AFF_NONE     'b'
9244 #define SQLITE_AFF_NUMERIC  'c'
9245 #define SQLITE_AFF_INTEGER  'd'
9246 #define SQLITE_AFF_REAL     'e'
9247
9248 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9249
9250 /*
9251 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9252 ** affinity value. 
9253 */
9254 #define SQLITE_AFF_MASK     0x67
9255
9256 /*
9257 ** Additional bit values that can be ORed with an affinity without
9258 ** changing the affinity.
9259 */
9260 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9261 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9262
9263 /*
9264 ** Each SQL table is represented in memory by an instance of the
9265 ** following structure.
9266 **
9267 ** Table.zName is the name of the table.  The case of the original
9268 ** CREATE TABLE statement is stored, but case is not significant for
9269 ** comparisons.
9270 **
9271 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9272 ** pointer to an array of Column structures, one for each column.
9273 **
9274 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9275 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9276 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9277 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9278 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9279 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9280 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9281 **
9282 ** Table.tnum is the page number for the root BTree page of the table in the
9283 ** database file.  If Table.iDb is the index of the database table backend
9284 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9285 ** holds temporary tables and indices.  If TF_Ephemeral is set
9286 ** then the table is stored in a file that is automatically deleted
9287 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9288 ** refers VDBE cursor number that holds the table open, not to the root
9289 ** page number.  Transient tables are used to hold the results of a
9290 ** sub-query that appears instead of a real table name in the FROM clause 
9291 ** of a SELECT statement.
9292 */
9293 struct Table {
9294   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
9295   char *zName;         /* Name of the table or view */
9296   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9297   int nCol;            /* Number of columns in this table */
9298   Column *aCol;        /* Information about each column */
9299   Index *pIndex;       /* List of SQL indexes on this table. */
9300   int tnum;            /* Root BTree node for this table (see note above) */
9301   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9302   u16 nRef;            /* Number of pointers to this Table */
9303   u8 tabFlags;         /* Mask of TF_* values */
9304   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9305   Trigger *pTrigger;   /* List of SQL triggers on this table */
9306   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9307   char *zColAff;       /* String defining the affinity of each column */
9308 #ifndef SQLITE_OMIT_CHECK
9309   Expr *pCheck;        /* The AND of all CHECK constraints */
9310 #endif
9311 #ifndef SQLITE_OMIT_ALTERTABLE
9312   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9313 #endif
9314 #ifndef SQLITE_OMIT_VIRTUALTABLE
9315   Module *pMod;        /* Pointer to the implementation of the module */
9316   sqlite3_vtab *pVtab; /* Pointer to the module instance */
9317   int nModuleArg;      /* Number of arguments to the module */
9318   char **azModuleArg;  /* Text of all module args. [0] is module name */
9319 #endif
9320   Schema *pSchema;     /* Schema that contains this table */
9321   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9322 };
9323
9324 /*
9325 ** Allowed values for Tabe.tabFlags.
9326 */
9327 #define TF_Readonly        0x01    /* Read-only system table */
9328 #define TF_Ephemeral       0x02    /* An emphermal table */
9329 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9330 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9331 #define TF_Virtual         0x10    /* Is a virtual table */
9332 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9333
9334
9335
9336 /*
9337 ** Test to see whether or not a table is a virtual table.  This is
9338 ** done as a macro so that it will be optimized out when virtual
9339 ** table support is omitted from the build.
9340 */
9341 #ifndef SQLITE_OMIT_VIRTUALTABLE
9342 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9343 #  define IsHiddenColumn(X) ((X)->isHidden)
9344 #else
9345 #  define IsVirtual(X)      0
9346 #  define IsHiddenColumn(X) 0
9347 #endif
9348
9349 /*
9350 ** Each foreign key constraint is an instance of the following structure.
9351 **
9352 ** A foreign key is associated with two tables.  The "from" table is
9353 ** the table that contains the REFERENCES clause that creates the foreign
9354 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9355 ** Consider this example:
9356 **
9357 **     CREATE TABLE ex1(
9358 **       a INTEGER PRIMARY KEY,
9359 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9360 **     );
9361 **
9362 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9363 **
9364 ** Each REFERENCES clause generates an instance of the following structure
9365 ** which is attached to the from-table.  The to-table need not exist when
9366 ** the from-table is created.  The existance of the to-table is not checked
9367 ** until an attempt is made to insert data into the from-table.
9368 **
9369 ** The sqlite.aFKey hash table stores pointers to this structure
9370 ** given the name of a to-table.  For each to-table, all foreign keys
9371 ** associated with that table are on a linked list using the FKey.pNextTo
9372 ** field.
9373 */
9374 struct FKey {
9375   Table *pFrom;     /* The table that constains the REFERENCES clause */
9376   FKey *pNextFrom;  /* Next foreign key in pFrom */
9377   char *zTo;        /* Name of table that the key points to */
9378   FKey *pNextTo;    /* Next foreign key that points to zTo */
9379   int nCol;         /* Number of columns in this key */
9380   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9381     int iFrom;         /* Index of column in pFrom */
9382     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9383   } *aCol;          /* One entry for each of nCol column s */
9384   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9385   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
9386   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
9387   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
9388 };
9389
9390 /*
9391 ** SQLite supports many different ways to resolve a constraint
9392 ** error.  ROLLBACK processing means that a constraint violation
9393 ** causes the operation in process to fail and for the current transaction
9394 ** to be rolled back.  ABORT processing means the operation in process
9395 ** fails and any prior changes from that one operation are backed out,
9396 ** but the transaction is not rolled back.  FAIL processing means that
9397 ** the operation in progress stops and returns an error code.  But prior
9398 ** changes due to the same operation are not backed out and no rollback
9399 ** occurs.  IGNORE means that the particular row that caused the constraint
9400 ** error is not inserted or updated.  Processing continues and no error
9401 ** is returned.  REPLACE means that preexisting database rows that caused
9402 ** a UNIQUE constraint violation are removed so that the new insert or
9403 ** update can proceed.  Processing continues and no error is reported.
9404 **
9405 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9406 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9407 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9408 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9409 ** referenced table row is propagated into the row that holds the
9410 ** foreign key.
9411 ** 
9412 ** The following symbolic values are used to record which type
9413 ** of action to take.
9414 */
9415 #define OE_None     0   /* There is no constraint to check */
9416 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9417 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9418 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9419 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9420 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9421
9422 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9423 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9424 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9425 #define OE_Cascade  9   /* Cascade the changes */
9426
9427 #define OE_Default  99  /* Do whatever the default action is */
9428
9429
9430 /*
9431 ** An instance of the following structure is passed as the first
9432 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9433 ** comparison of the two index keys.
9434 */
9435 struct KeyInfo {
9436   sqlite3 *db;        /* The database connection */
9437   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9438   u16 nField;         /* Number of entries in aColl[] */
9439   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9440   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9441 };
9442
9443 /*
9444 ** An instance of the following structure holds information about a
9445 ** single index record that has already been parsed out into individual
9446 ** values.
9447 **
9448 ** A record is an object that contains one or more fields of data.
9449 ** Records are used to store the content of a table row and to store
9450 ** the key of an index.  A blob encoding of a record is created by
9451 ** the OP_MakeRecord opcode of the VDBE and is disassemblied by the
9452 ** OP_Column opcode.
9453 **
9454 ** This structure holds a record that has already been disassembled
9455 ** into its constitutent fields.
9456 */
9457 struct UnpackedRecord {
9458   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9459   u16 nField;         /* Number of entries in apMem[] */
9460   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9461   Mem *aMem;          /* Values */
9462 };
9463
9464 /*
9465 ** Allowed values of UnpackedRecord.flags
9466 */
9467 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9468 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9469 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9470 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9471 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9472
9473 /*
9474 ** Each SQL index is represented in memory by an
9475 ** instance of the following structure.
9476 **
9477 ** The columns of the table that are to be indexed are described
9478 ** by the aiColumn[] field of this structure.  For example, suppose
9479 ** we have the following table and index:
9480 **
9481 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9482 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9483 **
9484 ** In the Table structure describing Ex1, nCol==3 because there are
9485 ** three columns in the table.  In the Index structure describing
9486 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9487 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9488 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9489 ** The second column to be indexed (c1) has an index of 0 in
9490 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9491 **
9492 ** The Index.onError field determines whether or not the indexed columns
9493 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9494 ** it means this is not a unique index.  Otherwise it is a unique index
9495 ** and the value of Index.onError indicate the which conflict resolution 
9496 ** algorithm to employ whenever an attempt is made to insert a non-unique
9497 ** element.
9498 */
9499 struct Index {
9500   char *zName;     /* Name of this index */
9501   int nColumn;     /* Number of columns in the table used by this index */
9502   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9503   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9504   Table *pTable;   /* The SQL table being indexed */
9505   int tnum;        /* Page containing root of this index in database file */
9506   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9507   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9508   char *zColAff;   /* String defining the affinity of each column */
9509   Index *pNext;    /* The next index associated with the same table */
9510   Schema *pSchema; /* Schema containing this index */
9511   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9512   char **azColl;   /* Array of collation sequence names for index */
9513 };
9514
9515 /*
9516 ** Each token coming out of the lexer is an instance of
9517 ** this structure.  Tokens are also used as part of an expression.
9518 **
9519 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9520 ** may contain random values.  Do not make any assuptions about Token.dyn
9521 ** and Token.n when Token.z==0.
9522 */
9523 struct Token {
9524   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
9525   unsigned dyn  : 1;      /* True for malloced memory, false for static */
9526   unsigned n    : 31;     /* Number of characters in this token */
9527 };
9528
9529 /*
9530 ** An instance of this structure contains information needed to generate
9531 ** code for a SELECT that contains aggregate functions.
9532 **
9533 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9534 ** pointer to this structure.  The Expr.iColumn field is the index in
9535 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9536 ** code for that node.
9537 **
9538 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9539 ** original Select structure that describes the SELECT statement.  These
9540 ** fields do not need to be freed when deallocating the AggInfo structure.
9541 */
9542 struct AggInfo {
9543   u8 directMode;          /* Direct rendering mode means take data directly
9544                           ** from source tables rather than from accumulators */
9545   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9546                           ** than the source table */
9547   int sortingIdx;         /* Cursor number of the sorting index */
9548   ExprList *pGroupBy;     /* The group by clause */
9549   int nSortingColumn;     /* Number of columns in the sorting index */
9550   struct AggInfo_col {    /* For each column used in source tables */
9551     Table *pTab;             /* Source table */
9552     int iTable;              /* Cursor number of the source table */
9553     int iColumn;             /* Column number within the source table */
9554     int iSorterColumn;       /* Column number in the sorting index */
9555     int iMem;                /* Memory location that acts as accumulator */
9556     Expr *pExpr;             /* The original expression */
9557   } *aCol;
9558   int nColumn;            /* Number of used entries in aCol[] */
9559   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9560   int nAccumulator;       /* Number of columns that show through to the output.
9561                           ** Additional columns are used only as parameters to
9562                           ** aggregate functions */
9563   struct AggInfo_func {   /* For each aggregate function */
9564     Expr *pExpr;             /* Expression encoding the function */
9565     FuncDef *pFunc;          /* The aggregate function implementation */
9566     int iMem;                /* Memory location that acts as accumulator */
9567     int iDistinct;           /* Ephermeral table used to enforce DISTINCT */
9568   } *aFunc;
9569   int nFunc;              /* Number of entries in aFunc[] */
9570   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9571 };
9572
9573 /*
9574 ** Each node of an expression in the parse tree is an instance
9575 ** of this structure.
9576 **
9577 ** Expr.op is the opcode.  The integer parser token codes are reused
9578 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
9579 ** code representing the ">=" operator.  This same integer code is reused
9580 ** to represent the greater-than-or-equal-to operator in the expression
9581 ** tree.
9582 **
9583 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
9584 ** of argument if the expression is a function.
9585 **
9586 ** Expr.token is the operator token for this node.  For some expressions
9587 ** that have subexpressions, Expr.token can be the complete text that gave
9588 ** rise to the Expr.  In the latter case, the token is marked as being
9589 ** a compound token.
9590 **
9591 ** An expression of the form ID or ID.ID refers to a column in a table.
9592 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9593 ** the integer cursor number of a VDBE cursor pointing to that table and
9594 ** Expr.iColumn is the column number for the specific column.  If the
9595 ** expression is used as a result in an aggregate SELECT, then the
9596 ** value is also stored in the Expr.iAgg column in the aggregate so that
9597 ** it can be accessed after all aggregates are computed.
9598 **
9599 ** If the expression is a function, the Expr.iTable is an integer code
9600 ** representing which function.  If the expression is an unbound variable
9601 ** marker (a question mark character '?' in the original SQL) then the
9602 ** Expr.iTable holds the index number for that variable.
9603 **
9604 ** If the expression is a subquery then Expr.iColumn holds an integer
9605 ** register number containing the result of the subquery.  If the
9606 ** subquery gives a constant result, then iTable is -1.  If the subquery
9607 ** gives a different answer at different times during statement processing
9608 ** then iTable is the address of a subroutine that computes the subquery.
9609 **
9610 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
9611 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
9612 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
9613 ** operand.
9614 **
9615 ** If the Expr is of type OP_Column, and the table it is selecting from
9616 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9617 ** corresponding table definition.
9618 */
9619 struct Expr {
9620   u8 op;                 /* Operation performed by this node */
9621   char affinity;         /* The affinity of the column or 0 if not a column */
9622   u16 flags;             /* Various flags.  See below */
9623   CollSeq *pColl;        /* The collation type of the column or 0 */
9624   Expr *pLeft, *pRight;  /* Left and right subnodes */
9625   ExprList *pList;       /* A list of expressions used as function arguments
9626                          ** or in "<expr> IN (<expr-list)" */
9627   Token token;           /* An operand token */
9628   Token span;            /* Complete text of the expression */
9629   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
9630                          ** iColumn-th field of the iTable-th table. */
9631   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9632   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9633   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9634   Select *pSelect;       /* When the expression is a sub-select.  Also the
9635                          ** right side of "<expr> IN (<select>)" */
9636   Table *pTab;           /* Table for TK_COLUMN expressions. */
9637 #if SQLITE_MAX_EXPR_DEPTH>0
9638   int nHeight;           /* Height of the tree headed by this node */
9639 #endif
9640 };
9641
9642 /*
9643 ** The following are the meanings of bits in the Expr.flags field.
9644 */
9645 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9646 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9647 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9648 #define EP_Error      0x0008  /* Expression contains one or more errors */
9649 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9650 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9651 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
9652 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9653 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9654 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
9655 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
9656 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
9657 /*
9658 ** These macros can be used to test, set, or clear bits in the 
9659 ** Expr.flags field.
9660 */
9661 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9662 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9663 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9664 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9665
9666 /*
9667 ** A list of expressions.  Each expression may optionally have a
9668 ** name.  An expr/name combination can be used in several ways, such
9669 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9670 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9671 ** also be used as the argument to a function, in which case the a.zName
9672 ** field is not used.
9673 */
9674 struct ExprList {
9675   int nExpr;             /* Number of expressions on the list */
9676   int nAlloc;            /* Number of entries allocated below */
9677   int iECursor;          /* VDBE Cursor associated with this ExprList */
9678   struct ExprList_item {
9679     Expr *pExpr;           /* The list of expressions */
9680     char *zName;           /* Token associated with this expression */
9681     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9682     u8 done;               /* A flag to indicate when processing is finished */
9683     u16 iCol;              /* For ORDER BY, column number in result set */
9684     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9685   } *a;                  /* One entry for each expression */
9686 };
9687
9688 /*
9689 ** An instance of this structure can hold a simple list of identifiers,
9690 ** such as the list "a,b,c" in the following statements:
9691 **
9692 **      INSERT INTO t(a,b,c) VALUES ...;
9693 **      CREATE INDEX idx ON t(a,b,c);
9694 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9695 **
9696 ** The IdList.a.idx field is used when the IdList represents the list of
9697 ** column names after a table name in an INSERT statement.  In the statement
9698 **
9699 **     INSERT INTO t(a,b,c) ...
9700 **
9701 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9702 */
9703 struct IdList {
9704   struct IdList_item {
9705     char *zName;      /* Name of the identifier */
9706     int idx;          /* Index in some Table.aCol[] of a column named zName */
9707   } *a;
9708   int nId;         /* Number of identifiers on the list */
9709   int nAlloc;      /* Number of entries allocated for a[] below */
9710 };
9711
9712 /*
9713 ** The bitmask datatype defined below is used for various optimizations.
9714 **
9715 ** Changing this from a 64-bit to a 32-bit type limits the number of
9716 ** tables in a join to 32 instead of 64.  But it also reduces the size
9717 ** of the library by 738 bytes on ix86.
9718 */
9719 typedef u64 Bitmask;
9720
9721 /*
9722 ** The following structure describes the FROM clause of a SELECT statement.
9723 ** Each table or subquery in the FROM clause is a separate element of
9724 ** the SrcList.a[] array.
9725 **
9726 ** With the addition of multiple database support, the following structure
9727 ** can also be used to describe a particular table such as the table that
9728 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9729 ** such a table must be a simple name: ID.  But in SQLite, the table can
9730 ** now be identified by a database name, a dot, then the table name: ID.ID.
9731 **
9732 ** The jointype starts out showing the join type between the current table
9733 ** and the next table on the list.  The parser builds the list this way.
9734 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9735 ** jointype expresses the join between the table and the previous table.
9736 */
9737 struct SrcList {
9738   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9739   i16 nAlloc;      /* Number of entries allocated in a[] below */
9740   struct SrcList_item {
9741     char *zDatabase;  /* Name of database holding this table */
9742     char *zName;      /* Name of the table */
9743     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9744     Table *pTab;      /* An SQL table corresponding to zName */
9745     Select *pSelect;  /* A SELECT statement used in place of a table name */
9746     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9747     u8 jointype;      /* Type of join between this able and the previous */
9748     int iCursor;      /* The VDBE cursor number used to access this table */
9749     Expr *pOn;        /* The ON clause of a join */
9750     IdList *pUsing;   /* The USING clause of a join */
9751     Bitmask colUsed;  /* Bit N (1<<N) set if column N or pTab is used */
9752     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9753     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9754     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9755   } a[1];             /* One entry for each identifier on the list */
9756 };
9757
9758 /*
9759 ** Permitted values of the SrcList.a.jointype field
9760 */
9761 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9762 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9763 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9764 #define JT_LEFT      0x0008    /* Left outer join */
9765 #define JT_RIGHT     0x0010    /* Right outer join */
9766 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9767 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9768
9769 /*
9770 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9771 ** structure contains a single instance of this structure.  This structure
9772 ** is intended to be private the the where.c module and should not be
9773 ** access or modified by other modules.
9774 **
9775 ** The pIdxInfo and pBestIdx fields are used to help pick the best
9776 ** index on a virtual table.  The pIdxInfo pointer contains indexing
9777 ** information for the i-th table in the FROM clause before reordering.
9778 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9779 ** The pBestIdx pointer is a copy of pIdxInfo for the i-th table after
9780 ** FROM clause ordering.  This is a little confusing so I will repeat
9781 ** it in different words.  WhereInfo.a[i].pIdxInfo is index information 
9782 ** for WhereInfo.pTabList.a[i].  WhereInfo.a[i].pBestInfo is the
9783 ** index information for the i-th loop of the join.  pBestInfo is always
9784 ** either NULL or a copy of some pIdxInfo.  So for cleanup it is 
9785 ** sufficient to free all of the pIdxInfo pointers.
9786 ** 
9787 */
9788 struct WhereLevel {
9789   int iFrom;            /* Which entry in the FROM clause */
9790   int flags;            /* Flags associated with this level */
9791   int iMem;             /* First memory cell used by this level */
9792   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9793   Index *pIdx;          /* Index used.  NULL if no index */
9794   int iTabCur;          /* The VDBE cursor used to access the table */
9795   int iIdxCur;          /* The VDBE cursor used to acesss pIdx */
9796   int brk;              /* Jump here to break out of the loop */
9797   int nxt;              /* Jump here to start the next IN combination */
9798   int cont;             /* Jump here to continue with the next loop cycle */
9799   int top;              /* First instruction of interior of the loop */
9800   int op, p1, p2, p5;   /* Opcode used to terminate the loop */
9801   int nEq;              /* Number of == or IN constraints on this loop */
9802   int nIn;              /* Number of IN operators constraining this loop */
9803   struct InLoop {
9804     int iCur;              /* The VDBE cursor used by this IN operator */
9805     int topAddr;           /* Top of the IN loop */
9806   } *aInLoop;           /* Information about each nested IN operator */
9807   sqlite3_index_info *pBestIdx;  /* Index information for this level */
9808
9809   /* The following field is really not part of the current level.  But
9810   ** we need a place to cache index information for each table in the
9811   ** FROM clause and the WhereLevel structure is a convenient place.
9812   */
9813   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9814 };
9815
9816 /*
9817 ** Flags appropriate for the wflags parameter of sqlite3WhereBegin().
9818 */
9819 #define WHERE_ORDERBY_NORMAL     0   /* No-op */
9820 #define WHERE_ORDERBY_MIN        1   /* ORDER BY processing for min() func */
9821 #define WHERE_ORDERBY_MAX        2   /* ORDER BY processing for max() func */
9822 #define WHERE_ONEPASS_DESIRED    4   /* Want to do one-pass UPDATE/DELETE */
9823
9824 /*
9825 ** The WHERE clause processing routine has two halves.  The
9826 ** first part does the start of the WHERE loop and the second
9827 ** half does the tail of the WHERE loop.  An instance of
9828 ** this structure is returned by the first half and passed
9829 ** into the second half to give some continuity.
9830 */
9831 struct WhereInfo {
9832   Parse *pParse;       /* Parsing and code generating context */
9833   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9834   SrcList *pTabList;   /* List of tables in the join */
9835   int iTop;            /* The very beginning of the WHERE loop */
9836   int iContinue;       /* Jump here to continue with next record */
9837   int iBreak;          /* Jump here to break out of the loop */
9838   int nLevel;          /* Number of nested loop */
9839   sqlite3_index_info **apInfo;  /* Array of pointers to index info structures */
9840   WhereLevel a[1];     /* Information about each nest loop in the WHERE */
9841 };
9842
9843 /*
9844 ** A NameContext defines a context in which to resolve table and column
9845 ** names.  The context consists of a list of tables (the pSrcList) field and
9846 ** a list of named expression (pEList).  The named expression list may
9847 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9848 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9849 ** pEList corresponds to the result set of a SELECT and is NULL for
9850 ** other statements.
9851 **
9852 ** NameContexts can be nested.  When resolving names, the inner-most 
9853 ** context is searched first.  If no match is found, the next outer
9854 ** context is checked.  If there is still no match, the next context
9855 ** is checked.  This process continues until either a match is found
9856 ** or all contexts are check.  When a match is found, the nRef member of
9857 ** the context containing the match is incremented. 
9858 **
9859 ** Each subquery gets a new NameContext.  The pNext field points to the
9860 ** NameContext in the parent query.  Thus the process of scanning the
9861 ** NameContext list corresponds to searching through successively outer
9862 ** subqueries looking for a match.
9863 */
9864 struct NameContext {
9865   Parse *pParse;       /* The parser */
9866   SrcList *pSrcList;   /* One or more tables used to resolve names */
9867   ExprList *pEList;    /* Optional list of named expressions */
9868   int nRef;            /* Number of names resolved by this context */
9869   int nErr;            /* Number of errors encountered while resolving names */
9870   u8 allowAgg;         /* Aggregate functions allowed here */
9871   u8 hasAgg;           /* True if aggregates are seen */
9872   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9873   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9874   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9875   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9876 };
9877
9878 /*
9879 ** An instance of the following structure contains all information
9880 ** needed to generate code for a single SELECT statement.
9881 **
9882 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9883 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9884 ** limit and nOffset to the value of the offset (or 0 if there is not
9885 ** offset).  But later on, nLimit and nOffset become the memory locations
9886 ** in the VDBE that record the limit and offset counters.
9887 **
9888 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9889 ** These addresses must be stored so that we can go back and fill in
9890 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9891 ** the number of columns in P2 can be computed at the same time
9892 ** as the OP_OpenEphm instruction is coded because not
9893 ** enough information about the compound query is known at that point.
9894 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9895 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9896 ** sequences for the ORDER BY clause.
9897 */
9898 struct Select {
9899   ExprList *pEList;      /* The fields of the result */
9900   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9901   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9902   u16 selFlags;          /* Various SF_* values */
9903   SrcList *pSrc;         /* The FROM clause */
9904   Expr *pWhere;          /* The WHERE clause */
9905   ExprList *pGroupBy;    /* The GROUP BY clause */
9906   Expr *pHaving;         /* The HAVING clause */
9907   ExprList *pOrderBy;    /* The ORDER BY clause */
9908   Select *pPrior;        /* Prior select in a compound select statement */
9909   Select *pNext;         /* Next select to the left in a compound */
9910   Select *pRightmost;    /* Right-most select in a compound select statement */
9911   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9912   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9913   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9914   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9915 };
9916
9917 /*
9918 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9919 ** "Select Flag".
9920 */
9921 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9922 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9923 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9924 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9925 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9926 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9927
9928
9929 /*
9930 ** The results of a select can be distributed in several ways.  The
9931 ** "SRT" prefix means "SELECT Result Type".
9932 */
9933 #define SRT_Union        1  /* Store result as keys in an index */
9934 #define SRT_Except       2  /* Remove result from a UNION index */
9935 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9936 #define SRT_Discard      4  /* Do not save the results anywhere */
9937
9938 /* The ORDER BY clause is ignored for all of the above */
9939 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9940
9941 #define SRT_Output       5  /* Output each row of result */
9942 #define SRT_Mem          6  /* Store result in a memory cell */
9943 #define SRT_Set          7  /* Store results as keys in an index */
9944 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9945 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9946 #define SRT_Coroutine   10  /* Generate a single row of result */
9947
9948 /*
9949 ** A structure used to customize the behaviour of sqlite3Select(). See
9950 ** comments above sqlite3Select() for details.
9951 */
9952 typedef struct SelectDest SelectDest;
9953 struct SelectDest {
9954   u8 eDest;         /* How to dispose of the results */
9955   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9956   int iParm;        /* A parameter used by the eDest disposal method */
9957   int iMem;         /* Base register where results are written */
9958   int nMem;         /* Number of registers allocated */
9959 };
9960
9961 /*
9962 ** An SQL parser context.  A copy of this structure is passed through
9963 ** the parser and down into all the parser action routine in order to
9964 ** carry around information that is global to the entire parse.
9965 **
9966 ** The structure is divided into two parts.  When the parser and code
9967 ** generate call themselves recursively, the first part of the structure
9968 ** is constant but the second part is reset at the beginning and end of
9969 ** each recursion.
9970 **
9971 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9972 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9973 ** used to store the set of table-locks required by the statement being
9974 ** compiled. Function sqlite3TableLock() is used to add entries to the
9975 ** list.
9976 */
9977 struct Parse {
9978   sqlite3 *db;         /* The main database structure */
9979   int rc;              /* Return code from execution */
9980   char *zErrMsg;       /* An error message */
9981   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9982   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9983   u8 nameClash;        /* A permanent table name clashes with temp table name */
9984   u8 checkSchema;      /* Causes schema cookie check after an error */
9985   u8 nested;           /* Number of nested calls to the parser/code generator */
9986   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9987   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9988   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9989   int aTempReg[8];     /* Holding area for temporary registers */
9990   int nRangeReg;       /* Size of the temporary register block */
9991   int iRangeReg;       /* First register in temporary register block */
9992   int nErr;            /* Number of errors seen */
9993   int nTab;            /* Number of previously allocated VDBE cursors */
9994   int nMem;            /* Number of memory cells used so far */
9995   int nSet;            /* Number of sets used so far */
9996   int ckBase;          /* Base register of data during check constraints */
9997   int disableColCache; /* True to disable adding to column cache */
9998   int nColCache;       /* Number of entries in the column cache */
9999   int iColCache;       /* Next entry of the cache to replace */
10000   struct yColCache {
10001     int iTable;           /* Table cursor number */
10002     int iColumn;          /* Table column number */
10003     char affChange;       /* True if this register has had an affinity change */
10004     int iReg;             /* Register holding value of this column */
10005   } aColCache[10];     /* One for each valid column cache entry */
10006   u32 writeMask;       /* Start a write transaction on these databases */
10007   u32 cookieMask;      /* Bitmask of schema verified databases */
10008   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10009   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10010 #ifndef SQLITE_OMIT_SHARED_CACHE
10011   int nTableLock;        /* Number of locks in aTableLock */
10012   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10013 #endif
10014   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10015   int regRoot;         /* Register holding root page number for new objects */
10016
10017   /* Above is constant between recursions.  Below is reset before and after
10018   ** each recursion */
10019
10020   int nVar;            /* Number of '?' variables seen in the SQL so far */
10021   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10022   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10023   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10024   int nAlias;          /* Number of aliased result set columns */
10025   int *aAlias;         /* Register used to hold aliased result */
10026   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10027   Token sErrToken;     /* The token at which the error occurred */
10028   Token sNameToken;    /* Token with unqualified schema object name */
10029   Token sLastToken;    /* The last token parsed */
10030   const char *zSql;    /* All SQL text */
10031   const char *zTail;   /* All SQL text past the last semicolon parsed */
10032   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10033   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10034   TriggerStack *trigStack;  /* Trigger actions being coded */
10035   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10036 #ifndef SQLITE_OMIT_VIRTUALTABLE
10037   Token sArg;                /* Complete text of a module argument */
10038   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10039   int nVtabLock;             /* Number of virtual tables to lock */
10040   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10041 #endif
10042   int nHeight;            /* Expression tree height of current sub-select */
10043   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10044 };
10045
10046 #ifdef SQLITE_OMIT_VIRTUALTABLE
10047   #define IN_DECLARE_VTAB 0
10048 #else
10049   #define IN_DECLARE_VTAB (pParse->declareVtab)
10050 #endif
10051
10052 /*
10053 ** An instance of the following structure can be declared on a stack and used
10054 ** to save the Parse.zAuthContext value so that it can be restored later.
10055 */
10056 struct AuthContext {
10057   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10058   Parse *pParse;              /* The Parse structure */
10059 };
10060
10061 /*
10062 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
10063 */
10064 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
10065 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
10066 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
10067 #define OPFLAG_APPEND    8    /* This is likely to be an append */
10068
10069 /*
10070  * Each trigger present in the database schema is stored as an instance of
10071  * struct Trigger. 
10072  *
10073  * Pointers to instances of struct Trigger are stored in two ways.
10074  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10075  *    database). This allows Trigger structures to be retrieved by name.
10076  * 2. All triggers associated with a single table form a linked list, using the
10077  *    pNext member of struct Trigger. A pointer to the first element of the
10078  *    linked list is stored as the "pTrigger" member of the associated
10079  *    struct Table.
10080  *
10081  * The "step_list" member points to the first element of a linked list
10082  * containing the SQL statements specified as the trigger program.
10083  */
10084 struct Trigger {
10085   char *name;             /* The name of the trigger                        */
10086   char *table;            /* The table or view to which the trigger applies */
10087   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10088   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10089   Expr *pWhen;            /* The WHEN clause of the expresion (may be NULL) */
10090   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10091                              the <column-list> is stored here */
10092   Token nameToken;        /* Token containing zName. Use during parsing only */
10093   Schema *pSchema;        /* Schema containing the trigger */
10094   Schema *pTabSchema;     /* Schema containing the table */
10095   TriggerStep *step_list; /* Link list of trigger program steps             */
10096   Trigger *pNext;         /* Next trigger associated with the table */
10097 };
10098
10099 /*
10100 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10101 ** determine which. 
10102 **
10103 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10104 ** In that cases, the constants below can be ORed together.
10105 */
10106 #define TRIGGER_BEFORE  1
10107 #define TRIGGER_AFTER   2
10108
10109 /*
10110  * An instance of struct TriggerStep is used to store a single SQL statement
10111  * that is a part of a trigger-program. 
10112  *
10113  * Instances of struct TriggerStep are stored in a singly linked list (linked
10114  * using the "pNext" member) referenced by the "step_list" member of the 
10115  * associated struct Trigger instance. The first element of the linked list is
10116  * the first step of the trigger-program.
10117  * 
10118  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10119  * "SELECT" statement. The meanings of the other members is determined by the 
10120  * value of "op" as follows:
10121  *
10122  * (op == TK_INSERT)
10123  * orconf    -> stores the ON CONFLICT algorithm
10124  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10125  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10126  * target    -> A token holding the name of the table to insert into.
10127  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10128  *              this stores values to be inserted. Otherwise NULL.
10129  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10130  *              statement, then this stores the column-names to be
10131  *              inserted into.
10132  *
10133  * (op == TK_DELETE)
10134  * target    -> A token holding the name of the table to delete from.
10135  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10136  *              Otherwise NULL.
10137  * 
10138  * (op == TK_UPDATE)
10139  * target    -> A token holding the name of the table to update rows of.
10140  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10141  *              Otherwise NULL.
10142  * pExprList -> A list of the columns to update and the expressions to update
10143  *              them to. See sqlite3Update() documentation of "pChanges"
10144  *              argument.
10145  * 
10146  */
10147 struct TriggerStep {
10148   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10149   int orconf;          /* OE_Rollback etc. */
10150   Trigger *pTrig;      /* The trigger that this step is a part of */
10151
10152   Select *pSelect;     /* Valid for SELECT and sometimes 
10153                           INSERT steps (when pExprList == 0) */
10154   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
10155   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
10156   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
10157                            INSERT steps (when pSelect == 0)         */
10158   IdList *pIdList;     /* Valid for INSERT statements only */
10159   TriggerStep *pNext;  /* Next in the link-list */
10160   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10161 };
10162
10163 /*
10164  * An instance of struct TriggerStack stores information required during code
10165  * generation of a single trigger program. While the trigger program is being
10166  * coded, its associated TriggerStack instance is pointed to by the
10167  * "pTriggerStack" member of the Parse structure.
10168  *
10169  * The pTab member points to the table that triggers are being coded on. The 
10170  * newIdx member contains the index of the vdbe cursor that points at the temp
10171  * table that stores the new.* references. If new.* references are not valid
10172  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
10173  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
10174  *
10175  * The ON CONFLICT policy to be used for the trigger program steps is stored 
10176  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
10177  * specified for individual triggers steps is used.
10178  *
10179  * struct TriggerStack has a "pNext" member, to allow linked lists to be
10180  * constructed. When coding nested triggers (triggers fired by other triggers)
10181  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
10182  * pointer. Once the nested trigger has been coded, the pNext value is restored
10183  * to the pTriggerStack member of the Parse stucture and coding of the parent
10184  * trigger continues.
10185  *
10186  * Before a nested trigger is coded, the linked list pointed to by the 
10187  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
10188  * recursively. If this condition is detected, the nested trigger is not coded.
10189  */
10190 struct TriggerStack {
10191   Table *pTab;         /* Table that triggers are currently being coded on */
10192   int newIdx;          /* Index of vdbe cursor to "new" temp table */
10193   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
10194   u32 newColMask;
10195   u32 oldColMask;
10196   int orconf;          /* Current orconf policy */
10197   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
10198   Trigger *pTrigger;   /* The trigger currently being coded */
10199   TriggerStack *pNext; /* Next trigger down on the trigger stack */
10200 };
10201
10202 /*
10203 ** The following structure contains information used by the sqliteFix...
10204 ** routines as they walk the parse tree to make database references
10205 ** explicit.  
10206 */
10207 typedef struct DbFixer DbFixer;
10208 struct DbFixer {
10209   Parse *pParse;      /* The parsing context.  Error messages written here */
10210   const char *zDb;    /* Make sure all objects are contained in this database */
10211   const char *zType;  /* Type of the container - used for error messages */
10212   const Token *pName; /* Name of the container - used for error messages */
10213 };
10214
10215 /*
10216 ** An objected used to accumulate the text of a string where we
10217 ** do not necessarily know how big the string will be in the end.
10218 */
10219 struct StrAccum {
10220   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10221   char *zBase;         /* A base allocation.  Not from malloc. */
10222   char *zText;         /* The string collected so far */
10223   int  nChar;          /* Length of the string so far */
10224   int  nAlloc;         /* Amount of space allocated in zText */
10225   int  mxAlloc;        /* Maximum allowed string length */
10226   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10227   u8   useMalloc;      /* True if zText is enlargable using realloc */
10228   u8   tooBig;         /* Becomes true if string size exceeds limits */
10229 };
10230
10231 /*
10232 ** A pointer to this structure is used to communicate information
10233 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10234 */
10235 typedef struct {
10236   sqlite3 *db;        /* The database being initialized */
10237   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10238   char **pzErrMsg;    /* Error message stored here */
10239   int rc;             /* Result code stored here */
10240 } InitData;
10241
10242 /*
10243 ** Structure containing global configuration data for the SQLite library.
10244 **
10245 ** This structure also contains some state information.
10246 */
10247 struct Sqlite3Config {
10248   int bMemstat;                     /* True to enable memory status */
10249   int bCoreMutex;                   /* True to enable core mutexing */
10250   int bFullMutex;                   /* True to enable full mutexing */
10251   int mxStrlen;                     /* Maximum string length */
10252   int szLookaside;                  /* Default lookaside buffer size */
10253   int nLookaside;                   /* Default lookaside buffer count */
10254   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10255   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10256   void *pHeap;                      /* Heap storage space */
10257   int nHeap;                        /* Size of pHeap[] */
10258   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10259   void *pScratch;                   /* Scratch memory */
10260   int szScratch;                    /* Size of each scratch buffer */
10261   int nScratch;                     /* Number of scratch buffers */
10262   void *pPage;                      /* Page cache memory */
10263   int szPage;                       /* Size of each page in pPage[] */
10264   int nPage;                        /* Number of pages in pPage[] */
10265   int isInit;                       /* True after initialization has finished */
10266   int inProgress;                   /* True while initialization in progress */
10267   int isMallocInit;                 /* True after malloc is initialized */
10268   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10269   int nRefInitMutex;                /* Number of users of pInitMutex */
10270   int nSmall;                       /* alloc size threshold used by mem6.c */
10271   int mxParserStack;                /* maximum depth of the parser stack */
10272   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10273 };
10274
10275 /*
10276 ** Context pointer passed down through the tree-walk.
10277 */
10278 struct Walker {
10279   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10280   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10281   Parse *pParse;                            /* Parser context.  */
10282   union {                                   /* Extra data for callback */
10283     NameContext *pNC;                          /* Naming context */
10284     int i;                                     /* Integer value */
10285   } u;
10286 };
10287
10288 /* Forward declarations */
10289 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10290 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10291 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10292 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10293 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10294
10295 /*
10296 ** Return code from the parse-tree walking primitives and their
10297 ** callbacks.
10298 */
10299 #define WRC_Continue    0
10300 #define WRC_Prune       1
10301 #define WRC_Abort       2
10302
10303 /*
10304 ** Assuming zIn points to the first byte of a UTF-8 character,
10305 ** advance zIn to point to the first byte of the next UTF-8 character.
10306 */
10307 #define SQLITE_SKIP_UTF8(zIn) {                        \
10308   if( (*(zIn++))>=0xc0 ){                              \
10309     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10310   }                                                    \
10311 }
10312
10313 /*
10314 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
10315 ** builds) or a function call (for debugging).  If it is a function call,
10316 ** it allows the operator to set a breakpoint at the spot where database
10317 ** corruption is first detected.
10318 */
10319 #ifdef SQLITE_DEBUG
10320 SQLITE_PRIVATE   int sqlite3Corrupt(void);
10321 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
10322 #else
10323 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
10324 #endif
10325
10326 /*
10327 ** Internal function prototypes
10328 */
10329 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10330 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
10331 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10332 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
10333
10334 SQLITE_PRIVATE int sqlite3MallocInit(void);
10335 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10336 SQLITE_PRIVATE void *sqlite3Malloc(int);
10337 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10338 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10339 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10340 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10341 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10342 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10343 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10344 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10345 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10346 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10347 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10348 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10349 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10350 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10351 SQLITE_PRIVATE void sqlite3PageFree(void*);
10352 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10353 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void);
10354 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10355 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10356 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void);
10357 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10358 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10359
10360 #ifndef SQLITE_MUTEX_OMIT
10361 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10362 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10363 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10364 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10365 #endif
10366
10367 SQLITE_PRIVATE int sqlite3StatusValue(int);
10368 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10369 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10370
10371 SQLITE_PRIVATE int sqlite3IsNaN(double);
10372
10373 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10374 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10375 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10376 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10377 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10378 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10379 #endif
10380 #if defined(SQLITE_TEST)
10381 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10382 #endif
10383 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10384 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10385 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10386 SQLITE_PRIVATE void sqlite3Dequote(char*);
10387 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
10388 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10389 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10390 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10391 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10392 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10393 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10394 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10395 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
10396 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10397 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
10398 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10399 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
10400 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10401 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10402 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3*, Expr*);
10403 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10404 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
10405 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10406 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10407 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10408 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10409 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10410 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10411 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10412 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10413 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10414 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10415 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10416 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10417 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10418 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10419 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10420 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
10421 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10422 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10423
10424 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10425 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10426 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10427 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
10428 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10429 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10430
10431 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10432
10433 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10434 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10435 #else
10436 # define sqlite3ViewGetColumnNames(A,B) 0
10437 #endif
10438
10439 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10440 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10441 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10442 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10443 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10444 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10445 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10446 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10447                                       Token*, Select*, Expr*, IdList*);
10448 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10449 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10450 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10451 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10452 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10453 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10454 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10455                         Token*, int, int);
10456 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10457 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10458 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10459                          Expr*,ExprList*,int,Expr*,Expr*);
10460 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10461 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10462 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10463 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10464 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10465 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10466 #endif
10467 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10468 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10469 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8);
10470 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10471 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
10472 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10473 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10474 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
10475 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10476 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse*,int,int);
10477 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10478 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10479 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10480 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10481 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10482 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10483 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10484 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10485 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10486 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10487 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10488 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10489 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10490 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10491 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10492 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10493 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10494 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10495 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10496 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10497 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10498 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
10499 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10500 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10501 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10502 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10503 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10504 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10505 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10506 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10507 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10508 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10509 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10510 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10511 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10512 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
10513 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10514 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10515 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10516                                      int*,int,int,int,int);
10517 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int);
10518 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10519 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10520 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
10521 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
10522 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
10523 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
10524 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10525 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
10526 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10527 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10528 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10529 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10530 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10531 SQLITE_PRIVATE int sqlite3GetBuiltinFunction(const char *, int, FuncDef **);
10532 #ifdef SQLITE_DEBUG
10533 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10534 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10535 #else
10536 # define sqlite3SafetyOn(A) 0
10537 # define sqlite3SafetyOff(A) 0
10538 #endif
10539 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10540 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10541 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10542
10543 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10544 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10545 #endif
10546
10547 #ifndef SQLITE_OMIT_TRIGGER
10548 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10549                            Expr*,int, int);
10550 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10551 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10552 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10553 SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
10554 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
10555                            int, int, u32*, u32*);
10556   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10557 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10558 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10559 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10560                                         ExprList*,Select*,int);
10561 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
10562 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10563 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10564 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10565 #else
10566 # define sqlite3TriggersExist(A,B,C,D,E,F) 0
10567 # define sqlite3DeleteTrigger(A,B)
10568 # define sqlite3DropTriggerPtr(A,B)
10569 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10570 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
10571 #endif
10572
10573 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10574 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10575 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10576 #ifndef SQLITE_OMIT_AUTHORIZATION
10577 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10578 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10579 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10580 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10581 #else
10582 # define sqlite3AuthRead(a,b,c,d)
10583 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10584 # define sqlite3AuthContextPush(a,b,c)
10585 # define sqlite3AuthContextPop(a)  ((void)(a))
10586 #endif
10587 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10588 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10589 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
10590                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10591 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10592 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10593 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10594 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10595 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10596 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10597 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10598 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10599 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10600 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10601 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10602 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
10603
10604 /*
10605 ** Routines to read and write variable-length integers.  These used to
10606 ** be defined locally, but now we use the varint routines in the util.c
10607 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10608 ** are coded to assume the single byte case is already handled (which 
10609 ** the MACRO form does).
10610 */
10611 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10612 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10613 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
10614 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
10615 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10616
10617 /*
10618 ** The header of a record consists of a sequence variable-length integers.
10619 ** These integers are almost always small and are encoded as a single byte.
10620 ** The following macros take advantage this fact to provide a fast encode
10621 ** and decode of the integers in a record header.  It is faster for the common
10622 ** case where the integer is a single byte.  It is a little slower when the
10623 ** integer is two or more bytes.  But overall it is faster.
10624 **
10625 ** The following expressions are equivalent:
10626 **
10627 **     x = sqlite3GetVarint32( A, &B );
10628 **     x = sqlite3PutVarint32( A, B );
10629 **
10630 **     x = getVarint32( A, B );
10631 **     x = putVarint32( A, B );
10632 **
10633 */
10634 #define getVarint32(A,B)  ((*(A)<(unsigned char)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), &(B)))
10635 #define putVarint32(A,B)  (((B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10636 #define getVarint    sqlite3GetVarint
10637 #define putVarint    sqlite3PutVarint
10638
10639
10640 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
10641 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10642 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10643 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10644 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10645 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10646 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10647 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10648 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10649 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10650 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10651 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
10652 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
10653 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10654 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10655 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10656 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10657 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10658
10659 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10660 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10661 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10662                         void(*)(void*));
10663 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10664 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10665 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10666 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10667 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10668 #ifndef SQLITE_AMALGAMATION
10669 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10670 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10671 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10672 #endif
10673 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10674 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10675 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10676 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10677 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10678 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10679 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10680 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int, int);
10681 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10682 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10683 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10684 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10685 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
10686 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10687 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10688 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
10689 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
10690 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10691 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10692 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10693 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10694 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10695 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10696 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10697 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
10698 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10699 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10700 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10701 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10702 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10703 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10704   void (*)(sqlite3_context*,int,sqlite3_value **),
10705   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10706 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10707 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10708
10709 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10710 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10711 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10712 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10713 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10714
10715 /*
10716 ** The interface to the LEMON-generated parser
10717 */
10718 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10719 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10720 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10721 #ifdef YYTRACKMAXSTACKDEPTH
10722 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10723 #endif
10724
10725 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
10726 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10727 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10728 #else
10729 # define sqlite3CloseExtensions(X)
10730 #endif
10731
10732 #ifndef SQLITE_OMIT_SHARED_CACHE
10733 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10734 #else
10735   #define sqlite3TableLock(v,w,x,y,z)
10736 #endif
10737
10738 #ifdef SQLITE_TEST
10739 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10740 #endif
10741
10742 #ifdef SQLITE_OMIT_VIRTUALTABLE
10743 #  define sqlite3VtabClear(X)
10744 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10745 #  define sqlite3VtabRollback(X)
10746 #  define sqlite3VtabCommit(X)
10747 #else
10748 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10749 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10750 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10751 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10752 #endif
10753 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10754 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
10755 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
10756 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10757 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10758 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10759 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10760 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10761 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10762 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10763 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
10764 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10765 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10766 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10767 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10768 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10769 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10770
10771
10772 /*
10773 ** Available fault injectors.  Should be numbered beginning with 0.
10774 */
10775 #define SQLITE_FAULTINJECTOR_MALLOC     0
10776 #define SQLITE_FAULTINJECTOR_COUNT      1
10777
10778 /*
10779 ** The interface to the code in fault.c used for identifying "benign"
10780 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10781 ** is not defined.
10782 */
10783 #ifndef SQLITE_OMIT_BUILTIN_TEST
10784 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10785 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10786 #else
10787   #define sqlite3BeginBenignMalloc()
10788   #define sqlite3EndBenignMalloc()
10789 #endif
10790
10791 #define IN_INDEX_ROWID           1
10792 #define IN_INDEX_EPH             2
10793 #define IN_INDEX_INDEX           3
10794 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10795
10796 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10797 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10798 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10799 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10800 #else
10801   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10802 #endif
10803
10804 #if SQLITE_MAX_EXPR_DEPTH>0
10805 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10806 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10807 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10808 #else
10809   #define sqlite3ExprSetHeight(x,y)
10810   #define sqlite3SelectExprHeight(x) 0
10811   #define sqlite3ExprCheckHeight(x,y)
10812 #endif
10813
10814 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10815 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10816
10817 #ifdef SQLITE_SSE
10818 #include "sseInt.h"
10819 #endif
10820
10821 #ifdef SQLITE_DEBUG
10822 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10823 #endif
10824
10825 /*
10826 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10827 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10828 ** print I/O tracing messages. 
10829 */
10830 #ifdef SQLITE_ENABLE_IOTRACE
10831 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10832 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10833 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10834 #else
10835 # define IOTRACE(A)
10836 # define sqlite3VdbeIOTraceSql(X)
10837 #endif
10838
10839 #endif
10840
10841 /************** End of sqliteInt.h *******************************************/
10842 /************** Begin file global.c ******************************************/
10843 /*
10844 ** 2008 June 13
10845 **
10846 ** The author disclaims copyright to this source code.  In place of
10847 ** a legal notice, here is a blessing:
10848 **
10849 **    May you do good and not evil.
10850 **    May you find forgiveness for yourself and forgive others.
10851 **    May you share freely, never taking more than you give.
10852 **
10853 *************************************************************************
10854 **
10855 ** This file contains definitions of global variables and contants.
10856 **
10857 ** $Id: global.c,v 1.8 2008/09/04 17:17:39 danielk1977 Exp $
10858 */
10859
10860
10861 /* An array to map all upper-case characters into their corresponding
10862 ** lower-case character. 
10863 **
10864 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10865 ** handle case conversions for the UTF character set since the tables
10866 ** involved are nearly as big or bigger than SQLite itself.
10867 */
10868 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10869 #ifdef SQLITE_ASCII
10870       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10871      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10872      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10873      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10874     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10875     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10876     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10877     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10878     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10879     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10880     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10881     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10882     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10883     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10884     252,253,254,255
10885 #endif
10886 #ifdef SQLITE_EBCDIC
10887       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10888      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10889      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10890      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10891      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10892      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10893      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10894     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10895     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10896     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10897     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10898     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10899     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10900     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10901     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10902     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10903 #endif
10904 };
10905
10906 /*
10907 ** The following singleton contains the global configuration for
10908 ** the SQLite library.
10909 */
10910 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10911    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10912    1,                         /* bCoreMutex */
10913    SQLITE_THREADSAFE==1,      /* bFullMutex */
10914    0x7ffffffe,                /* mxStrlen */
10915    100,                       /* szLookaside */
10916    500,                       /* nLookaside */
10917    /* Other fields all default to zero */
10918 };
10919
10920
10921 /*
10922 ** Hash table for global functions - functions common to all
10923 ** database connections.  After initialization, this table is
10924 ** read-only.
10925 */
10926 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10927
10928 /************** End of global.c **********************************************/
10929 /************** Begin file status.c ******************************************/
10930 /*
10931 ** 2008 June 18
10932 **
10933 ** The author disclaims copyright to this source code.  In place of
10934 ** a legal notice, here is a blessing:
10935 **
10936 **    May you do good and not evil.
10937 **    May you find forgiveness for yourself and forgive others.
10938 **    May you share freely, never taking more than you give.
10939 **
10940 *************************************************************************
10941 **
10942 ** This module implements the sqlite3_status() interface and related
10943 ** functionality.
10944 **
10945 ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
10946 */
10947
10948 /*
10949 ** Variables in which to record status information.
10950 */
10951 typedef struct sqlite3StatType sqlite3StatType;
10952 static SQLITE_WSD struct sqlite3StatType {
10953   int nowValue[9];         /* Current value */
10954   int mxValue[9];          /* Maximum value */
10955 } sqlite3Stat = { {0,}, {0,} };
10956
10957
10958 /* The "wsdStat" macro will resolve to the status information
10959 ** state vector.  If writable static data is unsupported on the target,
10960 ** we have to locate the state vector at run-time.  In the more common
10961 ** case where writable static data is supported, wsdStat can refer directly
10962 ** to the "sqlite3Stat" state vector declared above.
10963 */
10964 #ifdef SQLITE_OMIT_WSD
10965 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10966 # define wsdStat x[0]
10967 #else
10968 # define wsdStatInit
10969 # define wsdStat sqlite3Stat
10970 #endif
10971
10972 /*
10973 ** Return the current value of a status parameter.
10974 */
10975 SQLITE_PRIVATE int sqlite3StatusValue(int op){
10976   wsdStatInit;
10977   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10978   return wsdStat.nowValue[op];
10979 }
10980
10981 /*
10982 ** Add N to the value of a status record.  It is assumed that the
10983 ** caller holds appropriate locks.
10984 */
10985 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10986   wsdStatInit;
10987   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10988   wsdStat.nowValue[op] += N;
10989   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10990     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10991   }
10992 }
10993
10994 /*
10995 ** Set the value of a status to X.
10996 */
10997 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10998   wsdStatInit;
10999   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11000   wsdStat.nowValue[op] = X;
11001   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11002     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11003   }
11004 }
11005
11006 /*
11007 ** Query status information.
11008 **
11009 ** This implementation assumes that reading or writing an aligned
11010 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11011 ** then this routine is not threadsafe.
11012 */
11013 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11014   wsdStatInit;
11015   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11016     return SQLITE_MISUSE;
11017   }
11018   *pCurrent = wsdStat.nowValue[op];
11019   *pHighwater = wsdStat.mxValue[op];
11020   if( resetFlag ){
11021     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11022   }
11023   return SQLITE_OK;
11024 }
11025
11026 /*
11027 ** Query status information for a single database connection
11028 */
11029 SQLITE_API int sqlite3_db_status(
11030   sqlite3 *db,          /* The database connection whose status is desired */
11031   int op,               /* Status verb */
11032   int *pCurrent,        /* Write current value here */
11033   int *pHighwater,      /* Write high-water mark here */
11034   int resetFlag         /* Reset high-water mark if true */
11035 ){
11036   switch( op ){
11037     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11038       *pCurrent = db->lookaside.nOut;
11039       *pHighwater = db->lookaside.mxOut;
11040       if( resetFlag ){
11041         db->lookaside.mxOut = db->lookaside.nOut;
11042       }
11043       break;
11044     }
11045     default: {
11046       return SQLITE_ERROR;
11047     }
11048   }
11049   return SQLITE_OK;
11050 }
11051
11052 /************** End of status.c **********************************************/
11053 /************** Begin file date.c ********************************************/
11054 /*
11055 ** 2003 October 31
11056 **
11057 ** The author disclaims copyright to this source code.  In place of
11058 ** a legal notice, here is a blessing:
11059 **
11060 **    May you do good and not evil.
11061 **    May you find forgiveness for yourself and forgive others.
11062 **    May you share freely, never taking more than you give.
11063 **
11064 *************************************************************************
11065 ** This file contains the C functions that implement date and time
11066 ** functions for SQLite.  
11067 **
11068 ** There is only one exported symbol in this file - the function
11069 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11070 ** All other code has file scope.
11071 **
11072 ** $Id: date.c,v 1.92 2008/10/13 15:35:09 drh Exp $
11073 **
11074 ** SQLite processes all times and dates as Julian Day numbers.  The
11075 ** dates and times are stored as the number of days since noon
11076 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11077 ** calendar system. 
11078 **
11079 ** 1970-01-01 00:00:00 is JD 2440587.5
11080 ** 2000-01-01 00:00:00 is JD 2451544.5
11081 **
11082 ** This implemention requires years to be expressed as a 4-digit number
11083 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11084 ** be represented, even though julian day numbers allow a much wider
11085 ** range of dates.
11086 **
11087 ** The Gregorian calendar system is used for all dates and times,
11088 ** even those that predate the Gregorian calendar.  Historians usually
11089 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11090 ** dates afterwards, depending on locale.  Beware of this difference.
11091 **
11092 ** The conversion algorithms are implemented based on descriptions
11093 ** in the following text:
11094 **
11095 **      Jean Meeus
11096 **      Astronomical Algorithms, 2nd Edition, 1998
11097 **      ISBM 0-943396-61-1
11098 **      Willmann-Bell, Inc
11099 **      Richmond, Virginia (USA)
11100 */
11101 #include <ctype.h>
11102 #include <time.h>
11103
11104 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11105
11106 /*
11107 ** On recent Windows platforms, the localtime_s() function is available
11108 ** as part of the "Secure CRT". It is essentially equivalent to 
11109 ** localtime_r() available under most POSIX platforms, except that the 
11110 ** order of the parameters is reversed.
11111 **
11112 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11113 **
11114 ** If the user has not indicated to use localtime_r() or localtime_s()
11115 ** already, check for an MSVC build environment that provides 
11116 ** localtime_s().
11117 */
11118 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11119      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11120 #define HAVE_LOCALTIME_S 1
11121 #endif
11122
11123 /*
11124 ** A structure for holding a single date and time.
11125 */
11126 typedef struct DateTime DateTime;
11127 struct DateTime {
11128   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11129   int Y, M, D;       /* Year, month, and day */
11130   int h, m;          /* Hour and minutes */
11131   int tz;            /* Timezone offset in minutes */
11132   double s;          /* Seconds */
11133   char validYMD;     /* True if Y,M,D are valid */
11134   char validHMS;     /* True if h,m,s are valid */
11135   char validJD;      /* True if iJD is valid */
11136   char validTZ;      /* True if tz is valid */
11137 };
11138
11139
11140 /*
11141 ** Convert zDate into one or more integers.  Additional arguments
11142 ** come in groups of 5 as follows:
11143 **
11144 **       N       number of digits in the integer
11145 **       min     minimum allowed value of the integer
11146 **       max     maximum allowed value of the integer
11147 **       nextC   first character after the integer
11148 **       pVal    where to write the integers value.
11149 **
11150 ** Conversions continue until one with nextC==0 is encountered.
11151 ** The function returns the number of successful conversions.
11152 */
11153 static int getDigits(const char *zDate, ...){
11154   va_list ap;
11155   int val;
11156   int N;
11157   int min;
11158   int max;
11159   int nextC;
11160   int *pVal;
11161   int cnt = 0;
11162   va_start(ap, zDate);
11163   do{
11164     N = va_arg(ap, int);
11165     min = va_arg(ap, int);
11166     max = va_arg(ap, int);
11167     nextC = va_arg(ap, int);
11168     pVal = va_arg(ap, int*);
11169     val = 0;
11170     while( N-- ){
11171       if( !isdigit(*(u8*)zDate) ){
11172         goto end_getDigits;
11173       }
11174       val = val*10 + *zDate - '0';
11175       zDate++;
11176     }
11177     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11178       goto end_getDigits;
11179     }
11180     *pVal = val;
11181     zDate++;
11182     cnt++;
11183   }while( nextC );
11184 end_getDigits:
11185   va_end(ap);
11186   return cnt;
11187 }
11188
11189 /*
11190 ** Read text from z[] and convert into a floating point number.  Return
11191 ** the number of digits converted.
11192 */
11193 #define getValue sqlite3AtoF
11194
11195 /*
11196 ** Parse a timezone extension on the end of a date-time.
11197 ** The extension is of the form:
11198 **
11199 **        (+/-)HH:MM
11200 **
11201 ** Or the "zulu" notation:
11202 **
11203 **        Z
11204 **
11205 ** If the parse is successful, write the number of minutes
11206 ** of change in p->tz and return 0.  If a parser error occurs,
11207 ** return non-zero.
11208 **
11209 ** A missing specifier is not considered an error.
11210 */
11211 static int parseTimezone(const char *zDate, DateTime *p){
11212   int sgn = 0;
11213   int nHr, nMn;
11214   int c;
11215   while( isspace(*(u8*)zDate) ){ zDate++; }
11216   p->tz = 0;
11217   c = *zDate;
11218   if( c=='-' ){
11219     sgn = -1;
11220   }else if( c=='+' ){
11221     sgn = +1;
11222   }else if( c=='Z' || c=='z' ){
11223     zDate++;
11224     goto zulu_time;
11225   }else{
11226     return c!=0;
11227   }
11228   zDate++;
11229   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11230     return 1;
11231   }
11232   zDate += 5;
11233   p->tz = sgn*(nMn + nHr*60);
11234 zulu_time:
11235   while( isspace(*(u8*)zDate) ){ zDate++; }
11236   return *zDate!=0;
11237 }
11238
11239 /*
11240 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11241 ** The HH, MM, and SS must each be exactly 2 digits.  The
11242 ** fractional seconds FFFF can be one or more digits.
11243 **
11244 ** Return 1 if there is a parsing error and 0 on success.
11245 */
11246 static int parseHhMmSs(const char *zDate, DateTime *p){
11247   int h, m, s;
11248   double ms = 0.0;
11249   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11250     return 1;
11251   }
11252   zDate += 5;
11253   if( *zDate==':' ){
11254     zDate++;
11255     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11256       return 1;
11257     }
11258     zDate += 2;
11259     if( *zDate=='.' && isdigit((u8)zDate[1]) ){
11260       double rScale = 1.0;
11261       zDate++;
11262       while( isdigit(*(u8*)zDate) ){
11263         ms = ms*10.0 + *zDate - '0';
11264         rScale *= 10.0;
11265         zDate++;
11266       }
11267       ms /= rScale;
11268     }
11269   }else{
11270     s = 0;
11271   }
11272   p->validJD = 0;
11273   p->validHMS = 1;
11274   p->h = h;
11275   p->m = m;
11276   p->s = s + ms;
11277   if( parseTimezone(zDate, p) ) return 1;
11278   p->validTZ = p->tz!=0;
11279   return 0;
11280 }
11281
11282 /*
11283 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11284 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11285 **
11286 ** Reference:  Meeus page 61
11287 */
11288 static void computeJD(DateTime *p){
11289   int Y, M, D, A, B, X1, X2;
11290
11291   if( p->validJD ) return;
11292   if( p->validYMD ){
11293     Y = p->Y;
11294     M = p->M;
11295     D = p->D;
11296   }else{
11297     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11298     M = 1;
11299     D = 1;
11300   }
11301   if( M<=2 ){
11302     Y--;
11303     M += 12;
11304   }
11305   A = Y/100;
11306   B = 2 - A + (A/4);
11307   X1 = 365.25*(Y+4716);
11308   X2 = 30.6001*(M+1);
11309   p->iJD = (X1 + X2 + D + B - 1524.5)*86400000;
11310   p->validJD = 1;
11311   if( p->validHMS ){
11312     p->iJD += p->h*3600000 + p->m*60000 + p->s*1000;
11313     if( p->validTZ ){
11314       p->iJD -= p->tz*60000;
11315       p->validYMD = 0;
11316       p->validHMS = 0;
11317       p->validTZ = 0;
11318     }
11319   }
11320 }
11321
11322 /*
11323 ** Parse dates of the form
11324 **
11325 **     YYYY-MM-DD HH:MM:SS.FFF
11326 **     YYYY-MM-DD HH:MM:SS
11327 **     YYYY-MM-DD HH:MM
11328 **     YYYY-MM-DD
11329 **
11330 ** Write the result into the DateTime structure and return 0
11331 ** on success and 1 if the input string is not a well-formed
11332 ** date.
11333 */
11334 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11335   int Y, M, D, neg;
11336
11337   if( zDate[0]=='-' ){
11338     zDate++;
11339     neg = 1;
11340   }else{
11341     neg = 0;
11342   }
11343   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11344     return 1;
11345   }
11346   zDate += 10;
11347   while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11348   if( parseHhMmSs(zDate, p)==0 ){
11349     /* We got the time */
11350   }else if( *zDate==0 ){
11351     p->validHMS = 0;
11352   }else{
11353     return 1;
11354   }
11355   p->validJD = 0;
11356   p->validYMD = 1;
11357   p->Y = neg ? -Y : Y;
11358   p->M = M;
11359   p->D = D;
11360   if( p->validTZ ){
11361     computeJD(p);
11362   }
11363   return 0;
11364 }
11365
11366 /*
11367 ** Set the time to the current time reported by the VFS
11368 */
11369 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11370   double r;
11371   sqlite3 *db = sqlite3_context_db_handle(context);
11372   sqlite3OsCurrentTime(db->pVfs, &r);
11373   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11374   p->validJD = 1;
11375 }
11376
11377 /*
11378 ** Attempt to parse the given string into a Julian Day Number.  Return
11379 ** the number of errors.
11380 **
11381 ** The following are acceptable forms for the input string:
11382 **
11383 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11384 **      DDDD.DD 
11385 **      now
11386 **
11387 ** In the first form, the +/-HH:MM is always optional.  The fractional
11388 ** seconds extension (the ".FFF") is optional.  The seconds portion
11389 ** (":SS.FFF") is option.  The year and date can be omitted as long
11390 ** as there is a time string.  The time string can be omitted as long
11391 ** as there is a year and date.
11392 */
11393 static int parseDateOrTime(
11394   sqlite3_context *context, 
11395   const char *zDate, 
11396   DateTime *p
11397 ){
11398   if( parseYyyyMmDd(zDate,p)==0 ){
11399     return 0;
11400   }else if( parseHhMmSs(zDate, p)==0 ){
11401     return 0;
11402   }else if( sqlite3StrICmp(zDate,"now")==0){
11403     setDateTimeToCurrent(context, p);
11404     return 0;
11405   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
11406     double r;
11407     getValue(zDate, &r);
11408     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11409     p->validJD = 1;
11410     return 0;
11411   }
11412   return 1;
11413 }
11414
11415 /*
11416 ** Compute the Year, Month, and Day from the julian day number.
11417 */
11418 static void computeYMD(DateTime *p){
11419   int Z, A, B, C, D, E, X1;
11420   if( p->validYMD ) return;
11421   if( !p->validJD ){
11422     p->Y = 2000;
11423     p->M = 1;
11424     p->D = 1;
11425   }else{
11426     Z = (p->iJD + 43200000)/86400000;
11427     A = (Z - 1867216.25)/36524.25;
11428     A = Z + 1 + A - (A/4);
11429     B = A + 1524;
11430     C = (B - 122.1)/365.25;
11431     D = 365.25*C;
11432     E = (B-D)/30.6001;
11433     X1 = 30.6001*E;
11434     p->D = B - D - X1;
11435     p->M = E<14 ? E-1 : E-13;
11436     p->Y = p->M>2 ? C - 4716 : C - 4715;
11437   }
11438   p->validYMD = 1;
11439 }
11440
11441 /*
11442 ** Compute the Hour, Minute, and Seconds from the julian day number.
11443 */
11444 static void computeHMS(DateTime *p){
11445   int s;
11446   if( p->validHMS ) return;
11447   computeJD(p);
11448   s = (p->iJD + 43200000) % 86400000;
11449   p->s = s/1000.0;
11450   s = p->s;
11451   p->s -= s;
11452   p->h = s/3600;
11453   s -= p->h*3600;
11454   p->m = s/60;
11455   p->s += s - p->m*60;
11456   p->validHMS = 1;
11457 }
11458
11459 /*
11460 ** Compute both YMD and HMS
11461 */
11462 static void computeYMD_HMS(DateTime *p){
11463   computeYMD(p);
11464   computeHMS(p);
11465 }
11466
11467 /*
11468 ** Clear the YMD and HMS and the TZ
11469 */
11470 static void clearYMD_HMS_TZ(DateTime *p){
11471   p->validYMD = 0;
11472   p->validHMS = 0;
11473   p->validTZ = 0;
11474 }
11475
11476 #ifndef SQLITE_OMIT_LOCALTIME
11477 /*
11478 ** Compute the difference (in milliseconds)
11479 ** between localtime and UTC (a.k.a. GMT)
11480 ** for the time value p where p is in UTC.
11481 */
11482 static int localtimeOffset(DateTime *p){
11483   DateTime x, y;
11484   time_t t;
11485   x = *p;
11486   computeYMD_HMS(&x);
11487   if( x.Y<1971 || x.Y>=2038 ){
11488     x.Y = 2000;
11489     x.M = 1;
11490     x.D = 1;
11491     x.h = 0;
11492     x.m = 0;
11493     x.s = 0.0;
11494   } else {
11495     int s = x.s + 0.5;
11496     x.s = s;
11497   }
11498   x.tz = 0;
11499   x.validJD = 0;
11500   computeJD(&x);
11501   t = x.iJD/1000 - 2440587.5*86400.0;
11502 #ifdef HAVE_LOCALTIME_R
11503   {
11504     struct tm sLocal;
11505     localtime_r(&t, &sLocal);
11506     y.Y = sLocal.tm_year + 1900;
11507     y.M = sLocal.tm_mon + 1;
11508     y.D = sLocal.tm_mday;
11509     y.h = sLocal.tm_hour;
11510     y.m = sLocal.tm_min;
11511     y.s = sLocal.tm_sec;
11512   }
11513 #elif defined(HAVE_LOCALTIME_S)
11514   {
11515     struct tm sLocal;
11516     localtime_s(&sLocal, &t);
11517     y.Y = sLocal.tm_year + 1900;
11518     y.M = sLocal.tm_mon + 1;
11519     y.D = sLocal.tm_mday;
11520     y.h = sLocal.tm_hour;
11521     y.m = sLocal.tm_min;
11522     y.s = sLocal.tm_sec;
11523   }
11524 #else
11525   {
11526     struct tm *pTm;
11527     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11528     pTm = localtime(&t);
11529     y.Y = pTm->tm_year + 1900;
11530     y.M = pTm->tm_mon + 1;
11531     y.D = pTm->tm_mday;
11532     y.h = pTm->tm_hour;
11533     y.m = pTm->tm_min;
11534     y.s = pTm->tm_sec;
11535     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11536   }
11537 #endif
11538   y.validYMD = 1;
11539   y.validHMS = 1;
11540   y.validJD = 0;
11541   y.validTZ = 0;
11542   computeJD(&y);
11543   return y.iJD - x.iJD;
11544 }
11545 #endif /* SQLITE_OMIT_LOCALTIME */
11546
11547 /*
11548 ** Process a modifier to a date-time stamp.  The modifiers are
11549 ** as follows:
11550 **
11551 **     NNN days
11552 **     NNN hours
11553 **     NNN minutes
11554 **     NNN.NNNN seconds
11555 **     NNN months
11556 **     NNN years
11557 **     start of month
11558 **     start of year
11559 **     start of week
11560 **     start of day
11561 **     weekday N
11562 **     unixepoch
11563 **     localtime
11564 **     utc
11565 **
11566 ** Return 0 on success and 1 if there is any kind of error.
11567 */
11568 static int parseModifier(const char *zMod, DateTime *p){
11569   int rc = 1;
11570   int n;
11571   double r;
11572   char *z, zBuf[30];
11573   z = zBuf;
11574   for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
11575     z[n] = tolower(zMod[n]);
11576   }
11577   z[n] = 0;
11578   switch( z[0] ){
11579 #ifndef SQLITE_OMIT_LOCALTIME
11580     case 'l': {
11581       /*    localtime
11582       **
11583       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11584       ** show local time.
11585       */
11586       if( strcmp(z, "localtime")==0 ){
11587         computeJD(p);
11588         p->iJD += localtimeOffset(p);
11589         clearYMD_HMS_TZ(p);
11590         rc = 0;
11591       }
11592       break;
11593     }
11594 #endif
11595     case 'u': {
11596       /*
11597       **    unixepoch
11598       **
11599       ** Treat the current value of p->iJD as the number of
11600       ** seconds since 1970.  Convert to a real julian day number.
11601       */
11602       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11603         p->iJD = p->iJD/86400.0 + 2440587.5*86400000.0;
11604         clearYMD_HMS_TZ(p);
11605         rc = 0;
11606       }
11607 #ifndef SQLITE_OMIT_LOCALTIME
11608       else if( strcmp(z, "utc")==0 ){
11609         int c1;
11610         computeJD(p);
11611         c1 = localtimeOffset(p);
11612         p->iJD -= c1;
11613         clearYMD_HMS_TZ(p);
11614         p->iJD += c1 - localtimeOffset(p);
11615         rc = 0;
11616       }
11617 #endif
11618       break;
11619     }
11620     case 'w': {
11621       /*
11622       **    weekday N
11623       **
11624       ** Move the date to the same time on the next occurrence of
11625       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11626       ** date is already on the appropriate weekday, this is a no-op.
11627       */
11628       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11629                  && (n=r)==r && n>=0 && r<7 ){
11630         sqlite3_int64 Z;
11631         computeYMD_HMS(p);
11632         p->validTZ = 0;
11633         p->validJD = 0;
11634         computeJD(p);
11635         Z = ((p->iJD + 129600000)/86400000) % 7;
11636         if( Z>n ) Z -= 7;
11637         p->iJD += (n - Z)*86400000;
11638         clearYMD_HMS_TZ(p);
11639         rc = 0;
11640       }
11641       break;
11642     }
11643     case 's': {
11644       /*
11645       **    start of TTTTT
11646       **
11647       ** Move the date backwards to the beginning of the current day,
11648       ** or month or year.
11649       */
11650       if( strncmp(z, "start of ", 9)!=0 ) break;
11651       z += 9;
11652       computeYMD(p);
11653       p->validHMS = 1;
11654       p->h = p->m = 0;
11655       p->s = 0.0;
11656       p->validTZ = 0;
11657       p->validJD = 0;
11658       if( strcmp(z,"month")==0 ){
11659         p->D = 1;
11660         rc = 0;
11661       }else if( strcmp(z,"year")==0 ){
11662         computeYMD(p);
11663         p->M = 1;
11664         p->D = 1;
11665         rc = 0;
11666       }else if( strcmp(z,"day")==0 ){
11667         rc = 0;
11668       }
11669       break;
11670     }
11671     case '+':
11672     case '-':
11673     case '0':
11674     case '1':
11675     case '2':
11676     case '3':
11677     case '4':
11678     case '5':
11679     case '6':
11680     case '7':
11681     case '8':
11682     case '9': {
11683       n = getValue(z, &r);
11684       assert( n>=1 );
11685       if( z[n]==':' ){
11686         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11687         ** specified number of hours, minutes, seconds, and fractional seconds
11688         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11689         ** omitted.
11690         */
11691         const char *z2 = z;
11692         DateTime tx;
11693         sqlite3_int64 day;
11694         if( !isdigit(*(u8*)z2) ) z2++;
11695         memset(&tx, 0, sizeof(tx));
11696         if( parseHhMmSs(z2, &tx) ) break;
11697         computeJD(&tx);
11698         tx.iJD -= 43200000;
11699         day = tx.iJD/86400000;
11700         tx.iJD -= day*86400000;
11701         if( z[0]=='-' ) tx.iJD = -tx.iJD;
11702         computeJD(p);
11703         clearYMD_HMS_TZ(p);
11704         p->iJD += tx.iJD;
11705         rc = 0;
11706         break;
11707       }
11708       z += n;
11709       while( isspace(*(u8*)z) ) z++;
11710       n = strlen(z);
11711       if( n>10 || n<3 ) break;
11712       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11713       computeJD(p);
11714       rc = 0;
11715       if( n==3 && strcmp(z,"day")==0 ){
11716         p->iJD += r*86400000.0 + 0.5;
11717       }else if( n==4 && strcmp(z,"hour")==0 ){
11718         p->iJD += r*(86400000.0/24.0) + 0.5;
11719       }else if( n==6 && strcmp(z,"minute")==0 ){
11720         p->iJD += r*(86400000.0/(24.0*60.0)) + 0.5;
11721       }else if( n==6 && strcmp(z,"second")==0 ){
11722         p->iJD += r*(86400000.0/(24.0*60.0*60.0)) + 0.5;
11723       }else if( n==5 && strcmp(z,"month")==0 ){
11724         int x, y;
11725         computeYMD_HMS(p);
11726         p->M += r;
11727         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11728         p->Y += x;
11729         p->M -= x*12;
11730         p->validJD = 0;
11731         computeJD(p);
11732         y = r;
11733         if( y!=r ){
11734           p->iJD += (r - y)*30.0*86400000.0 + 0.5;
11735         }
11736       }else if( n==4 && strcmp(z,"year")==0 ){
11737         computeYMD_HMS(p);
11738         p->Y += r;
11739         p->validJD = 0;
11740         computeJD(p);
11741       }else{
11742         rc = 1;
11743       }
11744       clearYMD_HMS_TZ(p);
11745       break;
11746     }
11747     default: {
11748       break;
11749     }
11750   }
11751   return rc;
11752 }
11753
11754 /*
11755 ** Process time function arguments.  argv[0] is a date-time stamp.
11756 ** argv[1] and following are modifiers.  Parse them all and write
11757 ** the resulting time into the DateTime structure p.  Return 0
11758 ** on success and 1 if there are any errors.
11759 **
11760 ** If there are zero parameters (if even argv[0] is undefined)
11761 ** then assume a default value of "now" for argv[0].
11762 */
11763 static int isDate(
11764   sqlite3_context *context, 
11765   int argc, 
11766   sqlite3_value **argv, 
11767   DateTime *p
11768 ){
11769   int i;
11770   const unsigned char *z;
11771   int eType;
11772   memset(p, 0, sizeof(*p));
11773   if( argc==0 ){
11774     setDateTimeToCurrent(context, p);
11775   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11776                    || eType==SQLITE_INTEGER ){
11777     p->iJD = sqlite3_value_double(argv[0])*86400000.0 + 0.5;
11778     p->validJD = 1;
11779   }else{
11780     z = sqlite3_value_text(argv[0]);
11781     if( !z || parseDateOrTime(context, (char*)z, p) ){
11782       return 1;
11783     }
11784   }
11785   for(i=1; i<argc; i++){
11786     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11787       return 1;
11788     }
11789   }
11790   return 0;
11791 }
11792
11793
11794 /*
11795 ** The following routines implement the various date and time functions
11796 ** of SQLite.
11797 */
11798
11799 /*
11800 **    julianday( TIMESTRING, MOD, MOD, ...)
11801 **
11802 ** Return the julian day number of the date specified in the arguments
11803 */
11804 static void juliandayFunc(
11805   sqlite3_context *context,
11806   int argc,
11807   sqlite3_value **argv
11808 ){
11809   DateTime x;
11810   if( isDate(context, argc, argv, &x)==0 ){
11811     computeJD(&x);
11812     sqlite3_result_double(context, x.iJD/86400000.0);
11813   }
11814 }
11815
11816 /*
11817 **    datetime( TIMESTRING, MOD, MOD, ...)
11818 **
11819 ** Return YYYY-MM-DD HH:MM:SS
11820 */
11821 static void datetimeFunc(
11822   sqlite3_context *context,
11823   int argc,
11824   sqlite3_value **argv
11825 ){
11826   DateTime x;
11827   if( isDate(context, argc, argv, &x)==0 ){
11828     char zBuf[100];
11829     computeYMD_HMS(&x);
11830     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11831                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11832     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11833   }
11834 }
11835
11836 /*
11837 **    time( TIMESTRING, MOD, MOD, ...)
11838 **
11839 ** Return HH:MM:SS
11840 */
11841 static void timeFunc(
11842   sqlite3_context *context,
11843   int argc,
11844   sqlite3_value **argv
11845 ){
11846   DateTime x;
11847   if( isDate(context, argc, argv, &x)==0 ){
11848     char zBuf[100];
11849     computeHMS(&x);
11850     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11851     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11852   }
11853 }
11854
11855 /*
11856 **    date( TIMESTRING, MOD, MOD, ...)
11857 **
11858 ** Return YYYY-MM-DD
11859 */
11860 static void dateFunc(
11861   sqlite3_context *context,
11862   int argc,
11863   sqlite3_value **argv
11864 ){
11865   DateTime x;
11866   if( isDate(context, argc, argv, &x)==0 ){
11867     char zBuf[100];
11868     computeYMD(&x);
11869     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11870     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11871   }
11872 }
11873
11874 /*
11875 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11876 **
11877 ** Return a string described by FORMAT.  Conversions as follows:
11878 **
11879 **   %d  day of month
11880 **   %f  ** fractional seconds  SS.SSS
11881 **   %H  hour 00-24
11882 **   %j  day of year 000-366
11883 **   %J  ** Julian day number
11884 **   %m  month 01-12
11885 **   %M  minute 00-59
11886 **   %s  seconds since 1970-01-01
11887 **   %S  seconds 00-59
11888 **   %w  day of week 0-6  sunday==0
11889 **   %W  week of year 00-53
11890 **   %Y  year 0000-9999
11891 **   %%  %
11892 */
11893 static void strftimeFunc(
11894   sqlite3_context *context,
11895   int argc,
11896   sqlite3_value **argv
11897 ){
11898   DateTime x;
11899   u64 n;
11900   int i, j;
11901   char *z;
11902   sqlite3 *db;
11903   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11904   char zBuf[100];
11905   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11906   db = sqlite3_context_db_handle(context);
11907   for(i=0, n=1; zFmt[i]; i++, n++){
11908     if( zFmt[i]=='%' ){
11909       switch( zFmt[i+1] ){
11910         case 'd':
11911         case 'H':
11912         case 'm':
11913         case 'M':
11914         case 'S':
11915         case 'W':
11916           n++;
11917           /* fall thru */
11918         case 'w':
11919         case '%':
11920           break;
11921         case 'f':
11922           n += 8;
11923           break;
11924         case 'j':
11925           n += 3;
11926           break;
11927         case 'Y':
11928           n += 8;
11929           break;
11930         case 's':
11931         case 'J':
11932           n += 50;
11933           break;
11934         default:
11935           return;  /* ERROR.  return a NULL */
11936       }
11937       i++;
11938     }
11939   }
11940   if( n<sizeof(zBuf) ){
11941     z = zBuf;
11942   }else if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
11943     sqlite3_result_error_toobig(context);
11944     return;
11945   }else{
11946     z = sqlite3DbMallocRaw(db, n);
11947     if( z==0 ){
11948       sqlite3_result_error_nomem(context);
11949       return;
11950     }
11951   }
11952   computeJD(&x);
11953   computeYMD_HMS(&x);
11954   for(i=j=0; zFmt[i]; i++){
11955     if( zFmt[i]!='%' ){
11956       z[j++] = zFmt[i];
11957     }else{
11958       i++;
11959       switch( zFmt[i] ){
11960         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11961         case 'f': {
11962           double s = x.s;
11963           if( s>59.999 ) s = 59.999;
11964           sqlite3_snprintf(7, &z[j],"%06.3f", s);
11965           j += strlen(&z[j]);
11966           break;
11967         }
11968         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11969         case 'W': /* Fall thru */
11970         case 'j': {
11971           int nDay;             /* Number of days since 1st day of year */
11972           DateTime y = x;
11973           y.validJD = 0;
11974           y.M = 1;
11975           y.D = 1;
11976           computeJD(&y);
11977           nDay = (x.iJD - y.iJD)/86400000.0 + 0.5;
11978           if( zFmt[i]=='W' ){
11979             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11980             wd = ((x.iJD+43200000)/86400000) % 7;
11981             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11982             j += 2;
11983           }else{
11984             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11985             j += 3;
11986           }
11987           break;
11988         }
11989         case 'J': {
11990           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11991           j+=strlen(&z[j]);
11992           break;
11993         }
11994         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11995         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11996         case 's': {
11997           sqlite3_snprintf(30,&z[j],"%d",
11998                            (int)(x.iJD/1000.0 - 210866760000.0));
11999           j += strlen(&z[j]);
12000           break;
12001         }
12002         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12003         case 'w':  z[j++] = (((x.iJD+129600000)/86400000) % 7) + '0'; break;
12004         case 'Y':  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break;
12005         default:   z[j++] = '%'; break;
12006       }
12007     }
12008   }
12009   z[j] = 0;
12010   sqlite3_result_text(context, z, -1,
12011                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12012 }
12013
12014 /*
12015 ** current_time()
12016 **
12017 ** This function returns the same value as time('now').
12018 */
12019 static void ctimeFunc(
12020   sqlite3_context *context,
12021   int argc,
12022   sqlite3_value **argv
12023 ){
12024   timeFunc(context, 0, 0);
12025 }
12026
12027 /*
12028 ** current_date()
12029 **
12030 ** This function returns the same value as date('now').
12031 */
12032 static void cdateFunc(
12033   sqlite3_context *context,
12034   int argc,
12035   sqlite3_value **argv
12036 ){
12037   dateFunc(context, 0, 0);
12038 }
12039
12040 /*
12041 ** current_timestamp()
12042 **
12043 ** This function returns the same value as datetime('now').
12044 */
12045 static void ctimestampFunc(
12046   sqlite3_context *context,
12047   int argc,
12048   sqlite3_value **argv
12049 ){
12050   datetimeFunc(context, 0, 0);
12051 }
12052 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12053
12054 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12055 /*
12056 ** If the library is compiled to omit the full-scale date and time
12057 ** handling (to get a smaller binary), the following minimal version
12058 ** of the functions current_time(), current_date() and current_timestamp()
12059 ** are included instead. This is to support column declarations that
12060 ** include "DEFAULT CURRENT_TIME" etc.
12061 **
12062 ** This function uses the C-library functions time(), gmtime()
12063 ** and strftime(). The format string to pass to strftime() is supplied
12064 ** as the user-data for the function.
12065 */
12066 static void currentTimeFunc(
12067   sqlite3_context *context,
12068   int argc,
12069   sqlite3_value **argv
12070 ){
12071   time_t t;
12072   char *zFormat = (char *)sqlite3_user_data(context);
12073   sqlite3 *db;
12074   double rT;
12075   char zBuf[20];
12076
12077   db = sqlite3_context_db_handle(context);
12078   sqlite3OsCurrentTime(db->pVfs, &rT);
12079   t = 86400.0*(rT - 2440587.5) + 0.5;
12080 #ifdef HAVE_GMTIME_R
12081   {
12082     struct tm sNow;
12083     gmtime_r(&t, &sNow);
12084     strftime(zBuf, 20, zFormat, &sNow);
12085   }
12086 #else
12087   {
12088     struct tm *pTm;
12089     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12090     pTm = gmtime(&t);
12091     strftime(zBuf, 20, zFormat, pTm);
12092     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12093   }
12094 #endif
12095
12096   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12097 }
12098 #endif
12099
12100 /*
12101 ** This function registered all of the above C functions as SQL
12102 ** functions.  This should be the only routine in this file with
12103 ** external linkage.
12104 */
12105 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12106   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12107 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12108     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12109     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12110     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12111     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12112     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12113     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12114     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12115     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12116 #else
12117     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12118     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12119     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12120 #endif
12121   };
12122   int i;
12123   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12124   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12125
12126   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12127     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12128   }
12129 }
12130
12131 /************** End of date.c ************************************************/
12132 /************** Begin file os.c **********************************************/
12133 /*
12134 ** 2005 November 29
12135 **
12136 ** The author disclaims copyright to this source code.  In place of
12137 ** a legal notice, here is a blessing:
12138 **
12139 **    May you do good and not evil.
12140 **    May you find forgiveness for yourself and forgive others.
12141 **    May you share freely, never taking more than you give.
12142 **
12143 ******************************************************************************
12144 **
12145 ** This file contains OS interface code that is common to all
12146 ** architectures.
12147 **
12148 ** $Id: os.c,v 1.124 2008/10/07 15:25:48 drh Exp $
12149 */
12150 #define _SQLITE_OS_C_ 1
12151 #undef _SQLITE_OS_C_
12152
12153 /*
12154 ** The default SQLite sqlite3_vfs implementations do not allocate
12155 ** memory (actually, os_unix.c allocates a small amount of memory
12156 ** from within OsOpen()), but some third-party implementations may.
12157 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12158 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12159 **
12160 ** The following functions are instrumented for malloc() failure 
12161 ** testing:
12162 **
12163 **     sqlite3OsOpen()
12164 **     sqlite3OsRead()
12165 **     sqlite3OsWrite()
12166 **     sqlite3OsSync()
12167 **     sqlite3OsLock()
12168 **
12169 */
12170 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12171   #define DO_OS_MALLOC_TEST if (1) {            \
12172     void *pTstAlloc = sqlite3Malloc(10);       \
12173     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
12174     sqlite3_free(pTstAlloc);                    \
12175   }
12176 #else
12177   #define DO_OS_MALLOC_TEST
12178 #endif
12179
12180 /*
12181 ** The following routines are convenience wrappers around methods
12182 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12183 ** of this would be completely automatic if SQLite were coded using
12184 ** C++ instead of plain old C.
12185 */
12186 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12187   int rc = SQLITE_OK;
12188   if( pId->pMethods ){
12189     rc = pId->pMethods->xClose(pId);
12190     pId->pMethods = 0;
12191   }
12192   return rc;
12193 }
12194 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12195   DO_OS_MALLOC_TEST;
12196   return id->pMethods->xRead(id, pBuf, amt, offset);
12197 }
12198 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12199   DO_OS_MALLOC_TEST;
12200   return id->pMethods->xWrite(id, pBuf, amt, offset);
12201 }
12202 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12203   return id->pMethods->xTruncate(id, size);
12204 }
12205 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12206   DO_OS_MALLOC_TEST;
12207   return id->pMethods->xSync(id, flags);
12208 }
12209 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12210   DO_OS_MALLOC_TEST;
12211   return id->pMethods->xFileSize(id, pSize);
12212 }
12213 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12214   DO_OS_MALLOC_TEST;
12215   return id->pMethods->xLock(id, lockType);
12216 }
12217 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12218   return id->pMethods->xUnlock(id, lockType);
12219 }
12220 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12221   DO_OS_MALLOC_TEST;
12222   return id->pMethods->xCheckReservedLock(id, pResOut);
12223 }
12224 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12225   return id->pMethods->xFileControl(id, op, pArg);
12226 }
12227 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12228   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12229   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12230 }
12231 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12232   return id->pMethods->xDeviceCharacteristics(id);
12233 }
12234
12235 /*
12236 ** The next group of routines are convenience wrappers around the
12237 ** VFS methods.
12238 */
12239 SQLITE_PRIVATE int sqlite3OsOpen(
12240   sqlite3_vfs *pVfs, 
12241   const char *zPath, 
12242   sqlite3_file *pFile, 
12243   int flags, 
12244   int *pFlagsOut
12245 ){
12246   DO_OS_MALLOC_TEST;
12247   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
12248 }
12249 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12250   return pVfs->xDelete(pVfs, zPath, dirSync);
12251 }
12252 SQLITE_PRIVATE int sqlite3OsAccess(
12253   sqlite3_vfs *pVfs, 
12254   const char *zPath, 
12255   int flags, 
12256   int *pResOut
12257 ){
12258   DO_OS_MALLOC_TEST;
12259   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12260 }
12261 SQLITE_PRIVATE int sqlite3OsFullPathname(
12262   sqlite3_vfs *pVfs, 
12263   const char *zPath, 
12264   int nPathOut, 
12265   char *zPathOut
12266 ){
12267   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12268 }
12269 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12270 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12271   return pVfs->xDlOpen(pVfs, zPath);
12272 }
12273 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12274   pVfs->xDlError(pVfs, nByte, zBufOut);
12275 }
12276 SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
12277   return pVfs->xDlSym(pVfs, pHandle, zSymbol);
12278 }
12279 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12280   pVfs->xDlClose(pVfs, pHandle);
12281 }
12282 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12283 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12284   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12285 }
12286 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12287   return pVfs->xSleep(pVfs, nMicro);
12288 }
12289 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12290   return pVfs->xCurrentTime(pVfs, pTimeOut);
12291 }
12292
12293 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12294   sqlite3_vfs *pVfs, 
12295   const char *zFile, 
12296   sqlite3_file **ppFile, 
12297   int flags,
12298   int *pOutFlags
12299 ){
12300   int rc = SQLITE_NOMEM;
12301   sqlite3_file *pFile;
12302   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12303   if( pFile ){
12304     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12305     if( rc!=SQLITE_OK ){
12306       sqlite3_free(pFile);
12307     }else{
12308       *ppFile = pFile;
12309     }
12310   }
12311   return rc;
12312 }
12313 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12314   int rc = SQLITE_OK;
12315   assert( pFile );
12316   rc = sqlite3OsClose(pFile);
12317   sqlite3_free(pFile);
12318   return rc;
12319 }
12320
12321 /*
12322 ** The list of all registered VFS implementations.
12323 */
12324 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12325 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12326
12327 /*
12328 ** Locate a VFS by name.  If no name is given, simply return the
12329 ** first VFS on the list.
12330 */
12331 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12332   sqlite3_vfs *pVfs = 0;
12333 #if SQLITE_THREADSAFE
12334   sqlite3_mutex *mutex;
12335 #endif
12336 #ifndef SQLITE_OMIT_AUTOINIT
12337   int rc = sqlite3_initialize();
12338   if( rc ) return 0;
12339 #endif
12340 #if SQLITE_THREADSAFE
12341   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12342 #endif
12343   sqlite3_mutex_enter(mutex);
12344   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12345     if( zVfs==0 ) break;
12346     if( strcmp(zVfs, pVfs->zName)==0 ) break;
12347   }
12348   sqlite3_mutex_leave(mutex);
12349   return pVfs;
12350 }
12351
12352 /*
12353 ** Unlink a VFS from the linked list
12354 */
12355 static void vfsUnlink(sqlite3_vfs *pVfs){
12356   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12357   if( pVfs==0 ){
12358     /* No-op */
12359   }else if( vfsList==pVfs ){
12360     vfsList = pVfs->pNext;
12361   }else if( vfsList ){
12362     sqlite3_vfs *p = vfsList;
12363     while( p->pNext && p->pNext!=pVfs ){
12364       p = p->pNext;
12365     }
12366     if( p->pNext==pVfs ){
12367       p->pNext = pVfs->pNext;
12368     }
12369   }
12370 }
12371
12372 /*
12373 ** Register a VFS with the system.  It is harmless to register the same
12374 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
12375 ** true.
12376 */
12377 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12378   sqlite3_mutex *mutex = 0;
12379 #ifndef SQLITE_OMIT_AUTOINIT
12380   int rc = sqlite3_initialize();
12381   if( rc ) return rc;
12382 #endif
12383   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12384   sqlite3_mutex_enter(mutex);
12385   vfsUnlink(pVfs);
12386   if( makeDflt || vfsList==0 ){
12387     pVfs->pNext = vfsList;
12388     vfsList = pVfs;
12389   }else{
12390     pVfs->pNext = vfsList->pNext;
12391     vfsList->pNext = pVfs;
12392   }
12393   assert(vfsList);
12394   sqlite3_mutex_leave(mutex);
12395   return SQLITE_OK;
12396 }
12397
12398 /*
12399 ** Unregister a VFS so that it is no longer accessible.
12400 */
12401 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12402 #if SQLITE_THREADSAFE
12403   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12404 #endif
12405   sqlite3_mutex_enter(mutex);
12406   vfsUnlink(pVfs);
12407   sqlite3_mutex_leave(mutex);
12408   return SQLITE_OK;
12409 }
12410
12411 /************** End of os.c **************************************************/
12412 /************** Begin file fault.c *******************************************/
12413 /*
12414 ** 2008 Jan 22
12415 **
12416 ** The author disclaims copyright to this source code.  In place of
12417 ** a legal notice, here is a blessing:
12418 **
12419 **    May you do good and not evil.
12420 **    May you find forgiveness for yourself and forgive others.
12421 **    May you share freely, never taking more than you give.
12422 **
12423 *************************************************************************
12424 **
12425 ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
12426 */
12427
12428 /*
12429 ** This file contains code to support the concept of "benign" 
12430 ** malloc failures (when the xMalloc() or xRealloc() method of the
12431 ** sqlite3_mem_methods structure fails to allocate a block of memory
12432 ** and returns 0). 
12433 **
12434 ** Most malloc failures are non-benign. After they occur, SQLite
12435 ** abandons the current operation and returns an error code (usually
12436 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12437 ** fatal. For example, if a malloc fails while resizing a hash table, this 
12438 ** is completely recoverable simply by not carrying out the resize. The 
12439 ** hash table will continue to function normally.  So a malloc failure 
12440 ** during a hash table resize is a benign fault.
12441 */
12442
12443
12444 #ifndef SQLITE_OMIT_BUILTIN_TEST
12445
12446 /*
12447 ** Global variables.
12448 */
12449 typedef struct BenignMallocHooks BenignMallocHooks;
12450 static SQLITE_WSD struct BenignMallocHooks {
12451   void (*xBenignBegin)(void);
12452   void (*xBenignEnd)(void);
12453 } sqlite3Hooks = { 0, 0 };
12454
12455 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12456 ** structure.  If writable static data is unsupported on the target,
12457 ** we have to locate the state vector at run-time.  In the more common
12458 ** case where writable static data is supported, wsdHooks can refer directly
12459 ** to the "sqlite3Hooks" state vector declared above.
12460 */
12461 #ifdef SQLITE_OMIT_WSD
12462 # define wsdHooksInit \
12463   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12464 # define wsdHooks x[0]
12465 #else
12466 # define wsdHooksInit
12467 # define wsdHooks sqlite3Hooks
12468 #endif
12469
12470
12471 /*
12472 ** Register hooks to call when sqlite3BeginBenignMalloc() and
12473 ** sqlite3EndBenignMalloc() are called, respectively.
12474 */
12475 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12476   void (*xBenignBegin)(void),
12477   void (*xBenignEnd)(void)
12478 ){
12479   wsdHooksInit;
12480   wsdHooks.xBenignBegin = xBenignBegin;
12481   wsdHooks.xBenignEnd = xBenignEnd;
12482 }
12483
12484 /*
12485 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12486 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12487 ** indicates that subsequent malloc failures are non-benign.
12488 */
12489 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12490   wsdHooksInit;
12491   if( wsdHooks.xBenignBegin ){
12492     wsdHooks.xBenignBegin();
12493   }
12494 }
12495 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12496   wsdHooksInit;
12497   if( wsdHooks.xBenignEnd ){
12498     wsdHooks.xBenignEnd();
12499   }
12500 }
12501
12502 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12503
12504 /************** End of fault.c ***********************************************/
12505 /************** Begin file mem1.c ********************************************/
12506 /*
12507 ** 2007 August 14
12508 **
12509 ** The author disclaims copyright to this source code.  In place of
12510 ** a legal notice, here is a blessing:
12511 **
12512 **    May you do good and not evil.
12513 **    May you find forgiveness for yourself and forgive others.
12514 **    May you share freely, never taking more than you give.
12515 **
12516 *************************************************************************
12517 **
12518 ** This file contains low-level memory allocation drivers for when
12519 ** SQLite will use the standard C-library malloc/realloc/free interface
12520 ** to obtain the memory it needs.
12521 **
12522 ** This file contains implementations of the low-level memory allocation
12523 ** routines specified in the sqlite3_mem_methods object.
12524 **
12525 ** $Id: mem1.c,v 1.26 2008/09/01 18:34:20 danielk1977 Exp $
12526 */
12527
12528 /*
12529 ** This version of the memory allocator is the default.  It is
12530 ** used when no other memory allocator is specified using compile-time
12531 ** macros.
12532 */
12533 #ifdef SQLITE_SYSTEM_MALLOC
12534
12535 /*
12536 ** Like malloc(), but remember the size of the allocation
12537 ** so that we can find it later using sqlite3MemSize().
12538 **
12539 ** For this low-level routine, we are guaranteed that nByte>0 because
12540 ** cases of nByte<=0 will be intercepted and dealt with by higher level
12541 ** routines.
12542 */
12543 static void *sqlite3MemMalloc(int nByte){
12544   sqlite3_int64 *p;
12545   assert( nByte>0 );
12546   nByte = (nByte+7)&~7;
12547   p = malloc( nByte+8 );
12548   if( p ){
12549     p[0] = nByte;
12550     p++;
12551   }
12552   return (void *)p;
12553 }
12554
12555 /*
12556 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
12557 ** or sqlite3MemRealloc().
12558 **
12559 ** For this low-level routine, we already know that pPrior!=0 since
12560 ** cases where pPrior==0 will have been intecepted and dealt with
12561 ** by higher-level routines.
12562 */
12563 static void sqlite3MemFree(void *pPrior){
12564   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12565   assert( pPrior!=0 );
12566   p--;
12567   free(p);
12568 }
12569
12570 /*
12571 ** Like realloc().  Resize an allocation previously obtained from
12572 ** sqlite3MemMalloc().
12573 **
12574 ** For this low-level interface, we know that pPrior!=0.  Cases where
12575 ** pPrior==0 while have been intercepted by higher-level routine and
12576 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12577 ** cases where nByte<=0 will have been intercepted by higher-level
12578 ** routines and redirected to xFree.
12579 */
12580 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12581   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12582   assert( pPrior!=0 && nByte>0 );
12583   nByte = (nByte+7)&~7;
12584   p = (sqlite3_int64*)pPrior;
12585   p--;
12586   p = realloc(p, nByte+8 );
12587   if( p ){
12588     p[0] = nByte;
12589     p++;
12590   }
12591   return (void*)p;
12592 }
12593
12594 /*
12595 ** Report the allocated size of a prior return from xMalloc()
12596 ** or xRealloc().
12597 */
12598 static int sqlite3MemSize(void *pPrior){
12599   sqlite3_int64 *p;
12600   if( pPrior==0 ) return 0;
12601   p = (sqlite3_int64*)pPrior;
12602   p--;
12603   return p[0];
12604 }
12605
12606 /*
12607 ** Round up a request size to the next valid allocation size.
12608 */
12609 static int sqlite3MemRoundup(int n){
12610   return (n+7) & ~7;
12611 }
12612
12613 /*
12614 ** Initialize this module.
12615 */
12616 static int sqlite3MemInit(void *NotUsed){
12617   return SQLITE_OK;
12618 }
12619
12620 /*
12621 ** Deinitialize this module.
12622 */
12623 static void sqlite3MemShutdown(void *NotUsed){
12624   return;
12625 }
12626
12627 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12628   static const sqlite3_mem_methods defaultMethods = {
12629      sqlite3MemMalloc,
12630      sqlite3MemFree,
12631      sqlite3MemRealloc,
12632      sqlite3MemSize,
12633      sqlite3MemRoundup,
12634      sqlite3MemInit,
12635      sqlite3MemShutdown,
12636      0
12637   };
12638   return &defaultMethods;
12639 }
12640
12641 /*
12642 ** This routine is the only routine in this file with external linkage.
12643 **
12644 ** Populate the low-level memory allocation function pointers in
12645 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12646 */
12647 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12648   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12649 }
12650
12651 #endif /* SQLITE_SYSTEM_MALLOC */
12652
12653 /************** End of mem1.c ************************************************/
12654 /************** Begin file mem2.c ********************************************/
12655 /*
12656 ** 2007 August 15
12657 **
12658 ** The author disclaims copyright to this source code.  In place of
12659 ** a legal notice, here is a blessing:
12660 **
12661 **    May you do good and not evil.
12662 **    May you find forgiveness for yourself and forgive others.
12663 **    May you share freely, never taking more than you give.
12664 **
12665 *************************************************************************
12666 **
12667 ** This file contains low-level memory allocation drivers for when
12668 ** SQLite will use the standard C-library malloc/realloc/free interface
12669 ** to obtain the memory it needs while adding lots of additional debugging
12670 ** information to each allocation in order to help detect and fix memory
12671 ** leaks and memory usage errors.
12672 **
12673 ** This file contains implementations of the low-level memory allocation
12674 ** routines specified in the sqlite3_mem_methods object.
12675 **
12676 ** $Id: mem2.c,v 1.39 2008/09/01 18:34:20 danielk1977 Exp $
12677 */
12678
12679 /*
12680 ** This version of the memory allocator is used only if the
12681 ** SQLITE_MEMDEBUG macro is defined
12682 */
12683 #ifdef SQLITE_MEMDEBUG
12684
12685 /*
12686 ** The backtrace functionality is only available with GLIBC
12687 */
12688 #ifdef __GLIBC__
12689   extern int backtrace(void**,int);
12690   extern void backtrace_symbols_fd(void*const*,int,int);
12691 #else
12692 # define backtrace(A,B) 1
12693 # define backtrace_symbols_fd(A,B,C)
12694 #endif
12695
12696 /*
12697 ** Each memory allocation looks like this:
12698 **
12699 **  ------------------------------------------------------------------------
12700 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12701 **  ------------------------------------------------------------------------
12702 **
12703 ** The application code sees only a pointer to the allocation.  We have
12704 ** to back up from the allocation pointer to find the MemBlockHdr.  The
12705 ** MemBlockHdr tells us the size of the allocation and the number of
12706 ** backtrace pointers.  There is also a guard word at the end of the
12707 ** MemBlockHdr.
12708 */
12709 struct MemBlockHdr {
12710   i64 iSize;                          /* Size of this allocation */
12711   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12712   char nBacktrace;                    /* Number of backtraces on this alloc */
12713   char nBacktraceSlots;               /* Available backtrace slots */
12714   short nTitle;                       /* Bytes of title; includes '\0' */
12715   int iForeGuard;                     /* Guard word for sanity */
12716 };
12717
12718 /*
12719 ** Guard words
12720 */
12721 #define FOREGUARD 0x80F5E153
12722 #define REARGUARD 0xE4676B53
12723
12724 /*
12725 ** Number of malloc size increments to track.
12726 */
12727 #define NCSIZE  1000
12728
12729 /*
12730 ** All of the static variables used by this module are collected
12731 ** into a single structure named "mem".  This is to keep the
12732 ** static variables organized and to reduce namespace pollution
12733 ** when this module is combined with other in the amalgamation.
12734 */
12735 static struct {
12736   
12737   /*
12738   ** Mutex to control access to the memory allocation subsystem.
12739   */
12740   sqlite3_mutex *mutex;
12741
12742   /*
12743   ** Head and tail of a linked list of all outstanding allocations
12744   */
12745   struct MemBlockHdr *pFirst;
12746   struct MemBlockHdr *pLast;
12747   
12748   /*
12749   ** The number of levels of backtrace to save in new allocations.
12750   */
12751   int nBacktrace;
12752   void (*xBacktrace)(int, int, void **);
12753
12754   /*
12755   ** Title text to insert in front of each block
12756   */
12757   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12758   char zTitle[100];  /* The title text */
12759
12760   /* 
12761   ** sqlite3MallocDisallow() increments the following counter.
12762   ** sqlite3MallocAllow() decrements it.
12763   */
12764   int disallow; /* Do not allow memory allocation */
12765
12766   /*
12767   ** Gather statistics on the sizes of memory allocations.
12768   ** nAlloc[i] is the number of allocation attempts of i*8
12769   ** bytes.  i==NCSIZE is the number of allocation attempts for
12770   ** sizes more than NCSIZE*8 bytes.
12771   */
12772   int nAlloc[NCSIZE];      /* Total number of allocations */
12773   int nCurrent[NCSIZE];    /* Current number of allocations */
12774   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12775
12776 } mem;
12777
12778
12779 /*
12780 ** Adjust memory usage statistics
12781 */
12782 static void adjustStats(int iSize, int increment){
12783   int i = ((iSize+7)&~7)/8;
12784   if( i>NCSIZE-1 ){
12785     i = NCSIZE - 1;
12786   }
12787   if( increment>0 ){
12788     mem.nAlloc[i]++;
12789     mem.nCurrent[i]++;
12790     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12791       mem.mxCurrent[i] = mem.nCurrent[i];
12792     }
12793   }else{
12794     mem.nCurrent[i]--;
12795     assert( mem.nCurrent[i]>=0 );
12796   }
12797 }
12798
12799 /*
12800 ** Given an allocation, find the MemBlockHdr for that allocation.
12801 **
12802 ** This routine checks the guards at either end of the allocation and
12803 ** if they are incorrect it asserts.
12804 */
12805 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12806   struct MemBlockHdr *p;
12807   int *pInt;
12808   u8 *pU8;
12809   int nReserve;
12810
12811   p = (struct MemBlockHdr*)pAllocation;
12812   p--;
12813   assert( p->iForeGuard==FOREGUARD );
12814   nReserve = (p->iSize+7)&~7;
12815   pInt = (int*)pAllocation;
12816   pU8 = (u8*)pAllocation;
12817   assert( pInt[nReserve/sizeof(int)]==REARGUARD );
12818   assert( (nReserve-0)<=p->iSize || pU8[nReserve-1]==0x65 );
12819   assert( (nReserve-1)<=p->iSize || pU8[nReserve-2]==0x65 );
12820   assert( (nReserve-2)<=p->iSize || pU8[nReserve-3]==0x65 );
12821   return p;
12822 }
12823
12824 /*
12825 ** Return the number of bytes currently allocated at address p.
12826 */
12827 static int sqlite3MemSize(void *p){
12828   struct MemBlockHdr *pHdr;
12829   if( !p ){
12830     return 0;
12831   }
12832   pHdr = sqlite3MemsysGetHeader(p);
12833   return pHdr->iSize;
12834 }
12835
12836 /*
12837 ** Initialize the memory allocation subsystem.
12838 */
12839 static int sqlite3MemInit(void *NotUsed){
12840   if( !sqlite3GlobalConfig.bMemstat ){
12841     /* If memory status is enabled, then the malloc.c wrapper will already
12842     ** hold the STATIC_MEM mutex when the routines here are invoked. */
12843     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12844   }
12845   return SQLITE_OK;
12846 }
12847
12848 /*
12849 ** Deinitialize the memory allocation subsystem.
12850 */
12851 static void sqlite3MemShutdown(void *NotUsed){
12852   mem.mutex = 0;
12853 }
12854
12855 /*
12856 ** Round up a request size to the next valid allocation size.
12857 */
12858 static int sqlite3MemRoundup(int n){
12859   return (n+7) & ~7;
12860 }
12861
12862 /*
12863 ** Allocate nByte bytes of memory.
12864 */
12865 static void *sqlite3MemMalloc(int nByte){
12866   struct MemBlockHdr *pHdr;
12867   void **pBt;
12868   char *z;
12869   int *pInt;
12870   void *p = 0;
12871   int totalSize;
12872   int nReserve;
12873   sqlite3_mutex_enter(mem.mutex);
12874   assert( mem.disallow==0 );
12875   nReserve = (nByte+7)&~7;
12876   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12877                mem.nBacktrace*sizeof(void*) + mem.nTitle;
12878   p = malloc(totalSize);
12879   if( p ){
12880     z = p;
12881     pBt = (void**)&z[mem.nTitle];
12882     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12883     pHdr->pNext = 0;
12884     pHdr->pPrev = mem.pLast;
12885     if( mem.pLast ){
12886       mem.pLast->pNext = pHdr;
12887     }else{
12888       mem.pFirst = pHdr;
12889     }
12890     mem.pLast = pHdr;
12891     pHdr->iForeGuard = FOREGUARD;
12892     pHdr->nBacktraceSlots = mem.nBacktrace;
12893     pHdr->nTitle = mem.nTitle;
12894     if( mem.nBacktrace ){
12895       void *aAddr[40];
12896       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12897       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12898       if( mem.xBacktrace ){
12899         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12900       }
12901     }else{
12902       pHdr->nBacktrace = 0;
12903     }
12904     if( mem.nTitle ){
12905       memcpy(z, mem.zTitle, mem.nTitle);
12906     }
12907     pHdr->iSize = nByte;
12908     adjustStats(nByte, +1);
12909     pInt = (int*)&pHdr[1];
12910     pInt[nReserve/sizeof(int)] = REARGUARD;
12911     memset(pInt, 0x65, nReserve);
12912     p = (void*)pInt;
12913   }
12914   sqlite3_mutex_leave(mem.mutex);
12915   return p; 
12916 }
12917
12918 /*
12919 ** Free memory.
12920 */
12921 static void sqlite3MemFree(void *pPrior){
12922   struct MemBlockHdr *pHdr;
12923   void **pBt;
12924   char *z;
12925   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12926   pHdr = sqlite3MemsysGetHeader(pPrior);
12927   pBt = (void**)pHdr;
12928   pBt -= pHdr->nBacktraceSlots;
12929   sqlite3_mutex_enter(mem.mutex);
12930   if( pHdr->pPrev ){
12931     assert( pHdr->pPrev->pNext==pHdr );
12932     pHdr->pPrev->pNext = pHdr->pNext;
12933   }else{
12934     assert( mem.pFirst==pHdr );
12935     mem.pFirst = pHdr->pNext;
12936   }
12937   if( pHdr->pNext ){
12938     assert( pHdr->pNext->pPrev==pHdr );
12939     pHdr->pNext->pPrev = pHdr->pPrev;
12940   }else{
12941     assert( mem.pLast==pHdr );
12942     mem.pLast = pHdr->pPrev;
12943   }
12944   z = (char*)pBt;
12945   z -= pHdr->nTitle;
12946   adjustStats(pHdr->iSize, -1);
12947   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12948                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
12949   free(z);
12950   sqlite3_mutex_leave(mem.mutex);  
12951 }
12952
12953 /*
12954 ** Change the size of an existing memory allocation.
12955 **
12956 ** For this debugging implementation, we *always* make a copy of the
12957 ** allocation into a new place in memory.  In this way, if the 
12958 ** higher level code is using pointer to the old allocation, it is 
12959 ** much more likely to break and we are much more liking to find
12960 ** the error.
12961 */
12962 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12963   struct MemBlockHdr *pOldHdr;
12964   void *pNew;
12965   assert( mem.disallow==0 );
12966   pOldHdr = sqlite3MemsysGetHeader(pPrior);
12967   pNew = sqlite3MemMalloc(nByte);
12968   if( pNew ){
12969     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12970     if( nByte>pOldHdr->iSize ){
12971       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
12972     }
12973     sqlite3MemFree(pPrior);
12974   }
12975   return pNew;
12976 }
12977
12978
12979 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetDefault(void){
12980   static const sqlite3_mem_methods defaultMethods = {
12981      sqlite3MemMalloc,
12982      sqlite3MemFree,
12983      sqlite3MemRealloc,
12984      sqlite3MemSize,
12985      sqlite3MemRoundup,
12986      sqlite3MemInit,
12987      sqlite3MemShutdown,
12988      0
12989   };
12990   return &defaultMethods;
12991 }
12992
12993 /*
12994 ** Populate the low-level memory allocation function pointers in
12995 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12996 */
12997 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12998   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetDefault());
12999 }
13000
13001 /*
13002 ** Set the number of backtrace levels kept for each allocation.
13003 ** A value of zero turns off backtracing.  The number is always rounded
13004 ** up to a multiple of 2.
13005 */
13006 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13007   if( depth<0 ){ depth = 0; }
13008   if( depth>20 ){ depth = 20; }
13009   depth = (depth+1)&0xfe;
13010   mem.nBacktrace = depth;
13011 }
13012
13013 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13014   mem.xBacktrace = xBacktrace;
13015 }
13016
13017 /*
13018 ** Set the title string for subsequent allocations.
13019 */
13020 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13021   int n = strlen(zTitle) + 1;
13022   sqlite3_mutex_enter(mem.mutex);
13023   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13024   memcpy(mem.zTitle, zTitle, n);
13025   mem.zTitle[n] = 0;
13026   mem.nTitle = (n+7)&~7;
13027   sqlite3_mutex_leave(mem.mutex);
13028 }
13029
13030 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13031   struct MemBlockHdr *pHdr;
13032   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13033     void **pBt = (void**)pHdr;
13034     pBt -= pHdr->nBacktraceSlots;
13035     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13036   }
13037 }
13038
13039 /*
13040 ** Open the file indicated and write a log of all unfreed memory 
13041 ** allocations into that log.
13042 */
13043 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13044   FILE *out;
13045   struct MemBlockHdr *pHdr;
13046   void **pBt;
13047   int i;
13048   out = fopen(zFilename, "w");
13049   if( out==0 ){
13050     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13051                     zFilename);
13052     return;
13053   }
13054   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13055     char *z = (char*)pHdr;
13056     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13057     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13058             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13059     if( pHdr->nBacktrace ){
13060       fflush(out);
13061       pBt = (void**)pHdr;
13062       pBt -= pHdr->nBacktraceSlots;
13063       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13064       fprintf(out, "\n");
13065     }
13066   }
13067   fprintf(out, "COUNTS:\n");
13068   for(i=0; i<NCSIZE-1; i++){
13069     if( mem.nAlloc[i] ){
13070       fprintf(out, "   %5d: %10d %10d %10d\n", 
13071             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13072     }
13073   }
13074   if( mem.nAlloc[NCSIZE-1] ){
13075     fprintf(out, "   %5d: %10d %10d %10d\n",
13076              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13077              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13078   }
13079   fclose(out);
13080 }
13081
13082 /*
13083 ** Return the number of times sqlite3MemMalloc() has been called.
13084 */
13085 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13086   int i;
13087   int nTotal = 0;
13088   for(i=0; i<NCSIZE; i++){
13089     nTotal += mem.nAlloc[i];
13090   }
13091   return nTotal;
13092 }
13093
13094
13095 #endif /* SQLITE_MEMDEBUG */
13096
13097 /************** End of mem2.c ************************************************/
13098 /************** Begin file mem3.c ********************************************/
13099 /*
13100 ** 2007 October 14
13101 **
13102 ** The author disclaims copyright to this source code.  In place of
13103 ** a legal notice, here is a blessing:
13104 **
13105 **    May you do good and not evil.
13106 **    May you find forgiveness for yourself and forgive others.
13107 **    May you share freely, never taking more than you give.
13108 **
13109 *************************************************************************
13110 ** This file contains the C functions that implement a memory
13111 ** allocation subsystem for use by SQLite. 
13112 **
13113 ** This version of the memory allocation subsystem omits all
13114 ** use of malloc(). The SQLite user supplies a block of memory
13115 ** before calling sqlite3_initialize() from which allocations
13116 ** are made and returned by the xMalloc() and xRealloc() 
13117 ** implementations. Once sqlite3_initialize() has been called,
13118 ** the amount of memory available to SQLite is fixed and cannot
13119 ** be changed.
13120 **
13121 ** This version of the memory allocation subsystem is included
13122 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13123 **
13124 ** $Id: mem3.c,v 1.23 2008/09/02 17:52:52 danielk1977 Exp $
13125 */
13126
13127 /*
13128 ** This version of the memory allocator is only built into the library
13129 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13130 ** mean that the library will use a memory-pool by default, just that
13131 ** it is available. The mempool allocator is activated by calling
13132 ** sqlite3_config().
13133 */
13134 #ifdef SQLITE_ENABLE_MEMSYS3
13135
13136 /*
13137 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13138 */
13139 #define MX_SMALL 10
13140
13141
13142 /*
13143 ** Number of freelist hash slots
13144 */
13145 #define N_HASH  61
13146
13147 /*
13148 ** A memory allocation (also called a "chunk") consists of two or 
13149 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13150 ** a header that is not returned to the user.
13151 **
13152 ** A chunk is two or more blocks that is either checked out or
13153 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13154 ** size of the allocation in blocks if the allocation is free.
13155 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13156 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13157 ** is true if the previous chunk is checked out and false if the
13158 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13159 ** the previous chunk in blocks if the previous chunk is on the
13160 ** freelist. If the previous chunk is checked out, then
13161 ** u.hdr.prevSize can be part of the data for that chunk and should
13162 ** not be read or written.
13163 **
13164 ** We often identify a chunk by its index in mem3.aPool[].  When
13165 ** this is done, the chunk index refers to the second block of
13166 ** the chunk.  In this way, the first chunk has an index of 1.
13167 ** A chunk index of 0 means "no such chunk" and is the equivalent
13168 ** of a NULL pointer.
13169 **
13170 ** The second block of free chunks is of the form u.list.  The
13171 ** two fields form a double-linked list of chunks of related sizes.
13172 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13173 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13174 **
13175 ** The second block of a chunk is user data if the chunk is checked 
13176 ** out.  If a chunk is checked out, the user data may extend into
13177 ** the u.hdr.prevSize value of the following chunk.
13178 */
13179 typedef struct Mem3Block Mem3Block;
13180 struct Mem3Block {
13181   union {
13182     struct {
13183       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13184       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13185     } hdr;
13186     struct {
13187       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13188       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13189     } list;
13190   } u;
13191 };
13192
13193 /*
13194 ** All of the static variables used by this module are collected
13195 ** into a single structure named "mem3".  This is to keep the
13196 ** static variables organized and to reduce namespace pollution
13197 ** when this module is combined with other in the amalgamation.
13198 */
13199 static SQLITE_WSD struct Mem3Global {
13200   /*
13201   ** Memory available for allocation. nPool is the size of the array
13202   ** (in Mem3Blocks) pointed to by aPool less 2.
13203   */
13204   u32 nPool;
13205   Mem3Block *aPool;
13206
13207   /*
13208   ** True if we are evaluating an out-of-memory callback.
13209   */
13210   int alarmBusy;
13211   
13212   /*
13213   ** Mutex to control access to the memory allocation subsystem.
13214   */
13215   sqlite3_mutex *mutex;
13216   
13217   /*
13218   ** The minimum amount of free space that we have seen.
13219   */
13220   u32 mnMaster;
13221
13222   /*
13223   ** iMaster is the index of the master chunk.  Most new allocations
13224   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13225   ** of the current master.  iMaster is 0 if there is not master chunk.
13226   ** The master chunk is not in either the aiHash[] or aiSmall[].
13227   */
13228   u32 iMaster;
13229   u32 szMaster;
13230
13231   /*
13232   ** Array of lists of free blocks according to the block size 
13233   ** for smaller chunks, or a hash on the block size for larger
13234   ** chunks.
13235   */
13236   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13237   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13238 } mem3 = { 97535575 };
13239
13240 #define mem3 GLOBAL(struct Mem3Global, mem3)
13241
13242 /*
13243 ** Unlink the chunk at mem3.aPool[i] from list it is currently
13244 ** on.  *pRoot is the list that i is a member of.
13245 */
13246 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13247   u32 next = mem3.aPool[i].u.list.next;
13248   u32 prev = mem3.aPool[i].u.list.prev;
13249   assert( sqlite3_mutex_held(mem3.mutex) );
13250   if( prev==0 ){
13251     *pRoot = next;
13252   }else{
13253     mem3.aPool[prev].u.list.next = next;
13254   }
13255   if( next ){
13256     mem3.aPool[next].u.list.prev = prev;
13257   }
13258   mem3.aPool[i].u.list.next = 0;
13259   mem3.aPool[i].u.list.prev = 0;
13260 }
13261
13262 /*
13263 ** Unlink the chunk at index i from 
13264 ** whatever list is currently a member of.
13265 */
13266 static void memsys3Unlink(u32 i){
13267   u32 size, hash;
13268   assert( sqlite3_mutex_held(mem3.mutex) );
13269   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13270   assert( i>=1 );
13271   size = mem3.aPool[i-1].u.hdr.size4x/4;
13272   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13273   assert( size>=2 );
13274   if( size <= MX_SMALL ){
13275     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13276   }else{
13277     hash = size % N_HASH;
13278     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13279   }
13280 }
13281
13282 /*
13283 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
13284 ** at *pRoot.
13285 */
13286 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13287   assert( sqlite3_mutex_held(mem3.mutex) );
13288   mem3.aPool[i].u.list.next = *pRoot;
13289   mem3.aPool[i].u.list.prev = 0;
13290   if( *pRoot ){
13291     mem3.aPool[*pRoot].u.list.prev = i;
13292   }
13293   *pRoot = i;
13294 }
13295
13296 /*
13297 ** Link the chunk at index i into either the appropriate
13298 ** small chunk list, or into the large chunk hash table.
13299 */
13300 static void memsys3Link(u32 i){
13301   u32 size, hash;
13302   assert( sqlite3_mutex_held(mem3.mutex) );
13303   assert( i>=1 );
13304   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13305   size = mem3.aPool[i-1].u.hdr.size4x/4;
13306   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13307   assert( size>=2 );
13308   if( size <= MX_SMALL ){
13309     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13310   }else{
13311     hash = size % N_HASH;
13312     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13313   }
13314 }
13315
13316 /*
13317 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13318 ** will already be held (obtained by code in malloc.c) if
13319 ** sqlite3GlobalConfig.bMemStat is true.
13320 */
13321 static void memsys3Enter(void){
13322   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13323     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13324   }
13325   sqlite3_mutex_enter(mem3.mutex);
13326 }
13327 static void memsys3Leave(void){
13328   sqlite3_mutex_leave(mem3.mutex);
13329 }
13330
13331 /*
13332 ** Called when we are unable to satisfy an allocation of nBytes.
13333 */
13334 static void memsys3OutOfMemory(int nByte){
13335   if( !mem3.alarmBusy ){
13336     mem3.alarmBusy = 1;
13337     assert( sqlite3_mutex_held(mem3.mutex) );
13338     sqlite3_mutex_leave(mem3.mutex);
13339     sqlite3_release_memory(nByte);
13340     sqlite3_mutex_enter(mem3.mutex);
13341     mem3.alarmBusy = 0;
13342   }
13343 }
13344
13345
13346 /*
13347 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
13348 ** size parameters for check-out and return a pointer to the 
13349 ** user portion of the chunk.
13350 */
13351 static void *memsys3Checkout(u32 i, int nBlock){
13352   u32 x;
13353   assert( sqlite3_mutex_held(mem3.mutex) );
13354   assert( i>=1 );
13355   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13356   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13357   x = mem3.aPool[i-1].u.hdr.size4x;
13358   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13359   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13360   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13361   return &mem3.aPool[i];
13362 }
13363
13364 /*
13365 ** Carve a piece off of the end of the mem3.iMaster free chunk.
13366 ** Return a pointer to the new allocation.  Or, if the master chunk
13367 ** is not large enough, return 0.
13368 */
13369 static void *memsys3FromMaster(int nBlock){
13370   assert( sqlite3_mutex_held(mem3.mutex) );
13371   assert( mem3.szMaster>=nBlock );
13372   if( nBlock>=mem3.szMaster-1 ){
13373     /* Use the entire master */
13374     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13375     mem3.iMaster = 0;
13376     mem3.szMaster = 0;
13377     mem3.mnMaster = 0;
13378     return p;
13379   }else{
13380     /* Split the master block.  Return the tail. */
13381     u32 newi, x;
13382     newi = mem3.iMaster + mem3.szMaster - nBlock;
13383     assert( newi > mem3.iMaster+1 );
13384     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13385     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13386     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13387     mem3.szMaster -= nBlock;
13388     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13389     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13390     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13391     if( mem3.szMaster < mem3.mnMaster ){
13392       mem3.mnMaster = mem3.szMaster;
13393     }
13394     return (void*)&mem3.aPool[newi];
13395   }
13396 }
13397
13398 /*
13399 ** *pRoot is the head of a list of free chunks of the same size
13400 ** or same size hash.  In other words, *pRoot is an entry in either
13401 ** mem3.aiSmall[] or mem3.aiHash[].  
13402 **
13403 ** This routine examines all entries on the given list and tries
13404 ** to coalesce each entries with adjacent free chunks.  
13405 **
13406 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13407 ** the current mem3.iMaster with the new larger chunk.  In order for
13408 ** this mem3.iMaster replacement to work, the master chunk must be
13409 ** linked into the hash tables.  That is not the normal state of
13410 ** affairs, of course.  The calling routine must link the master
13411 ** chunk before invoking this routine, then must unlink the (possibly
13412 ** changed) master chunk once this routine has finished.
13413 */
13414 static void memsys3Merge(u32 *pRoot){
13415   u32 iNext, prev, size, i, x;
13416
13417   assert( sqlite3_mutex_held(mem3.mutex) );
13418   for(i=*pRoot; i>0; i=iNext){
13419     iNext = mem3.aPool[i].u.list.next;
13420     size = mem3.aPool[i-1].u.hdr.size4x;
13421     assert( (size&1)==0 );
13422     if( (size&2)==0 ){
13423       memsys3UnlinkFromList(i, pRoot);
13424       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13425       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13426       if( prev==iNext ){
13427         iNext = mem3.aPool[prev].u.list.next;
13428       }
13429       memsys3Unlink(prev);
13430       size = i + size/4 - prev;
13431       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13432       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13433       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13434       memsys3Link(prev);
13435       i = prev;
13436     }else{
13437       size /= 4;
13438     }
13439     if( size>mem3.szMaster ){
13440       mem3.iMaster = i;
13441       mem3.szMaster = size;
13442     }
13443   }
13444 }
13445
13446 /*
13447 ** Return a block of memory of at least nBytes in size.
13448 ** Return NULL if unable.
13449 **
13450 ** This function assumes that the necessary mutexes, if any, are
13451 ** already held by the caller. Hence "Unsafe".
13452 */
13453 static void *memsys3MallocUnsafe(int nByte){
13454   u32 i;
13455   int nBlock;
13456   int toFree;
13457
13458   assert( sqlite3_mutex_held(mem3.mutex) );
13459   assert( sizeof(Mem3Block)==8 );
13460   if( nByte<=12 ){
13461     nBlock = 2;
13462   }else{
13463     nBlock = (nByte + 11)/8;
13464   }
13465   assert( nBlock>=2 );
13466
13467   /* STEP 1:
13468   ** Look for an entry of the correct size in either the small
13469   ** chunk table or in the large chunk hash table.  This is
13470   ** successful most of the time (about 9 times out of 10).
13471   */
13472   if( nBlock <= MX_SMALL ){
13473     i = mem3.aiSmall[nBlock-2];
13474     if( i>0 ){
13475       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13476       return memsys3Checkout(i, nBlock);
13477     }
13478   }else{
13479     int hash = nBlock % N_HASH;
13480     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13481       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13482         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13483         return memsys3Checkout(i, nBlock);
13484       }
13485     }
13486   }
13487
13488   /* STEP 2:
13489   ** Try to satisfy the allocation by carving a piece off of the end
13490   ** of the master chunk.  This step usually works if step 1 fails.
13491   */
13492   if( mem3.szMaster>=nBlock ){
13493     return memsys3FromMaster(nBlock);
13494   }
13495
13496
13497   /* STEP 3:  
13498   ** Loop through the entire memory pool.  Coalesce adjacent free
13499   ** chunks.  Recompute the master chunk as the largest free chunk.
13500   ** Then try again to satisfy the allocation by carving a piece off
13501   ** of the end of the master chunk.  This step happens very
13502   ** rarely (we hope!)
13503   */
13504   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13505     memsys3OutOfMemory(toFree);
13506     if( mem3.iMaster ){
13507       memsys3Link(mem3.iMaster);
13508       mem3.iMaster = 0;
13509       mem3.szMaster = 0;
13510     }
13511     for(i=0; i<N_HASH; i++){
13512       memsys3Merge(&mem3.aiHash[i]);
13513     }
13514     for(i=0; i<MX_SMALL-1; i++){
13515       memsys3Merge(&mem3.aiSmall[i]);
13516     }
13517     if( mem3.szMaster ){
13518       memsys3Unlink(mem3.iMaster);
13519       if( mem3.szMaster>=nBlock ){
13520         return memsys3FromMaster(nBlock);
13521       }
13522     }
13523   }
13524
13525   /* If none of the above worked, then we fail. */
13526   return 0;
13527 }
13528
13529 /*
13530 ** Free an outstanding memory allocation.
13531 **
13532 ** This function assumes that the necessary mutexes, if any, are
13533 ** already held by the caller. Hence "Unsafe".
13534 */
13535 void memsys3FreeUnsafe(void *pOld){
13536   Mem3Block *p = (Mem3Block*)pOld;
13537   int i;
13538   u32 size, x;
13539   assert( sqlite3_mutex_held(mem3.mutex) );
13540   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13541   i = p - mem3.aPool;
13542   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13543   size = mem3.aPool[i-1].u.hdr.size4x/4;
13544   assert( i+size<=mem3.nPool+1 );
13545   mem3.aPool[i-1].u.hdr.size4x &= ~1;
13546   mem3.aPool[i+size-1].u.hdr.prevSize = size;
13547   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13548   memsys3Link(i);
13549
13550   /* Try to expand the master using the newly freed chunk */
13551   if( mem3.iMaster ){
13552     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13553       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13554       mem3.iMaster -= size;
13555       mem3.szMaster += size;
13556       memsys3Unlink(mem3.iMaster);
13557       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13558       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13559       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13560     }
13561     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13562     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13563       memsys3Unlink(mem3.iMaster+mem3.szMaster);
13564       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13565       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13566       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13567     }
13568   }
13569 }
13570
13571 /*
13572 ** Return the size of an outstanding allocation, in bytes.  The
13573 ** size returned omits the 8-byte header overhead.  This only
13574 ** works for chunks that are currently checked out.
13575 */
13576 static int memsys3Size(void *p){
13577   Mem3Block *pBlock;
13578   if( p==0 ) return 0;
13579   pBlock = (Mem3Block*)p;
13580   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13581   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13582 }
13583
13584 /*
13585 ** Round up a request size to the next valid allocation size.
13586 */
13587 static int memsys3Roundup(int n){
13588   if( n<=12 ){
13589     return 12;
13590   }else{
13591     return ((n+11)&~7) - 4;
13592   }
13593 }
13594
13595 /*
13596 ** Allocate nBytes of memory.
13597 */
13598 static void *memsys3Malloc(int nBytes){
13599   sqlite3_int64 *p;
13600   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13601   memsys3Enter();
13602   p = memsys3MallocUnsafe(nBytes);
13603   memsys3Leave();
13604   return (void*)p; 
13605 }
13606
13607 /*
13608 ** Free memory.
13609 */
13610 void memsys3Free(void *pPrior){
13611   assert( pPrior );
13612   memsys3Enter();
13613   memsys3FreeUnsafe(pPrior);
13614   memsys3Leave();
13615 }
13616
13617 /*
13618 ** Change the size of an existing memory allocation
13619 */
13620 void *memsys3Realloc(void *pPrior, int nBytes){
13621   int nOld;
13622   void *p;
13623   if( pPrior==0 ){
13624     return sqlite3_malloc(nBytes);
13625   }
13626   if( nBytes<=0 ){
13627     sqlite3_free(pPrior);
13628     return 0;
13629   }
13630   nOld = memsys3Size(pPrior);
13631   if( nBytes<=nOld && nBytes>=nOld-128 ){
13632     return pPrior;
13633   }
13634   memsys3Enter();
13635   p = memsys3MallocUnsafe(nBytes);
13636   if( p ){
13637     if( nOld<nBytes ){
13638       memcpy(p, pPrior, nOld);
13639     }else{
13640       memcpy(p, pPrior, nBytes);
13641     }
13642     memsys3FreeUnsafe(pPrior);
13643   }
13644   memsys3Leave();
13645   return p;
13646 }
13647
13648 /*
13649 ** Initialize this module.
13650 */
13651 static int memsys3Init(void *NotUsed){
13652   if( !sqlite3GlobalConfig.pHeap ){
13653     return SQLITE_ERROR;
13654   }
13655
13656   /* Store a pointer to the memory block in global structure mem3. */
13657   assert( sizeof(Mem3Block)==8 );
13658   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13659   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13660
13661   /* Initialize the master block. */
13662   mem3.szMaster = mem3.nPool;
13663   mem3.mnMaster = mem3.szMaster;
13664   mem3.iMaster = 1;
13665   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13666   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13667   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13668
13669   return SQLITE_OK;
13670 }
13671
13672 /*
13673 ** Deinitialize this module.
13674 */
13675 static void memsys3Shutdown(void *NotUsed){
13676   return;
13677 }
13678
13679
13680
13681 /*
13682 ** Open the file indicated and write a log of all unfreed memory 
13683 ** allocations into that log.
13684 */
13685 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13686 #ifdef SQLITE_DEBUG
13687   FILE *out;
13688   int i, j;
13689   u32 size;
13690   if( zFilename==0 || zFilename[0]==0 ){
13691     out = stdout;
13692   }else{
13693     out = fopen(zFilename, "w");
13694     if( out==0 ){
13695       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13696                       zFilename);
13697       return;
13698     }
13699   }
13700   memsys3Enter();
13701   fprintf(out, "CHUNKS:\n");
13702   for(i=1; i<=mem3.nPool; i+=size/4){
13703     size = mem3.aPool[i-1].u.hdr.size4x;
13704     if( size/4<=1 ){
13705       fprintf(out, "%p size error\n", &mem3.aPool[i]);
13706       assert( 0 );
13707       break;
13708     }
13709     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13710       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13711       assert( 0 );
13712       break;
13713     }
13714     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13715       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13716       assert( 0 );
13717       break;
13718     }
13719     if( size&1 ){
13720       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13721     }else{
13722       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13723                   i==mem3.iMaster ? " **master**" : "");
13724     }
13725   }
13726   for(i=0; i<MX_SMALL-1; i++){
13727     if( mem3.aiSmall[i]==0 ) continue;
13728     fprintf(out, "small(%2d):", i);
13729     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13730       fprintf(out, " %p(%d)", &mem3.aPool[j],
13731               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13732     }
13733     fprintf(out, "\n"); 
13734   }
13735   for(i=0; i<N_HASH; i++){
13736     if( mem3.aiHash[i]==0 ) continue;
13737     fprintf(out, "hash(%2d):", i);
13738     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13739       fprintf(out, " %p(%d)", &mem3.aPool[j],
13740               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13741     }
13742     fprintf(out, "\n"); 
13743   }
13744   fprintf(out, "master=%d\n", mem3.iMaster);
13745   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13746   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13747   sqlite3_mutex_leave(mem3.mutex);
13748   if( out==stdout ){
13749     fflush(stdout);
13750   }else{
13751     fclose(out);
13752   }
13753 #endif
13754 }
13755
13756 /*
13757 ** This routine is the only routine in this file with external 
13758 ** linkage.
13759 **
13760 ** Populate the low-level memory allocation function pointers in
13761 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13762 ** arguments specify the block of memory to manage.
13763 **
13764 ** This routine is only called by sqlite3_config(), and therefore
13765 ** is not required to be threadsafe (it is not).
13766 */
13767 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13768   static const sqlite3_mem_methods mempoolMethods = {
13769      memsys3Malloc,
13770      memsys3Free,
13771      memsys3Realloc,
13772      memsys3Size,
13773      memsys3Roundup,
13774      memsys3Init,
13775      memsys3Shutdown,
13776      0
13777   };
13778   return &mempoolMethods;
13779 }
13780
13781 #endif /* SQLITE_ENABLE_MEMSYS3 */
13782
13783 /************** End of mem3.c ************************************************/
13784 /************** Begin file mem5.c ********************************************/
13785 /*
13786 ** 2007 October 14
13787 **
13788 ** The author disclaims copyright to this source code.  In place of
13789 ** a legal notice, here is a blessing:
13790 **
13791 **    May you do good and not evil.
13792 **    May you find forgiveness for yourself and forgive others.
13793 **    May you share freely, never taking more than you give.
13794 **
13795 *************************************************************************
13796 ** This file contains the C functions that implement a memory
13797 ** allocation subsystem for use by SQLite. 
13798 **
13799 ** This version of the memory allocation subsystem omits all
13800 ** use of malloc(). The SQLite user supplies a block of memory
13801 ** before calling sqlite3_initialize() from which allocations
13802 ** are made and returned by the xMalloc() and xRealloc() 
13803 ** implementations. Once sqlite3_initialize() has been called,
13804 ** the amount of memory available to SQLite is fixed and cannot
13805 ** be changed.
13806 **
13807 ** This version of the memory allocation subsystem is included
13808 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13809 **
13810 ** $Id: mem5.c,v 1.14 2008/09/02 17:52:52 danielk1977 Exp $
13811 */
13812
13813 /*
13814 ** This version of the memory allocator is used only when 
13815 ** SQLITE_POW2_MEMORY_SIZE is defined.
13816 */
13817 #ifdef SQLITE_ENABLE_MEMSYS5
13818
13819 /*
13820 ** Log2 of the minimum size of an allocation.  For example, if
13821 ** 4 then all allocations will be rounded up to at least 16 bytes.
13822 ** If 5 then all allocations will be rounded up to at least 32 bytes.
13823 */
13824 #ifndef SQLITE_POW2_LOGMIN
13825 # define SQLITE_POW2_LOGMIN 6
13826 #endif
13827
13828 /*
13829 ** Log2 of the maximum size of an allocation.
13830 */
13831 #ifndef SQLITE_POW2_LOGMAX
13832 # define SQLITE_POW2_LOGMAX 20
13833 #endif
13834 #define POW2_MAX (((unsigned int)1)<<SQLITE_POW2_LOGMAX)
13835
13836 /*
13837 ** Number of distinct allocation sizes.
13838 */
13839 #define NSIZE (SQLITE_POW2_LOGMAX - SQLITE_POW2_LOGMIN + 1)
13840
13841 /*
13842 ** A minimum allocation is an instance of the following structure.
13843 ** Larger allocations are an array of these structures where the
13844 ** size of the array is a power of 2.
13845 */
13846 typedef struct Mem5Link Mem5Link;
13847 struct Mem5Link {
13848   int next;       /* Index of next free chunk */
13849   int prev;       /* Index of previous free chunk */
13850 };
13851
13852 /*
13853 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
13854 ** mem5.nAtom is always at least 8, this is not really a practical
13855 ** limitation.
13856 */
13857 #define LOGMAX 30
13858
13859 /*
13860 ** Masks used for mem5.aCtrl[] elements.
13861 */
13862 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
13863 #define CTRL_FREE     0x20    /* True if not checked out */
13864
13865 /*
13866 ** All of the static variables used by this module are collected
13867 ** into a single structure named "mem5".  This is to keep the
13868 ** static variables organized and to reduce namespace pollution
13869 ** when this module is combined with other in the amalgamation.
13870 */
13871 static SQLITE_WSD struct Mem5Global {
13872   /*
13873   ** Memory available for allocation
13874   */
13875   int nAtom;       /* Smallest possible allocation in bytes */
13876   int nBlock;      /* Number of nAtom sized blocks in zPool */
13877   u8 *zPool;
13878   
13879   /*
13880   ** Mutex to control access to the memory allocation subsystem.
13881   */
13882   sqlite3_mutex *mutex;
13883
13884   /*
13885   ** Performance statistics
13886   */
13887   u64 nAlloc;         /* Total number of calls to malloc */
13888   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13889   u64 totalExcess;    /* Total internal fragmentation */
13890   u32 currentOut;     /* Current checkout, including internal fragmentation */
13891   u32 currentCount;   /* Current number of distinct checkouts */
13892   u32 maxOut;         /* Maximum instantaneous currentOut */
13893   u32 maxCount;       /* Maximum instantaneous currentCount */
13894   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13895   
13896   /*
13897   ** Lists of free blocks of various sizes.
13898   */
13899   int aiFreelist[LOGMAX+1];
13900
13901   /*
13902   ** Space for tracking which blocks are checked out and the size
13903   ** of each block.  One byte per block.
13904   */
13905   u8 *aCtrl;
13906
13907 } mem5 = { 19804167 };
13908
13909 #define mem5 GLOBAL(struct Mem5Global, mem5)
13910
13911 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
13912
13913 /*
13914 ** Unlink the chunk at mem5.aPool[i] from list it is currently
13915 ** on.  It should be found on mem5.aiFreelist[iLogsize].
13916 */
13917 static void memsys5Unlink(int i, int iLogsize){
13918   int next, prev;
13919   assert( i>=0 && i<mem5.nBlock );
13920   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13921   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13922
13923   next = MEM5LINK(i)->next;
13924   prev = MEM5LINK(i)->prev;
13925   if( prev<0 ){
13926     mem5.aiFreelist[iLogsize] = next;
13927   }else{
13928     MEM5LINK(prev)->next = next;
13929   }
13930   if( next>=0 ){
13931     MEM5LINK(next)->prev = prev;
13932   }
13933 }
13934
13935 /*
13936 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13937 ** free list.
13938 */
13939 static void memsys5Link(int i, int iLogsize){
13940   int x;
13941   assert( sqlite3_mutex_held(mem5.mutex) );
13942   assert( i>=0 && i<mem5.nBlock );
13943   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13944   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13945
13946   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13947   MEM5LINK(i)->prev = -1;
13948   if( x>=0 ){
13949     assert( x<mem5.nBlock );
13950     MEM5LINK(x)->prev = i;
13951   }
13952   mem5.aiFreelist[iLogsize] = i;
13953 }
13954
13955 /*
13956 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13957 ** will already be held (obtained by code in malloc.c) if
13958 ** sqlite3GlobalConfig.bMemStat is true.
13959 */
13960 static void memsys5Enter(void){
13961   if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
13962     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13963   }
13964   sqlite3_mutex_enter(mem5.mutex);
13965 }
13966 static void memsys5Leave(void){
13967   sqlite3_mutex_leave(mem5.mutex);
13968 }
13969
13970 /*
13971 ** Return the size of an outstanding allocation, in bytes.  The
13972 ** size returned omits the 8-byte header overhead.  This only
13973 ** works for chunks that are currently checked out.
13974 */
13975 static int memsys5Size(void *p){
13976   int iSize = 0;
13977   if( p ){
13978     int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
13979     assert( i>=0 && i<mem5.nBlock );
13980     iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
13981   }
13982   return iSize;
13983 }
13984
13985 /*
13986 ** Find the first entry on the freelist iLogsize.  Unlink that
13987 ** entry and return its index. 
13988 */
13989 static int memsys5UnlinkFirst(int iLogsize){
13990   int i;
13991   int iFirst;
13992
13993   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13994   i = iFirst = mem5.aiFreelist[iLogsize];
13995   assert( iFirst>=0 );
13996   while( i>0 ){
13997     if( i<iFirst ) iFirst = i;
13998     i = MEM5LINK(i)->next;
13999   }
14000   memsys5Unlink(iFirst, iLogsize);
14001   return iFirst;
14002 }
14003
14004 /*
14005 ** Return a block of memory of at least nBytes in size.
14006 ** Return NULL if unable.
14007 */
14008 static void *memsys5MallocUnsafe(int nByte){
14009   int i;           /* Index of a mem5.aPool[] slot */
14010   int iBin;        /* Index into mem5.aiFreelist[] */
14011   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14012   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14013
14014   /* Keep track of the maximum allocation request.  Even unfulfilled
14015   ** requests are counted */
14016   if( nByte>mem5.maxRequest ){
14017     mem5.maxRequest = nByte;
14018   }
14019
14020   /* Round nByte up to the next valid power of two */
14021   if( nByte>POW2_MAX ) return 0;
14022   for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14023
14024   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14025   ** block.  If not, then split a block of the next larger power of
14026   ** two in order to create a new free block of size iLogsize.
14027   */
14028   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14029   if( iBin>LOGMAX ) return 0;
14030   i = memsys5UnlinkFirst(iBin);
14031   while( iBin>iLogsize ){
14032     int newSize;
14033
14034     iBin--;
14035     newSize = 1 << iBin;
14036     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14037     memsys5Link(i+newSize, iBin);
14038   }
14039   mem5.aCtrl[i] = iLogsize;
14040
14041   /* Update allocator performance statistics. */
14042   mem5.nAlloc++;
14043   mem5.totalAlloc += iFullSz;
14044   mem5.totalExcess += iFullSz - nByte;
14045   mem5.currentCount++;
14046   mem5.currentOut += iFullSz;
14047   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14048   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14049
14050   /* Return a pointer to the allocated memory. */
14051   return (void*)&mem5.zPool[i*mem5.nAtom];
14052 }
14053
14054 /*
14055 ** Free an outstanding memory allocation.
14056 */
14057 static void memsys5FreeUnsafe(void *pOld){
14058   u32 size, iLogsize;
14059   int iBlock;             
14060
14061   /* Set iBlock to the index of the block pointed to by pOld in 
14062   ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
14063   */
14064   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
14065
14066   /* Check that the pointer pOld points to a valid, non-free block. */
14067   assert( iBlock>=0 && iBlock<mem5.nBlock );
14068   assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
14069   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14070
14071   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14072   size = 1<<iLogsize;
14073   assert( iBlock+size-1<mem5.nBlock );
14074
14075   mem5.aCtrl[iBlock] |= CTRL_FREE;
14076   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14077   assert( mem5.currentCount>0 );
14078   assert( mem5.currentOut>=0 );
14079   mem5.currentCount--;
14080   mem5.currentOut -= size*mem5.nAtom;
14081   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14082   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14083
14084   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14085   while( iLogsize<LOGMAX ){
14086     int iBuddy;
14087     if( (iBlock>>iLogsize) & 1 ){
14088       iBuddy = iBlock - size;
14089     }else{
14090       iBuddy = iBlock + size;
14091     }
14092     assert( iBuddy>=0 );
14093     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14094     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14095     memsys5Unlink(iBuddy, iLogsize);
14096     iLogsize++;
14097     if( iBuddy<iBlock ){
14098       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14099       mem5.aCtrl[iBlock] = 0;
14100       iBlock = iBuddy;
14101     }else{
14102       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14103       mem5.aCtrl[iBuddy] = 0;
14104     }
14105     size *= 2;
14106   }
14107   memsys5Link(iBlock, iLogsize);
14108 }
14109
14110 /*
14111 ** Allocate nBytes of memory
14112 */
14113 static void *memsys5Malloc(int nBytes){
14114   sqlite3_int64 *p = 0;
14115   if( nBytes>0 ){
14116     memsys5Enter();
14117     p = memsys5MallocUnsafe(nBytes);
14118     memsys5Leave();
14119   }
14120   return (void*)p; 
14121 }
14122
14123 /*
14124 ** Free memory.
14125 */
14126 static void memsys5Free(void *pPrior){
14127   if( pPrior==0 ){
14128 assert(0);
14129     return;
14130   }
14131   memsys5Enter();
14132   memsys5FreeUnsafe(pPrior);
14133   memsys5Leave();  
14134 }
14135
14136 /*
14137 ** Change the size of an existing memory allocation
14138 */
14139 static void *memsys5Realloc(void *pPrior, int nBytes){
14140   int nOld;
14141   void *p;
14142   if( pPrior==0 ){
14143     return memsys5Malloc(nBytes);
14144   }
14145   if( nBytes<=0 ){
14146     memsys5Free(pPrior);
14147     return 0;
14148   }
14149   nOld = memsys5Size(pPrior);
14150   if( nBytes<=nOld ){
14151     return pPrior;
14152   }
14153   memsys5Enter();
14154   p = memsys5MallocUnsafe(nBytes);
14155   if( p ){
14156     memcpy(p, pPrior, nOld);
14157     memsys5FreeUnsafe(pPrior);
14158   }
14159   memsys5Leave();
14160   return p;
14161 }
14162
14163 /*
14164 ** Round up a request size to the next valid allocation size.
14165 */
14166 static int memsys5Roundup(int n){
14167   int iFullSz;
14168   for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
14169   return iFullSz;
14170 }
14171
14172 static int memsys5Log(int iValue){
14173   int iLog;
14174   for(iLog=0; (1<<iLog)<iValue; iLog++);
14175   return iLog;
14176 }
14177
14178 /*
14179 ** Initialize this module.
14180 */
14181 static int memsys5Init(void *NotUsed){
14182   int ii;
14183   int nByte = sqlite3GlobalConfig.nHeap;
14184   u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
14185   int nMinLog;                 /* Log of minimum allocation size in bytes*/
14186   int iOffset;
14187
14188   if( !zByte ){
14189     return SQLITE_ERROR;
14190   }
14191
14192   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14193   mem5.nAtom = (1<<nMinLog);
14194   while( sizeof(Mem5Link)>mem5.nAtom ){
14195     mem5.nAtom = mem5.nAtom << 1;
14196   }
14197
14198   mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
14199   mem5.zPool = zByte;
14200   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
14201
14202   for(ii=0; ii<=LOGMAX; ii++){
14203     mem5.aiFreelist[ii] = -1;
14204   }
14205
14206   iOffset = 0;
14207   for(ii=LOGMAX; ii>=0; ii--){
14208     int nAlloc = (1<<ii);
14209     if( (iOffset+nAlloc)<=mem5.nBlock ){
14210       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14211       memsys5Link(iOffset, ii);
14212       iOffset += nAlloc;
14213     }
14214     assert((iOffset+nAlloc)>mem5.nBlock);
14215   }
14216
14217   return SQLITE_OK;
14218 }
14219
14220 /*
14221 ** Deinitialize this module.
14222 */
14223 static void memsys5Shutdown(void *NotUsed){
14224   return;
14225 }
14226
14227 /*
14228 ** Open the file indicated and write a log of all unfreed memory 
14229 ** allocations into that log.
14230 */
14231 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14232 #ifdef SQLITE_DEBUG
14233   FILE *out;
14234   int i, j, n;
14235   int nMinLog;
14236
14237   if( zFilename==0 || zFilename[0]==0 ){
14238     out = stdout;
14239   }else{
14240     out = fopen(zFilename, "w");
14241     if( out==0 ){
14242       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14243                       zFilename);
14244       return;
14245     }
14246   }
14247   memsys5Enter();
14248   nMinLog = memsys5Log(mem5.nAtom);
14249   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14250     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14251     fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
14252   }
14253   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14254   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14255   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14256   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14257   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14258   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14259   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14260   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14261   memsys5Leave();
14262   if( out==stdout ){
14263     fflush(stdout);
14264   }else{
14265     fclose(out);
14266   }
14267 #endif
14268 }
14269
14270 /*
14271 ** This routine is the only routine in this file with external 
14272 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14273 ** struct populated with the memsys5 methods.
14274 */
14275 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14276   static const sqlite3_mem_methods memsys5Methods = {
14277      memsys5Malloc,
14278      memsys5Free,
14279      memsys5Realloc,
14280      memsys5Size,
14281      memsys5Roundup,
14282      memsys5Init,
14283      memsys5Shutdown,
14284      0
14285   };
14286   return &memsys5Methods;
14287 }
14288
14289 #endif /* SQLITE_ENABLE_MEMSYS5 */
14290
14291 /************** End of mem5.c ************************************************/
14292 /************** Begin file mem6.c ********************************************/
14293 /*
14294 ** 2008 July 24
14295 **
14296 ** The author disclaims copyright to this source code.  In place of
14297 ** a legal notice, here is a blessing:
14298 **
14299 **    May you do good and not evil.
14300 **    May you find forgiveness for yourself and forgive others.
14301 **    May you share freely, never taking more than you give.
14302 **
14303 *************************************************************************
14304 **
14305 ** This file contains an alternative memory allocation system for SQLite.
14306 ** This system is implemented as a wrapper around the system provided
14307 ** by the operating system - vanilla malloc(), realloc() and free().
14308 **
14309 ** This system differentiates between requests for "small" allocations 
14310 ** (by default those of 128 bytes or less) and "large" allocations (all
14311 ** others). The 256 byte threshhold is configurable at runtime.
14312 **
14313 ** All requests for large allocations are passed through to the 
14314 ** default system.
14315 **
14316 ** Requests for small allocations are met by allocating space within
14317 ** one or more larger "chunks" of memory obtained from the default
14318 ** memory allocation system. Chunks of memory are usually 64KB or 
14319 ** larger. The algorithm used to manage space within each chunk is
14320 ** the same as that used by mem5.c. 
14321 **
14322 ** This strategy is designed to prevent the default memory allocation
14323 ** system (usually the system malloc) from suffering from heap 
14324 ** fragmentation. On some systems, heap fragmentation can cause a 
14325 ** significant real-time slowdown.
14326 **
14327 ** $Id: mem6.c,v 1.10 2008/09/02 17:52:52 danielk1977 Exp $
14328 */
14329
14330 #ifdef SQLITE_ENABLE_MEMSYS6
14331
14332
14333 /*
14334 ** Maximum size of any "small" allocation is ((1<<LOGMAX)*Mem6Chunk.nAtom).
14335 ** Mem6Chunk.nAtom is always at least 8, so this is not a practical
14336 ** limitation
14337 */
14338 #define LOGMAX 30
14339
14340 /*
14341 ** Default value for the "small" allocation size threshold.
14342 */
14343 #define SMALL_MALLOC_DEFAULT_THRESHOLD 256
14344
14345 /*
14346 ** Minimum size for a memory chunk.
14347 */
14348 #define MIN_CHUNKSIZE (1<<16)
14349
14350 #define LOG2_MINALLOC 4
14351
14352
14353 typedef struct Mem6Chunk Mem6Chunk;
14354 typedef struct Mem6Link Mem6Link;
14355
14356 /*
14357 ** A minimum allocation is an instance of the following structure.
14358 ** Larger allocations are an array of these structures where the
14359 ** size of the array is a power of 2.
14360 */
14361 struct Mem6Link {
14362   int next;       /* Index of next free chunk */
14363   int prev;       /* Index of previous free chunk */
14364 };
14365
14366 /*
14367 ** Masks used for mem5.aCtrl[] elements.
14368 */
14369 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
14370 #define CTRL_FREE     0x20    /* True if not checked out */
14371
14372 struct Mem6Chunk {
14373   Mem6Chunk *pNext;
14374
14375   /*
14376   ** Lists of free blocks of various sizes.
14377   */
14378   int aiFreelist[LOGMAX+1];
14379
14380   int nCheckedOut; /* Number of currently outstanding allocations */
14381
14382   /*
14383   ** Space for tracking which blocks are checked out and the size
14384   ** of each block. One byte per block.
14385   */
14386   u8 *aCtrl;
14387
14388   /*
14389   ** Memory available for allocation
14390   */
14391   int nAtom;       /* Smallest possible allocation in bytes */
14392   int nBlock;      /* Number of nAtom sized blocks in zPool */
14393   u8 *zPool;       /* Pointer to memory chunk from which allocations are made */
14394 };
14395
14396 #define MEM6LINK(idx) ((Mem6Link *)(&pChunk->zPool[(idx)*pChunk->nAtom]))
14397
14398 static SQLITE_WSD struct Mem6Global {
14399   int nMinAlloc;                  /* Minimum allowed allocation size */
14400   int nThreshold;                 /* Allocs larger than this go to malloc() */
14401   int nLogThreshold;              /* log2 of (nThreshold/nMinAlloc) */
14402   sqlite3_mutex *mutex;
14403   Mem6Chunk *pChunk;              /* Singly linked list of all memory chunks */
14404 } mem6 = { 48642791 };
14405
14406 #define mem6 GLOBAL(struct Mem6Global, mem6)
14407
14408 /*
14409 ** Unlink the chunk at pChunk->aPool[i] from list it is currently
14410 ** on.  It should be found on pChunk->aiFreelist[iLogsize].
14411 */
14412 static void memsys6Unlink(Mem6Chunk *pChunk, int i, int iLogsize){
14413   int next, prev;
14414   assert( i>=0 && i<pChunk->nBlock );
14415   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14416   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14417
14418   next = MEM6LINK(i)->next;
14419   prev = MEM6LINK(i)->prev;
14420   if( prev<0 ){
14421     pChunk->aiFreelist[iLogsize] = next;
14422   }else{
14423     MEM6LINK(prev)->next = next;
14424   }
14425   if( next>=0 ){
14426     MEM6LINK(next)->prev = prev;
14427   }
14428 }
14429
14430 /*
14431 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14432 ** free list.
14433 */
14434 static void memsys6Link(Mem6Chunk *pChunk, int i, int iLogsize){
14435   int x;
14436   assert( i>=0 && i<pChunk->nBlock );
14437   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14438   assert( (pChunk->aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14439
14440   x = MEM6LINK(i)->next = pChunk->aiFreelist[iLogsize];
14441   MEM6LINK(i)->prev = -1;
14442   if( x>=0 ){
14443     assert( x<pChunk->nBlock );
14444     MEM6LINK(x)->prev = i;
14445   }
14446   pChunk->aiFreelist[iLogsize] = i;
14447 }
14448
14449
14450 /*
14451 ** Find the first entry on the freelist iLogsize.  Unlink that
14452 ** entry and return its index. 
14453 */
14454 static int memsys6UnlinkFirst(Mem6Chunk *pChunk, int iLogsize){
14455   int i;
14456   int iFirst;
14457
14458   assert( iLogsize>=0 && iLogsize<=mem6.nLogThreshold );
14459   i = iFirst = pChunk->aiFreelist[iLogsize];
14460   assert( iFirst>=0 );
14461   memsys6Unlink(pChunk, iFirst, iLogsize);
14462   return iFirst;
14463 }
14464
14465 static int roundupLog2(int n){
14466   static const char LogTable256[256] = {
14467     0,                                                    /* 1 */
14468     1,                                                    /* 2 */
14469     2, 2,                                                 /* 3..4 */
14470     3, 3, 3, 3,                                           /* 5..8 */
14471     4, 4, 4, 4, 4, 4, 4, 4,                               /* 9..16 */
14472     5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,       /* 17..32 */
14473     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
14474     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,       /* 33..64 */
14475     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14476     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14477     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
14478     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,       /* 65..128 */
14479     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14480     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14481     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14482     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14483     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14484     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14485     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
14486     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,       /* 129..256 */
14487   };
14488
14489   assert(n<=(1<<16) && n>0);
14490   if( n<=256 ) return LogTable256[n-1];
14491   return LogTable256[(n>>8) - ((n&0xFF)?0:1)] + 8;
14492 }
14493
14494 /*
14495 ** Allocate and return a block of (pChunk->nAtom << iLogsize) bytes from chunk
14496 ** pChunk. If the allocation request cannot be satisfied, return 0.
14497 */
14498 static void *chunkMalloc(Mem6Chunk *pChunk, int iLogsize){
14499   int i;           /* Index of a mem5.aPool[] slot */
14500   int iBin;        /* Index into mem5.aiFreelist[] */
14501
14502   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14503   ** block.  If not, then split a block of the next larger power of
14504   ** two in order to create a new free block of size iLogsize.
14505   */
14506   for(iBin=iLogsize; pChunk->aiFreelist[iBin]<0 && iBin<=mem6.nLogThreshold; iBin++){}
14507   if( iBin>mem6.nLogThreshold ) return 0;
14508   i = memsys6UnlinkFirst(pChunk, iBin);
14509   while( iBin>iLogsize ){
14510     int newSize;
14511     iBin--;
14512     newSize = 1 << iBin;
14513     pChunk->aCtrl[i+newSize] = CTRL_FREE | iBin;
14514     memsys6Link(pChunk, i+newSize, iBin);
14515   }
14516   pChunk->aCtrl[i] = iLogsize;
14517
14518   /* Return a pointer to the allocated memory. */
14519   pChunk->nCheckedOut++;
14520   return (void*)&pChunk->zPool[i*pChunk->nAtom];
14521 }
14522
14523 /*
14524 ** Free the allocation pointed to by p, which is guaranteed to be non-zero
14525 ** and a part of chunk object pChunk.
14526 */
14527 static void chunkFree(Mem6Chunk *pChunk, void *pOld){
14528   u32 size, iLogsize;
14529   int iBlock;             
14530
14531   /* Set iBlock to the index of the block pointed to by pOld in 
14532   ** the array of pChunk->nAtom byte blocks pointed to by pChunk->zPool.
14533   */
14534   iBlock = ((u8 *)pOld-pChunk->zPool)/pChunk->nAtom;
14535
14536   /* Check that the pointer pOld points to a valid, non-free block. */
14537   assert( iBlock>=0 && iBlock<pChunk->nBlock );
14538   assert( ((u8 *)pOld-pChunk->zPool)%pChunk->nAtom==0 );
14539   assert( (pChunk->aCtrl[iBlock] & CTRL_FREE)==0 );
14540
14541   iLogsize = pChunk->aCtrl[iBlock] & CTRL_LOGSIZE;
14542   size = 1<<iLogsize;
14543   assert( iBlock+size-1<pChunk->nBlock );
14544
14545   pChunk->aCtrl[iBlock] |= CTRL_FREE;
14546   pChunk->aCtrl[iBlock+size-1] |= CTRL_FREE;
14547
14548   pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
14549   while( iLogsize<mem6.nLogThreshold ){
14550     int iBuddy;
14551     if( (iBlock>>iLogsize) & 1 ){
14552       iBuddy = iBlock - size;
14553     }else{
14554       iBuddy = iBlock + size;
14555     }
14556     assert( iBuddy>=0 );
14557     if( (iBuddy+(1<<iLogsize))>pChunk->nBlock ) break;
14558     if( pChunk->aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14559     memsys6Unlink(pChunk, iBuddy, iLogsize);
14560     iLogsize++;
14561     if( iBuddy<iBlock ){
14562       pChunk->aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14563       pChunk->aCtrl[iBlock] = 0;
14564       iBlock = iBuddy;
14565     }else{
14566       pChunk->aCtrl[iBlock] = CTRL_FREE | iLogsize;
14567       pChunk->aCtrl[iBuddy] = 0;
14568     }
14569     size *= 2;
14570   }
14571   pChunk->nCheckedOut--;
14572   memsys6Link(pChunk, iBlock, iLogsize);
14573 }
14574
14575 /*
14576 ** Return the actual size of the block pointed to by p, which is guaranteed
14577 ** to have been allocated from chunk pChunk.
14578 */
14579 static int chunkSize(Mem6Chunk *pChunk, void *p){
14580   int iSize = 0;
14581   if( p ){
14582     int i = ((u8 *)p-pChunk->zPool)/pChunk->nAtom;
14583     assert( i>=0 && i<pChunk->nBlock );
14584     iSize = pChunk->nAtom * (1 << (pChunk->aCtrl[i]&CTRL_LOGSIZE));
14585   }
14586   return iSize;
14587 }
14588
14589 /*
14590 ** Return true if there are currently no outstanding allocations.
14591 */
14592 static int chunkIsEmpty(Mem6Chunk *pChunk){
14593   return (pChunk->nCheckedOut==0);
14594 }
14595
14596 /*
14597 ** Initialize the buffer zChunk, which is nChunk bytes in size, as
14598 ** an Mem6Chunk object. Return a copy of the zChunk pointer.
14599 */
14600 static Mem6Chunk *chunkInit(u8 *zChunk, int nChunk, int nMinAlloc){
14601   int ii;
14602   int iOffset;
14603   Mem6Chunk *pChunk = (Mem6Chunk *)zChunk;
14604
14605   assert( nChunk>sizeof(Mem6Chunk) );
14606   assert( nMinAlloc>sizeof(Mem6Link) );
14607
14608   memset(pChunk, 0, sizeof(Mem6Chunk));
14609   pChunk->nAtom = nMinAlloc;
14610   pChunk->nBlock = ((nChunk-sizeof(Mem6Chunk)) / (pChunk->nAtom+sizeof(u8)));
14611
14612   pChunk->zPool = (u8 *)&pChunk[1];
14613   pChunk->aCtrl = &pChunk->zPool[pChunk->nBlock*pChunk->nAtom];
14614
14615   for(ii=0; ii<=mem6.nLogThreshold; ii++){
14616     pChunk->aiFreelist[ii] = -1;
14617   }
14618
14619   iOffset = 0;
14620   for(ii=mem6.nLogThreshold; ii>=0; ii--){
14621     int nAlloc = (1<<ii);
14622     while( (iOffset+nAlloc)<=pChunk->nBlock ){
14623       pChunk->aCtrl[iOffset] = ii | CTRL_FREE;
14624       memsys6Link(pChunk, iOffset, ii);
14625       iOffset += nAlloc;
14626     }
14627   }
14628
14629   return pChunk;
14630 }
14631
14632
14633 static void mem6Enter(void){
14634   sqlite3_mutex_enter(mem6.mutex);
14635 }
14636
14637 static void mem6Leave(void){
14638   sqlite3_mutex_leave(mem6.mutex);
14639 }
14640
14641 /*
14642 ** Based on the number and size of the currently allocated chunks, return
14643 ** the size of the next chunk to allocate, in bytes.
14644 */
14645 static int nextChunkSize(void){
14646   int iTotal = MIN_CHUNKSIZE;
14647   Mem6Chunk *p;
14648   for(p=mem6.pChunk; p; p=p->pNext){
14649     iTotal = iTotal*2;
14650   }
14651   return iTotal;
14652 }
14653
14654 static void freeChunk(Mem6Chunk *pChunk){
14655   Mem6Chunk **pp = &mem6.pChunk;
14656   for( pp=&mem6.pChunk; *pp!=pChunk; pp = &(*pp)->pNext );
14657   *pp = (*pp)->pNext;
14658   free(pChunk);
14659 }
14660
14661 static void *memsys6Malloc(int nByte){
14662   Mem6Chunk *pChunk;
14663   void *p = 0;
14664   int nTotal = nByte+8;
14665   int iOffset = 0;
14666
14667   if( nTotal>mem6.nThreshold ){
14668     p = malloc(nTotal);
14669   }else{
14670     int iLogsize = 0;
14671     if( nTotal>(1<<LOG2_MINALLOC) ){
14672       iLogsize = roundupLog2(nTotal) - LOG2_MINALLOC;
14673     }
14674     mem6Enter();
14675     for(pChunk=mem6.pChunk; pChunk; pChunk=pChunk->pNext){
14676       p = chunkMalloc(pChunk, iLogsize);
14677       if( p ){
14678         break;
14679       }
14680     }
14681     if( !p ){
14682       int iSize = nextChunkSize();
14683       p = malloc(iSize);
14684       if( p ){
14685         pChunk = chunkInit((u8 *)p, iSize, mem6.nMinAlloc);
14686         pChunk->pNext = mem6.pChunk;
14687         mem6.pChunk = pChunk;
14688         p = chunkMalloc(pChunk, iLogsize);
14689         assert(p);
14690       }
14691     }
14692     iOffset = ((u8*)p - (u8*)pChunk);
14693     mem6Leave();
14694   }
14695
14696   if( !p ){
14697     return 0;
14698   }
14699   ((u32 *)p)[0] = iOffset;
14700   ((u32 *)p)[1] = nByte;
14701   return &((u32 *)p)[2];
14702 }
14703
14704 static int memsys6Size(void *pPrior){
14705   if( pPrior==0 ) return 0;
14706   return ((u32*)pPrior)[-1];
14707 }
14708
14709 static void memsys6Free(void *pPrior){
14710   int iSlot;
14711   void *p = &((u32 *)pPrior)[-2];
14712   iSlot = ((u32 *)p)[0];
14713   if( iSlot ){
14714     Mem6Chunk *pChunk;
14715     mem6Enter();
14716     pChunk = (Mem6Chunk *)(&((u8 *)p)[-1 * iSlot]);
14717     chunkFree(pChunk, p);
14718     if( chunkIsEmpty(pChunk) ){
14719       freeChunk(pChunk);
14720     }
14721     mem6Leave();
14722   }else{
14723     free(p);
14724   }
14725 }
14726
14727 static void *memsys6Realloc(void *p, int nByte){
14728   void *p2;
14729
14730   if( p && nByte<=memsys6Size(p) ){
14731     p2 = p;
14732   }else{
14733     p2 = memsys6Malloc(nByte);
14734     if( p && p2 ){
14735       memcpy(p2, p, memsys6Size(p));
14736       memsys6Free(p);
14737     }
14738   }
14739
14740   return p2;
14741 }
14742
14743 static int memsys6Roundup(int n){
14744   if( n>mem6.nThreshold ){
14745     return n;
14746   }else{
14747     return (1<<roundupLog2(n));
14748   }
14749 }
14750
14751 static int memsys6Init(void *pCtx){
14752   u8 bMemstat = sqlite3GlobalConfig.bMemstat;
14753   mem6.nMinAlloc = (1 << LOG2_MINALLOC);
14754   mem6.pChunk = 0;
14755   mem6.nThreshold = sqlite3GlobalConfig.nSmall;
14756   if( mem6.nThreshold<=0 ){
14757     mem6.nThreshold = SMALL_MALLOC_DEFAULT_THRESHOLD;
14758   }
14759   mem6.nLogThreshold = roundupLog2(mem6.nThreshold) - LOG2_MINALLOC;
14760   if( !bMemstat ){
14761     mem6.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14762   }
14763   return SQLITE_OK;
14764 }
14765
14766 static void memsys6Shutdown(void *pCtx){
14767   memset(&mem6, 0, sizeof(mem6));
14768 }
14769
14770 /*
14771 ** This routine is the only routine in this file with external 
14772 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14773 ** struct populated with the memsys6 methods.
14774 */
14775 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys6(void){
14776   static const sqlite3_mem_methods memsys6Methods = {
14777      memsys6Malloc,
14778      memsys6Free,
14779      memsys6Realloc,
14780      memsys6Size,
14781      memsys6Roundup,
14782      memsys6Init,
14783      memsys6Shutdown,
14784      0
14785   };
14786   return &memsys6Methods;
14787 }
14788
14789 #endif
14790
14791 /************** End of mem6.c ************************************************/
14792 /************** Begin file mutex.c *******************************************/
14793 /*
14794 ** 2007 August 14
14795 **
14796 ** The author disclaims copyright to this source code.  In place of
14797 ** a legal notice, here is a blessing:
14798 **
14799 **    May you do good and not evil.
14800 **    May you find forgiveness for yourself and forgive others.
14801 **    May you share freely, never taking more than you give.
14802 **
14803 *************************************************************************
14804 ** This file contains the C functions that implement mutexes.
14805 **
14806 ** This file contains code that is common across all mutex implementations.
14807
14808 **
14809 ** $Id: mutex.c,v 1.29 2008/10/07 15:25:48 drh Exp $
14810 */
14811
14812 #ifndef SQLITE_MUTEX_OMIT
14813 /*
14814 ** Initialize the mutex system.
14815 */
14816 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14817   int rc = SQLITE_OK;
14818   if( sqlite3GlobalConfig.bCoreMutex ){
14819     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14820       /* If the xMutexAlloc method has not been set, then the user did not
14821       ** install a mutex implementation via sqlite3_config() prior to 
14822       ** sqlite3_initialize() being called. This block copies pointers to
14823       ** the default implementation into the sqlite3GlobalConfig structure.
14824       **
14825       ** The danger is that although sqlite3_config() is not a threadsafe
14826       ** API, sqlite3_initialize() is, and so multiple threads may be
14827       ** attempting to run this function simultaneously. To guard write
14828       ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
14829       ** is obtained before modifying it.
14830       */
14831       sqlite3_mutex_methods *p = sqlite3DefaultMutex();
14832       sqlite3_mutex *pMaster = 0;
14833   
14834       rc = p->xMutexInit();
14835       if( rc==SQLITE_OK ){
14836         pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14837         assert(pMaster);
14838         p->xMutexEnter(pMaster);
14839         assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0 
14840              || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
14841         );
14842         if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14843           sqlite3GlobalConfig.mutex = *p;
14844         }
14845         p->xMutexLeave(pMaster);
14846       }
14847     }else{
14848       rc = sqlite3GlobalConfig.mutex.xMutexInit();
14849     }
14850   }
14851
14852   return rc;
14853 }
14854
14855 /*
14856 ** Shutdown the mutex system. This call frees resources allocated by
14857 ** sqlite3MutexInit().
14858 */
14859 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14860   int rc = SQLITE_OK;
14861   rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14862   return rc;
14863 }
14864
14865 /*
14866 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14867 */
14868 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14869 #ifndef SQLITE_OMIT_AUTOINIT
14870   if( sqlite3_initialize() ) return 0;
14871 #endif
14872   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14873 }
14874
14875 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14876   if( !sqlite3GlobalConfig.bCoreMutex ){
14877     return 0;
14878   }
14879   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14880 }
14881
14882 /*
14883 ** Free a dynamic mutex.
14884 */
14885 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14886   if( p ){
14887     sqlite3GlobalConfig.mutex.xMutexFree(p);
14888   }
14889 }
14890
14891 /*
14892 ** Obtain the mutex p. If some other thread already has the mutex, block
14893 ** until it can be obtained.
14894 */
14895 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14896   if( p ){
14897     sqlite3GlobalConfig.mutex.xMutexEnter(p);
14898   }
14899 }
14900
14901 /*
14902 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14903 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14904 */
14905 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14906   int rc = SQLITE_OK;
14907   if( p ){
14908     return sqlite3GlobalConfig.mutex.xMutexTry(p);
14909   }
14910   return rc;
14911 }
14912
14913 /*
14914 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14915 ** entered by the same thread.  The behavior is undefined if the mutex 
14916 ** is not currently entered. If a NULL pointer is passed as an argument
14917 ** this function is a no-op.
14918 */
14919 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14920   if( p ){
14921     sqlite3GlobalConfig.mutex.xMutexLeave(p);
14922   }
14923 }
14924
14925 #ifndef NDEBUG
14926 /*
14927 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14928 ** intended for use inside assert() statements.
14929 */
14930 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14931   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14932 }
14933 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14934   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14935 }
14936 #endif
14937
14938 #endif /* SQLITE_OMIT_MUTEX */
14939
14940 /************** End of mutex.c ***********************************************/
14941 /************** Begin file mutex_noop.c **************************************/
14942 /*
14943 ** 2008 October 07
14944 **
14945 ** The author disclaims copyright to this source code.  In place of
14946 ** a legal notice, here is a blessing:
14947 **
14948 **    May you do good and not evil.
14949 **    May you find forgiveness for yourself and forgive others.
14950 **    May you share freely, never taking more than you give.
14951 **
14952 *************************************************************************
14953 ** This file contains the C functions that implement mutexes.
14954 **
14955 ** This implementation in this file does not provide any mutual
14956 ** exclusion and is thus suitable for use only in applications
14957 ** that use SQLite in a single thread.  The routines defined
14958 ** here are place-holders.  Applications can substitute working
14959 ** mutex routines at start-time using the
14960 **
14961 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14962 **
14963 ** interface.
14964 **
14965 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
14966 ** that does error checking on mutexes to make sure they are being
14967 ** called correctly.
14968 **
14969 ** $Id: mutex_noop.c,v 1.1 2008/10/07 15:25:48 drh Exp $
14970 */
14971
14972
14973 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14974 /*
14975 ** Stub routines for all mutex methods.
14976 **
14977 ** This routines provide no mutual exclusion or error checking.
14978 */
14979 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14980 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14981 static int noopMutexInit(void){ return SQLITE_OK; }
14982 static int noopMutexEnd(void){ return SQLITE_OK; }
14983 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14984 static void noopMutexFree(sqlite3_mutex *p){ return; }
14985 static void noopMutexEnter(sqlite3_mutex *p){ return; }
14986 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14987 static void debugMutexLeave(sqlite3_mutex *p){ return; }
14988
14989 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14990   static sqlite3_mutex_methods sMutex = {
14991     noopMutexInit,
14992     noopMutexEnd,
14993     noopMutexAlloc,
14994     noopMutexFree,
14995     noopMutexEnter,
14996     noopMutexTry,
14997     noopMutexLeave,
14998
14999     noopMutexHeld,
15000     noopMutexNotheld
15001   };
15002
15003   return &sMutex;
15004 }
15005 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
15006
15007 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
15008 /*
15009 ** In this implementation, error checking is provided for testing
15010 ** and debugging purposes.  The mutexes still do not provide any
15011 ** mutual exclusion.
15012 */
15013
15014 /*
15015 ** The mutex object
15016 */
15017 struct sqlite3_mutex {
15018   int id;     /* The mutex type */
15019   int cnt;    /* Number of entries without a matching leave */
15020 };
15021
15022 /*
15023 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15024 ** intended for use inside assert() statements.
15025 */
15026 static int debugMutexHeld(sqlite3_mutex *p){
15027   return p==0 || p->cnt>0;
15028 }
15029 static int debugMutexNotheld(sqlite3_mutex *p){
15030   return p==0 || p->cnt==0;
15031 }
15032
15033 /*
15034 ** Initialize and deinitialize the mutex subsystem.
15035 */
15036 static int debugMutexInit(void){ return SQLITE_OK; }
15037 static int debugMutexEnd(void){ return SQLITE_OK; }
15038
15039 /*
15040 ** The sqlite3_mutex_alloc() routine allocates a new
15041 ** mutex and returns a pointer to it.  If it returns NULL
15042 ** that means that a mutex could not be allocated. 
15043 */
15044 static sqlite3_mutex *debugMutexAlloc(int id){
15045   static sqlite3_mutex aStatic[6];
15046   sqlite3_mutex *pNew = 0;
15047   switch( id ){
15048     case SQLITE_MUTEX_FAST:
15049     case SQLITE_MUTEX_RECURSIVE: {
15050       pNew = sqlite3Malloc(sizeof(*pNew));
15051       if( pNew ){
15052         pNew->id = id;
15053         pNew->cnt = 0;
15054       }
15055       break;
15056     }
15057     default: {
15058       assert( id-2 >= 0 );
15059       assert( id-2 < sizeof(aStatic)/sizeof(aStatic[0]) );
15060       pNew = &aStatic[id-2];
15061       pNew->id = id;
15062       break;
15063     }
15064   }
15065   return pNew;
15066 }
15067
15068 /*
15069 ** This routine deallocates a previously allocated mutex.
15070 */
15071 static void debugMutexFree(sqlite3_mutex *p){
15072   assert( p->cnt==0 );
15073   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15074   sqlite3_free(p);
15075 }
15076
15077 /*
15078 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15079 ** to enter a mutex.  If another thread is already within the mutex,
15080 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15081 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15082 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15083 ** be entered multiple times by the same thread.  In such cases the,
15084 ** mutex must be exited an equal number of times before another thread
15085 ** can enter.  If the same thread tries to enter any other kind of mutex
15086 ** more than once, the behavior is undefined.
15087 */
15088 static void debugMutexEnter(sqlite3_mutex *p){
15089   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15090   p->cnt++;
15091 }
15092 static int debugMutexTry(sqlite3_mutex *p){
15093   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15094   p->cnt++;
15095   return SQLITE_OK;
15096 }
15097
15098 /*
15099 ** The sqlite3_mutex_leave() routine exits a mutex that was
15100 ** previously entered by the same thread.  The behavior
15101 ** is undefined if the mutex is not currently entered or
15102 ** is not currently allocated.  SQLite will never do either.
15103 */
15104 static void debugMutexLeave(sqlite3_mutex *p){
15105   assert( debugMutexHeld(p) );
15106   p->cnt--;
15107   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15108 }
15109
15110 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15111   static sqlite3_mutex_methods sMutex = {
15112     debugMutexInit,
15113     debugMutexEnd,
15114     debugMutexAlloc,
15115     debugMutexFree,
15116     debugMutexEnter,
15117     debugMutexTry,
15118     debugMutexLeave,
15119
15120     debugMutexHeld,
15121     debugMutexNotheld
15122   };
15123
15124   return &sMutex;
15125 }
15126 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
15127
15128 /************** End of mutex_noop.c ******************************************/
15129 /************** Begin file mutex_os2.c ***************************************/
15130 /*
15131 ** 2007 August 28
15132 **
15133 ** The author disclaims copyright to this source code.  In place of
15134 ** a legal notice, here is a blessing:
15135 **
15136 **    May you do good and not evil.
15137 **    May you find forgiveness for yourself and forgive others.
15138 **    May you share freely, never taking more than you give.
15139 **
15140 *************************************************************************
15141 ** This file contains the C functions that implement mutexes for OS/2
15142 **
15143 ** $Id: mutex_os2.c,v 1.10 2008/06/23 22:13:28 pweilbacher Exp $
15144 */
15145
15146 /*
15147 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15148 ** See the mutex.h file for details.
15149 */
15150 #ifdef SQLITE_MUTEX_OS2
15151
15152 /********************** OS/2 Mutex Implementation **********************
15153 **
15154 ** This implementation of mutexes is built using the OS/2 API.
15155 */
15156
15157 /*
15158 ** The mutex object
15159 ** Each recursive mutex is an instance of the following structure.
15160 */
15161 struct sqlite3_mutex {
15162   HMTX mutex;       /* Mutex controlling the lock */
15163   int  id;          /* Mutex type */
15164   int  nRef;        /* Number of references */
15165   TID  owner;       /* Thread holding this mutex */
15166 };
15167
15168 #define OS2_MUTEX_INITIALIZER   0,0,0,0
15169
15170 /*
15171 ** Initialize and deinitialize the mutex subsystem.
15172 */
15173 static int os2MutexInit(void){ return SQLITE_OK; }
15174 static int os2MutexEnd(void){ return SQLITE_OK; }
15175
15176 /*
15177 ** The sqlite3_mutex_alloc() routine allocates a new
15178 ** mutex and returns a pointer to it.  If it returns NULL
15179 ** that means that a mutex could not be allocated. 
15180 ** SQLite will unwind its stack and return an error.  The argument
15181 ** to sqlite3_mutex_alloc() is one of these integer constants:
15182 **
15183 ** <ul>
15184 ** <li>  SQLITE_MUTEX_FAST               0
15185 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15186 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15187 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15188 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15189 ** </ul>
15190 **
15191 ** The first two constants cause sqlite3_mutex_alloc() to create
15192 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15193 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15194 ** The mutex implementation does not need to make a distinction
15195 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15196 ** not want to.  But SQLite will only request a recursive mutex in
15197 ** cases where it really needs one.  If a faster non-recursive mutex
15198 ** implementation is available on the host platform, the mutex subsystem
15199 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15200 **
15201 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15202 ** a pointer to a static preexisting mutex.  Three static mutexes are
15203 ** used by the current version of SQLite.  Future versions of SQLite
15204 ** may add additional static mutexes.  Static mutexes are for internal
15205 ** use by SQLite only.  Applications that use SQLite mutexes should
15206 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15207 ** SQLITE_MUTEX_RECURSIVE.
15208 **
15209 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15210 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15211 ** returns a different mutex on every call.  But for the static
15212 ** mutex types, the same mutex is returned on every call that has
15213 ** the same type number.
15214 */
15215 static sqlite3_mutex *os2MutexAlloc(int iType){
15216   sqlite3_mutex *p = NULL;
15217   switch( iType ){
15218     case SQLITE_MUTEX_FAST:
15219     case SQLITE_MUTEX_RECURSIVE: {
15220       p = sqlite3MallocZero( sizeof(*p) );
15221       if( p ){
15222         p->id = iType;
15223         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15224           sqlite3_free( p );
15225           p = NULL;
15226         }
15227       }
15228       break;
15229     }
15230     default: {
15231       static volatile int isInit = 0;
15232       static sqlite3_mutex staticMutexes[] = {
15233         { OS2_MUTEX_INITIALIZER, },
15234         { OS2_MUTEX_INITIALIZER, },
15235         { OS2_MUTEX_INITIALIZER, },
15236         { OS2_MUTEX_INITIALIZER, },
15237         { OS2_MUTEX_INITIALIZER, },
15238         { OS2_MUTEX_INITIALIZER, },
15239       };
15240       if ( !isInit ){
15241         APIRET rc;
15242         PTIB ptib;
15243         PPIB ppib;
15244         HMTX mutex;
15245         char name[32];
15246         DosGetInfoBlocks( &ptib, &ppib );
15247         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15248                           ppib->pib_ulpid );
15249         while( !isInit ){
15250           mutex = 0;
15251           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15252           if( rc == NO_ERROR ){
15253             int i;
15254             if( !isInit ){
15255               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15256                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15257               }
15258               isInit = 1;
15259             }
15260             DosCloseMutexSem( mutex );
15261           }else if( rc == ERROR_DUPLICATE_NAME ){
15262             DosSleep( 1 );
15263           }else{
15264             return p;
15265           }
15266         }
15267       }
15268       assert( iType-2 >= 0 );
15269       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15270       p = &staticMutexes[iType-2];
15271       p->id = iType;
15272       break;
15273     }
15274   }
15275   return p;
15276 }
15277
15278
15279 /*
15280 ** This routine deallocates a previously allocated mutex.
15281 ** SQLite is careful to deallocate every mutex that it allocates.
15282 */
15283 static void os2MutexFree(sqlite3_mutex *p){
15284   if( p==0 ) return;
15285   assert( p->nRef==0 );
15286   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15287   DosCloseMutexSem( p->mutex );
15288   sqlite3_free( p );
15289 }
15290
15291 /*
15292 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15293 ** to enter a mutex.  If another thread is already within the mutex,
15294 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15295 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15296 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15297 ** be entered multiple times by the same thread.  In such cases the,
15298 ** mutex must be exited an equal number of times before another thread
15299 ** can enter.  If the same thread tries to enter any other kind of mutex
15300 ** more than once, the behavior is undefined.
15301 */
15302 static void os2MutexEnter(sqlite3_mutex *p){
15303   TID tid;
15304   PID holder1;
15305   ULONG holder2;
15306   if( p==0 ) return;
15307   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15308   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15309   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15310   p->owner = tid;
15311   p->nRef++;
15312 }
15313 static int os2MutexTry(sqlite3_mutex *p){
15314   int rc;
15315   TID tid;
15316   PID holder1;
15317   ULONG holder2;
15318   if( p==0 ) return SQLITE_OK;
15319   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15320   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15321     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15322     p->owner = tid;
15323     p->nRef++;
15324     rc = SQLITE_OK;
15325   } else {
15326     rc = SQLITE_BUSY;
15327   }
15328
15329   return rc;
15330 }
15331
15332 /*
15333 ** The sqlite3_mutex_leave() routine exits a mutex that was
15334 ** previously entered by the same thread.  The behavior
15335 ** is undefined if the mutex is not currently entered or
15336 ** is not currently allocated.  SQLite will never do either.
15337 */
15338 static void os2MutexLeave(sqlite3_mutex *p){
15339   TID tid;
15340   PID holder1;
15341   ULONG holder2;
15342   if( p==0 ) return;
15343   assert( p->nRef>0 );
15344   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15345   assert( p->owner==tid );
15346   p->nRef--;
15347   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15348   DosReleaseMutexSem(p->mutex);
15349 }
15350
15351 #ifdef SQLITE_DEBUG
15352 /*
15353 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15354 ** intended for use inside assert() statements.
15355 */
15356 static int os2MutexHeld(sqlite3_mutex *p){
15357   TID tid;
15358   PID pid;
15359   ULONG ulCount;
15360   PTIB ptib;
15361   if( p!=0 ) {
15362     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15363   } else {
15364     DosGetInfoBlocks(&ptib, NULL);
15365     tid = ptib->tib_ptib2->tib2_ultid;
15366   }
15367   return p==0 || (p->nRef!=0 && p->owner==tid);
15368 }
15369 static int os2MutexNotheld(sqlite3_mutex *p){
15370   TID tid;
15371   PID pid;
15372   ULONG ulCount;
15373   PTIB ptib;
15374   if( p!= 0 ) {
15375     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15376   } else {
15377     DosGetInfoBlocks(&ptib, NULL);
15378     tid = ptib->tib_ptib2->tib2_ultid;
15379   }
15380   return p==0 || p->nRef==0 || p->owner!=tid;
15381 }
15382 #endif
15383
15384 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15385   static sqlite3_mutex_methods sMutex = {
15386     os2MutexInit,
15387     os2MutexEnd,
15388     os2MutexAlloc,
15389     os2MutexFree,
15390     os2MutexEnter,
15391     os2MutexTry,
15392     os2MutexLeave,
15393 #ifdef SQLITE_DEBUG
15394     os2MutexHeld,
15395     os2MutexNotheld
15396 #endif
15397   };
15398
15399   return &sMutex;
15400 }
15401 #endif /* SQLITE_MUTEX_OS2 */
15402
15403 /************** End of mutex_os2.c *******************************************/
15404 /************** Begin file mutex_unix.c **************************************/
15405 /*
15406 ** 2007 August 28
15407 **
15408 ** The author disclaims copyright to this source code.  In place of
15409 ** a legal notice, here is a blessing:
15410 **
15411 **    May you do good and not evil.
15412 **    May you find forgiveness for yourself and forgive others.
15413 **    May you share freely, never taking more than you give.
15414 **
15415 *************************************************************************
15416 ** This file contains the C functions that implement mutexes for pthreads
15417 **
15418 ** $Id: mutex_unix.c,v 1.13 2008/07/16 12:33:24 drh Exp $
15419 */
15420
15421 /*
15422 ** The code in this file is only used if we are compiling threadsafe
15423 ** under unix with pthreads.
15424 **
15425 ** Note that this implementation requires a version of pthreads that
15426 ** supports recursive mutexes.
15427 */
15428 #ifdef SQLITE_MUTEX_PTHREADS
15429
15430 #include <pthread.h>
15431
15432
15433 /*
15434 ** Each recursive mutex is an instance of the following structure.
15435 */
15436 struct sqlite3_mutex {
15437   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15438   int id;                    /* Mutex type */
15439   int nRef;                  /* Number of entrances */
15440   pthread_t owner;           /* Thread that is within this mutex */
15441 #ifdef SQLITE_DEBUG
15442   int trace;                 /* True to trace changes */
15443 #endif
15444 };
15445 #ifdef SQLITE_DEBUG
15446 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15447 #else
15448 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15449 #endif
15450
15451 /*
15452 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15453 ** intended for use only inside assert() statements.  On some platforms,
15454 ** there might be race conditions that can cause these routines to
15455 ** deliver incorrect results.  In particular, if pthread_equal() is
15456 ** not an atomic operation, then these routines might delivery
15457 ** incorrect results.  On most platforms, pthread_equal() is a 
15458 ** comparison of two integers and is therefore atomic.  But we are
15459 ** told that HPUX is not such a platform.  If so, then these routines
15460 ** will not always work correctly on HPUX.
15461 **
15462 ** On those platforms where pthread_equal() is not atomic, SQLite
15463 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15464 ** make sure no assert() statements are evaluated and hence these
15465 ** routines are never called.
15466 */
15467 #ifndef NDEBUG
15468 static int pthreadMutexHeld(sqlite3_mutex *p){
15469   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15470 }
15471 static int pthreadMutexNotheld(sqlite3_mutex *p){
15472   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15473 }
15474 #endif
15475
15476 /*
15477 ** Initialize and deinitialize the mutex subsystem.
15478 */
15479 static int pthreadMutexInit(void){ return SQLITE_OK; }
15480 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15481
15482 /*
15483 ** The sqlite3_mutex_alloc() routine allocates a new
15484 ** mutex and returns a pointer to it.  If it returns NULL
15485 ** that means that a mutex could not be allocated.  SQLite
15486 ** will unwind its stack and return an error.  The argument
15487 ** to sqlite3_mutex_alloc() is one of these integer constants:
15488 **
15489 ** <ul>
15490 ** <li>  SQLITE_MUTEX_FAST
15491 ** <li>  SQLITE_MUTEX_RECURSIVE
15492 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15493 ** <li>  SQLITE_MUTEX_STATIC_MEM
15494 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15495 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15496 ** <li>  SQLITE_MUTEX_STATIC_LRU
15497 ** </ul>
15498 **
15499 ** The first two constants cause sqlite3_mutex_alloc() to create
15500 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15501 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15502 ** The mutex implementation does not need to make a distinction
15503 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15504 ** not want to.  But SQLite will only request a recursive mutex in
15505 ** cases where it really needs one.  If a faster non-recursive mutex
15506 ** implementation is available on the host platform, the mutex subsystem
15507 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15508 **
15509 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15510 ** a pointer to a static preexisting mutex.  Three static mutexes are
15511 ** used by the current version of SQLite.  Future versions of SQLite
15512 ** may add additional static mutexes.  Static mutexes are for internal
15513 ** use by SQLite only.  Applications that use SQLite mutexes should
15514 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15515 ** SQLITE_MUTEX_RECURSIVE.
15516 **
15517 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15518 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15519 ** returns a different mutex on every call.  But for the static 
15520 ** mutex types, the same mutex is returned on every call that has
15521 ** the same type number.
15522 */
15523 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15524   static sqlite3_mutex staticMutexes[] = {
15525     SQLITE3_MUTEX_INITIALIZER,
15526     SQLITE3_MUTEX_INITIALIZER,
15527     SQLITE3_MUTEX_INITIALIZER,
15528     SQLITE3_MUTEX_INITIALIZER,
15529     SQLITE3_MUTEX_INITIALIZER,
15530     SQLITE3_MUTEX_INITIALIZER
15531   };
15532   sqlite3_mutex *p;
15533   switch( iType ){
15534     case SQLITE_MUTEX_RECURSIVE: {
15535       p = sqlite3MallocZero( sizeof(*p) );
15536       if( p ){
15537 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15538         /* If recursive mutexes are not available, we will have to
15539         ** build our own.  See below. */
15540         pthread_mutex_init(&p->mutex, 0);
15541 #else
15542         /* Use a recursive mutex if it is available */
15543         pthread_mutexattr_t recursiveAttr;
15544         pthread_mutexattr_init(&recursiveAttr);
15545         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15546         pthread_mutex_init(&p->mutex, &recursiveAttr);
15547         pthread_mutexattr_destroy(&recursiveAttr);
15548 #endif
15549         p->id = iType;
15550       }
15551       break;
15552     }
15553     case SQLITE_MUTEX_FAST: {
15554       p = sqlite3MallocZero( sizeof(*p) );
15555       if( p ){
15556         p->id = iType;
15557         pthread_mutex_init(&p->mutex, 0);
15558       }
15559       break;
15560     }
15561     default: {
15562       assert( iType-2 >= 0 );
15563       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15564       p = &staticMutexes[iType-2];
15565       p->id = iType;
15566       break;
15567     }
15568   }
15569   return p;
15570 }
15571
15572
15573 /*
15574 ** This routine deallocates a previously
15575 ** allocated mutex.  SQLite is careful to deallocate every
15576 ** mutex that it allocates.
15577 */
15578 static void pthreadMutexFree(sqlite3_mutex *p){
15579   assert( p->nRef==0 );
15580   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15581   pthread_mutex_destroy(&p->mutex);
15582   sqlite3_free(p);
15583 }
15584
15585 /*
15586 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15587 ** to enter a mutex.  If another thread is already within the mutex,
15588 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15589 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15590 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15591 ** be entered multiple times by the same thread.  In such cases the,
15592 ** mutex must be exited an equal number of times before another thread
15593 ** can enter.  If the same thread tries to enter any other kind of mutex
15594 ** more than once, the behavior is undefined.
15595 */
15596 static void pthreadMutexEnter(sqlite3_mutex *p){
15597   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15598
15599 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15600   /* If recursive mutexes are not available, then we have to grow
15601   ** our own.  This implementation assumes that pthread_equal()
15602   ** is atomic - that it cannot be deceived into thinking self
15603   ** and p->owner are equal if p->owner changes between two values
15604   ** that are not equal to self while the comparison is taking place.
15605   ** This implementation also assumes a coherent cache - that 
15606   ** separate processes cannot read different values from the same
15607   ** address at the same time.  If either of these two conditions
15608   ** are not met, then the mutexes will fail and problems will result.
15609   */
15610   {
15611     pthread_t self = pthread_self();
15612     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15613       p->nRef++;
15614     }else{
15615       pthread_mutex_lock(&p->mutex);
15616       assert( p->nRef==0 );
15617       p->owner = self;
15618       p->nRef = 1;
15619     }
15620   }
15621 #else
15622   /* Use the built-in recursive mutexes if they are available.
15623   */
15624   pthread_mutex_lock(&p->mutex);
15625   p->owner = pthread_self();
15626   p->nRef++;
15627 #endif
15628
15629 #ifdef SQLITE_DEBUG
15630   if( p->trace ){
15631     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15632   }
15633 #endif
15634 }
15635 static int pthreadMutexTry(sqlite3_mutex *p){
15636   int rc;
15637   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15638
15639 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15640   /* If recursive mutexes are not available, then we have to grow
15641   ** our own.  This implementation assumes that pthread_equal()
15642   ** is atomic - that it cannot be deceived into thinking self
15643   ** and p->owner are equal if p->owner changes between two values
15644   ** that are not equal to self while the comparison is taking place.
15645   ** This implementation also assumes a coherent cache - that 
15646   ** separate processes cannot read different values from the same
15647   ** address at the same time.  If either of these two conditions
15648   ** are not met, then the mutexes will fail and problems will result.
15649   */
15650   {
15651     pthread_t self = pthread_self();
15652     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15653       p->nRef++;
15654       rc = SQLITE_OK;
15655     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15656       assert( p->nRef==0 );
15657       p->owner = self;
15658       p->nRef = 1;
15659       rc = SQLITE_OK;
15660     }else{
15661       rc = SQLITE_BUSY;
15662     }
15663   }
15664 #else
15665   /* Use the built-in recursive mutexes if they are available.
15666   */
15667   if( pthread_mutex_trylock(&p->mutex)==0 ){
15668     p->owner = pthread_self();
15669     p->nRef++;
15670     rc = SQLITE_OK;
15671   }else{
15672     rc = SQLITE_BUSY;
15673   }
15674 #endif
15675
15676 #ifdef SQLITE_DEBUG
15677   if( rc==SQLITE_OK && p->trace ){
15678     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15679   }
15680 #endif
15681   return rc;
15682 }
15683
15684 /*
15685 ** The sqlite3_mutex_leave() routine exits a mutex that was
15686 ** previously entered by the same thread.  The behavior
15687 ** is undefined if the mutex is not currently entered or
15688 ** is not currently allocated.  SQLite will never do either.
15689 */
15690 static void pthreadMutexLeave(sqlite3_mutex *p){
15691   assert( pthreadMutexHeld(p) );
15692   p->nRef--;
15693   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15694
15695 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15696   if( p->nRef==0 ){
15697     pthread_mutex_unlock(&p->mutex);
15698   }
15699 #else
15700   pthread_mutex_unlock(&p->mutex);
15701 #endif
15702
15703 #ifdef SQLITE_DEBUG
15704   if( p->trace ){
15705     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15706   }
15707 #endif
15708 }
15709
15710 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15711   static sqlite3_mutex_methods sMutex = {
15712     pthreadMutexInit,
15713     pthreadMutexEnd,
15714     pthreadMutexAlloc,
15715     pthreadMutexFree,
15716     pthreadMutexEnter,
15717     pthreadMutexTry,
15718     pthreadMutexLeave,
15719 #ifdef SQLITE_DEBUG
15720     pthreadMutexHeld,
15721     pthreadMutexNotheld
15722 #endif
15723   };
15724
15725   return &sMutex;
15726 }
15727
15728 #endif /* SQLITE_MUTEX_PTHREAD */
15729
15730 /************** End of mutex_unix.c ******************************************/
15731 /************** Begin file mutex_w32.c ***************************************/
15732 /*
15733 ** 2007 August 14
15734 **
15735 ** The author disclaims copyright to this source code.  In place of
15736 ** a legal notice, here is a blessing:
15737 **
15738 **    May you do good and not evil.
15739 **    May you find forgiveness for yourself and forgive others.
15740 **    May you share freely, never taking more than you give.
15741 **
15742 *************************************************************************
15743 ** This file contains the C functions that implement mutexes for win32
15744 **
15745 ** $Id: mutex_w32.c,v 1.11 2008/06/26 10:41:19 danielk1977 Exp $
15746 */
15747
15748 /*
15749 ** The code in this file is only used if we are compiling multithreaded
15750 ** on a win32 system.
15751 */
15752 #ifdef SQLITE_MUTEX_W32
15753
15754 /*
15755 ** Each recursive mutex is an instance of the following structure.
15756 */
15757 struct sqlite3_mutex {
15758   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15759   int id;                    /* Mutex type */
15760   int nRef;                  /* Number of enterances */
15761   DWORD owner;               /* Thread holding this mutex */
15762 };
15763
15764 /*
15765 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15766 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15767 **
15768 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15769 ** the LockFileEx() API.  But we can still statically link against that
15770 ** API as long as we don't call it win running Win95/98/ME.  A call to
15771 ** this routine is used to determine if the host is Win95/98/ME or
15772 ** WinNT/2K/XP so that we will know whether or not we can safely call
15773 ** the LockFileEx() API.
15774 */
15775 #if SQLITE_OS_WINCE
15776 # define mutexIsNT()  (1)
15777 #else
15778   static int mutexIsNT(void){
15779     static int osType = 0;
15780     if( osType==0 ){
15781       OSVERSIONINFO sInfo;
15782       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15783       GetVersionEx(&sInfo);
15784       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15785     }
15786     return osType==2;
15787   }
15788 #endif /* SQLITE_OS_WINCE */
15789
15790
15791 #ifdef SQLITE_DEBUG
15792 /*
15793 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15794 ** intended for use only inside assert() statements.
15795 */
15796 static int winMutexHeld(sqlite3_mutex *p){
15797   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15798 }
15799 static int winMutexNotheld(sqlite3_mutex *p){
15800   return p->nRef==0 || p->owner!=GetCurrentThreadId();
15801 }
15802 #endif
15803
15804
15805 /*
15806 ** Initialize and deinitialize the mutex subsystem.
15807 */
15808 static int winMutexInit(void){ return SQLITE_OK; }
15809 static int winMutexEnd(void){ return SQLITE_OK; }
15810
15811 /*
15812 ** The sqlite3_mutex_alloc() routine allocates a new
15813 ** mutex and returns a pointer to it.  If it returns NULL
15814 ** that means that a mutex could not be allocated.  SQLite
15815 ** will unwind its stack and return an error.  The argument
15816 ** to sqlite3_mutex_alloc() is one of these integer constants:
15817 **
15818 ** <ul>
15819 ** <li>  SQLITE_MUTEX_FAST               0
15820 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15821 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15822 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15823 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15824 ** </ul>
15825 **
15826 ** The first two constants cause sqlite3_mutex_alloc() to create
15827 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15828 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15829 ** The mutex implementation does not need to make a distinction
15830 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15831 ** not want to.  But SQLite will only request a recursive mutex in
15832 ** cases where it really needs one.  If a faster non-recursive mutex
15833 ** implementation is available on the host platform, the mutex subsystem
15834 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15835 **
15836 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15837 ** a pointer to a static preexisting mutex.  Three static mutexes are
15838 ** used by the current version of SQLite.  Future versions of SQLite
15839 ** may add additional static mutexes.  Static mutexes are for internal
15840 ** use by SQLite only.  Applications that use SQLite mutexes should
15841 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15842 ** SQLITE_MUTEX_RECURSIVE.
15843 **
15844 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15845 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15846 ** returns a different mutex on every call.  But for the static 
15847 ** mutex types, the same mutex is returned on every call that has
15848 ** the same type number.
15849 */
15850 static sqlite3_mutex *winMutexAlloc(int iType){
15851   sqlite3_mutex *p;
15852
15853   switch( iType ){
15854     case SQLITE_MUTEX_FAST:
15855     case SQLITE_MUTEX_RECURSIVE: {
15856       p = sqlite3MallocZero( sizeof(*p) );
15857       if( p ){
15858         p->id = iType;
15859         InitializeCriticalSection(&p->mutex);
15860       }
15861       break;
15862     }
15863     default: {
15864       static sqlite3_mutex staticMutexes[6];
15865       static int isInit = 0;
15866       while( !isInit ){
15867         static long lock = 0;
15868         if( InterlockedIncrement(&lock)==1 ){
15869           int i;
15870           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
15871             InitializeCriticalSection(&staticMutexes[i].mutex);
15872           }
15873           isInit = 1;
15874         }else{
15875           Sleep(1);
15876         }
15877       }
15878       assert( iType-2 >= 0 );
15879       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15880       p = &staticMutexes[iType-2];
15881       p->id = iType;
15882       break;
15883     }
15884   }
15885   return p;
15886 }
15887
15888
15889 /*
15890 ** This routine deallocates a previously
15891 ** allocated mutex.  SQLite is careful to deallocate every
15892 ** mutex that it allocates.
15893 */
15894 static void winMutexFree(sqlite3_mutex *p){
15895   assert( p );
15896   assert( p->nRef==0 );
15897   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15898   DeleteCriticalSection(&p->mutex);
15899   sqlite3_free(p);
15900 }
15901
15902 /*
15903 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15904 ** to enter a mutex.  If another thread is already within the mutex,
15905 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15906 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15907 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15908 ** be entered multiple times by the same thread.  In such cases the,
15909 ** mutex must be exited an equal number of times before another thread
15910 ** can enter.  If the same thread tries to enter any other kind of mutex
15911 ** more than once, the behavior is undefined.
15912 */
15913 static void winMutexEnter(sqlite3_mutex *p){
15914   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15915   EnterCriticalSection(&p->mutex);
15916   p->owner = GetCurrentThreadId(); 
15917   p->nRef++;
15918 }
15919 static int winMutexTry(sqlite3_mutex *p){
15920   int rc = SQLITE_BUSY;
15921   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15922   /*
15923   ** The sqlite3_mutex_try() routine is very rarely used, and when it
15924   ** is used it is merely an optimization.  So it is OK for it to always
15925   ** fail.  
15926   **
15927   ** The TryEnterCriticalSection() interface is only available on WinNT.
15928   ** And some windows compilers complain if you try to use it without
15929   ** first doing some #defines that prevent SQLite from building on Win98.
15930   ** For that reason, we will omit this optimization for now.  See
15931   ** ticket #2685.
15932   */
15933 #if 0
15934   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15935     p->owner = GetCurrentThreadId();
15936     p->nRef++;
15937     rc = SQLITE_OK;
15938   }
15939 #endif
15940   return rc;
15941 }
15942
15943 /*
15944 ** The sqlite3_mutex_leave() routine exits a mutex that was
15945 ** previously entered by the same thread.  The behavior
15946 ** is undefined if the mutex is not currently entered or
15947 ** is not currently allocated.  SQLite will never do either.
15948 */
15949 static void winMutexLeave(sqlite3_mutex *p){
15950   assert( p->nRef>0 );
15951   assert( p->owner==GetCurrentThreadId() );
15952   p->nRef--;
15953   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15954   LeaveCriticalSection(&p->mutex);
15955 }
15956
15957 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15958   static sqlite3_mutex_methods sMutex = {
15959     winMutexInit,
15960     winMutexEnd,
15961     winMutexAlloc,
15962     winMutexFree,
15963     winMutexEnter,
15964     winMutexTry,
15965     winMutexLeave,
15966 #ifdef SQLITE_DEBUG
15967     winMutexHeld,
15968     winMutexNotheld
15969 #endif
15970   };
15971
15972   return &sMutex;
15973 }
15974 #endif /* SQLITE_MUTEX_W32 */
15975
15976 /************** End of mutex_w32.c *******************************************/
15977 /************** Begin file malloc.c ******************************************/
15978 /*
15979 ** 2001 September 15
15980 **
15981 ** The author disclaims copyright to this source code.  In place of
15982 ** a legal notice, here is a blessing:
15983 **
15984 **    May you do good and not evil.
15985 **    May you find forgiveness for yourself and forgive others.
15986 **    May you share freely, never taking more than you give.
15987 **
15988 *************************************************************************
15989 **
15990 ** Memory allocation functions used throughout sqlite.
15991 **
15992 ** $Id: malloc.c,v 1.45 2008/10/12 00:27:53 shane Exp $
15993 */
15994
15995 /*
15996 ** This routine runs when the memory allocator sees that the
15997 ** total memory allocation is about to exceed the soft heap
15998 ** limit.
15999 */
16000 static void softHeapLimitEnforcer(
16001   void *NotUsed, 
16002   sqlite3_int64 inUse,
16003   int allocSize
16004 ){
16005   sqlite3_release_memory(allocSize);
16006 }
16007
16008 /*
16009 ** Set the soft heap-size limit for the library. Passing a zero or 
16010 ** negative value indicates no limit.
16011 */
16012 SQLITE_API void sqlite3_soft_heap_limit(int n){
16013   sqlite3_uint64 iLimit;
16014   int overage;
16015   if( n<0 ){
16016     iLimit = 0;
16017   }else{
16018     iLimit = n;
16019   }
16020   sqlite3_initialize();
16021   if( iLimit>0 ){
16022     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16023   }else{
16024     sqlite3MemoryAlarm(0, 0, 0);
16025   }
16026   overage = sqlite3_memory_used() - n;
16027   if( overage>0 ){
16028     sqlite3_release_memory(overage);
16029   }
16030 }
16031
16032 /*
16033 ** Attempt to release up to n bytes of non-essential memory currently
16034 ** held by SQLite. An example of non-essential memory is memory used to
16035 ** cache database pages that are not currently in use.
16036 */
16037 SQLITE_API int sqlite3_release_memory(int n){
16038 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16039   int nRet = 0;
16040 #if 0
16041   nRet += sqlite3VdbeReleaseMemory(n);
16042 #endif
16043   nRet += sqlite3PcacheReleaseMemory(n-nRet);
16044   return nRet;
16045 #else
16046   return SQLITE_OK;
16047 #endif
16048 }
16049
16050 /*
16051 ** State information local to the memory allocation subsystem.
16052 */
16053 static SQLITE_WSD struct Mem0Global {
16054   /* Number of free pages for scratch and page-cache memory */
16055   u32 nScratchFree;
16056   u32 nPageFree;
16057
16058   sqlite3_mutex *mutex;         /* Mutex to serialize access */
16059
16060   /*
16061   ** The alarm callback and its arguments.  The mem0.mutex lock will
16062   ** be held while the callback is running.  Recursive calls into
16063   ** the memory subsystem are allowed, but no new callbacks will be
16064   ** issued.  The alarmBusy variable is set to prevent recursive
16065   ** callbacks.
16066   */
16067   sqlite3_int64 alarmThreshold;
16068   void (*alarmCallback)(void*, sqlite3_int64,int);
16069   void *alarmArg;
16070   int alarmBusy;
16071
16072   /*
16073   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16074   ** sqlite3GlobalConfig.pPage to a block of memory that records
16075   ** which pages are available.
16076   */
16077   u32 *aScratchFree;
16078   u32 *aPageFree;
16079 } mem0 = { 62560955 };
16080
16081 #define mem0 GLOBAL(struct Mem0Global, mem0)
16082
16083 /*
16084 ** Initialize the memory allocation subsystem.
16085 */
16086 SQLITE_PRIVATE int sqlite3MallocInit(void){
16087   if( sqlite3GlobalConfig.m.xMalloc==0 ){
16088     sqlite3MemSetDefault();
16089   }
16090   memset(&mem0, 0, sizeof(mem0));
16091   if( sqlite3GlobalConfig.bCoreMutex ){
16092     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16093   }
16094   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16095       && sqlite3GlobalConfig.nScratch>=0 ){
16096     int i;
16097     sqlite3GlobalConfig.szScratch -= 4;
16098     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16099                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16100     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16101     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16102   }else{
16103     sqlite3GlobalConfig.pScratch = 0;
16104     sqlite3GlobalConfig.szScratch = 0;
16105   }
16106   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16107       && sqlite3GlobalConfig.nPage>=1 ){
16108     int i;
16109     int overhead;
16110     int sz = sqlite3GlobalConfig.szPage;
16111     int n = sqlite3GlobalConfig.nPage;
16112     overhead = (4*n + sz - 1)/sz;
16113     sqlite3GlobalConfig.nPage -= overhead;
16114     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16115                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16116     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16117     mem0.nPageFree = sqlite3GlobalConfig.nPage;
16118   }else{
16119     sqlite3GlobalConfig.pPage = 0;
16120     sqlite3GlobalConfig.szPage = 0;
16121   }
16122   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16123 }
16124
16125 /*
16126 ** Deinitialize the memory allocation subsystem.
16127 */
16128 SQLITE_PRIVATE void sqlite3MallocEnd(void){
16129   sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16130   memset(&mem0, 0, sizeof(mem0));
16131 }
16132
16133 /*
16134 ** Return the amount of memory currently checked out.
16135 */
16136 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16137   int n, mx;
16138   sqlite3_int64 res;
16139   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16140   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16141   return res;
16142 }
16143
16144 /*
16145 ** Return the maximum amount of memory that has ever been
16146 ** checked out since either the beginning of this process
16147 ** or since the most recent reset.
16148 */
16149 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16150   int n, mx;
16151   sqlite3_int64 res;
16152   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16153   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16154   return res;
16155 }
16156
16157 /*
16158 ** Change the alarm callback
16159 */
16160 SQLITE_PRIVATE int sqlite3MemoryAlarm(
16161   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16162   void *pArg,
16163   sqlite3_int64 iThreshold
16164 ){
16165   sqlite3_mutex_enter(mem0.mutex);
16166   mem0.alarmCallback = xCallback;
16167   mem0.alarmArg = pArg;
16168   mem0.alarmThreshold = iThreshold;
16169   sqlite3_mutex_leave(mem0.mutex);
16170   return SQLITE_OK;
16171 }
16172
16173 #ifndef SQLITE_OMIT_DEPRECATED
16174 /*
16175 ** Deprecated external interface.  Internal/core SQLite code
16176 ** should call sqlite3MemoryAlarm.
16177 */
16178 SQLITE_API int sqlite3_memory_alarm(
16179   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16180   void *pArg,
16181   sqlite3_int64 iThreshold
16182 ){
16183   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16184 }
16185 #endif
16186
16187 /*
16188 ** Trigger the alarm 
16189 */
16190 static void sqlite3MallocAlarm(int nByte){
16191   void (*xCallback)(void*,sqlite3_int64,int);
16192   sqlite3_int64 nowUsed;
16193   void *pArg;
16194   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
16195   mem0.alarmBusy = 1;
16196   xCallback = mem0.alarmCallback;
16197   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16198   pArg = mem0.alarmArg;
16199   sqlite3_mutex_leave(mem0.mutex);
16200   xCallback(pArg, nowUsed, nByte);
16201   sqlite3_mutex_enter(mem0.mutex);
16202   mem0.alarmBusy = 0;
16203 }
16204
16205 /*
16206 ** Do a memory allocation with statistics and alarms.  Assume the
16207 ** lock is already held.
16208 */
16209 static int mallocWithAlarm(int n, void **pp){
16210   int nFull;
16211   void *p;
16212   assert( sqlite3_mutex_held(mem0.mutex) );
16213   nFull = sqlite3GlobalConfig.m.xRoundup(n);
16214   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16215   if( mem0.alarmCallback!=0 ){
16216     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16217     if( nUsed+nFull >= mem0.alarmThreshold ){
16218       sqlite3MallocAlarm(nFull);
16219     }
16220   }
16221   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16222   if( p==0 && mem0.alarmCallback ){
16223     sqlite3MallocAlarm(nFull);
16224     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16225   }
16226   if( p ){
16227     nFull = sqlite3MallocSize(p);
16228     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16229   }
16230   *pp = p;
16231   return nFull;
16232 }
16233
16234 /*
16235 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16236 ** assumes the memory subsystem has already been initialized.
16237 */
16238 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16239   void *p;
16240   if( n<=0 ){
16241     p = 0;
16242   }else if( sqlite3GlobalConfig.bMemstat ){
16243     sqlite3_mutex_enter(mem0.mutex);
16244     mallocWithAlarm(n, &p);
16245     sqlite3_mutex_leave(mem0.mutex);
16246   }else{
16247     p = sqlite3GlobalConfig.m.xMalloc(n);
16248   }
16249   return p;
16250 }
16251
16252 /*
16253 ** This version of the memory allocation is for use by the application.
16254 ** First make sure the memory subsystem is initialized, then do the
16255 ** allocation.
16256 */
16257 SQLITE_API void *sqlite3_malloc(int n){
16258 #ifndef SQLITE_OMIT_AUTOINIT
16259   if( sqlite3_initialize() ) return 0;
16260 #endif
16261   return sqlite3Malloc(n);
16262 }
16263
16264 /*
16265 ** Each thread may only have a single outstanding allocation from
16266 ** xScratchMalloc().  We verify this constraint in the single-threaded
16267 ** case by setting scratchAllocOut to 1 when an allocation
16268 ** is outstanding clearing it when the allocation is freed.
16269 */
16270 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16271 static int scratchAllocOut = 0;
16272 #endif
16273
16274
16275 /*
16276 ** Allocate memory that is to be used and released right away.
16277 ** This routine is similar to alloca() in that it is not intended
16278 ** for situations where the memory might be held long-term.  This
16279 ** routine is intended to get memory to old large transient data
16280 ** structures that would not normally fit on the stack of an
16281 ** embedded processor.
16282 */
16283 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16284   void *p;
16285   assert( n>0 );
16286
16287 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16288   /* Verify that no more than one scratch allocation per thread
16289   ** is outstanding at one time.  (This is only checked in the
16290   ** single-threaded case since checking in the multi-threaded case
16291   ** would be much more complicated.) */
16292   assert( scratchAllocOut==0 );
16293 #endif
16294
16295   if( sqlite3GlobalConfig.szScratch<n ){
16296     goto scratch_overflow;
16297   }else{  
16298     sqlite3_mutex_enter(mem0.mutex);
16299     if( mem0.nScratchFree==0 ){
16300       sqlite3_mutex_leave(mem0.mutex);
16301       goto scratch_overflow;
16302     }else{
16303       int i;
16304       i = mem0.aScratchFree[--mem0.nScratchFree];
16305       i *= sqlite3GlobalConfig.szScratch;
16306       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16307       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16308       sqlite3_mutex_leave(mem0.mutex);
16309       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16310     }
16311   }
16312 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16313   scratchAllocOut = p!=0;
16314 #endif
16315
16316   return p;
16317
16318 scratch_overflow:
16319   if( sqlite3GlobalConfig.bMemstat ){
16320     sqlite3_mutex_enter(mem0.mutex);
16321     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16322     n = mallocWithAlarm(n, &p);
16323     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16324     sqlite3_mutex_leave(mem0.mutex);
16325   }else{
16326     p = sqlite3GlobalConfig.m.xMalloc(n);
16327   }
16328 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16329   scratchAllocOut = p!=0;
16330 #endif
16331   return p;    
16332 }
16333 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16334   if( p ){
16335
16336 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16337     /* Verify that no more than one scratch allocation per thread
16338     ** is outstanding at one time.  (This is only checked in the
16339     ** single-threaded case since checking in the multi-threaded case
16340     ** would be much more complicated.) */
16341     assert( scratchAllocOut==1 );
16342     scratchAllocOut = 0;
16343 #endif
16344
16345     if( sqlite3GlobalConfig.pScratch==0
16346            || p<sqlite3GlobalConfig.pScratch
16347            || p>=(void*)mem0.aScratchFree ){
16348       if( sqlite3GlobalConfig.bMemstat ){
16349         int iSize = sqlite3MallocSize(p);
16350         sqlite3_mutex_enter(mem0.mutex);
16351         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16352         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16353         sqlite3GlobalConfig.m.xFree(p);
16354         sqlite3_mutex_leave(mem0.mutex);
16355       }else{
16356         sqlite3GlobalConfig.m.xFree(p);
16357       }
16358     }else{
16359       int i;
16360       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pScratch;
16361       i /= sqlite3GlobalConfig.szScratch;
16362       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16363       sqlite3_mutex_enter(mem0.mutex);
16364       assert( mem0.nScratchFree<sqlite3GlobalConfig.nScratch );
16365       mem0.aScratchFree[mem0.nScratchFree++] = i;
16366       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16367       sqlite3_mutex_leave(mem0.mutex);
16368     }
16369   }
16370 }
16371
16372 /*
16373 ** Allocate memory to be used by the page cache.  Make use of the
16374 ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
16375 ** and that memory is of the right size and is not completely
16376 ** consumed.  Otherwise, failover to sqlite3Malloc().
16377 */
16378 #if 0
16379 SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
16380   void *p;
16381   assert( n>0 );
16382   assert( (n & (n-1))==0 );
16383   assert( n>=512 && n<=32768 );
16384
16385   if( sqlite3GlobalConfig.szPage<n ){
16386     goto page_overflow;
16387   }else{  
16388     sqlite3_mutex_enter(mem0.mutex);
16389     if( mem0.nPageFree==0 ){
16390       sqlite3_mutex_leave(mem0.mutex);
16391       goto page_overflow;
16392     }else{
16393       int i;
16394       i = mem0.aPageFree[--mem0.nPageFree];
16395       sqlite3_mutex_leave(mem0.mutex);
16396       i *= sqlite3GlobalConfig.szPage;
16397       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16398       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
16399       p = (void*)&((char*)sqlite3GlobalConfig.pPage)[i];
16400     }
16401   }
16402   return p;
16403
16404 page_overflow:
16405   if( sqlite3GlobalConfig.bMemstat ){
16406     sqlite3_mutex_enter(mem0.mutex);
16407     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16408     n = mallocWithAlarm(n, &p);
16409     if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
16410     sqlite3_mutex_leave(mem0.mutex);
16411   }else{
16412     p = sqlite3GlobalConfig.m.xMalloc(n);
16413   }
16414   return p;    
16415 }
16416 SQLITE_PRIVATE void sqlite3PageFree(void *p){
16417   if( p ){
16418     if( sqlite3GlobalConfig.pPage==0
16419            || p<sqlite3GlobalConfig.pPage
16420            || p>=(void*)mem0.aPageFree ){
16421       /* In this case, the page allocation was obtained from a regular 
16422       ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory 
16423       ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
16424       */
16425       if( sqlite3GlobalConfig.bMemstat ){
16426         int iSize = sqlite3MallocSize(p);
16427         sqlite3_mutex_enter(mem0.mutex);
16428         sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
16429         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16430         sqlite3GlobalConfig.m.xFree(p);
16431         sqlite3_mutex_leave(mem0.mutex);
16432       }else{
16433         sqlite3GlobalConfig.m.xFree(p);
16434       }
16435     }else{
16436       /* The page allocation was allocated from the sqlite3GlobalConfig.pPage
16437       ** buffer. In this case all that is add the index of the page in
16438       ** the sqlite3GlobalConfig.pPage array to the set of free indexes stored
16439       ** in the mem0.aPageFree[] array.
16440       */
16441       int i;
16442       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pPage;
16443       i /= sqlite3GlobalConfig.szPage;
16444       assert( i>=0 && i<sqlite3GlobalConfig.nPage );
16445       sqlite3_mutex_enter(mem0.mutex);
16446       assert( mem0.nPageFree<sqlite3GlobalConfig.nPage );
16447       mem0.aPageFree[mem0.nPageFree++] = i;
16448       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
16449       sqlite3_mutex_leave(mem0.mutex);
16450 #if !defined(NDEBUG) && 0
16451       /* Assert that a duplicate was not just inserted into aPageFree[]. */
16452       for(i=0; i<mem0.nPageFree-1; i++){
16453         assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
16454       }
16455 #endif
16456     }
16457   }
16458 }
16459 #endif
16460
16461 /*
16462 ** TRUE if p is a lookaside memory allocation from db
16463 */
16464 #ifndef SQLITE_OMIT_LOOKASIDE
16465 static int isLookaside(sqlite3 *db, void *p){
16466   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16467 }
16468 #else
16469 #define isLookaside(A,B) 0
16470 #endif
16471
16472 /*
16473 ** Return the size of a memory allocation previously obtained from
16474 ** sqlite3Malloc() or sqlite3_malloc().
16475 */
16476 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16477   return sqlite3GlobalConfig.m.xSize(p);
16478 }
16479 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16480   if( isLookaside(db, p) ){
16481     return db->lookaside.sz;
16482   }else{
16483     return sqlite3GlobalConfig.m.xSize(p);
16484   }
16485 }
16486
16487 /*
16488 ** Free memory previously obtained from sqlite3Malloc().
16489 */
16490 SQLITE_API void sqlite3_free(void *p){
16491   if( p==0 ) return;
16492   if( sqlite3GlobalConfig.bMemstat ){
16493     sqlite3_mutex_enter(mem0.mutex);
16494     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16495     sqlite3GlobalConfig.m.xFree(p);
16496     sqlite3_mutex_leave(mem0.mutex);
16497   }else{
16498     sqlite3GlobalConfig.m.xFree(p);
16499   }
16500 }
16501
16502 /*
16503 ** Free memory that might be associated with a particular database
16504 ** connection.
16505 */
16506 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16507   if( isLookaside(db, p) ){
16508     LookasideSlot *pBuf = (LookasideSlot*)p;
16509     pBuf->pNext = db->lookaside.pFree;
16510     db->lookaside.pFree = pBuf;
16511     db->lookaside.nOut--;
16512   }else{
16513     sqlite3_free(p);
16514   }
16515 }
16516
16517 /*
16518 ** Change the size of an existing memory allocation
16519 */
16520 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16521   int nOld, nNew;
16522   void *pNew;
16523   if( pOld==0 ){
16524     return sqlite3Malloc(nBytes);
16525   }
16526   if( nBytes<=0 ){
16527     sqlite3_free(pOld);
16528     return 0;
16529   }
16530   nOld = sqlite3MallocSize(pOld);
16531   if( sqlite3GlobalConfig.bMemstat ){
16532     sqlite3_mutex_enter(mem0.mutex);
16533     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16534     nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16535     if( nOld==nNew ){
16536       pNew = pOld;
16537     }else{
16538       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16539             mem0.alarmThreshold ){
16540         sqlite3MallocAlarm(nNew-nOld);
16541       }
16542       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16543       if( pNew==0 && mem0.alarmCallback ){
16544         sqlite3MallocAlarm(nBytes);
16545         pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16546       }
16547       if( pNew ){
16548         nNew = sqlite3MallocSize(pNew);
16549         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16550       }
16551     }
16552     sqlite3_mutex_leave(mem0.mutex);
16553   }else{
16554     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
16555   }
16556   return pNew;
16557 }
16558
16559 /*
16560 ** The public interface to sqlite3Realloc.  Make sure that the memory
16561 ** subsystem is initialized prior to invoking sqliteRealloc.
16562 */
16563 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16564 #ifndef SQLITE_OMIT_AUTOINIT
16565   if( sqlite3_initialize() ) return 0;
16566 #endif
16567   return sqlite3Realloc(pOld, n);
16568 }
16569
16570
16571 /*
16572 ** Allocate and zero memory.
16573 */ 
16574 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16575   void *p = sqlite3Malloc(n);
16576   if( p ){
16577     memset(p, 0, n);
16578   }
16579   return p;
16580 }
16581
16582 /*
16583 ** Allocate and zero memory.  If the allocation fails, make
16584 ** the mallocFailed flag in the connection pointer.
16585 */
16586 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16587   void *p = sqlite3DbMallocRaw(db, n);
16588   if( p ){
16589     memset(p, 0, n);
16590   }
16591   return p;
16592 }
16593
16594 /*
16595 ** Allocate and zero memory.  If the allocation fails, make
16596 ** the mallocFailed flag in the connection pointer.
16597 **
16598 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16599 ** failure on the same database connection) then always return 0.
16600 ** Hence for a particular database connection, once malloc starts
16601 ** failing, it fails consistently until mallocFailed is reset.
16602 ** This is an important assumption.  There are many places in the
16603 ** code that do things like this:
16604 **
16605 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16606 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16607 **         if( b ) a[10] = 9;
16608 **
16609 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16610 ** that all prior mallocs (ex: "a") worked too.
16611 */
16612 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16613   void *p;
16614 #ifndef SQLITE_OMIT_LOOKASIDE
16615   if( db ){
16616     LookasideSlot *pBuf;
16617     if( db->mallocFailed ){
16618       return 0;
16619     }
16620     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16621          && (pBuf = db->lookaside.pFree)!=0 ){
16622       db->lookaside.pFree = pBuf->pNext;
16623       db->lookaside.nOut++;
16624       if( db->lookaside.nOut>db->lookaside.mxOut ){
16625         db->lookaside.mxOut = db->lookaside.nOut;
16626       }
16627       return (void*)pBuf;
16628     }
16629   }
16630 #else
16631   if( db && db->mallocFailed ){
16632     return 0;
16633   }
16634 #endif
16635   p = sqlite3Malloc(n);
16636   if( !p && db ){
16637     db->mallocFailed = 1;
16638   }
16639   return p;
16640 }
16641
16642 /*
16643 ** Resize the block of memory pointed to by p to n bytes. If the
16644 ** resize fails, set the mallocFailed flag in the connection object.
16645 */
16646 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16647   void *pNew = 0;
16648   if( db->mallocFailed==0 ){
16649     if( p==0 ){
16650       return sqlite3DbMallocRaw(db, n);
16651     }
16652     if( isLookaside(db, p) ){
16653       if( n<=db->lookaside.sz ){
16654         return p;
16655       }
16656       pNew = sqlite3DbMallocRaw(db, n);
16657       if( pNew ){
16658         memcpy(pNew, p, db->lookaside.sz);
16659         sqlite3DbFree(db, p);
16660       }
16661     }else{
16662       pNew = sqlite3_realloc(p, n);
16663       if( !pNew ){
16664         db->mallocFailed = 1;
16665       }
16666     }
16667   }
16668   return pNew;
16669 }
16670
16671 /*
16672 ** Attempt to reallocate p.  If the reallocation fails, then free p
16673 ** and set the mallocFailed flag in the database connection.
16674 */
16675 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16676   void *pNew;
16677   pNew = sqlite3DbRealloc(db, p, n);
16678   if( !pNew ){
16679     sqlite3DbFree(db, p);
16680   }
16681   return pNew;
16682 }
16683
16684 /*
16685 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16686 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16687 ** is because when memory debugging is turned on, these two functions are 
16688 ** called via macros that record the current file and line number in the
16689 ** ThreadData structure.
16690 */
16691 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16692   char *zNew;
16693   size_t n;
16694   if( z==0 ){
16695     return 0;
16696   }
16697   n = strlen(z)+1;
16698   assert( (n&0x7fffffff)==n );
16699   zNew = sqlite3DbMallocRaw(db, (int)n);
16700   if( zNew ){
16701     memcpy(zNew, z, n);
16702   }
16703   return zNew;
16704 }
16705 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16706   char *zNew;
16707   if( z==0 ){
16708     return 0;
16709   }
16710   assert( (n&0x7fffffff)==n );
16711   zNew = sqlite3DbMallocRaw(db, n+1);
16712   if( zNew ){
16713     memcpy(zNew, z, n);
16714     zNew[n] = 0;
16715   }
16716   return zNew;
16717 }
16718
16719 /*
16720 ** Create a string from the zFromat argument and the va_list that follows.
16721 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16722 ** point to that string.
16723 */
16724 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16725   va_list ap;
16726   char *z;
16727
16728   va_start(ap, zFormat);
16729   z = sqlite3VMPrintf(db, zFormat, ap);
16730   va_end(ap);
16731   sqlite3DbFree(db, *pz);
16732   *pz = z;
16733 }
16734
16735
16736 /*
16737 ** This function must be called before exiting any API function (i.e. 
16738 ** returning control to the user) that has called sqlite3_malloc or
16739 ** sqlite3_realloc.
16740 **
16741 ** The returned value is normally a copy of the second argument to this
16742 ** function. However, if a malloc() failure has occured since the previous
16743 ** invocation SQLITE_NOMEM is returned instead. 
16744 **
16745 ** If the first argument, db, is not NULL and a malloc() error has occured,
16746 ** then the connection error-code (the value returned by sqlite3_errcode())
16747 ** is set to SQLITE_NOMEM.
16748 */
16749 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16750   /* If the db handle is not NULL, then we must hold the connection handle
16751   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16752   ** is unsafe, as is the call to sqlite3Error().
16753   */
16754   assert( !db || sqlite3_mutex_held(db->mutex) );
16755   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16756     sqlite3Error(db, SQLITE_NOMEM, 0);
16757     db->mallocFailed = 0;
16758     rc = SQLITE_NOMEM;
16759   }
16760   return rc & (db ? db->errMask : 0xff);
16761 }
16762
16763 /************** End of malloc.c **********************************************/
16764 /************** Begin file printf.c ******************************************/
16765 /*
16766 ** The "printf" code that follows dates from the 1980's.  It is in
16767 ** the public domain.  The original comments are included here for
16768 ** completeness.  They are very out-of-date but might be useful as
16769 ** an historical reference.  Most of the "enhancements" have been backed
16770 ** out so that the functionality is now the same as standard printf().
16771 **
16772 ** $Id: printf.c,v 1.94 2008/08/22 14:08:36 drh Exp $
16773 **
16774 **************************************************************************
16775 **
16776 ** The following modules is an enhanced replacement for the "printf" subroutines
16777 ** found in the standard C library.  The following enhancements are
16778 ** supported:
16779 **
16780 **      +  Additional functions.  The standard set of "printf" functions
16781 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16782 **         vsprintf.  This module adds the following:
16783 **
16784 **           *  snprintf -- Works like sprintf, but has an extra argument
16785 **                          which is the size of the buffer written to.
16786 **
16787 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16788 **                          obtained from malloc.
16789 **
16790 **           *  xprintf --  Calls a function to dispose of output.
16791 **
16792 **           *  nprintf --  No output, but returns the number of characters
16793 **                          that would have been output by printf.
16794 **
16795 **           *  A v- version (ex: vsnprintf) of every function is also
16796 **              supplied.
16797 **
16798 **      +  A few extensions to the formatting notation are supported:
16799 **
16800 **           *  The "=" flag (similar to "-") causes the output to be
16801 **              be centered in the appropriately sized field.
16802 **
16803 **           *  The %b field outputs an integer in binary notation.
16804 **
16805 **           *  The %c field now accepts a precision.  The character output
16806 **              is repeated by the number of times the precision specifies.
16807 **
16808 **           *  The %' field works like %c, but takes as its character the
16809 **              next character of the format string, instead of the next
16810 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16811 **              signs, the same as  printf("%.78c",'-').
16812 **
16813 **      +  When compiled using GCC on a SPARC, this version of printf is
16814 **         faster than the library printf for SUN OS 4.1.
16815 **
16816 **      +  All functions are fully reentrant.
16817 **
16818 */
16819
16820 /*
16821 ** Conversion types fall into various categories as defined by the
16822 ** following enumeration.
16823 */
16824 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16825 #define etFLOAT       2 /* Floating point.  %f */
16826 #define etEXP         3 /* Exponentional notation. %e and %E */
16827 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16828 #define etSIZE        5 /* Return number of characters processed so far. %n */
16829 #define etSTRING      6 /* Strings. %s */
16830 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16831 #define etPERCENT     8 /* Percent symbol. %% */
16832 #define etCHARX       9 /* Characters. %c */
16833 /* The rest are extensions, not normally found in printf() */
16834 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16835 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16836                           NULL pointers replaced by SQL NULL.  %Q */
16837 #define etTOKEN      12 /* a pointer to a Token structure */
16838 #define etSRCLIST    13 /* a pointer to a SrcList */
16839 #define etPOINTER    14 /* The %p conversion */
16840 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16841 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16842
16843
16844 /*
16845 ** An "etByte" is an 8-bit unsigned value.
16846 */
16847 typedef unsigned char etByte;
16848
16849 /*
16850 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16851 ** by an instance of the following structure
16852 */
16853 typedef struct et_info {   /* Information about each format field */
16854   char fmttype;            /* The format field code letter */
16855   etByte base;             /* The base for radix conversion */
16856   etByte flags;            /* One or more of FLAG_ constants below */
16857   etByte type;             /* Conversion paradigm */
16858   etByte charset;          /* Offset into aDigits[] of the digits string */
16859   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16860 } et_info;
16861
16862 /*
16863 ** Allowed values for et_info.flags
16864 */
16865 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16866 #define FLAG_INTERN  2     /* True if for internal use only */
16867 #define FLAG_STRING  4     /* Allow infinity precision */
16868
16869
16870 /*
16871 ** The following table is searched linearly, so it is good to put the
16872 ** most frequently used conversion types first.
16873 */
16874 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16875 static const char aPrefix[] = "-x0\000X0";
16876 static const et_info fmtinfo[] = {
16877   {  'd', 10, 1, etRADIX,      0,  0 },
16878   {  's',  0, 4, etSTRING,     0,  0 },
16879   {  'g',  0, 1, etGENERIC,    30, 0 },
16880   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16881   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16882   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16883   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16884   {  'c',  0, 0, etCHARX,      0,  0 },
16885   {  'o',  8, 0, etRADIX,      0,  2 },
16886   {  'u', 10, 0, etRADIX,      0,  0 },
16887   {  'x', 16, 0, etRADIX,      16, 1 },
16888   {  'X', 16, 0, etRADIX,      0,  4 },
16889 #ifndef SQLITE_OMIT_FLOATING_POINT
16890   {  'f',  0, 1, etFLOAT,      0,  0 },
16891   {  'e',  0, 1, etEXP,        30, 0 },
16892   {  'E',  0, 1, etEXP,        14, 0 },
16893   {  'G',  0, 1, etGENERIC,    14, 0 },
16894 #endif
16895   {  'i', 10, 1, etRADIX,      0,  0 },
16896   {  'n',  0, 0, etSIZE,       0,  0 },
16897   {  '%',  0, 0, etPERCENT,    0,  0 },
16898   {  'p', 16, 0, etPOINTER,    0,  1 },
16899   {  'T',  0, 2, etTOKEN,      0,  0 },
16900   {  'S',  0, 2, etSRCLIST,    0,  0 },
16901   {  'r', 10, 3, etORDINAL,    0,  0 },
16902 };
16903 #define etNINFO  (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
16904
16905 /*
16906 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16907 ** conversions will work.
16908 */
16909 #ifndef SQLITE_OMIT_FLOATING_POINT
16910 /*
16911 ** "*val" is a double such that 0.1 <= *val < 10.0
16912 ** Return the ascii code for the leading digit of *val, then
16913 ** multiply "*val" by 10.0 to renormalize.
16914 **
16915 ** Example:
16916 **     input:     *val = 3.14159
16917 **     output:    *val = 1.4159    function return = '3'
16918 **
16919 ** The counter *cnt is incremented each time.  After counter exceeds
16920 ** 16 (the number of significant digits in a 64-bit float) '0' is
16921 ** always returned.
16922 */
16923 static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16924   int digit;
16925   LONGDOUBLE_TYPE d;
16926   if( (*cnt)++ >= 16 ) return '0';
16927   digit = (int)*val;
16928   d = digit;
16929   digit += '0';
16930   *val = (*val - d)*10.0;
16931   return digit;
16932 }
16933 #endif /* SQLITE_OMIT_FLOATING_POINT */
16934
16935 /*
16936 ** Append N space characters to the given string buffer.
16937 */
16938 static void appendSpace(StrAccum *pAccum, int N){
16939   static const char zSpaces[] = "                             ";
16940   while( N>=sizeof(zSpaces)-1 ){
16941     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16942     N -= sizeof(zSpaces)-1;
16943   }
16944   if( N>0 ){
16945     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16946   }
16947 }
16948
16949 /*
16950 ** On machines with a small stack size, you can redefine the
16951 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
16952 ** smaller values some %f conversions may go into an infinite loop.
16953 */
16954 #ifndef SQLITE_PRINT_BUF_SIZE
16955 # define SQLITE_PRINT_BUF_SIZE 350
16956 #endif
16957 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16958
16959 /*
16960 ** The root program.  All variations call this core.
16961 **
16962 ** INPUTS:
16963 **   func   This is a pointer to a function taking three arguments
16964 **            1. A pointer to anything.  Same as the "arg" parameter.
16965 **            2. A pointer to the list of characters to be output
16966 **               (Note, this list is NOT null terminated.)
16967 **            3. An integer number of characters to be output.
16968 **               (Note: This number might be zero.)
16969 **
16970 **   arg    This is the pointer to anything which will be passed as the
16971 **          first argument to "func".  Use it for whatever you like.
16972 **
16973 **   fmt    This is the format string, as in the usual print.
16974 **
16975 **   ap     This is a pointer to a list of arguments.  Same as in
16976 **          vfprint.
16977 **
16978 ** OUTPUTS:
16979 **          The return value is the total number of characters sent to
16980 **          the function "func".  Returns -1 on a error.
16981 **
16982 ** Note that the order in which automatic variables are declared below
16983 ** seems to make a big difference in determining how fast this beast
16984 ** will run.
16985 */
16986 SQLITE_PRIVATE void sqlite3VXPrintf(
16987   StrAccum *pAccum,                  /* Accumulate results here */
16988   int useExtended,                   /* Allow extended %-conversions */
16989   const char *fmt,                   /* Format string */
16990   va_list ap                         /* arguments */
16991 ){
16992   int c;                     /* Next character in the format string */
16993   char *bufpt;               /* Pointer to the conversion buffer */
16994   int precision;             /* Precision of the current field */
16995   int length;                /* Length of the field */
16996   int idx;                   /* A general purpose loop counter */
16997   int width;                 /* Width of the current field */
16998   etByte flag_leftjustify;   /* True if "-" flag is present */
16999   etByte flag_plussign;      /* True if "+" flag is present */
17000   etByte flag_blanksign;     /* True if " " flag is present */
17001   etByte flag_alternateform; /* True if "#" flag is present */
17002   etByte flag_altform2;      /* True if "!" flag is present */
17003   etByte flag_zeropad;       /* True if field width constant starts with zero */
17004   etByte flag_long;          /* True if "l" flag is present */
17005   etByte flag_longlong;      /* True if the "ll" flag is present */
17006   etByte done;               /* Loop termination flag */
17007   sqlite_uint64 longvalue;   /* Value for integer types */
17008   LONGDOUBLE_TYPE realvalue; /* Value for real types */
17009   const et_info *infop;      /* Pointer to the appropriate info structure */
17010   char buf[etBUFSIZE];       /* Conversion buffer */
17011   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17012   etByte xtype;              /* Conversion paradigm */
17013   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17014 #ifndef SQLITE_OMIT_FLOATING_POINT
17015   int  exp, e2;              /* exponent of real numbers */
17016   double rounder;            /* Used for rounding floating point values */
17017   etByte flag_dp;            /* True if decimal point should be shown */
17018   etByte flag_rtz;           /* True if trailing zeros should be removed */
17019   etByte flag_exp;           /* True to force display of the exponent */
17020   int nsd;                   /* Number of significant digits returned */
17021 #endif
17022
17023   length = 0;
17024   bufpt = 0;
17025   for(; (c=(*fmt))!=0; ++fmt){
17026     if( c!='%' ){
17027       int amt;
17028       bufpt = (char *)fmt;
17029       amt = 1;
17030       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17031       sqlite3StrAccumAppend(pAccum, bufpt, amt);
17032       if( c==0 ) break;
17033     }
17034     if( (c=(*++fmt))==0 ){
17035       sqlite3StrAccumAppend(pAccum, "%", 1);
17036       break;
17037     }
17038     /* Find out what flags are present */
17039     flag_leftjustify = flag_plussign = flag_blanksign = 
17040      flag_alternateform = flag_altform2 = flag_zeropad = 0;
17041     done = 0;
17042     do{
17043       switch( c ){
17044         case '-':   flag_leftjustify = 1;     break;
17045         case '+':   flag_plussign = 1;        break;
17046         case ' ':   flag_blanksign = 1;       break;
17047         case '#':   flag_alternateform = 1;   break;
17048         case '!':   flag_altform2 = 1;        break;
17049         case '0':   flag_zeropad = 1;         break;
17050         default:    done = 1;                 break;
17051       }
17052     }while( !done && (c=(*++fmt))!=0 );
17053     /* Get the field width */
17054     width = 0;
17055     if( c=='*' ){
17056       width = va_arg(ap,int);
17057       if( width<0 ){
17058         flag_leftjustify = 1;
17059         width = -width;
17060       }
17061       c = *++fmt;
17062     }else{
17063       while( c>='0' && c<='9' ){
17064         width = width*10 + c - '0';
17065         c = *++fmt;
17066       }
17067     }
17068     if( width > etBUFSIZE-10 ){
17069       width = etBUFSIZE-10;
17070     }
17071     /* Get the precision */
17072     if( c=='.' ){
17073       precision = 0;
17074       c = *++fmt;
17075       if( c=='*' ){
17076         precision = va_arg(ap,int);
17077         if( precision<0 ) precision = -precision;
17078         c = *++fmt;
17079       }else{
17080         while( c>='0' && c<='9' ){
17081           precision = precision*10 + c - '0';
17082           c = *++fmt;
17083         }
17084       }
17085     }else{
17086       precision = -1;
17087     }
17088     /* Get the conversion type modifier */
17089     if( c=='l' ){
17090       flag_long = 1;
17091       c = *++fmt;
17092       if( c=='l' ){
17093         flag_longlong = 1;
17094         c = *++fmt;
17095       }else{
17096         flag_longlong = 0;
17097       }
17098     }else{
17099       flag_long = flag_longlong = 0;
17100     }
17101     /* Fetch the info entry for the field */
17102     infop = 0;
17103     for(idx=0; idx<etNINFO; idx++){
17104       if( c==fmtinfo[idx].fmttype ){
17105         infop = &fmtinfo[idx];
17106         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17107           xtype = infop->type;
17108         }else{
17109           return;
17110         }
17111         break;
17112       }
17113     }
17114     zExtra = 0;
17115     if( infop==0 ){
17116       return;
17117     }
17118
17119
17120     /* Limit the precision to prevent overflowing buf[] during conversion */
17121     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17122       precision = etBUFSIZE-40;
17123     }
17124
17125     /*
17126     ** At this point, variables are initialized as follows:
17127     **
17128     **   flag_alternateform          TRUE if a '#' is present.
17129     **   flag_altform2               TRUE if a '!' is present.
17130     **   flag_plussign               TRUE if a '+' is present.
17131     **   flag_leftjustify            TRUE if a '-' is present or if the
17132     **                               field width was negative.
17133     **   flag_zeropad                TRUE if the width began with 0.
17134     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17135     **                               the conversion character.
17136     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17137     **                               the conversion character.
17138     **   flag_blanksign              TRUE if a ' ' is present.
17139     **   width                       The specified field width.  This is
17140     **                               always non-negative.  Zero is the default.
17141     **   precision                   The specified precision.  The default
17142     **                               is -1.
17143     **   xtype                       The class of the conversion.
17144     **   infop                       Pointer to the appropriate info struct.
17145     */
17146     switch( xtype ){
17147       case etPOINTER:
17148         flag_longlong = sizeof(char*)==sizeof(i64);
17149         flag_long = sizeof(char*)==sizeof(long int);
17150         /* Fall through into the next case */
17151       case etORDINAL:
17152       case etRADIX:
17153         if( infop->flags & FLAG_SIGNED ){
17154           i64 v;
17155           if( flag_longlong )   v = va_arg(ap,i64);
17156           else if( flag_long )  v = va_arg(ap,long int);
17157           else                  v = va_arg(ap,int);
17158           if( v<0 ){
17159             longvalue = -v;
17160             prefix = '-';
17161           }else{
17162             longvalue = v;
17163             if( flag_plussign )        prefix = '+';
17164             else if( flag_blanksign )  prefix = ' ';
17165             else                       prefix = 0;
17166           }
17167         }else{
17168           if( flag_longlong )   longvalue = va_arg(ap,u64);
17169           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
17170           else                  longvalue = va_arg(ap,unsigned int);
17171           prefix = 0;
17172         }
17173         if( longvalue==0 ) flag_alternateform = 0;
17174         if( flag_zeropad && precision<width-(prefix!=0) ){
17175           precision = width-(prefix!=0);
17176         }
17177         bufpt = &buf[etBUFSIZE-1];
17178         if( xtype==etORDINAL ){
17179           static const char zOrd[] = "thstndrd";
17180           int x = longvalue % 10;
17181           if( x>=4 || (longvalue/10)%10==1 ){
17182             x = 0;
17183           }
17184           buf[etBUFSIZE-3] = zOrd[x*2];
17185           buf[etBUFSIZE-2] = zOrd[x*2+1];
17186           bufpt -= 2;
17187         }
17188         {
17189           register const char *cset;      /* Use registers for speed */
17190           register int base;
17191           cset = &aDigits[infop->charset];
17192           base = infop->base;
17193           do{                                           /* Convert to ascii */
17194             *(--bufpt) = cset[longvalue%base];
17195             longvalue = longvalue/base;
17196           }while( longvalue>0 );
17197         }
17198         length = &buf[etBUFSIZE-1]-bufpt;
17199         for(idx=precision-length; idx>0; idx--){
17200           *(--bufpt) = '0';                             /* Zero pad */
17201         }
17202         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17203         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17204           const char *pre;
17205           char x;
17206           pre = &aPrefix[infop->prefix];
17207           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17208         }
17209         length = &buf[etBUFSIZE-1]-bufpt;
17210         break;
17211       case etFLOAT:
17212       case etEXP:
17213       case etGENERIC:
17214         realvalue = va_arg(ap,double);
17215 #ifndef SQLITE_OMIT_FLOATING_POINT
17216         if( precision<0 ) precision = 6;         /* Set default precision */
17217         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17218         if( realvalue<0.0 ){
17219           realvalue = -realvalue;
17220           prefix = '-';
17221         }else{
17222           if( flag_plussign )          prefix = '+';
17223           else if( flag_blanksign )    prefix = ' ';
17224           else                         prefix = 0;
17225         }
17226         if( xtype==etGENERIC && precision>0 ) precision--;
17227 #if 0
17228         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17229         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17230 #else
17231         /* It makes more sense to use 0.5 */
17232         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17233 #endif
17234         if( xtype==etFLOAT ) realvalue += rounder;
17235         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17236         exp = 0;
17237         if( sqlite3IsNaN(realvalue) ){
17238           bufpt = "NaN";
17239           length = 3;
17240           break;
17241         }
17242         if( realvalue>0.0 ){
17243           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17244           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17245           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17246           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17247           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17248           if( exp>350 ){
17249             if( prefix=='-' ){
17250               bufpt = "-Inf";
17251             }else if( prefix=='+' ){
17252               bufpt = "+Inf";
17253             }else{
17254               bufpt = "Inf";
17255             }
17256             length = strlen(bufpt);
17257             break;
17258           }
17259         }
17260         bufpt = buf;
17261         /*
17262         ** If the field type is etGENERIC, then convert to either etEXP
17263         ** or etFLOAT, as appropriate.
17264         */
17265         flag_exp = xtype==etEXP;
17266         if( xtype!=etFLOAT ){
17267           realvalue += rounder;
17268           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17269         }
17270         if( xtype==etGENERIC ){
17271           flag_rtz = !flag_alternateform;
17272           if( exp<-4 || exp>precision ){
17273             xtype = etEXP;
17274           }else{
17275             precision = precision - exp;
17276             xtype = etFLOAT;
17277           }
17278         }else{
17279           flag_rtz = 0;
17280         }
17281         if( xtype==etEXP ){
17282           e2 = 0;
17283         }else{
17284           e2 = exp;
17285         }
17286         nsd = 0;
17287         flag_dp = (precision>0) | flag_alternateform | flag_altform2;
17288         /* The sign in front of the number */
17289         if( prefix ){
17290           *(bufpt++) = prefix;
17291         }
17292         /* Digits prior to the decimal point */
17293         if( e2<0 ){
17294           *(bufpt++) = '0';
17295         }else{
17296           for(; e2>=0; e2--){
17297             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17298           }
17299         }
17300         /* The decimal point */
17301         if( flag_dp ){
17302           *(bufpt++) = '.';
17303         }
17304         /* "0" digits after the decimal point but before the first
17305         ** significant digit of the number */
17306         for(e2++; e2<0; precision--, e2++){
17307           assert( precision>0 );
17308           *(bufpt++) = '0';
17309         }
17310         /* Significant digits after the decimal point */
17311         while( (precision--)>0 ){
17312           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17313         }
17314         /* Remove trailing zeros and the "." if no digits follow the "." */
17315         if( flag_rtz && flag_dp ){
17316           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17317           assert( bufpt>buf );
17318           if( bufpt[-1]=='.' ){
17319             if( flag_altform2 ){
17320               *(bufpt++) = '0';
17321             }else{
17322               *(--bufpt) = 0;
17323             }
17324           }
17325         }
17326         /* Add the "eNNN" suffix */
17327         if( flag_exp || xtype==etEXP ){
17328           *(bufpt++) = aDigits[infop->charset];
17329           if( exp<0 ){
17330             *(bufpt++) = '-'; exp = -exp;
17331           }else{
17332             *(bufpt++) = '+';
17333           }
17334           if( exp>=100 ){
17335             *(bufpt++) = (exp/100)+'0';                /* 100's digit */
17336             exp %= 100;
17337           }
17338           *(bufpt++) = exp/10+'0';                     /* 10's digit */
17339           *(bufpt++) = exp%10+'0';                     /* 1's digit */
17340         }
17341         *bufpt = 0;
17342
17343         /* The converted number is in buf[] and zero terminated. Output it.
17344         ** Note that the number is in the usual order, not reversed as with
17345         ** integer conversions. */
17346         length = bufpt-buf;
17347         bufpt = buf;
17348
17349         /* Special case:  Add leading zeros if the flag_zeropad flag is
17350         ** set and we are not left justified */
17351         if( flag_zeropad && !flag_leftjustify && length < width){
17352           int i;
17353           int nPad = width - length;
17354           for(i=width; i>=nPad; i--){
17355             bufpt[i] = bufpt[i-nPad];
17356           }
17357           i = prefix!=0;
17358           while( nPad-- ) bufpt[i++] = '0';
17359           length = width;
17360         }
17361 #endif
17362         break;
17363       case etSIZE:
17364         *(va_arg(ap,int*)) = pAccum->nChar;
17365         length = width = 0;
17366         break;
17367       case etPERCENT:
17368         buf[0] = '%';
17369         bufpt = buf;
17370         length = 1;
17371         break;
17372       case etCHARX:
17373         c = buf[0] = va_arg(ap,int);
17374         if( precision>=0 ){
17375           for(idx=1; idx<precision; idx++) buf[idx] = c;
17376           length = precision;
17377         }else{
17378           length =1;
17379         }
17380         bufpt = buf;
17381         break;
17382       case etSTRING:
17383       case etDYNSTRING:
17384         bufpt = va_arg(ap,char*);
17385         if( bufpt==0 ){
17386           bufpt = "";
17387         }else if( xtype==etDYNSTRING ){
17388           zExtra = bufpt;
17389         }
17390         if( precision>=0 ){
17391           for(length=0; length<precision && bufpt[length]; length++){}
17392         }else{
17393           length = strlen(bufpt);
17394         }
17395         break;
17396       case etSQLESCAPE:
17397       case etSQLESCAPE2:
17398       case etSQLESCAPE3: {
17399         int i, j, n, ch, isnull;
17400         int needQuote;
17401         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17402         char *escarg = va_arg(ap,char*);
17403         isnull = escarg==0;
17404         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17405         for(i=n=0; (ch=escarg[i])!=0; i++){
17406           if( ch==q )  n++;
17407         }
17408         needQuote = !isnull && xtype==etSQLESCAPE2;
17409         n += i + 1 + needQuote*2;
17410         if( n>etBUFSIZE ){
17411           bufpt = zExtra = sqlite3Malloc( n );
17412           if( bufpt==0 ) return;
17413         }else{
17414           bufpt = buf;
17415         }
17416         j = 0;
17417         if( needQuote ) bufpt[j++] = q;
17418         for(i=0; (ch=escarg[i])!=0; i++){
17419           bufpt[j++] = ch;
17420           if( ch==q ) bufpt[j++] = ch;
17421         }
17422         if( needQuote ) bufpt[j++] = q;
17423         bufpt[j] = 0;
17424         length = j;
17425         /* The precision is ignored on %q and %Q */
17426         /* if( precision>=0 && precision<length ) length = precision; */
17427         break;
17428       }
17429       case etTOKEN: {
17430         Token *pToken = va_arg(ap, Token*);
17431         if( pToken ){
17432           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17433         }
17434         length = width = 0;
17435         break;
17436       }
17437       case etSRCLIST: {
17438         SrcList *pSrc = va_arg(ap, SrcList*);
17439         int k = va_arg(ap, int);
17440         struct SrcList_item *pItem = &pSrc->a[k];
17441         assert( k>=0 && k<pSrc->nSrc );
17442         if( pItem->zDatabase ){
17443           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17444           sqlite3StrAccumAppend(pAccum, ".", 1);
17445         }
17446         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17447         length = width = 0;
17448         break;
17449       }
17450     }/* End switch over the format type */
17451     /*
17452     ** The text of the conversion is pointed to by "bufpt" and is
17453     ** "length" characters long.  The field width is "width".  Do
17454     ** the output.
17455     */
17456     if( !flag_leftjustify ){
17457       register int nspace;
17458       nspace = width-length;
17459       if( nspace>0 ){
17460         appendSpace(pAccum, nspace);
17461       }
17462     }
17463     if( length>0 ){
17464       sqlite3StrAccumAppend(pAccum, bufpt, length);
17465     }
17466     if( flag_leftjustify ){
17467       register int nspace;
17468       nspace = width-length;
17469       if( nspace>0 ){
17470         appendSpace(pAccum, nspace);
17471       }
17472     }
17473     if( zExtra ){
17474       sqlite3_free(zExtra);
17475     }
17476   }/* End for loop over the format string */
17477 } /* End of function */
17478
17479 /*
17480 ** Append N bytes of text from z to the StrAccum object.
17481 */
17482 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17483   if( p->tooBig | p->mallocFailed ){
17484     return;
17485   }
17486   if( N<0 ){
17487     N = strlen(z);
17488   }
17489   if( N==0 ){
17490     return;
17491   }
17492   if( p->nChar+N >= p->nAlloc ){
17493     char *zNew;
17494     if( !p->useMalloc ){
17495       p->tooBig = 1;
17496       N = p->nAlloc - p->nChar - 1;
17497       if( N<=0 ){
17498         return;
17499       }
17500     }else{
17501       i64 szNew = p->nChar;
17502       szNew += N + 1;
17503       if( szNew > p->mxAlloc ){
17504         sqlite3StrAccumReset(p);
17505         p->tooBig = 1;
17506         return;
17507       }else{
17508         p->nAlloc = szNew;
17509       }
17510       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17511       if( zNew ){
17512         memcpy(zNew, p->zText, p->nChar);
17513         sqlite3StrAccumReset(p);
17514         p->zText = zNew;
17515       }else{
17516         p->mallocFailed = 1;
17517         sqlite3StrAccumReset(p);
17518         return;
17519       }
17520     }
17521   }
17522   memcpy(&p->zText[p->nChar], z, N);
17523   p->nChar += N;
17524 }
17525
17526 /*
17527 ** Finish off a string by making sure it is zero-terminated.
17528 ** Return a pointer to the resulting string.  Return a NULL
17529 ** pointer if any kind of error was encountered.
17530 */
17531 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17532   if( p->zText ){
17533     p->zText[p->nChar] = 0;
17534     if( p->useMalloc && p->zText==p->zBase ){
17535       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17536       if( p->zText ){
17537         memcpy(p->zText, p->zBase, p->nChar+1);
17538       }else{
17539         p->mallocFailed = 1;
17540       }
17541     }
17542   }
17543   return p->zText;
17544 }
17545
17546 /*
17547 ** Reset an StrAccum string.  Reclaim all malloced memory.
17548 */
17549 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17550   if( p->zText!=p->zBase ){
17551     sqlite3DbFree(p->db, p->zText);
17552   }
17553   p->zText = 0;
17554 }
17555
17556 /*
17557 ** Initialize a string accumulator
17558 */
17559 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17560   p->zText = p->zBase = zBase;
17561   p->db = 0;
17562   p->nChar = 0;
17563   p->nAlloc = n;
17564   p->mxAlloc = mx;
17565   p->useMalloc = 1;
17566   p->tooBig = 0;
17567   p->mallocFailed = 0;
17568 }
17569
17570 /*
17571 ** Print into memory obtained from sqliteMalloc().  Use the internal
17572 ** %-conversion extensions.
17573 */
17574 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17575   char *z;
17576   char zBase[SQLITE_PRINT_BUF_SIZE];
17577   StrAccum acc;
17578   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17579                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
17580   acc.db = db;
17581   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17582   z = sqlite3StrAccumFinish(&acc);
17583   if( acc.mallocFailed && db ){
17584     db->mallocFailed = 1;
17585   }
17586   return z;
17587 }
17588
17589 /*
17590 ** Print into memory obtained from sqliteMalloc().  Use the internal
17591 ** %-conversion extensions.
17592 */
17593 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17594   va_list ap;
17595   char *z;
17596   va_start(ap, zFormat);
17597   z = sqlite3VMPrintf(db, zFormat, ap);
17598   va_end(ap);
17599   return z;
17600 }
17601
17602 /*
17603 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17604 ** the string and before returnning.  This routine is intended to be used
17605 ** to modify an existing string.  For example:
17606 **
17607 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17608 **
17609 */
17610 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17611   va_list ap;
17612   char *z;
17613   va_start(ap, zFormat);
17614   z = sqlite3VMPrintf(db, zFormat, ap);
17615   va_end(ap);
17616   sqlite3DbFree(db, zStr);
17617   return z;
17618 }
17619
17620 /*
17621 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17622 ** %-conversion extensions.
17623 */
17624 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17625   char *z;
17626   char zBase[SQLITE_PRINT_BUF_SIZE];
17627   StrAccum acc;
17628 #ifndef SQLITE_OMIT_AUTOINIT
17629   if( sqlite3_initialize() ) return 0;
17630 #endif
17631   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17632   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17633   z = sqlite3StrAccumFinish(&acc);
17634   return z;
17635 }
17636
17637 /*
17638 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17639 ** %-conversion extensions.
17640 */
17641 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17642   va_list ap;
17643   char *z;
17644 #ifndef SQLITE_OMIT_AUTOINIT
17645   if( sqlite3_initialize() ) return 0;
17646 #endif
17647   va_start(ap, zFormat);
17648   z = sqlite3_vmprintf(zFormat, ap);
17649   va_end(ap);
17650   return z;
17651 }
17652
17653 /*
17654 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17655 ** current locale settings.  This is important for SQLite because we
17656 ** are not able to use a "," as the decimal point in place of "." as
17657 ** specified by some locales.
17658 */
17659 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17660   char *z;
17661   va_list ap;
17662   StrAccum acc;
17663
17664   if( n<=0 ){
17665     return zBuf;
17666   }
17667   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17668   acc.useMalloc = 0;
17669   va_start(ap,zFormat);
17670   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17671   va_end(ap);
17672   z = sqlite3StrAccumFinish(&acc);
17673   return z;
17674 }
17675
17676 #if defined(SQLITE_DEBUG)
17677 /*
17678 ** A version of printf() that understands %lld.  Used for debugging.
17679 ** The printf() built into some versions of windows does not understand %lld
17680 ** and segfaults if you give it a long long int.
17681 */
17682 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17683   va_list ap;
17684   StrAccum acc;
17685   char zBuf[500];
17686   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17687   acc.useMalloc = 0;
17688   va_start(ap,zFormat);
17689   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17690   va_end(ap);
17691   sqlite3StrAccumFinish(&acc);
17692   fprintf(stdout,"%s", zBuf);
17693   fflush(stdout);
17694 }
17695 #endif
17696
17697 /************** End of printf.c **********************************************/
17698 /************** Begin file random.c ******************************************/
17699 /*
17700 ** 2001 September 15
17701 **
17702 ** The author disclaims copyright to this source code.  In place of
17703 ** a legal notice, here is a blessing:
17704 **
17705 **    May you do good and not evil.
17706 **    May you find forgiveness for yourself and forgive others.
17707 **    May you share freely, never taking more than you give.
17708 **
17709 *************************************************************************
17710 ** This file contains code to implement a pseudo-random number
17711 ** generator (PRNG) for SQLite.
17712 **
17713 ** Random numbers are used by some of the database backends in order
17714 ** to generate random integer keys for tables or random filenames.
17715 **
17716 ** $Id: random.c,v 1.27 2008/10/07 15:25:48 drh Exp $
17717 */
17718
17719
17720 /* All threads share a single random number generator.
17721 ** This structure is the current state of the generator.
17722 */
17723 static SQLITE_WSD struct sqlite3PrngType {
17724   unsigned char isInit;          /* True if initialized */
17725   unsigned char i, j;            /* State variables */
17726   unsigned char s[256];          /* State variables */
17727 } sqlite3Prng = { 0, };
17728
17729 /*
17730 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17731 ** must be held while executing this routine.
17732 **
17733 ** Why not just use a library random generator like lrand48() for this?
17734 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17735 ** good source of random numbers.  The lrand48() library function may
17736 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17737 ** subtle problems on some systems that could cause problems.  It is hard
17738 ** to know.  To minimize the risk of problems due to bad lrand48()
17739 ** implementations, SQLite uses this random number generator based
17740 ** on RC4, which we know works very well.
17741 **
17742 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17743 ** randomness any more.  But we will leave this code in all the same.
17744 */
17745 static int randomByte(void){
17746   unsigned char t;
17747
17748
17749   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17750   ** state vector.  If writable static data is unsupported on the target,
17751   ** we have to locate the state vector at run-time.  In the more common
17752   ** case where writable static data is supported, wsdPrng can refer directly
17753   ** to the "sqlite3Prng" state vector declared above.
17754   */
17755 #ifdef SQLITE_OMIT_WSD
17756   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17757 # define wsdPrng p[0]
17758 #else
17759 # define wsdPrng sqlite3Prng
17760 #endif
17761
17762
17763   /* Initialize the state of the random number generator once,
17764   ** the first time this routine is called.  The seed value does
17765   ** not need to contain a lot of randomness since we are not
17766   ** trying to do secure encryption or anything like that...
17767   **
17768   ** Nothing in this file or anywhere else in SQLite does any kind of
17769   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17770   ** number generator) not as an encryption device.
17771   */
17772   if( !wsdPrng.isInit ){
17773     int i;
17774     char k[256];
17775     wsdPrng.j = 0;
17776     wsdPrng.i = 0;
17777     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17778     for(i=0; i<256; i++){
17779       wsdPrng.s[i] = i;
17780     }
17781     for(i=0; i<256; i++){
17782       wsdPrng.j += wsdPrng.s[i] + k[i];
17783       t = wsdPrng.s[wsdPrng.j];
17784       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17785       wsdPrng.s[i] = t;
17786     }
17787     wsdPrng.isInit = 1;
17788   }
17789
17790   /* Generate and return single random byte
17791   */
17792   wsdPrng.i++;
17793   t = wsdPrng.s[wsdPrng.i];
17794   wsdPrng.j += t;
17795   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17796   wsdPrng.s[wsdPrng.j] = t;
17797   t += wsdPrng.s[wsdPrng.i];
17798   return wsdPrng.s[t];
17799 }
17800
17801 /*
17802 ** Return N random bytes.
17803 */
17804 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17805   unsigned char *zBuf = pBuf;
17806 #if SQLITE_THREADSAFE
17807   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17808 #endif
17809   sqlite3_mutex_enter(mutex);
17810   while( N-- ){
17811     *(zBuf++) = randomByte();
17812   }
17813   sqlite3_mutex_leave(mutex);
17814 }
17815
17816 #ifndef SQLITE_OMIT_BUILTIN_TEST
17817 /*
17818 ** For testing purposes, we sometimes want to preserve the state of
17819 ** PRNG and restore the PRNG to its saved state at a later time, or
17820 ** to reset the PRNG to its initial state.  These routines accomplish
17821 ** those tasks.
17822 **
17823 ** The sqlite3_test_control() interface calls these routines to
17824 ** control the PRNG.
17825 */
17826 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng = { 0, };
17827 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17828   memcpy(
17829     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17830     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17831     sizeof(sqlite3Prng)
17832   );
17833 }
17834 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17835   memcpy(
17836     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17837     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17838     sizeof(sqlite3Prng)
17839   );
17840 }
17841 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17842   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17843 }
17844 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17845
17846 /************** End of random.c **********************************************/
17847 /************** Begin file utf.c *********************************************/
17848 /*
17849 ** 2004 April 13
17850 **
17851 ** The author disclaims copyright to this source code.  In place of
17852 ** a legal notice, here is a blessing:
17853 **
17854 **    May you do good and not evil.
17855 **    May you find forgiveness for yourself and forgive others.
17856 **    May you share freely, never taking more than you give.
17857 **
17858 *************************************************************************
17859 ** This file contains routines used to translate between UTF-8, 
17860 ** UTF-16, UTF-16BE, and UTF-16LE.
17861 **
17862 ** $Id: utf.c,v 1.65 2008/08/12 15:04:59 danielk1977 Exp $
17863 **
17864 ** Notes on UTF-8:
17865 **
17866 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17867 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17868 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17869 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17870 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17871 **
17872 **
17873 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17874 **
17875 **      Word-0               Word-1          Value
17876 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17877 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17878 **
17879 **
17880 ** BOM or Byte Order Mark:
17881 **     0xff 0xfe   little-endian utf-16 follows
17882 **     0xfe 0xff   big-endian utf-16 follows
17883 **
17884 */
17885 /************** Include vdbeInt.h in the middle of utf.c *********************/
17886 /************** Begin file vdbeInt.h *****************************************/
17887 /*
17888 ** 2003 September 6
17889 **
17890 ** The author disclaims copyright to this source code.  In place of
17891 ** a legal notice, here is a blessing:
17892 **
17893 **    May you do good and not evil.
17894 **    May you find forgiveness for yourself and forgive others.
17895 **    May you share freely, never taking more than you give.
17896 **
17897 *************************************************************************
17898 ** This is the header file for information that is private to the
17899 ** VDBE.  This information used to all be at the top of the single
17900 ** source code file "vdbe.c".  When that file became too big (over
17901 ** 6000 lines long) it was split up into several smaller files and
17902 ** this header information was factored out.
17903 **
17904 ** $Id: vdbeInt.h,v 1.155 2008/10/07 23:46:38 drh Exp $
17905 */
17906 #ifndef _VDBEINT_H_
17907 #define _VDBEINT_H_
17908
17909 /*
17910 ** intToKey() and keyToInt() used to transform the rowid.  But with
17911 ** the latest versions of the design they are no-ops.
17912 */
17913 #define keyToInt(X)   (X)
17914 #define intToKey(X)   (X)
17915
17916
17917 /*
17918 ** SQL is translated into a sequence of instructions to be
17919 ** executed by a virtual machine.  Each instruction is an instance
17920 ** of the following structure.
17921 */
17922 typedef struct VdbeOp Op;
17923
17924 /*
17925 ** Boolean values
17926 */
17927 typedef unsigned char Bool;
17928
17929 /*
17930 ** A cursor is a pointer into a single BTree within a database file.
17931 ** The cursor can seek to a BTree entry with a particular key, or
17932 ** loop over all entries of the Btree.  You can also insert new BTree
17933 ** entries or retrieve the key or data from the entry that the cursor
17934 ** is currently pointing to.
17935 ** 
17936 ** Every cursor that the virtual machine has open is represented by an
17937 ** instance of the following structure.
17938 **
17939 ** If the Cursor.isTriggerRow flag is set it means that this cursor is
17940 ** really a single row that represents the NEW or OLD pseudo-table of
17941 ** a row trigger.  The data for the row is stored in Cursor.pData and
17942 ** the rowid is in Cursor.iKey.
17943 */
17944 struct Cursor {
17945   BtCursor *pCursor;    /* The cursor structure of the backend */
17946   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17947   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17948   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
17949   Bool zeroed;          /* True if zeroed out and ready for reuse */
17950   Bool rowidIsValid;    /* True if lastRowid is valid */
17951   Bool atFirst;         /* True if pointing to first entry */
17952   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17953   Bool nullRow;         /* True if pointing to a row with no data */
17954   Bool nextRowidValid;  /* True if the nextRowid field is valid */
17955   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
17956   Bool ephemPseudoTable;
17957   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17958   Bool isTable;         /* True if a table requiring integer keys */
17959   Bool isIndex;         /* True if an index containing keys only - no data */
17960   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17961   Btree *pBt;           /* Separate file holding temporary table */
17962   int nData;            /* Number of bytes in pData */
17963   char *pData;          /* Data for a NEW or OLD pseudo-table */
17964   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
17965   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17966   int nField;           /* Number of fields in the header */
17967   i64 seqCount;         /* Sequence counter */
17968   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17969   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17970
17971   /* Cached information about the header for the data record that the
17972   ** cursor is currently pointing to.  Only valid if cacheValid is true.
17973   ** aRow might point to (ephemeral) data for the current row, or it might
17974   ** be NULL.
17975   */
17976   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17977   int payloadSize;      /* Total number of bytes in the record */
17978   u32 *aType;           /* Type values for all entries in the record */
17979   u32 *aOffset;         /* Cached offsets to the start of each columns data */
17980   u8 *aRow;             /* Data for the current row, if all on one page */
17981 };
17982 typedef struct Cursor Cursor;
17983
17984 /*
17985 ** A value for Cursor.cacheValid that means the cache is always invalid.
17986 */
17987 #define CACHE_STALE 0
17988
17989 /*
17990 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17991 ** structures. Each Mem struct may cache multiple representations (string,
17992 ** integer etc.) of the same value.  A value (and therefore Mem structure)
17993 ** has the following properties:
17994 **
17995 ** Each value has a manifest type. The manifest type of the value stored
17996 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17997 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17998 ** SQLITE_BLOB.
17999 */
18000 struct Mem {
18001   union {
18002     i64 i;              /* Integer value. Or FuncDef* when flags==MEM_Agg */
18003     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18004   } u;
18005   double r;           /* Real value */
18006   sqlite3 *db;        /* The associated database connection */
18007   char *z;            /* String or BLOB value */
18008   int n;              /* Number of characters in string value, excluding '\0' */
18009   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18010   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18011   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18012   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18013   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18014 };
18015
18016 /* One or more of the following flags are set to indicate the validOK
18017 ** representations of the value stored in the Mem struct.
18018 **
18019 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18020 ** No other flags may be set in this case.
18021 **
18022 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18023 ** Usually this is encoded in the same unicode encoding as the main
18024 ** database (see below for exceptions). If the MEM_Term flag is also
18025 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
18026 ** flags may coexist with the MEM_Str flag.
18027 **
18028 ** Multiple of these values can appear in Mem.flags.  But only one
18029 ** at a time can appear in Mem.type.
18030 */
18031 #define MEM_Null      0x0001   /* Value is NULL */
18032 #define MEM_Str       0x0002   /* Value is a string */
18033 #define MEM_Int       0x0004   /* Value is an integer */
18034 #define MEM_Real      0x0008   /* Value is a real number */
18035 #define MEM_Blob      0x0010   /* Value is a BLOB */
18036
18037 #define MemSetTypeFlag(p, f) \
18038   ((p)->flags = ((p)->flags&~(MEM_Int|MEM_Real|MEM_Null|MEM_Blob|MEM_Str))|f)
18039
18040 /* Whenever Mem contains a valid string or blob representation, one of
18041 ** the following flags must be set to determine the memory management
18042 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18043 ** string is \000 or \u0000 terminated
18044 */
18045 #define MEM_Term      0x0020   /* String rep is nul terminated */
18046 #define MEM_Dyn       0x0040   /* Need to call sqliteFree() on Mem.z */
18047 #define MEM_Static    0x0080   /* Mem.z points to a static string */
18048 #define MEM_Ephem     0x0100   /* Mem.z points to an ephemeral string */
18049 #define MEM_Agg       0x0400   /* Mem.z points to an agg function context */
18050 #define MEM_Zero      0x0800   /* Mem.i contains count of 0s appended to blob */
18051
18052 #ifdef SQLITE_OMIT_INCRBLOB
18053   #undef MEM_Zero
18054   #define MEM_Zero 0x0000
18055 #endif
18056
18057
18058 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18059 ** additional information about auxiliary information bound to arguments
18060 ** of the function.  This is used to implement the sqlite3_get_auxdata()
18061 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18062 ** that can be associated with a constant argument to a function.  This
18063 ** allows functions such as "regexp" to compile their constant regular
18064 ** expression argument once and reused the compiled code for multiple
18065 ** invocations.
18066 */
18067 struct VdbeFunc {
18068   FuncDef *pFunc;               /* The definition of the function */
18069   int nAux;                     /* Number of entries allocated for apAux[] */
18070   struct AuxData {
18071     void *pAux;                   /* Aux data for the i-th argument */
18072     void (*xDelete)(void *);      /* Destructor for the aux data */
18073   } apAux[1];                   /* One slot for each function argument */
18074 };
18075
18076 /*
18077 ** The "context" argument for a installable function.  A pointer to an
18078 ** instance of this structure is the first argument to the routines used
18079 ** implement the SQL functions.
18080 **
18081 ** There is a typedef for this structure in sqlite.h.  So all routines,
18082 ** even the public interface to SQLite, can use a pointer to this structure.
18083 ** But this file is the only place where the internal details of this
18084 ** structure are known.
18085 **
18086 ** This structure is defined inside of vdbeInt.h because it uses substructures
18087 ** (Mem) which are only defined there.
18088 */
18089 struct sqlite3_context {
18090   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18091   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18092   Mem s;                /* The return value is stored here */
18093   Mem *pMem;            /* Memory cell used to store aggregate context */
18094   int isError;          /* Error code returned by the function. */
18095   CollSeq *pColl;       /* Collating sequence */
18096 };
18097
18098 /*
18099 ** A Set structure is used for quick testing to see if a value
18100 ** is part of a small set.  Sets are used to implement code like
18101 ** this:
18102 **            x.y IN ('hi','hoo','hum')
18103 */
18104 typedef struct Set Set;
18105 struct Set {
18106   Hash hash;             /* A set is just a hash table */
18107   HashElem *prev;        /* Previously accessed hash elemen */
18108 };
18109
18110 /*
18111 ** A FifoPage structure holds a single page of valves.  Pages are arranged
18112 ** in a list.
18113 */
18114 typedef struct FifoPage FifoPage;
18115 struct FifoPage {
18116   int nSlot;         /* Number of entries aSlot[] */
18117   int iWrite;        /* Push the next value into this entry in aSlot[] */
18118   int iRead;         /* Read the next value from this entry in aSlot[] */
18119   FifoPage *pNext;   /* Next page in the fifo */
18120   i64 aSlot[1];      /* One or more slots for rowid values */
18121 };
18122
18123 /*
18124 ** The Fifo structure is typedef-ed in vdbeInt.h.  But the implementation
18125 ** of that structure is private to this file.
18126 **
18127 ** The Fifo structure describes the entire fifo.  
18128 */
18129 typedef struct Fifo Fifo;
18130 struct Fifo {
18131   int nEntry;         /* Total number of entries */
18132   sqlite3 *db;        /* The associated database connection */
18133   FifoPage *pFirst;   /* First page on the list */
18134   FifoPage *pLast;    /* Last page on the list */
18135 };
18136
18137 /*
18138 ** A Context stores the last insert rowid, the last statement change count,
18139 ** and the current statement change count (i.e. changes since last statement).
18140 ** The current keylist is also stored in the context.
18141 ** Elements of Context structure type make up the ContextStack, which is
18142 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
18143 ** The context is pushed before executing a trigger a popped when the
18144 ** trigger finishes.
18145 */
18146 typedef struct Context Context;
18147 struct Context {
18148   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
18149   int nChange;      /* Statement changes (Vdbe.nChanges)     */
18150   Fifo sFifo;       /* Records that will participate in a DELETE or UPDATE */
18151 };
18152
18153 /*
18154 ** An instance of the virtual machine.  This structure contains the complete
18155 ** state of the virtual machine.
18156 **
18157 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18158 ** is really a pointer to an instance of this structure.
18159 **
18160 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18161 ** any virtual table method invocations made by the vdbe program. It is
18162 ** set to 2 for xDestroy method calls and 1 for all other methods. This
18163 ** variable is used for two purposes: to allow xDestroy methods to execute
18164 ** "DROP TABLE" statements and to prevent some nasty side effects of
18165 ** malloc failure when SQLite is invoked recursively by a virtual table 
18166 ** method function.
18167 */
18168 struct Vdbe {
18169   sqlite3 *db;        /* The whole database */
18170   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
18171   int nOp;            /* Number of instructions in the program */
18172   int nOpAlloc;       /* Number of slots allocated for aOp[] */
18173   Op *aOp;            /* Space to hold the virtual machine's program */
18174   int nLabel;         /* Number of labels used */
18175   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
18176   int *aLabel;        /* Space to hold the labels */
18177   Mem **apArg;        /* Arguments to currently executing user function */
18178   Mem *aColName;      /* Column names to return */
18179   int nCursor;        /* Number of slots in apCsr[] */
18180   Cursor **apCsr;     /* One element of this array for each open cursor */
18181   int nVar;           /* Number of entries in aVar[] */
18182   Mem *aVar;          /* Values for the OP_Variable opcode. */
18183   char **azVar;       /* Name of variables */
18184   int okVar;          /* True if azVar[] has been initialized */
18185   int magic;              /* Magic number for sanity checking */
18186   int nMem;               /* Number of memory locations currently allocated */
18187   Mem *aMem;              /* The memory locations */
18188   int nCallback;          /* Number of callbacks invoked so far */
18189   int cacheCtr;           /* Cursor row cache generation counter */
18190   Fifo sFifo;             /* A list of ROWIDs */
18191   int contextStackTop;    /* Index of top element in the context stack */
18192   int contextStackDepth;  /* The size of the "context" stack */
18193   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
18194   int pc;                 /* The program counter */
18195   int rc;                 /* Value to return */
18196   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
18197   int errorAction;        /* Recovery action to do in case of an error */
18198   int inTempTrans;        /* True if temp database is transactioned */
18199   int nResColumn;         /* Number of columns in one row of the result set */
18200   char **azResColumn;     /* Values for one row of result */ 
18201   char *zErrMsg;          /* Error message written here */
18202   Mem *pResultSet;        /* Pointer to an array of results */
18203   u8 explain;             /* True if EXPLAIN present on SQL command */
18204   u8 changeCntOn;         /* True to update the change-counter */
18205   u8 expired;             /* True if the VM needs to be recompiled */
18206   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18207   u8 inVtabMethod;        /* See comments above */
18208   int nChange;            /* Number of db changes made since last reset */
18209   i64 startTime;          /* Time when query started - used for profiling */
18210   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18211   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18212   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
18213   int nSql;             /* Number of bytes in zSql */
18214   char *zSql;           /* Text of the SQL statement that generated this */
18215 #ifdef SQLITE_DEBUG
18216   FILE *trace;          /* Write an execution trace here, if not NULL */
18217 #endif
18218   int openedStatement;  /* True if this VM has opened a statement journal */
18219 #ifdef SQLITE_SSE
18220   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
18221   int lru;              /* Counter used for LRU cache replacement */
18222 #endif
18223 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18224   Vdbe *pLruPrev;
18225   Vdbe *pLruNext;
18226 #endif
18227 };
18228
18229 /*
18230 ** The following are allowed values for Vdbe.magic
18231 */
18232 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18233 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18234 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18235 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18236
18237 /*
18238 ** Function prototypes
18239 */
18240 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
18241 void sqliteVdbePopStack(Vdbe*,int);
18242 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
18243 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18244 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18245 #endif
18246 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
18247 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18248 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18249 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18250 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18251
18252 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18253 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*,UnpackedRecord*,int*);
18254 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
18255 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18256 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18257 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18258 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18259 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18260 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18261 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18262 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18263 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18264 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18265 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18266 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18267 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18268 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18269 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18270 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18271 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18272 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18273 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18274 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18275 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18276 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18277 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18278 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18279 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18280 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18281 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18282 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18283 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
18284 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18285 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18286 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
18287 #endif
18288
18289 #ifndef NDEBUG
18290 SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
18291 #endif
18292 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18293 #ifdef SQLITE_DEBUG
18294 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18295 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18296 #endif
18297 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18298 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*, sqlite3*);
18299 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
18300 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
18301 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);
18302
18303 #ifndef SQLITE_OMIT_INCRBLOB
18304 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18305 #else
18306   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18307 #endif
18308
18309 #endif /* !defined(_VDBEINT_H_) */
18310
18311 /************** End of vdbeInt.h *********************************************/
18312 /************** Continuing where we left off in utf.c ************************/
18313
18314 /*
18315 ** The following constant value is used by the SQLITE_BIGENDIAN and
18316 ** SQLITE_LITTLEENDIAN macros.
18317 */
18318 SQLITE_PRIVATE const int sqlite3one = 1;
18319
18320 /*
18321 ** This lookup table is used to help decode the first byte of
18322 ** a multi-byte UTF8 character.
18323 */
18324 static const unsigned char sqlite3UtfTrans1[] = {
18325   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18326   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18327   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18328   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18329   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18330   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18331   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18332   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18333 };
18334
18335
18336 #define WRITE_UTF8(zOut, c) {                          \
18337   if( c<0x00080 ){                                     \
18338     *zOut++ = (c&0xFF);                                \
18339   }                                                    \
18340   else if( c<0x00800 ){                                \
18341     *zOut++ = 0xC0 + ((c>>6)&0x1F);                    \
18342     *zOut++ = 0x80 + (c & 0x3F);                       \
18343   }                                                    \
18344   else if( c<0x10000 ){                                \
18345     *zOut++ = 0xE0 + ((c>>12)&0x0F);                   \
18346     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18347     *zOut++ = 0x80 + (c & 0x3F);                       \
18348   }else{                                               \
18349     *zOut++ = 0xF0 + ((c>>18) & 0x07);                 \
18350     *zOut++ = 0x80 + ((c>>12) & 0x3F);                 \
18351     *zOut++ = 0x80 + ((c>>6) & 0x3F);                  \
18352     *zOut++ = 0x80 + (c & 0x3F);                       \
18353   }                                                    \
18354 }
18355
18356 #define WRITE_UTF16LE(zOut, c) {                                \
18357   if( c<=0xFFFF ){                                              \
18358     *zOut++ = (c&0x00FF);                                       \
18359     *zOut++ = ((c>>8)&0x00FF);                                  \
18360   }else{                                                        \
18361     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18362     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18363     *zOut++ = (c&0x00FF);                                       \
18364     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18365   }                                                             \
18366 }
18367
18368 #define WRITE_UTF16BE(zOut, c) {                                \
18369   if( c<=0xFFFF ){                                              \
18370     *zOut++ = ((c>>8)&0x00FF);                                  \
18371     *zOut++ = (c&0x00FF);                                       \
18372   }else{                                                        \
18373     *zOut++ = (0x00D8 + (((c-0x10000)>>18)&0x03));              \
18374     *zOut++ = (((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18375     *zOut++ = (0x00DC + ((c>>8)&0x03));                         \
18376     *zOut++ = (c&0x00FF);                                       \
18377   }                                                             \
18378 }
18379
18380 #define READ_UTF16LE(zIn, c){                                         \
18381   c = (*zIn++);                                                       \
18382   c += ((*zIn++)<<8);                                                 \
18383   if( c>=0xD800 && c<0xE000 ){                                       \
18384     int c2 = (*zIn++);                                                \
18385     c2 += ((*zIn++)<<8);                                              \
18386     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18387     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18388   }                                                                   \
18389 }
18390
18391 #define READ_UTF16BE(zIn, c){                                         \
18392   c = ((*zIn++)<<8);                                                  \
18393   c += (*zIn++);                                                      \
18394   if( c>=0xD800 && c<0xE000 ){                                       \
18395     int c2 = ((*zIn++)<<8);                                           \
18396     c2 += (*zIn++);                                                   \
18397     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18398     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18399   }                                                                   \
18400 }
18401
18402 /*
18403 ** Translate a single UTF-8 character.  Return the unicode value.
18404 **
18405 ** During translation, assume that the byte that zTerm points
18406 ** is a 0x00.
18407 **
18408 ** Write a pointer to the next unread byte back into *pzNext.
18409 **
18410 ** Notes On Invalid UTF-8:
18411 **
18412 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18413 **     be encoded as a multi-byte character.  Any multi-byte character that
18414 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18415 **
18416 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18417 **     If a multi-byte character attempts to encode a value between
18418 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18419 **
18420 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18421 **     byte of a character are interpreted as single-byte characters
18422 **     and rendered as themselves even though they are technically
18423 **     invalid characters.
18424 **
18425 **  *  This routine accepts an infinite number of different UTF8 encodings
18426 **     for unicode values 0x80 and greater.  It do not change over-length
18427 **     encodings to 0xfffd as some systems recommend.
18428 */
18429 #define READ_UTF8(zIn, zTerm, c)                           \
18430   c = *(zIn++);                                            \
18431   if( c>=0xc0 ){                                           \
18432     c = sqlite3UtfTrans1[c-0xc0];                          \
18433     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18434       c = (c<<6) + (0x3f & *(zIn++));                      \
18435     }                                                      \
18436     if( c<0x80                                             \
18437         || (c&0xFFFFF800)==0xD800                          \
18438         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18439   }
18440 SQLITE_PRIVATE int sqlite3Utf8Read(
18441   const unsigned char *z,         /* First byte of UTF-8 character */
18442   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
18443   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18444 ){
18445   int c;
18446   READ_UTF8(z, zTerm, c);
18447   *pzNext = z;
18448   return c;
18449 }
18450
18451
18452
18453
18454 /*
18455 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18456 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18457 */ 
18458 /* #define TRANSLATE_TRACE 1 */
18459
18460 #ifndef SQLITE_OMIT_UTF16
18461 /*
18462 ** This routine transforms the internal text encoding used by pMem to
18463 ** desiredEnc. It is an error if the string is already of the desired
18464 ** encoding, or if *pMem does not contain a string value.
18465 */
18466 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18467   int len;                    /* Maximum length of output string in bytes */
18468   unsigned char *zOut;                  /* Output buffer */
18469   unsigned char *zIn;                   /* Input iterator */
18470   unsigned char *zTerm;                 /* End of input */
18471   unsigned char *z;                     /* Output iterator */
18472   unsigned int c;
18473
18474   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18475   assert( pMem->flags&MEM_Str );
18476   assert( pMem->enc!=desiredEnc );
18477   assert( pMem->enc!=0 );
18478   assert( pMem->n>=0 );
18479
18480 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18481   {
18482     char zBuf[100];
18483     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18484     fprintf(stderr, "INPUT:  %s\n", zBuf);
18485   }
18486 #endif
18487
18488   /* If the translation is between UTF-16 little and big endian, then 
18489   ** all that is required is to swap the byte order. This case is handled
18490   ** differently from the others.
18491   */
18492   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18493     u8 temp;
18494     int rc;
18495     rc = sqlite3VdbeMemMakeWriteable(pMem);
18496     if( rc!=SQLITE_OK ){
18497       assert( rc==SQLITE_NOMEM );
18498       return SQLITE_NOMEM;
18499     }
18500     zIn = (u8*)pMem->z;
18501     zTerm = &zIn[pMem->n];
18502     while( zIn<zTerm ){
18503       temp = *zIn;
18504       *zIn = *(zIn+1);
18505       zIn++;
18506       *zIn++ = temp;
18507     }
18508     pMem->enc = desiredEnc;
18509     goto translate_out;
18510   }
18511
18512   /* Set len to the maximum number of bytes required in the output buffer. */
18513   if( desiredEnc==SQLITE_UTF8 ){
18514     /* When converting from UTF-16, the maximum growth results from
18515     ** translating a 2-byte character to a 4-byte UTF-8 character.
18516     ** A single byte is required for the output string
18517     ** nul-terminator.
18518     */
18519     len = pMem->n * 2 + 1;
18520   }else{
18521     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18522     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18523     ** character. Two bytes are required in the output buffer for the
18524     ** nul-terminator.
18525     */
18526     len = pMem->n * 2 + 2;
18527   }
18528
18529   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18530   ** byte past the end.
18531   **
18532   ** Variable zOut is set to point at the output buffer, space obtained
18533   ** from sqlite3_malloc().
18534   */
18535   zIn = (u8*)pMem->z;
18536   zTerm = &zIn[pMem->n];
18537   zOut = sqlite3DbMallocRaw(pMem->db, len);
18538   if( !zOut ){
18539     return SQLITE_NOMEM;
18540   }
18541   z = zOut;
18542
18543   if( pMem->enc==SQLITE_UTF8 ){
18544     if( desiredEnc==SQLITE_UTF16LE ){
18545       /* UTF-8 -> UTF-16 Little-endian */
18546       while( zIn<zTerm ){
18547         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18548         READ_UTF8(zIn, zTerm, c);
18549         WRITE_UTF16LE(z, c);
18550       }
18551     }else{
18552       assert( desiredEnc==SQLITE_UTF16BE );
18553       /* UTF-8 -> UTF-16 Big-endian */
18554       while( zIn<zTerm ){
18555         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18556         READ_UTF8(zIn, zTerm, c);
18557         WRITE_UTF16BE(z, c);
18558       }
18559     }
18560     pMem->n = z - zOut;
18561     *z++ = 0;
18562   }else{
18563     assert( desiredEnc==SQLITE_UTF8 );
18564     if( pMem->enc==SQLITE_UTF16LE ){
18565       /* UTF-16 Little-endian -> UTF-8 */
18566       while( zIn<zTerm ){
18567         READ_UTF16LE(zIn, c); 
18568         WRITE_UTF8(z, c);
18569       }
18570     }else{
18571       /* UTF-16 Big-endian -> UTF-8 */
18572       while( zIn<zTerm ){
18573         READ_UTF16BE(zIn, c); 
18574         WRITE_UTF8(z, c);
18575       }
18576     }
18577     pMem->n = z - zOut;
18578   }
18579   *z = 0;
18580   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18581
18582   sqlite3VdbeMemRelease(pMem);
18583   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18584   pMem->enc = desiredEnc;
18585   pMem->flags |= (MEM_Term|MEM_Dyn);
18586   pMem->z = (char*)zOut;
18587   pMem->zMalloc = pMem->z;
18588
18589 translate_out:
18590 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18591   {
18592     char zBuf[100];
18593     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18594     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18595   }
18596 #endif
18597   return SQLITE_OK;
18598 }
18599
18600 /*
18601 ** This routine checks for a byte-order mark at the beginning of the 
18602 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18603 ** the encoding of the Mem adjusted. This routine does not do any
18604 ** byte-swapping, it just sets Mem.enc appropriately.
18605 **
18606 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18607 ** changed by this function.
18608 */
18609 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18610   int rc = SQLITE_OK;
18611   u8 bom = 0;
18612
18613   if( pMem->n<0 || pMem->n>1 ){
18614     u8 b1 = *(u8 *)pMem->z;
18615     u8 b2 = *(((u8 *)pMem->z) + 1);
18616     if( b1==0xFE && b2==0xFF ){
18617       bom = SQLITE_UTF16BE;
18618     }
18619     if( b1==0xFF && b2==0xFE ){
18620       bom = SQLITE_UTF16LE;
18621     }
18622   }
18623   
18624   if( bom ){
18625     rc = sqlite3VdbeMemMakeWriteable(pMem);
18626     if( rc==SQLITE_OK ){
18627       pMem->n -= 2;
18628       memmove(pMem->z, &pMem->z[2], pMem->n);
18629       pMem->z[pMem->n] = '\0';
18630       pMem->z[pMem->n+1] = '\0';
18631       pMem->flags |= MEM_Term;
18632       pMem->enc = bom;
18633     }
18634   }
18635   return rc;
18636 }
18637 #endif /* SQLITE_OMIT_UTF16 */
18638
18639 /*
18640 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18641 ** return the number of unicode characters in pZ up to (but not including)
18642 ** the first 0x00 byte. If nByte is not less than zero, return the
18643 ** number of unicode characters in the first nByte of pZ (or up to 
18644 ** the first 0x00, whichever comes first).
18645 */
18646 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18647   int r = 0;
18648   const u8 *z = (const u8*)zIn;
18649   const u8 *zTerm;
18650   if( nByte>=0 ){
18651     zTerm = &z[nByte];
18652   }else{
18653     zTerm = (const u8*)(-1);
18654   }
18655   assert( z<=zTerm );
18656   while( *z!=0 && z<zTerm ){
18657     SQLITE_SKIP_UTF8(z);
18658     r++;
18659   }
18660   return r;
18661 }
18662
18663 /* This test function is not currently used by the automated test-suite. 
18664 ** Hence it is only available in debug builds.
18665 */
18666 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18667 /*
18668 ** Translate UTF-8 to UTF-8.
18669 **
18670 ** This has the effect of making sure that the string is well-formed
18671 ** UTF-8.  Miscoded characters are removed.
18672 **
18673 ** The translation is done in-place (since it is impossible for the
18674 ** correct UTF-8 encoding to be longer than a malformed encoding).
18675 */
18676 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18677   unsigned char *zOut = zIn;
18678   unsigned char *zStart = zIn;
18679   unsigned char *zTerm = &zIn[strlen((char *)zIn)];
18680   u32 c;
18681
18682   while( zIn[0] ){
18683     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
18684     if( c!=0xfffd ){
18685       WRITE_UTF8(zOut, c);
18686     }
18687   }
18688   *zOut = 0;
18689   return zOut - zStart;
18690 }
18691 #endif
18692
18693 #ifndef SQLITE_OMIT_UTF16
18694 /*
18695 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18696 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18697 ** be freed by the calling function.
18698 **
18699 ** NULL is returned if there is an allocation error.
18700 */
18701 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18702   Mem m;
18703   memset(&m, 0, sizeof(m));
18704   m.db = db;
18705   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18706   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18707   if( db->mallocFailed ){
18708     sqlite3VdbeMemRelease(&m);
18709     m.z = 0;
18710   }
18711   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18712   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18713   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18714 }
18715
18716 /*
18717 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
18718 ** return the number of bytes up to (but not including), the first pair
18719 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
18720 ** then return the number of bytes in the first nChar unicode characters
18721 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
18722 */
18723 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18724   unsigned int c = 1;
18725   char const *z = zIn;
18726   int n = 0;
18727   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18728     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
18729     ** and in other parts of this file means that at one branch will
18730     ** not be covered by coverage testing on any single host. But coverage
18731     ** will be complete if the tests are run on both a little-endian and 
18732     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
18733     ** macros are constant at compile time the compiler can determine
18734     ** which branch will be followed. It is therefore assumed that no runtime
18735     ** penalty is paid for this "if" statement.
18736     */
18737     while( c && ((nChar<0) || n<nChar) ){
18738       READ_UTF16BE(z, c);
18739       n++;
18740     }
18741   }else{
18742     while( c && ((nChar<0) || n<nChar) ){
18743       READ_UTF16LE(z, c);
18744       n++;
18745     }
18746   }
18747   return (z-(char const *)zIn)-((c==0)?2:0);
18748 }
18749
18750 #if defined(SQLITE_TEST)
18751 /*
18752 ** This routine is called from the TCL test function "translate_selftest".
18753 ** It checks that the primitives for serializing and deserializing
18754 ** characters in each encoding are inverses of each other.
18755 */
18756 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18757   unsigned int i, t;
18758   unsigned char zBuf[20];
18759   unsigned char *z;
18760   unsigned char *zTerm;
18761   int n;
18762   unsigned int c;
18763
18764   for(i=0; i<0x00110000; i++){
18765     z = zBuf;
18766     WRITE_UTF8(z, i);
18767     n = z-zBuf;
18768     z[0] = 0;
18769     zTerm = z;
18770     z = zBuf;
18771     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
18772     t = i;
18773     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18774     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18775     assert( c==t );
18776     assert( (z-zBuf)==n );
18777   }
18778   for(i=0; i<0x00110000; i++){
18779     if( i>=0xD800 && i<0xE000 ) continue;
18780     z = zBuf;
18781     WRITE_UTF16LE(z, i);
18782     n = z-zBuf;
18783     z[0] = 0;
18784     z = zBuf;
18785     READ_UTF16LE(z, c);
18786     assert( c==i );
18787     assert( (z-zBuf)==n );
18788   }
18789   for(i=0; i<0x00110000; i++){
18790     if( i>=0xD800 && i<0xE000 ) continue;
18791     z = zBuf;
18792     WRITE_UTF16BE(z, i);
18793     n = z-zBuf;
18794     z[0] = 0;
18795     z = zBuf;
18796     READ_UTF16BE(z, c);
18797     assert( c==i );
18798     assert( (z-zBuf)==n );
18799   }
18800 }
18801 #endif /* SQLITE_TEST */
18802 #endif /* SQLITE_OMIT_UTF16 */
18803
18804 /************** End of utf.c *************************************************/
18805 /************** Begin file util.c ********************************************/
18806 /*
18807 ** 2001 September 15
18808 **
18809 ** The author disclaims copyright to this source code.  In place of
18810 ** a legal notice, here is a blessing:
18811 **
18812 **    May you do good and not evil.
18813 **    May you find forgiveness for yourself and forgive others.
18814 **    May you share freely, never taking more than you give.
18815 **
18816 *************************************************************************
18817 ** Utility functions used throughout sqlite.
18818 **
18819 ** This file contains functions for allocating memory, comparing
18820 ** strings, and stuff like that.
18821 **
18822 ** $Id: util.c,v 1.241 2008/07/28 19:34:54 drh Exp $
18823 */
18824
18825
18826 /*
18827 ** Return true if the floating point value is Not a Number (NaN).
18828 */
18829 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18830   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
18831   ** On the other hand, the use of -ffast-math comes with the following
18832   ** warning:
18833   **
18834   **      This option [-ffast-math] should never be turned on by any
18835   **      -O option since it can result in incorrect output for programs
18836   **      which depend on an exact implementation of IEEE or ISO 
18837   **      rules/specifications for math functions.
18838   **
18839   ** Under MSVC, this NaN test may fail if compiled with a floating-
18840   ** point precision mode other than /fp:precise.  From the MSDN 
18841   ** documentation:
18842   **
18843   **      The compiler [with /fp:precise] will properly handle comparisons 
18844   **      involving NaN. For example, x != x evaluates to true if x is NaN 
18845   **      ...
18846   */
18847 #ifdef __FAST_MATH__
18848 # error SQLite will not work correctly with the -ffast-math option of GCC.
18849 #endif
18850   volatile double y = x;
18851   volatile double z = y;
18852   return y!=z;
18853 }
18854
18855 /*
18856 ** Return the length of a string, except do not allow the string length
18857 ** to exceed the SQLITE_LIMIT_LENGTH setting.
18858 */
18859 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
18860   const char *z2 = z;
18861   int len;
18862   size_t x;
18863   while( *z2 ){ z2++; }
18864   x = z2 - z;
18865   len = 0x7fffffff & x;
18866   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
18867     return db->aLimit[SQLITE_LIMIT_LENGTH];
18868   }else{
18869     return len;
18870   }
18871 }
18872
18873 /*
18874 ** Set the most recent error code and error string for the sqlite
18875 ** handle "db". The error code is set to "err_code".
18876 **
18877 ** If it is not NULL, string zFormat specifies the format of the
18878 ** error string in the style of the printf functions: The following
18879 ** format characters are allowed:
18880 **
18881 **      %s      Insert a string
18882 **      %z      A string that should be freed after use
18883 **      %d      Insert an integer
18884 **      %T      Insert a token
18885 **      %S      Insert the first element of a SrcList
18886 **
18887 ** zFormat and any string tokens that follow it are assumed to be
18888 ** encoded in UTF-8.
18889 **
18890 ** To clear the most recent error for sqlite handle "db", sqlite3Error
18891 ** should be called with err_code set to SQLITE_OK and zFormat set
18892 ** to NULL.
18893 */
18894 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18895   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18896     db->errCode = err_code;
18897     if( zFormat ){
18898       char *z;
18899       va_list ap;
18900       va_start(ap, zFormat);
18901       z = sqlite3VMPrintf(db, zFormat, ap);
18902       va_end(ap);
18903       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18904     }else{
18905       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18906     }
18907   }
18908 }
18909
18910 /*
18911 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18912 ** The following formatting characters are allowed:
18913 **
18914 **      %s      Insert a string
18915 **      %z      A string that should be freed after use
18916 **      %d      Insert an integer
18917 **      %T      Insert a token
18918 **      %S      Insert the first element of a SrcList
18919 **
18920 ** This function should be used to report any error that occurs whilst
18921 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18922 ** last thing the sqlite3_prepare() function does is copy the error
18923 ** stored by this function into the database handle using sqlite3Error().
18924 ** Function sqlite3Error() should be used during statement execution
18925 ** (sqlite3_step() etc.).
18926 */
18927 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18928   va_list ap;
18929   sqlite3 *db = pParse->db;
18930   pParse->nErr++;
18931   sqlite3DbFree(db, pParse->zErrMsg);
18932   va_start(ap, zFormat);
18933   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18934   va_end(ap);
18935   if( pParse->rc==SQLITE_OK ){
18936     pParse->rc = SQLITE_ERROR;
18937   }
18938 }
18939
18940 /*
18941 ** Clear the error message in pParse, if any
18942 */
18943 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18944   sqlite3DbFree(pParse->db, pParse->zErrMsg);
18945   pParse->zErrMsg = 0;
18946   pParse->nErr = 0;
18947 }
18948
18949 /*
18950 ** Convert an SQL-style quoted string into a normal string by removing
18951 ** the quote characters.  The conversion is done in-place.  If the
18952 ** input does not begin with a quote character, then this routine
18953 ** is a no-op.
18954 **
18955 ** 2002-Feb-14: This routine is extended to remove MS-Access style
18956 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
18957 ** "a-b-c".
18958 */
18959 SQLITE_PRIVATE void sqlite3Dequote(char *z){
18960   int quote;
18961   int i, j;
18962   if( z==0 ) return;
18963   quote = z[0];
18964   switch( quote ){
18965     case '\'':  break;
18966     case '"':   break;
18967     case '`':   break;                /* For MySQL compatibility */
18968     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18969     default:    return;
18970   }
18971   for(i=1, j=0; z[i]; i++){
18972     if( z[i]==quote ){
18973       if( z[i+1]==quote ){
18974         z[j++] = quote;
18975         i++;
18976       }else{
18977         z[j++] = 0;
18978         break;
18979       }
18980     }else{
18981       z[j++] = z[i];
18982     }
18983   }
18984 }
18985
18986 /* Convenient short-hand */
18987 #define UpperToLower sqlite3UpperToLower
18988
18989 /*
18990 ** Some systems have stricmp().  Others have strcasecmp().  Because
18991 ** there is no consistency, we will define our own.
18992 */
18993 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18994   register unsigned char *a, *b;
18995   a = (unsigned char *)zLeft;
18996   b = (unsigned char *)zRight;
18997   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18998   return UpperToLower[*a] - UpperToLower[*b];
18999 }
19000 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
19001   register unsigned char *a, *b;
19002   a = (unsigned char *)zLeft;
19003   b = (unsigned char *)zRight;
19004   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19005   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19006 }
19007
19008 /*
19009 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
19010 ** string contains any character which is not part of a number. If
19011 ** the string is numeric and contains the '.' character, set *realnum
19012 ** to TRUE (otherwise FALSE).
19013 **
19014 ** An empty string is considered non-numeric.
19015 */
19016 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19017   int incr = (enc==SQLITE_UTF8?1:2);
19018   if( enc==SQLITE_UTF16BE ) z++;
19019   if( *z=='-' || *z=='+' ) z += incr;
19020   if( !isdigit(*(u8*)z) ){
19021     return 0;
19022   }
19023   z += incr;
19024   if( realnum ) *realnum = 0;
19025   while( isdigit(*(u8*)z) ){ z += incr; }
19026   if( *z=='.' ){
19027     z += incr;
19028     if( !isdigit(*(u8*)z) ) return 0;
19029     while( isdigit(*(u8*)z) ){ z += incr; }
19030     if( realnum ) *realnum = 1;
19031   }
19032   if( *z=='e' || *z=='E' ){
19033     z += incr;
19034     if( *z=='+' || *z=='-' ) z += incr;
19035     if( !isdigit(*(u8*)z) ) return 0;
19036     while( isdigit(*(u8*)z) ){ z += incr; }
19037     if( realnum ) *realnum = 1;
19038   }
19039   return *z==0;
19040 }
19041
19042 /*
19043 ** The string z[] is an ascii representation of a real number.
19044 ** Convert this string to a double.
19045 **
19046 ** This routine assumes that z[] really is a valid number.  If it
19047 ** is not, the result is undefined.
19048 **
19049 ** This routine is used instead of the library atof() function because
19050 ** the library atof() might want to use "," as the decimal point instead
19051 ** of "." depending on how locale is set.  But that would cause problems
19052 ** for SQL.  So this routine always uses "." regardless of locale.
19053 */
19054 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19055 #ifndef SQLITE_OMIT_FLOATING_POINT
19056   int sign = 1;
19057   const char *zBegin = z;
19058   LONGDOUBLE_TYPE v1 = 0.0;
19059   int nSignificant = 0;
19060   while( isspace(*(u8*)z) ) z++;
19061   if( *z=='-' ){
19062     sign = -1;
19063     z++;
19064   }else if( *z=='+' ){
19065     z++;
19066   }
19067   while( z[0]=='0' ){
19068     z++;
19069   }
19070   while( isdigit(*(u8*)z) ){
19071     v1 = v1*10.0 + (*z - '0');
19072     z++;
19073     nSignificant++;
19074   }
19075   if( *z=='.' ){
19076     LONGDOUBLE_TYPE divisor = 1.0;
19077     z++;
19078     if( nSignificant==0 ){
19079       while( z[0]=='0' ){
19080         divisor *= 10.0;
19081         z++;
19082       }
19083     }
19084     while( isdigit(*(u8*)z) ){
19085       if( nSignificant<18 ){
19086         v1 = v1*10.0 + (*z - '0');
19087         divisor *= 10.0;
19088         nSignificant++;
19089       }
19090       z++;
19091     }
19092     v1 /= divisor;
19093   }
19094   if( *z=='e' || *z=='E' ){
19095     int esign = 1;
19096     int eval = 0;
19097     LONGDOUBLE_TYPE scale = 1.0;
19098     z++;
19099     if( *z=='-' ){
19100       esign = -1;
19101       z++;
19102     }else if( *z=='+' ){
19103       z++;
19104     }
19105     while( isdigit(*(u8*)z) ){
19106       eval = eval*10 + *z - '0';
19107       z++;
19108     }
19109     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
19110     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
19111     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
19112     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
19113     if( esign<0 ){
19114       v1 /= scale;
19115     }else{
19116       v1 *= scale;
19117     }
19118   }
19119   *pResult = sign<0 ? -v1 : v1;
19120   return z - zBegin;
19121 #else
19122   return sqlite3Atoi64(z, pResult);
19123 #endif /* SQLITE_OMIT_FLOATING_POINT */
19124 }
19125
19126 /*
19127 ** Compare the 19-character string zNum against the text representation
19128 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19129 ** if zNum is less than, equal to, or greater than the string.
19130 **
19131 ** Unlike memcmp() this routine is guaranteed to return the difference
19132 ** in the values of the last digit if the only difference is in the
19133 ** last digit.  So, for example,
19134 **
19135 **      compare2pow63("9223372036854775800")
19136 **
19137 ** will return -8.
19138 */
19139 static int compare2pow63(const char *zNum){
19140   int c;
19141   c = memcmp(zNum,"922337203685477580",18);
19142   if( c==0 ){
19143     c = zNum[18] - '8';
19144   }
19145   return c;
19146 }
19147
19148
19149 /*
19150 ** Return TRUE if zNum is a 64-bit signed integer and write
19151 ** the value of the integer into *pNum.  If zNum is not an integer
19152 ** or is an integer that is too large to be expressed with 64 bits,
19153 ** then return false.
19154 **
19155 ** When this routine was originally written it dealt with only
19156 ** 32-bit numbers.  At that time, it was much faster than the
19157 ** atoi() library routine in RedHat 7.2.
19158 */
19159 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19160   i64 v = 0;
19161   int neg;
19162   int i, c;
19163   const char *zStart;
19164   while( isspace(*(u8*)zNum) ) zNum++;
19165   if( *zNum=='-' ){
19166     neg = 1;
19167     zNum++;
19168   }else if( *zNum=='+' ){
19169     neg = 0;
19170     zNum++;
19171   }else{
19172     neg = 0;
19173   }
19174   zStart = zNum;
19175   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19176   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19177     v = v*10 + c - '0';
19178   }
19179   *pNum = neg ? -v : v;
19180   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19181     /* zNum is empty or contains non-numeric text or is longer
19182     ** than 19 digits (thus guaranting that it is too large) */
19183     return 0;
19184   }else if( i<19 ){
19185     /* Less than 19 digits, so we know that it fits in 64 bits */
19186     return 1;
19187   }else{
19188     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19189     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19190     ** is 2^63. */
19191     return compare2pow63(zNum)<neg;
19192   }
19193 }
19194
19195 /*
19196 ** The string zNum represents an integer.  There might be some other
19197 ** information following the integer too, but that part is ignored.
19198 ** If the integer that the prefix of zNum represents will fit in a
19199 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19200 **
19201 ** This routine returns FALSE for the string -9223372036854775808 even that
19202 ** that number will, in theory fit in a 64-bit integer.  Positive
19203 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
19204 ** false.
19205 */
19206 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19207   int i, c;
19208   int neg = 0;
19209   if( *zNum=='-' ){
19210     neg = 1;
19211     zNum++;
19212   }else if( *zNum=='+' ){
19213     zNum++;
19214   }
19215   if( negFlag ) neg = 1-neg;
19216   while( *zNum=='0' ){
19217     zNum++;   /* Skip leading zeros.  Ticket #2454 */
19218   }
19219   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
19220   if( i<19 ){
19221     /* Guaranteed to fit if less than 19 digits */
19222     return 1;
19223   }else if( i>19 ){
19224     /* Guaranteed to be too big if greater than 19 digits */
19225     return 0;
19226   }else{
19227     /* Compare against 2^63. */
19228     return compare2pow63(zNum)<neg;
19229   }
19230 }
19231
19232 /*
19233 ** If zNum represents an integer that will fit in 32-bits, then set
19234 ** *pValue to that integer and return true.  Otherwise return false.
19235 **
19236 ** Any non-numeric characters that following zNum are ignored.
19237 ** This is different from sqlite3Atoi64() which requires the
19238 ** input number to be zero-terminated.
19239 */
19240 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19241   sqlite_int64 v = 0;
19242   int i, c;
19243   int neg = 0;
19244   if( zNum[0]=='-' ){
19245     neg = 1;
19246     zNum++;
19247   }else if( zNum[0]=='+' ){
19248     zNum++;
19249   }
19250   while( zNum[0]=='0' ) zNum++;
19251   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19252     v = v*10 + c;
19253   }
19254
19255   /* The longest decimal representation of a 32 bit integer is 10 digits:
19256   **
19257   **             1234567890
19258   **     2^31 -> 2147483648
19259   */
19260   if( i>10 ){
19261     return 0;
19262   }
19263   if( v-neg>2147483647 ){
19264     return 0;
19265   }
19266   if( neg ){
19267     v = -v;
19268   }
19269   *pValue = (int)v;
19270   return 1;
19271 }
19272
19273 /*
19274 ** The variable-length integer encoding is as follows:
19275 **
19276 ** KEY:
19277 **         A = 0xxxxxxx    7 bits of data and one flag bit
19278 **         B = 1xxxxxxx    7 bits of data and one flag bit
19279 **         C = xxxxxxxx    8 bits of data
19280 **
19281 **  7 bits - A
19282 ** 14 bits - BA
19283 ** 21 bits - BBA
19284 ** 28 bits - BBBA
19285 ** 35 bits - BBBBA
19286 ** 42 bits - BBBBBA
19287 ** 49 bits - BBBBBBA
19288 ** 56 bits - BBBBBBBA
19289 ** 64 bits - BBBBBBBBC
19290 */
19291
19292 /*
19293 ** Write a 64-bit variable-length integer to memory starting at p[0].
19294 ** The length of data write will be between 1 and 9 bytes.  The number
19295 ** of bytes written is returned.
19296 **
19297 ** A variable-length integer consists of the lower 7 bits of each byte
19298 ** for all bytes that have the 8th bit set and one byte with the 8th
19299 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19300 ** 8 bits and is the last byte.
19301 */
19302 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19303   int i, j, n;
19304   u8 buf[10];
19305   if( v & (((u64)0xff000000)<<32) ){
19306     p[8] = v;
19307     v >>= 8;
19308     for(i=7; i>=0; i--){
19309       p[i] = (v & 0x7f) | 0x80;
19310       v >>= 7;
19311     }
19312     return 9;
19313   }    
19314   n = 0;
19315   do{
19316     buf[n++] = (v & 0x7f) | 0x80;
19317     v >>= 7;
19318   }while( v!=0 );
19319   buf[0] &= 0x7f;
19320   assert( n<=9 );
19321   for(i=0, j=n-1; j>=0; j--, i++){
19322     p[i] = buf[j];
19323   }
19324   return n;
19325 }
19326
19327 /*
19328 ** This routine is a faster version of sqlite3PutVarint() that only
19329 ** works for 32-bit positive integers and which is optimized for
19330 ** the common case of small integers.  A MACRO version, putVarint32,
19331 ** is provided which inlines the single-byte case.  All code should use
19332 ** the MACRO version as this function assumes the single-byte case has
19333 ** already been handled.
19334 */
19335 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19336 #ifndef putVarint32
19337   if( (v & ~0x7f)==0 ){
19338     p[0] = v;
19339     return 1;
19340   }
19341 #endif
19342   if( (v & ~0x3fff)==0 ){
19343     p[0] = (v>>7) | 0x80;
19344     p[1] = v & 0x7f;
19345     return 2;
19346   }
19347   return sqlite3PutVarint(p, v);
19348 }
19349
19350 /*
19351 ** Read a 64-bit variable-length integer from memory starting at p[0].
19352 ** Return the number of bytes read.  The value is stored in *v.
19353 */
19354 SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
19355   u32 a,b,s;
19356
19357   a = *p;
19358   /* a: p0 (unmasked) */
19359   if (!(a&0x80))
19360   {
19361     *v = a;
19362     return 1;
19363   }
19364
19365   p++;
19366   b = *p;
19367   /* b: p1 (unmasked) */
19368   if (!(b&0x80))
19369   {
19370     a &= 0x7f;
19371     a = a<<7;
19372     a |= b;
19373     *v = a;
19374     return 2;
19375   }
19376
19377   p++;
19378   a = a<<14;
19379   a |= *p;
19380   /* a: p0<<14 | p2 (unmasked) */
19381   if (!(a&0x80))
19382   {
19383     a &= (0x7f<<14)|(0x7f);
19384     b &= 0x7f;
19385     b = b<<7;
19386     a |= b;
19387     *v = a;
19388     return 3;
19389   }
19390
19391   /* CSE1 from below */
19392   a &= (0x7f<<14)|(0x7f);
19393   p++;
19394   b = b<<14;
19395   b |= *p;
19396   /* b: p1<<14 | p3 (unmasked) */
19397   if (!(b&0x80))
19398   {
19399     b &= (0x7f<<14)|(0x7f);
19400     /* moved CSE1 up */
19401     /* a &= (0x7f<<14)|(0x7f); */
19402     a = a<<7;
19403     a |= b;
19404     *v = a;
19405     return 4;
19406   }
19407
19408   /* a: p0<<14 | p2 (masked) */
19409   /* b: p1<<14 | p3 (unmasked) */
19410   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19411   /* moved CSE1 up */
19412   /* a &= (0x7f<<14)|(0x7f); */
19413   b &= (0x7f<<14)|(0x7f);
19414   s = a;
19415   /* s: p0<<14 | p2 (masked) */
19416
19417   p++;
19418   a = a<<14;
19419   a |= *p;
19420   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19421   if (!(a&0x80))
19422   {
19423     /* we can skip these cause they were (effectively) done above in calc'ing s */
19424     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19425     /* b &= (0x7f<<14)|(0x7f); */
19426     b = b<<7;
19427     a |= b;
19428     s = s>>18;
19429     *v = ((u64)s)<<32 | a;
19430     return 5;
19431   }
19432
19433   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19434   s = s<<7;
19435   s |= b;
19436   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19437
19438   p++;
19439   b = b<<14;
19440   b |= *p;
19441   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19442   if (!(b&0x80))
19443   {
19444     /* we can skip this cause it was (effectively) done above in calc'ing s */
19445     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19446     a &= (0x7f<<14)|(0x7f);
19447     a = a<<7;
19448     a |= b;
19449     s = s>>18;
19450     *v = ((u64)s)<<32 | a;
19451     return 6;
19452   }
19453
19454   p++;
19455   a = a<<14;
19456   a |= *p;
19457   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19458   if (!(a&0x80))
19459   {
19460     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19461     b &= (0x7f<<14)|(0x7f);
19462     b = b<<7;
19463     a |= b;
19464     s = s>>11;
19465     *v = ((u64)s)<<32 | a;
19466     return 7;
19467   }
19468
19469   /* CSE2 from below */
19470   a &= (0x7f<<14)|(0x7f);
19471   p++;
19472   b = b<<14;
19473   b |= *p;
19474   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19475   if (!(b&0x80))
19476   {
19477     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19478     /* moved CSE2 up */
19479     /* a &= (0x7f<<14)|(0x7f); */
19480     a = a<<7;
19481     a |= b;
19482     s = s>>4;
19483     *v = ((u64)s)<<32 | a;
19484     return 8;
19485   }
19486
19487   p++;
19488   a = a<<15;
19489   a |= *p;
19490   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19491
19492   /* moved CSE2 up */
19493   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19494   b &= (0x7f<<14)|(0x7f);
19495   b = b<<8;
19496   a |= b;
19497
19498   s = s<<4;
19499   b = p[-4];
19500   b &= 0x7f;
19501   b = b>>3;
19502   s |= b;
19503
19504   *v = ((u64)s)<<32 | a;
19505
19506   return 9;
19507 }
19508
19509 /*
19510 ** Read a 32-bit variable-length integer from memory starting at p[0].
19511 ** Return the number of bytes read.  The value is stored in *v.
19512 ** A MACRO version, getVarint32, is provided which inlines the 
19513 ** single-byte case.  All code should use the MACRO version as 
19514 ** this function assumes the single-byte case has already been handled.
19515 */
19516 SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
19517   u32 a,b;
19518
19519   a = *p;
19520   /* a: p0 (unmasked) */
19521 #ifndef getVarint32
19522   if (!(a&0x80))
19523   {
19524     *v = a;
19525     return 1;
19526   }
19527 #endif
19528
19529   p++;
19530   b = *p;
19531   /* b: p1 (unmasked) */
19532   if (!(b&0x80))
19533   {
19534     a &= 0x7f;
19535     a = a<<7;
19536     *v = a | b;
19537     return 2;
19538   }
19539
19540   p++;
19541   a = a<<14;
19542   a |= *p;
19543   /* a: p0<<14 | p2 (unmasked) */
19544   if (!(a&0x80))
19545   {
19546     a &= (0x7f<<14)|(0x7f);
19547     b &= 0x7f;
19548     b = b<<7;
19549     *v = a | b;
19550     return 3;
19551   }
19552
19553   p++;
19554   b = b<<14;
19555   b |= *p;
19556   /* b: p1<<14 | p3 (unmasked) */
19557   if (!(b&0x80))
19558   {
19559     b &= (0x7f<<14)|(0x7f);
19560     a &= (0x7f<<14)|(0x7f);
19561     a = a<<7;
19562     *v = a | b;
19563     return 4;
19564   }
19565
19566   p++;
19567   a = a<<14;
19568   a |= *p;
19569   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19570   if (!(a&0x80))
19571   {
19572     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19573     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19574     b = b<<7;
19575     *v = a | b;
19576     return 5;
19577   }
19578
19579   /* We can only reach this point when reading a corrupt database
19580   ** file.  In that case we are not in any hurry.  Use the (relatively
19581   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19582   ** value. */
19583   {
19584     u64 v64;
19585     int n;
19586
19587     p -= 4;
19588     n = sqlite3GetVarint(p, &v64);
19589     assert( n>5 && n<=9 );
19590     *v = (u32)v64;
19591     return n;
19592   }
19593 }
19594
19595 /*
19596 ** Return the number of bytes that will be needed to store the given
19597 ** 64-bit integer.
19598 */
19599 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19600   int i = 0;
19601   do{
19602     i++;
19603     v >>= 7;
19604   }while( v!=0 && i<9 );
19605   return i;
19606 }
19607
19608
19609 /*
19610 ** Read or write a four-byte big-endian integer value.
19611 */
19612 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19613   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19614 }
19615 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19616   p[0] = v>>24;
19617   p[1] = v>>16;
19618   p[2] = v>>8;
19619   p[3] = v;
19620 }
19621
19622
19623
19624 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19625 /*
19626 ** Translate a single byte of Hex into an integer.
19627 ** This routinen only works if h really is a valid hexadecimal
19628 ** character:  0..9a..fA..F
19629 */
19630 static int hexToInt(int h){
19631   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19632 #ifdef SQLITE_ASCII
19633   h += 9*(1&(h>>6));
19634 #endif
19635 #ifdef SQLITE_EBCDIC
19636   h += 9*(1&~(h>>4));
19637 #endif
19638   return h & 0xf;
19639 }
19640 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19641
19642 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19643 /*
19644 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19645 ** value.  Return a pointer to its binary value.  Space to hold the
19646 ** binary value has been obtained from malloc and must be freed by
19647 ** the calling routine.
19648 */
19649 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19650   char *zBlob;
19651   int i;
19652
19653   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19654   n--;
19655   if( zBlob ){
19656     for(i=0; i<n; i+=2){
19657       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19658     }
19659     zBlob[i/2] = 0;
19660   }
19661   return zBlob;
19662 }
19663 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19664
19665
19666 /*
19667 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19668 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19669 ** when this routine is called.
19670 **
19671 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19672 ** value indicates that the database connection passed into the API is
19673 ** open and is not being used by another thread.  By changing the value
19674 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19675 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19676 ** when the API exits. 
19677 **
19678 ** This routine is a attempt to detect if two threads use the
19679 ** same sqlite* pointer at the same time.  There is a race 
19680 ** condition so it is possible that the error is not detected.
19681 ** But usually the problem will be seen.  The result will be an
19682 ** error which can be used to debug the application that is
19683 ** using SQLite incorrectly.
19684 **
19685 ** Ticket #202:  If db->magic is not a valid open value, take care not
19686 ** to modify the db structure at all.  It could be that db is a stale
19687 ** pointer.  In other words, it could be that there has been a prior
19688 ** call to sqlite3_close(db) and db has been deallocated.  And we do
19689 ** not want to write into deallocated memory.
19690 */
19691 #ifdef SQLITE_DEBUG
19692 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19693   if( db->magic==SQLITE_MAGIC_OPEN ){
19694     db->magic = SQLITE_MAGIC_BUSY;
19695     assert( sqlite3_mutex_held(db->mutex) );
19696     return 0;
19697   }else if( db->magic==SQLITE_MAGIC_BUSY ){
19698     db->magic = SQLITE_MAGIC_ERROR;
19699     db->u1.isInterrupted = 1;
19700   }
19701   return 1;
19702 }
19703 #endif
19704
19705 /*
19706 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19707 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19708 ** when this routine is called.
19709 */
19710 #ifdef SQLITE_DEBUG
19711 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19712   if( db->magic==SQLITE_MAGIC_BUSY ){
19713     db->magic = SQLITE_MAGIC_OPEN;
19714     assert( sqlite3_mutex_held(db->mutex) );
19715     return 0;
19716   }else{
19717     db->magic = SQLITE_MAGIC_ERROR;
19718     db->u1.isInterrupted = 1;
19719     return 1;
19720   }
19721 }
19722 #endif
19723
19724 /*
19725 ** Check to make sure we have a valid db pointer.  This test is not
19726 ** foolproof but it does provide some measure of protection against
19727 ** misuse of the interface such as passing in db pointers that are
19728 ** NULL or which have been previously closed.  If this routine returns
19729 ** 1 it means that the db pointer is valid and 0 if it should not be
19730 ** dereferenced for any reason.  The calling function should invoke
19731 ** SQLITE_MISUSE immediately.
19732 **
19733 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19734 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19735 ** open properly and is not fit for general use but which can be
19736 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19737 */
19738 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19739   int magic;
19740   if( db==0 ) return 0;
19741   magic = db->magic;
19742   if( magic!=SQLITE_MAGIC_OPEN &&
19743       magic!=SQLITE_MAGIC_BUSY ) return 0;
19744   return 1;
19745 }
19746 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19747   int magic;
19748   if( db==0 ) return 0;
19749   magic = db->magic;
19750   if( magic!=SQLITE_MAGIC_SICK &&
19751       magic!=SQLITE_MAGIC_OPEN &&
19752       magic!=SQLITE_MAGIC_BUSY ) return 0;
19753   return 1;
19754 }
19755
19756 /************** End of util.c ************************************************/
19757 /************** Begin file hash.c ********************************************/
19758 /*
19759 ** 2001 September 22
19760 **
19761 ** The author disclaims copyright to this source code.  In place of
19762 ** a legal notice, here is a blessing:
19763 **
19764 **    May you do good and not evil.
19765 **    May you find forgiveness for yourself and forgive others.
19766 **    May you share freely, never taking more than you give.
19767 **
19768 *************************************************************************
19769 ** This is the implementation of generic hash-tables
19770 ** used in SQLite.
19771 **
19772 ** $Id: hash.c,v 1.31 2008/10/10 17:41:29 drh Exp $
19773 */
19774
19775 /* Turn bulk memory into a hash table object by initializing the
19776 ** fields of the Hash structure.
19777 **
19778 ** "pNew" is a pointer to the hash table that is to be initialized.
19779 ** "copyKey" is true if the hash table should make its own private
19780 ** copy of keys and false if it should just use the supplied pointer.
19781 */
19782 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
19783   assert( pNew!=0 );
19784   pNew->copyKey = copyKey!=0;
19785   pNew->first = 0;
19786   pNew->count = 0;
19787   pNew->htsize = 0;
19788   pNew->ht = 0;
19789 }
19790
19791 /* Remove all entries from a hash table.  Reclaim all memory.
19792 ** Call this routine to delete a hash table or to reset a hash table
19793 ** to the empty state.
19794 */
19795 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19796   HashElem *elem;         /* For looping over all elements of the table */
19797
19798   assert( pH!=0 );
19799   elem = pH->first;
19800   pH->first = 0;
19801   sqlite3_free(pH->ht);
19802   pH->ht = 0;
19803   pH->htsize = 0;
19804   while( elem ){
19805     HashElem *next_elem = elem->next;
19806     if( pH->copyKey && elem->pKey ){
19807       sqlite3_free(elem->pKey);
19808     }
19809     sqlite3_free(elem);
19810     elem = next_elem;
19811   }
19812   pH->count = 0;
19813 }
19814
19815 /*
19816 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
19817 */
19818 static int strHash(const void *pKey, int nKey){
19819   const char *z = (const char *)pKey;
19820   int h = 0;
19821   if( nKey<=0 ) nKey = strlen(z);
19822   while( nKey > 0  ){
19823     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19824     nKey--;
19825   }
19826   return h & 0x7fffffff;
19827 }
19828 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
19829   if( n1!=n2 ) return 1;
19830   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
19831 }
19832
19833
19834 /* Link an element into the hash table
19835 */
19836 static void insertElement(
19837   Hash *pH,              /* The complete hash table */
19838   struct _ht *pEntry,    /* The entry into which pNew is inserted */
19839   HashElem *pNew         /* The element to be inserted */
19840 ){
19841   HashElem *pHead;       /* First element already in pEntry */
19842   pHead = pEntry->chain;
19843   if( pHead ){
19844     pNew->next = pHead;
19845     pNew->prev = pHead->prev;
19846     if( pHead->prev ){ pHead->prev->next = pNew; }
19847     else             { pH->first = pNew; }
19848     pHead->prev = pNew;
19849   }else{
19850     pNew->next = pH->first;
19851     if( pH->first ){ pH->first->prev = pNew; }
19852     pNew->prev = 0;
19853     pH->first = pNew;
19854   }
19855   pEntry->count++;
19856   pEntry->chain = pNew;
19857 }
19858
19859
19860 /* Resize the hash table so that it cantains "new_size" buckets.
19861 ** "new_size" must be a power of 2.  The hash table might fail 
19862 ** to resize if sqlite3_malloc() fails.
19863 */
19864 static void rehash(Hash *pH, int new_size){
19865   struct _ht *new_ht;            /* The new hash table */
19866   HashElem *elem, *next_elem;    /* For looping over existing elements */
19867
19868 #ifdef SQLITE_MALLOC_SOFT_LIMIT
19869   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19870     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19871   }
19872   if( new_size==pH->htsize ) return;
19873 #endif
19874
19875   /* There is a call to sqlite3_malloc() inside rehash(). If there is
19876   ** already an allocation at pH->ht, then if this malloc() fails it
19877   ** is benign (since failing to resize a hash table is a performance
19878   ** hit only, not a fatal error).
19879   */
19880   if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
19881   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
19882   if( pH->htsize>0 ) sqlite3EndBenignMalloc();
19883
19884   if( new_ht==0 ) return;
19885   sqlite3_free(pH->ht);
19886   pH->ht = new_ht;
19887   pH->htsize = new_size;
19888   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19889     int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
19890     next_elem = elem->next;
19891     insertElement(pH, &new_ht[h], elem);
19892   }
19893 }
19894
19895 /* This function (for internal use only) locates an element in an
19896 ** hash table that matches the given key.  The hash for this key has
19897 ** already been computed and is passed as the 4th parameter.
19898 */
19899 static HashElem *findElementGivenHash(
19900   const Hash *pH,     /* The pH to be searched */
19901   const void *pKey,   /* The key we are searching for */
19902   int nKey,
19903   int h               /* The hash for this key. */
19904 ){
19905   HashElem *elem;                /* Used to loop thru the element list */
19906   int count;                     /* Number of elements left to test */
19907
19908   if( pH->ht ){
19909     struct _ht *pEntry = &pH->ht[h];
19910     elem = pEntry->chain;
19911     count = pEntry->count;
19912     while( count-- && elem ){
19913       if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
19914         return elem;
19915       }
19916       elem = elem->next;
19917     }
19918   }
19919   return 0;
19920 }
19921
19922 /* Remove a single entry from the hash table given a pointer to that
19923 ** element and a hash on the element's key.
19924 */
19925 static void removeElementGivenHash(
19926   Hash *pH,         /* The pH containing "elem" */
19927   HashElem* elem,   /* The element to be removed from the pH */
19928   int h             /* Hash value for the element */
19929 ){
19930   struct _ht *pEntry;
19931   if( elem->prev ){
19932     elem->prev->next = elem->next; 
19933   }else{
19934     pH->first = elem->next;
19935   }
19936   if( elem->next ){
19937     elem->next->prev = elem->prev;
19938   }
19939   pEntry = &pH->ht[h];
19940   if( pEntry->chain==elem ){
19941     pEntry->chain = elem->next;
19942   }
19943   pEntry->count--;
19944   if( pEntry->count<=0 ){
19945     pEntry->chain = 0;
19946   }
19947   if( pH->copyKey ){
19948     sqlite3_free(elem->pKey);
19949   }
19950   sqlite3_free( elem );
19951   pH->count--;
19952   if( pH->count<=0 ){
19953     assert( pH->first==0 );
19954     assert( pH->count==0 );
19955     sqlite3HashClear(pH);
19956   }
19957 }
19958
19959 /* Attempt to locate an element of the hash table pH with a key
19960 ** that matches pKey,nKey.  Return a pointer to the corresponding 
19961 ** HashElem structure for this element if it is found, or NULL
19962 ** otherwise.
19963 */
19964 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
19965   int h;             /* A hash on key */
19966   HashElem *elem;    /* The element that matches key */
19967
19968   if( pH==0 || pH->ht==0 ) return 0;
19969   h = strHash(pKey,nKey);
19970   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
19971   return elem;
19972 }
19973
19974 /* Attempt to locate an element of the hash table pH with a key
19975 ** that matches pKey,nKey.  Return the data for this element if it is
19976 ** found, or NULL if there is no match.
19977 */
19978 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
19979   HashElem *elem;    /* The element that matches key */
19980   elem = sqlite3HashFindElem(pH, pKey, nKey);
19981   return elem ? elem->data : 0;
19982 }
19983
19984 /* Insert an element into the hash table pH.  The key is pKey,nKey
19985 ** and the data is "data".
19986 **
19987 ** If no element exists with a matching key, then a new
19988 ** element is created.  A copy of the key is made if the copyKey
19989 ** flag is set.  NULL is returned.
19990 **
19991 ** If another element already exists with the same key, then the
19992 ** new data replaces the old data and the old data is returned.
19993 ** The key is not copied in this instance.  If a malloc fails, then
19994 ** the new data is returned and the hash table is unchanged.
19995 **
19996 ** If the "data" parameter to this function is NULL, then the
19997 ** element corresponding to "key" is removed from the hash table.
19998 */
19999 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
20000   int hraw;             /* Raw hash value of the key */
20001   int h;                /* the hash of the key modulo hash table size */
20002   HashElem *elem;       /* Used to loop thru the element list */
20003   HashElem *new_elem;   /* New element added to the pH */
20004
20005   assert( pH!=0 );
20006   hraw = strHash(pKey, nKey);
20007   if( pH->htsize ){
20008     h = hraw % pH->htsize;
20009     elem = findElementGivenHash(pH,pKey,nKey,h);
20010     if( elem ){
20011       void *old_data = elem->data;
20012       if( data==0 ){
20013         removeElementGivenHash(pH,elem,h);
20014       }else{
20015         elem->data = data;
20016         if( !pH->copyKey ){
20017           elem->pKey = (void *)pKey;
20018         }
20019         assert(nKey==elem->nKey);
20020       }
20021       return old_data;
20022     }
20023   }
20024   if( data==0 ) return 0;
20025   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20026   if( new_elem==0 ) return data;
20027   if( pH->copyKey && pKey!=0 ){
20028     new_elem->pKey = sqlite3Malloc( nKey );
20029     if( new_elem->pKey==0 ){
20030       sqlite3_free(new_elem);
20031       return data;
20032     }
20033     memcpy((void*)new_elem->pKey, pKey, nKey);
20034   }else{
20035     new_elem->pKey = (void*)pKey;
20036   }
20037   new_elem->nKey = nKey;
20038   pH->count++;
20039   if( pH->htsize==0 ){
20040     rehash(pH, 128/sizeof(pH->ht[0]));
20041     if( pH->htsize==0 ){
20042       pH->count = 0;
20043       if( pH->copyKey ){
20044         sqlite3_free(new_elem->pKey);
20045       }
20046       sqlite3_free(new_elem);
20047       return data;
20048     }
20049   }
20050   if( pH->count > pH->htsize ){
20051     rehash(pH,pH->htsize*2);
20052   }
20053   assert( pH->htsize>0 );
20054   h = hraw % pH->htsize;
20055   insertElement(pH, &pH->ht[h], new_elem);
20056   new_elem->data = data;
20057   return 0;
20058 }
20059
20060 /************** End of hash.c ************************************************/
20061 /************** Begin file opcodes.c *****************************************/
20062 /* Automatically generated.  Do not edit */
20063 /* See the mkopcodec.awk script for details. */
20064 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20065 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20066  static const char *const azName[] = { "?",
20067      /*   1 */ "VNext",
20068      /*   2 */ "Affinity",
20069      /*   3 */ "Column",
20070      /*   4 */ "SetCookie",
20071      /*   5 */ "Sequence",
20072      /*   6 */ "MoveGt",
20073      /*   7 */ "RowKey",
20074      /*   8 */ "SCopy",
20075      /*   9 */ "OpenWrite",
20076      /*  10 */ "If",
20077      /*  11 */ "VRowid",
20078      /*  12 */ "CollSeq",
20079      /*  13 */ "OpenRead",
20080      /*  14 */ "Expire",
20081      /*  15 */ "AutoCommit",
20082      /*  16 */ "Not",
20083      /*  17 */ "Pagecount",
20084      /*  18 */ "IntegrityCk",
20085      /*  19 */ "Sort",
20086      /*  20 */ "Copy",
20087      /*  21 */ "Trace",
20088      /*  22 */ "Function",
20089      /*  23 */ "IfNeg",
20090      /*  24 */ "Noop",
20091      /*  25 */ "Return",
20092      /*  26 */ "NewRowid",
20093      /*  27 */ "Variable",
20094      /*  28 */ "String",
20095      /*  29 */ "RealAffinity",
20096      /*  30 */ "VRename",
20097      /*  31 */ "ParseSchema",
20098      /*  32 */ "VOpen",
20099      /*  33 */ "Close",
20100      /*  34 */ "CreateIndex",
20101      /*  35 */ "IsUnique",
20102      /*  36 */ "NotFound",
20103      /*  37 */ "Int64",
20104      /*  38 */ "MustBeInt",
20105      /*  39 */ "Halt",
20106      /*  40 */ "Rowid",
20107      /*  41 */ "IdxLT",
20108      /*  42 */ "AddImm",
20109      /*  43 */ "Statement",
20110      /*  44 */ "RowData",
20111      /*  45 */ "MemMax",
20112      /*  46 */ "NotExists",
20113      /*  47 */ "Gosub",
20114      /*  48 */ "Integer",
20115      /*  49 */ "Prev",
20116      /*  50 */ "VColumn",
20117      /*  51 */ "CreateTable",
20118      /*  52 */ "Last",
20119      /*  53 */ "IncrVacuum",
20120      /*  54 */ "IdxRowid",
20121      /*  55 */ "ResetCount",
20122      /*  56 */ "FifoWrite",
20123      /*  57 */ "ContextPush",
20124      /*  58 */ "Yield",
20125      /*  59 */ "DropTrigger",
20126      /*  60 */ "Or",
20127      /*  61 */ "And",
20128      /*  62 */ "DropIndex",
20129      /*  63 */ "IdxGE",
20130      /*  64 */ "IdxDelete",
20131      /*  65 */ "IsNull",
20132      /*  66 */ "NotNull",
20133      /*  67 */ "Ne",
20134      /*  68 */ "Eq",
20135      /*  69 */ "Gt",
20136      /*  70 */ "Le",
20137      /*  71 */ "Lt",
20138      /*  72 */ "Ge",
20139      /*  73 */ "Vacuum",
20140      /*  74 */ "BitAnd",
20141      /*  75 */ "BitOr",
20142      /*  76 */ "ShiftLeft",
20143      /*  77 */ "ShiftRight",
20144      /*  78 */ "Add",
20145      /*  79 */ "Subtract",
20146      /*  80 */ "Multiply",
20147      /*  81 */ "Divide",
20148      /*  82 */ "Remainder",
20149      /*  83 */ "Concat",
20150      /*  84 */ "MoveLe",
20151      /*  85 */ "IfNot",
20152      /*  86 */ "DropTable",
20153      /*  87 */ "BitNot",
20154      /*  88 */ "String8",
20155      /*  89 */ "MakeRecord",
20156      /*  90 */ "ResultRow",
20157      /*  91 */ "Delete",
20158      /*  92 */ "AggFinal",
20159      /*  93 */ "Compare",
20160      /*  94 */ "Goto",
20161      /*  95 */ "TableLock",
20162      /*  96 */ "FifoRead",
20163      /*  97 */ "Clear",
20164      /*  98 */ "MoveLt",
20165      /*  99 */ "VerifyCookie",
20166      /* 100 */ "AggStep",
20167      /* 101 */ "SetNumColumns",
20168      /* 102 */ "Transaction",
20169      /* 103 */ "VFilter",
20170      /* 104 */ "VDestroy",
20171      /* 105 */ "ContextPop",
20172      /* 106 */ "Next",
20173      /* 107 */ "IdxInsert",
20174      /* 108 */ "Insert",
20175      /* 109 */ "Destroy",
20176      /* 110 */ "ReadCookie",
20177      /* 111 */ "ForceInt",
20178      /* 112 */ "LoadAnalysis",
20179      /* 113 */ "Explain",
20180      /* 114 */ "OpenPseudo",
20181      /* 115 */ "OpenEphemeral",
20182      /* 116 */ "Null",
20183      /* 117 */ "Move",
20184      /* 118 */ "Blob",
20185      /* 119 */ "Rewind",
20186      /* 120 */ "MoveGe",
20187      /* 121 */ "VBegin",
20188      /* 122 */ "VUpdate",
20189      /* 123 */ "IfZero",
20190      /* 124 */ "VCreate",
20191      /* 125 */ "Found",
20192      /* 126 */ "Real",
20193      /* 127 */ "IfPos",
20194      /* 128 */ "NullRow",
20195      /* 129 */ "Jump",
20196      /* 130 */ "Permutation",
20197      /* 131 */ "NotUsed_131",
20198      /* 132 */ "NotUsed_132",
20199      /* 133 */ "NotUsed_133",
20200      /* 134 */ "NotUsed_134",
20201      /* 135 */ "NotUsed_135",
20202      /* 136 */ "NotUsed_136",
20203      /* 137 */ "NotUsed_137",
20204      /* 138 */ "NotUsed_138",
20205      /* 139 */ "ToText",
20206      /* 140 */ "ToBlob",
20207      /* 141 */ "ToNumeric",
20208      /* 142 */ "ToInt",
20209      /* 143 */ "ToReal",
20210   };
20211   return azName[i];
20212 }
20213 #endif
20214
20215 /************** End of opcodes.c *********************************************/
20216 /************** Begin file os_os2.c ******************************************/
20217 /*
20218 ** 2006 Feb 14
20219 **
20220 ** The author disclaims copyright to this source code.  In place of
20221 ** a legal notice, here is a blessing:
20222 **
20223 **    May you do good and not evil.
20224 **    May you find forgiveness for yourself and forgive others.
20225 **    May you share freely, never taking more than you give.
20226 **
20227 ******************************************************************************
20228 **
20229 ** This file contains code that is specific to OS/2.
20230 **
20231 ** $Id: os_os2.c,v 1.57 2008/10/13 21:46:47 pweilbacher Exp $
20232 */
20233
20234
20235 #if SQLITE_OS_OS2
20236
20237 /*
20238 ** A Note About Memory Allocation:
20239 **
20240 ** This driver uses malloc()/free() directly rather than going through
20241 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20242 ** are designed for use on embedded systems where memory is scarce and
20243 ** malloc failures happen frequently.  OS/2 does not typically run on
20244 ** embedded systems, and when it does the developers normally have bigger
20245 ** problems to worry about than running out of memory.  So there is not
20246 ** a compelling need to use the wrappers.
20247 **
20248 ** But there is a good reason to not use the wrappers.  If we use the
20249 ** wrappers then we will get simulated malloc() failures within this
20250 ** driver.  And that causes all kinds of problems for our tests.  We
20251 ** could enhance SQLite to deal with simulated malloc failures within
20252 ** the OS driver, but the code to deal with those failure would not
20253 ** be exercised on Linux (which does not need to malloc() in the driver)
20254 ** and so we would have difficulty writing coverage tests for that
20255 ** code.  Better to leave the code out, we think.
20256 **
20257 ** The point of this discussion is as follows:  When creating a new
20258 ** OS layer for an embedded system, if you use this file as an example,
20259 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20260 ** desktops but not so well in embedded systems.
20261 */
20262
20263 /*
20264 ** Macros used to determine whether or not to use threads.
20265 */
20266 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20267 # define SQLITE_OS2_THREADS 1
20268 #endif
20269
20270 /*
20271 ** Include code that is common to all os_*.c files
20272 */
20273 /************** Include os_common.h in the middle of os_os2.c ****************/
20274 /************** Begin file os_common.h ***************************************/
20275 /*
20276 ** 2004 May 22
20277 **
20278 ** The author disclaims copyright to this source code.  In place of
20279 ** a legal notice, here is a blessing:
20280 **
20281 **    May you do good and not evil.
20282 **    May you find forgiveness for yourself and forgive others.
20283 **    May you share freely, never taking more than you give.
20284 **
20285 ******************************************************************************
20286 **
20287 ** This file contains macros and a little bit of code that is common to
20288 ** all of the platform-specific files (os_*.c) and is #included into those
20289 ** files.
20290 **
20291 ** This file should be #included by the os_*.c files only.  It is not a
20292 ** general purpose header file.
20293 **
20294 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
20295 */
20296 #ifndef _OS_COMMON_H_
20297 #define _OS_COMMON_H_
20298
20299 /*
20300 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20301 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20302 ** switch.  The following code should catch this problem at compile-time.
20303 */
20304 #ifdef MEMORY_DEBUG
20305 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20306 #endif
20307
20308
20309 /*
20310  * When testing, this global variable stores the location of the
20311  * pending-byte in the database file.
20312  */
20313 #ifdef SQLITE_TEST
20314 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
20315 #endif
20316
20317 #ifdef SQLITE_DEBUG
20318 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20319 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20320 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20321 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20322 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20323 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20324 #define OSTRACE6(X,Y,Z,A,B,C) \
20325     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20326 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20327     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20328 #else
20329 #define OSTRACE1(X)
20330 #define OSTRACE2(X,Y)
20331 #define OSTRACE3(X,Y,Z)
20332 #define OSTRACE4(X,Y,Z,A)
20333 #define OSTRACE5(X,Y,Z,A,B)
20334 #define OSTRACE6(X,Y,Z,A,B,C)
20335 #define OSTRACE7(X,Y,Z,A,B,C,D)
20336 #endif
20337
20338 /*
20339 ** Macros for performance tracing.  Normally turned off.  Only works
20340 ** on i486 hardware.
20341 */
20342 #ifdef SQLITE_PERFORMANCE_TRACE
20343
20344 /* 
20345 ** hwtime.h contains inline assembler code for implementing 
20346 ** high-performance timing routines.
20347 */
20348 /************** Include hwtime.h in the middle of os_common.h ****************/
20349 /************** Begin file hwtime.h ******************************************/
20350 /*
20351 ** 2008 May 27
20352 **
20353 ** The author disclaims copyright to this source code.  In place of
20354 ** a legal notice, here is a blessing:
20355 **
20356 **    May you do good and not evil.
20357 **    May you find forgiveness for yourself and forgive others.
20358 **    May you share freely, never taking more than you give.
20359 **
20360 ******************************************************************************
20361 **
20362 ** This file contains inline asm code for retrieving "high-performance"
20363 ** counters for x86 class CPUs.
20364 **
20365 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
20366 */
20367 #ifndef _HWTIME_H_
20368 #define _HWTIME_H_
20369
20370 /*
20371 ** The following routine only works on pentium-class (or newer) processors.
20372 ** It uses the RDTSC opcode to read the cycle count value out of the
20373 ** processor and returns that value.  This can be used for high-res
20374 ** profiling.
20375 */
20376 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20377       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20378
20379   #if defined(__GNUC__)
20380
20381   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20382      unsigned int lo, hi;
20383      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20384      return (sqlite_uint64)hi << 32 | lo;
20385   }
20386
20387   #elif defined(_MSC_VER)
20388
20389   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20390      __asm {
20391         rdtsc
20392         ret       ; return value at EDX:EAX
20393      }
20394   }
20395
20396   #endif
20397
20398 #elif (defined(__GNUC__) && defined(__x86_64__))
20399
20400   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20401       unsigned long val;
20402       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20403       return val;
20404   }
20405  
20406 #elif (defined(__GNUC__) && defined(__ppc__))
20407
20408   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20409       unsigned long long retval;
20410       unsigned long junk;
20411       __asm__ __volatile__ ("\n\
20412           1:      mftbu   %1\n\
20413                   mftb    %L0\n\
20414                   mftbu   %0\n\
20415                   cmpw    %0,%1\n\
20416                   bne     1b"
20417                   : "=r" (retval), "=r" (junk));
20418       return retval;
20419   }
20420
20421 #else
20422
20423   #error Need implementation of sqlite3Hwtime() for your platform.
20424
20425   /*
20426   ** To compile without implementing sqlite3Hwtime() for your platform,
20427   ** you can remove the above #error and use the following
20428   ** stub function.  You will lose timing support for many
20429   ** of the debugging and testing utilities, but it should at
20430   ** least compile and run.
20431   */
20432 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20433
20434 #endif
20435
20436 #endif /* !defined(_HWTIME_H_) */
20437
20438 /************** End of hwtime.h **********************************************/
20439 /************** Continuing where we left off in os_common.h ******************/
20440
20441 static sqlite_uint64 g_start;
20442 static sqlite_uint64 g_elapsed;
20443 #define TIMER_START       g_start=sqlite3Hwtime()
20444 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20445 #define TIMER_ELAPSED     g_elapsed
20446 #else
20447 #define TIMER_START
20448 #define TIMER_END
20449 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20450 #endif
20451
20452 /*
20453 ** If we compile with the SQLITE_TEST macro set, then the following block
20454 ** of code will give us the ability to simulate a disk I/O error.  This
20455 ** is used for testing the I/O recovery logic.
20456 */
20457 #ifdef SQLITE_TEST
20458 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20459 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20460 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20461 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20462 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20463 SQLITE_API int sqlite3_diskfull_pending = 0;
20464 SQLITE_API int sqlite3_diskfull = 0;
20465 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20466 #define SimulateIOError(CODE)  \
20467   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20468        || sqlite3_io_error_pending-- == 1 )  \
20469               { local_ioerr(); CODE; }
20470 static void local_ioerr(){
20471   IOTRACE(("IOERR\n"));
20472   sqlite3_io_error_hit++;
20473   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20474 }
20475 #define SimulateDiskfullError(CODE) \
20476    if( sqlite3_diskfull_pending ){ \
20477      if( sqlite3_diskfull_pending == 1 ){ \
20478        local_ioerr(); \
20479        sqlite3_diskfull = 1; \
20480        sqlite3_io_error_hit = 1; \
20481        CODE; \
20482      }else{ \
20483        sqlite3_diskfull_pending--; \
20484      } \
20485    }
20486 #else
20487 #define SimulateIOErrorBenign(X)
20488 #define SimulateIOError(A)
20489 #define SimulateDiskfullError(A)
20490 #endif
20491
20492 /*
20493 ** When testing, keep a count of the number of open files.
20494 */
20495 #ifdef SQLITE_TEST
20496 SQLITE_API int sqlite3_open_file_count = 0;
20497 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20498 #else
20499 #define OpenCounter(X)
20500 #endif
20501
20502 #endif /* !defined(_OS_COMMON_H_) */
20503
20504 /************** End of os_common.h *******************************************/
20505 /************** Continuing where we left off in os_os2.c *********************/
20506
20507 /*
20508 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20509 ** protability layer.
20510 */
20511 typedef struct os2File os2File;
20512 struct os2File {
20513   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20514   HFILE h;                  /* Handle for accessing the file */
20515   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20516   unsigned char locktype;   /* Type of lock currently held on this file */
20517 };
20518
20519 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20520
20521 /*****************************************************************************
20522 ** The next group of routines implement the I/O methods specified
20523 ** by the sqlite3_io_methods object.
20524 ******************************************************************************/
20525
20526 /*
20527 ** Close a file.
20528 */
20529 static int os2Close( sqlite3_file *id ){
20530   APIRET rc = NO_ERROR;
20531   os2File *pFile;
20532   if( id && (pFile = (os2File*)id) != 0 ){
20533     OSTRACE2( "CLOSE %d\n", pFile->h );
20534     rc = DosClose( pFile->h );
20535     pFile->locktype = NO_LOCK;
20536     if( pFile->pathToDel != NULL ){
20537       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20538       free( pFile->pathToDel );
20539       pFile->pathToDel = NULL;
20540     }
20541     id = 0;
20542     OpenCounter( -1 );
20543   }
20544
20545   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20546 }
20547
20548 /*
20549 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20550 ** bytes were read successfully and SQLITE_IOERR if anything goes
20551 ** wrong.
20552 */
20553 static int os2Read(
20554   sqlite3_file *id,               /* File to read from */
20555   void *pBuf,                     /* Write content into this buffer */
20556   int amt,                        /* Number of bytes to read */
20557   sqlite3_int64 offset            /* Begin reading at this offset */
20558 ){
20559   ULONG fileLocation = 0L;
20560   ULONG got;
20561   os2File *pFile = (os2File*)id;
20562   assert( id!=0 );
20563   SimulateIOError( return SQLITE_IOERR_READ );
20564   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20565   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20566     return SQLITE_IOERR;
20567   }
20568   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20569     return SQLITE_IOERR_READ;
20570   }
20571   if( got == (ULONG)amt )
20572     return SQLITE_OK;
20573   else {
20574     memset(&((char*)pBuf)[got], 0, amt-got);
20575     return SQLITE_IOERR_SHORT_READ;
20576   }
20577 }
20578
20579 /*
20580 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20581 ** or some other error code on failure.
20582 */
20583 static int os2Write(
20584   sqlite3_file *id,               /* File to write into */
20585   const void *pBuf,               /* The bytes to be written */
20586   int amt,                        /* Number of bytes to write */
20587   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20588 ){
20589   ULONG fileLocation = 0L;
20590   APIRET rc = NO_ERROR;
20591   ULONG wrote;
20592   os2File *pFile = (os2File*)id;
20593   assert( id!=0 );
20594   SimulateIOError( return SQLITE_IOERR_WRITE );
20595   SimulateDiskfullError( return SQLITE_FULL );
20596   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20597   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20598     return SQLITE_IOERR;
20599   }
20600   assert( amt>0 );
20601   while( amt > 0 &&
20602          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20603          wrote > 0
20604   ){
20605     amt -= wrote;
20606     pBuf = &((char*)pBuf)[wrote];
20607   }
20608
20609   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20610 }
20611
20612 /*
20613 ** Truncate an open file to a specified size
20614 */
20615 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20616   APIRET rc = NO_ERROR;
20617   os2File *pFile = (os2File*)id;
20618   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20619   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20620   rc = DosSetFileSize( pFile->h, nByte );
20621   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20622 }
20623
20624 #ifdef SQLITE_TEST
20625 /*
20626 ** Count the number of fullsyncs and normal syncs.  This is used to test
20627 ** that syncs and fullsyncs are occuring at the right times.
20628 */
20629 SQLITE_API int sqlite3_sync_count = 0;
20630 SQLITE_API int sqlite3_fullsync_count = 0;
20631 #endif
20632
20633 /*
20634 ** Make sure all writes to a particular file are committed to disk.
20635 */
20636 static int os2Sync( sqlite3_file *id, int flags ){
20637   os2File *pFile = (os2File*)id;
20638   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20639 #ifdef SQLITE_TEST
20640   if( flags & SQLITE_SYNC_FULL){
20641     sqlite3_fullsync_count++;
20642   }
20643   sqlite3_sync_count++;
20644 #endif
20645   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20646 }
20647
20648 /*
20649 ** Determine the current size of a file in bytes
20650 */
20651 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20652   APIRET rc = NO_ERROR;
20653   FILESTATUS3 fsts3FileInfo;
20654   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20655   assert( id!=0 );
20656   SimulateIOError( return SQLITE_IOERR_FSTAT );
20657   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20658   if( rc == NO_ERROR ){
20659     *pSize = fsts3FileInfo.cbFile;
20660     return SQLITE_OK;
20661   }else{
20662     return SQLITE_IOERR_FSTAT;
20663   }
20664 }
20665
20666 /*
20667 ** Acquire a reader lock.
20668 */
20669 static int getReadLock( os2File *pFile ){
20670   FILELOCK  LockArea,
20671             UnlockArea;
20672   APIRET res;
20673   memset(&LockArea, 0, sizeof(LockArea));
20674   memset(&UnlockArea, 0, sizeof(UnlockArea));
20675   LockArea.lOffset = SHARED_FIRST;
20676   LockArea.lRange = SHARED_SIZE;
20677   UnlockArea.lOffset = 0L;
20678   UnlockArea.lRange = 0L;
20679   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20680   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20681   return res;
20682 }
20683
20684 /*
20685 ** Undo a readlock
20686 */
20687 static int unlockReadLock( os2File *id ){
20688   FILELOCK  LockArea,
20689             UnlockArea;
20690   APIRET res;
20691   memset(&LockArea, 0, sizeof(LockArea));
20692   memset(&UnlockArea, 0, sizeof(UnlockArea));
20693   LockArea.lOffset = 0L;
20694   LockArea.lRange = 0L;
20695   UnlockArea.lOffset = SHARED_FIRST;
20696   UnlockArea.lRange = SHARED_SIZE;
20697   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20698   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20699   return res;
20700 }
20701
20702 /*
20703 ** Lock the file with the lock specified by parameter locktype - one
20704 ** of the following:
20705 **
20706 **     (1) SHARED_LOCK
20707 **     (2) RESERVED_LOCK
20708 **     (3) PENDING_LOCK
20709 **     (4) EXCLUSIVE_LOCK
20710 **
20711 ** Sometimes when requesting one lock state, additional lock states
20712 ** are inserted in between.  The locking might fail on one of the later
20713 ** transitions leaving the lock state different from what it started but
20714 ** still short of its goal.  The following chart shows the allowed
20715 ** transitions and the inserted intermediate states:
20716 **
20717 **    UNLOCKED -> SHARED
20718 **    SHARED -> RESERVED
20719 **    SHARED -> (PENDING) -> EXCLUSIVE
20720 **    RESERVED -> (PENDING) -> EXCLUSIVE
20721 **    PENDING -> EXCLUSIVE
20722 **
20723 ** This routine will only increase a lock.  The os2Unlock() routine
20724 ** erases all locks at once and returns us immediately to locking level 0.
20725 ** It is not possible to lower the locking level one step at a time.  You
20726 ** must go straight to locking level 0.
20727 */
20728 static int os2Lock( sqlite3_file *id, int locktype ){
20729   int rc = SQLITE_OK;       /* Return code from subroutines */
20730   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20731   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20732   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20733   FILELOCK  LockArea,
20734             UnlockArea;
20735   os2File *pFile = (os2File*)id;
20736   memset(&LockArea, 0, sizeof(LockArea));
20737   memset(&UnlockArea, 0, sizeof(UnlockArea));
20738   assert( pFile!=0 );
20739   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20740
20741   /* If there is already a lock of this type or more restrictive on the
20742   ** os2File, do nothing. Don't use the end_lock: exit path, as
20743   ** sqlite3_mutex_enter() hasn't been called yet.
20744   */
20745   if( pFile->locktype>=locktype ){
20746     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20747     return SQLITE_OK;
20748   }
20749
20750   /* Make sure the locking sequence is correct
20751   */
20752   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20753   assert( locktype!=PENDING_LOCK );
20754   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20755
20756   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20757   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20758   ** the PENDING_LOCK byte is temporary.
20759   */
20760   newLocktype = pFile->locktype;
20761   if( pFile->locktype==NO_LOCK
20762       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20763   ){
20764     LockArea.lOffset = PENDING_BYTE;
20765     LockArea.lRange = 1L;
20766     UnlockArea.lOffset = 0L;
20767     UnlockArea.lRange = 0L;
20768
20769     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20770     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20771     if( res == NO_ERROR ){
20772       gotPendingLock = 1;
20773       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20774     }
20775   }
20776
20777   /* Acquire a shared lock
20778   */
20779   if( locktype==SHARED_LOCK && res == NO_ERROR ){
20780     assert( pFile->locktype==NO_LOCK );
20781     res = getReadLock(pFile);
20782     if( res == NO_ERROR ){
20783       newLocktype = SHARED_LOCK;
20784     }
20785     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20786   }
20787
20788   /* Acquire a RESERVED lock
20789   */
20790   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20791     assert( pFile->locktype==SHARED_LOCK );
20792     LockArea.lOffset = RESERVED_BYTE;
20793     LockArea.lRange = 1L;
20794     UnlockArea.lOffset = 0L;
20795     UnlockArea.lRange = 0L;
20796     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20797     if( res == NO_ERROR ){
20798       newLocktype = RESERVED_LOCK;
20799     }
20800     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20801   }
20802
20803   /* Acquire a PENDING lock
20804   */
20805   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20806     newLocktype = PENDING_LOCK;
20807     gotPendingLock = 0;
20808     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20809   }
20810
20811   /* Acquire an EXCLUSIVE lock
20812   */
20813   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20814     assert( pFile->locktype>=SHARED_LOCK );
20815     res = unlockReadLock(pFile);
20816     OSTRACE2( "unreadlock = %d\n", res );
20817     LockArea.lOffset = SHARED_FIRST;
20818     LockArea.lRange = SHARED_SIZE;
20819     UnlockArea.lOffset = 0L;
20820     UnlockArea.lRange = 0L;
20821     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20822     if( res == NO_ERROR ){
20823       newLocktype = EXCLUSIVE_LOCK;
20824     }else{
20825       OSTRACE2( "OS/2 error-code = %d\n", res );
20826       getReadLock(pFile);
20827     }
20828     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20829   }
20830
20831   /* If we are holding a PENDING lock that ought to be released, then
20832   ** release it now.
20833   */
20834   if( gotPendingLock && locktype==SHARED_LOCK ){
20835     int r;
20836     LockArea.lOffset = 0L;
20837     LockArea.lRange = 0L;
20838     UnlockArea.lOffset = PENDING_BYTE;
20839     UnlockArea.lRange = 1L;
20840     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20841     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20842   }
20843
20844   /* Update the state of the lock has held in the file descriptor then
20845   ** return the appropriate result code.
20846   */
20847   if( res == NO_ERROR ){
20848     rc = SQLITE_OK;
20849   }else{
20850     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20851               locktype, newLocktype );
20852     rc = SQLITE_BUSY;
20853   }
20854   pFile->locktype = newLocktype;
20855   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20856   return rc;
20857 }
20858
20859 /*
20860 ** This routine checks if there is a RESERVED lock held on the specified
20861 ** file by this or any other process. If such a lock is held, return
20862 ** non-zero, otherwise zero.
20863 */
20864 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20865   int r = 0;
20866   os2File *pFile = (os2File*)id;
20867   assert( pFile!=0 );
20868   if( pFile->locktype>=RESERVED_LOCK ){
20869     r = 1;
20870     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20871   }else{
20872     FILELOCK  LockArea,
20873               UnlockArea;
20874     APIRET rc = NO_ERROR;
20875     memset(&LockArea, 0, sizeof(LockArea));
20876     memset(&UnlockArea, 0, sizeof(UnlockArea));
20877     LockArea.lOffset = RESERVED_BYTE;
20878     LockArea.lRange = 1L;
20879     UnlockArea.lOffset = 0L;
20880     UnlockArea.lRange = 0L;
20881     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20882     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20883     if( rc == NO_ERROR ){
20884       APIRET rcu = NO_ERROR; /* return code for unlocking */
20885       LockArea.lOffset = 0L;
20886       LockArea.lRange = 0L;
20887       UnlockArea.lOffset = RESERVED_BYTE;
20888       UnlockArea.lRange = 1L;
20889       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20890       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20891     }
20892     r = !(rc == NO_ERROR);
20893     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20894   }
20895   *pOut = r;
20896   return SQLITE_OK;
20897 }
20898
20899 /*
20900 ** Lower the locking level on file descriptor id to locktype.  locktype
20901 ** must be either NO_LOCK or SHARED_LOCK.
20902 **
20903 ** If the locking level of the file descriptor is already at or below
20904 ** the requested locking level, this routine is a no-op.
20905 **
20906 ** It is not possible for this routine to fail if the second argument
20907 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20908 ** might return SQLITE_IOERR;
20909 */
20910 static int os2Unlock( sqlite3_file *id, int locktype ){
20911   int type;
20912   os2File *pFile = (os2File*)id;
20913   APIRET rc = SQLITE_OK;
20914   APIRET res = NO_ERROR;
20915   FILELOCK  LockArea,
20916             UnlockArea;
20917   memset(&LockArea, 0, sizeof(LockArea));
20918   memset(&UnlockArea, 0, sizeof(UnlockArea));
20919   assert( pFile!=0 );
20920   assert( locktype<=SHARED_LOCK );
20921   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20922   type = pFile->locktype;
20923   if( type>=EXCLUSIVE_LOCK ){
20924     LockArea.lOffset = 0L;
20925     LockArea.lRange = 0L;
20926     UnlockArea.lOffset = SHARED_FIRST;
20927     UnlockArea.lRange = SHARED_SIZE;
20928     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20929     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20930     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20931       /* This should never happen.  We should always be able to
20932       ** reacquire the read lock */
20933       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20934       rc = SQLITE_IOERR_UNLOCK;
20935     }
20936   }
20937   if( type>=RESERVED_LOCK ){
20938     LockArea.lOffset = 0L;
20939     LockArea.lRange = 0L;
20940     UnlockArea.lOffset = RESERVED_BYTE;
20941     UnlockArea.lRange = 1L;
20942     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20943     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20944   }
20945   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20946     res = unlockReadLock(pFile);
20947     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20948   }
20949   if( type>=PENDING_LOCK ){
20950     LockArea.lOffset = 0L;
20951     LockArea.lRange = 0L;
20952     UnlockArea.lOffset = PENDING_BYTE;
20953     UnlockArea.lRange = 1L;
20954     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20955     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20956   }
20957   pFile->locktype = locktype;
20958   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20959   return rc;
20960 }
20961
20962 /*
20963 ** Control and query of the open file handle.
20964 */
20965 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20966   switch( op ){
20967     case SQLITE_FCNTL_LOCKSTATE: {
20968       *(int*)pArg = ((os2File*)id)->locktype;
20969       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20970       return SQLITE_OK;
20971     }
20972   }
20973   return SQLITE_ERROR;
20974 }
20975
20976 /*
20977 ** Return the sector size in bytes of the underlying block device for
20978 ** the specified file. This is almost always 512 bytes, but may be
20979 ** larger for some devices.
20980 **
20981 ** SQLite code assumes this function cannot fail. It also assumes that
20982 ** if two files are created in the same file-system directory (i.e.
20983 ** a database and its journal file) that the sector size will be the
20984 ** same for both.
20985 */
20986 static int os2SectorSize(sqlite3_file *id){
20987   return SQLITE_DEFAULT_SECTOR_SIZE;
20988 }
20989
20990 /*
20991 ** Return a vector of device characteristics.
20992 */
20993 static int os2DeviceCharacteristics(sqlite3_file *id){
20994   return 0;
20995 }
20996
20997
20998 /*
20999 ** Character set conversion objects used by conversion routines.
21000 */
21001 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21002 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21003
21004 /*
21005 ** Helper function to initialize the conversion objects from and to UTF-8.
21006 */
21007 static void initUconvObjects( void ){
21008   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21009     ucUtf8 = NULL;
21010   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21011     uclCp = NULL;
21012 }
21013
21014 /*
21015 ** Helper function to free the conversion objects from and to UTF-8.
21016 */
21017 static void freeUconvObjects( void ){
21018   if ( ucUtf8 )
21019     UniFreeUconvObject( ucUtf8 );
21020   if ( uclCp )
21021     UniFreeUconvObject( uclCp );
21022   ucUtf8 = NULL;
21023   uclCp = NULL;
21024 }
21025
21026 /*
21027 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21028 ** The two-step process: first convert the incoming UTF-8 string
21029 ** into UCS-2 and then from UCS-2 to the current codepage.
21030 ** The returned char pointer has to be freed.
21031 */
21032 static char *convertUtf8PathToCp( const char *in ){
21033   UniChar tempPath[CCHMAXPATH];
21034   char *out = (char *)calloc( CCHMAXPATH, 1 );
21035
21036   if( !out )
21037     return NULL;
21038
21039   if( !ucUtf8 || !uclCp )
21040     initUconvObjects();
21041
21042   /* determine string for the conversion of UTF-8 which is CP1208 */
21043   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21044     return out; /* if conversion fails, return the empty string */
21045
21046   /* conversion for current codepage which can be used for paths */
21047   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21048
21049   return out;
21050 }
21051
21052 /*
21053 ** Helper function to convert filenames from local codepage to UTF-8.
21054 ** The two-step process: first convert the incoming codepage-specific
21055 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21056 ** The returned char pointer has to be freed.
21057 **
21058 ** This function is non-static to be able to use this in shell.c and
21059 ** similar applications that take command line arguments.
21060 */
21061 char *convertCpPathToUtf8( const char *in ){
21062   UniChar tempPath[CCHMAXPATH];
21063   char *out = (char *)calloc( CCHMAXPATH, 1 );
21064
21065   if( !out )
21066     return NULL;
21067
21068   if( !ucUtf8 || !uclCp )
21069     initUconvObjects();
21070
21071   /* conversion for current codepage which can be used for paths */
21072   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21073     return out; /* if conversion fails, return the empty string */
21074
21075   /* determine string for the conversion of UTF-8 which is CP1208 */
21076   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21077
21078   return out;
21079 }
21080
21081 /*
21082 ** This vector defines all the methods that can operate on an
21083 ** sqlite3_file for os2.
21084 */
21085 static const sqlite3_io_methods os2IoMethod = {
21086   1,                        /* iVersion */
21087   os2Close,
21088   os2Read,
21089   os2Write,
21090   os2Truncate,
21091   os2Sync,
21092   os2FileSize,
21093   os2Lock,
21094   os2Unlock,
21095   os2CheckReservedLock,
21096   os2FileControl,
21097   os2SectorSize,
21098   os2DeviceCharacteristics
21099 };
21100
21101 /***************************************************************************
21102 ** Here ends the I/O methods that form the sqlite3_io_methods object.
21103 **
21104 ** The next block of code implements the VFS methods.
21105 ****************************************************************************/
21106
21107 /*
21108 ** Create a temporary file name in zBuf.  zBuf must be big enough to
21109 ** hold at pVfs->mxPathname characters.
21110 */
21111 static int getTempname(int nBuf, char *zBuf ){
21112   static const unsigned char zChars[] =
21113     "abcdefghijklmnopqrstuvwxyz"
21114     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21115     "0123456789";
21116   int i, j;
21117   char zTempPathBuf[3];
21118   PSZ zTempPath = (PSZ)&zTempPathBuf;
21119   if( sqlite3_temp_directory ){
21120     zTempPath = sqlite3_temp_directory;
21121   }else{
21122     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21123       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21124         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21125            ULONG ulDriveNum = 0, ulDriveMap = 0;
21126            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21127            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21128         }
21129       }
21130     }
21131   }
21132   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21133    * multiple (back)slashes which causes DosOpen() to fail.              *
21134    * Trailing spaces are not allowed, either.                            */
21135   j = strlen(zTempPath);
21136   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21137                     || zTempPath[j-1] == ' ' ) ){
21138     j--;
21139   }
21140   zTempPath[j] = '\0';
21141   if( !sqlite3_temp_directory ){
21142     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21143     sqlite3_snprintf( nBuf-30, zBuf,
21144                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21145     free( zTempPathUTF );
21146   }else{
21147     sqlite3_snprintf( nBuf-30, zBuf,
21148                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21149   }
21150   j = strlen( zBuf );
21151   sqlite3_randomness( 20, &zBuf[j] );
21152   for( i = 0; i < 20; i++, j++ ){
21153     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21154   }
21155   zBuf[j] = 0;
21156   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
21157   return SQLITE_OK;
21158 }
21159
21160
21161 /*
21162 ** Turn a relative pathname into a full pathname.  Write the full
21163 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21164 ** bytes in size.
21165 */
21166 static int os2FullPathname(
21167   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21168   const char *zRelative,      /* Possibly relative input path */
21169   int nFull,                  /* Size of output buffer in bytes */
21170   char *zFull                 /* Output buffer */
21171 ){
21172   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21173   char zFullCp[CCHMAXPATH] = "\0";
21174   char *zFullUTF;
21175   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21176                                 CCHMAXPATH );
21177   free( zRelativeCp );
21178   zFullUTF = convertCpPathToUtf8( zFullCp );
21179   sqlite3_snprintf( nFull, zFull, zFullUTF );
21180   free( zFullUTF );
21181   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21182 }
21183
21184
21185 /*
21186 ** Open a file.
21187 */
21188 static int os2Open(
21189   sqlite3_vfs *pVfs,            /* Not used */
21190   const char *zName,            /* Name of the file */
21191   sqlite3_file *id,             /* Write the SQLite file handle here */
21192   int flags,                    /* Open mode flags */
21193   int *pOutFlags                /* Status return flags */
21194 ){
21195   HFILE h;
21196   ULONG ulFileAttribute = FILE_NORMAL;
21197   ULONG ulOpenFlags = 0;
21198   ULONG ulOpenMode = 0;
21199   os2File *pFile = (os2File*)id;
21200   APIRET rc = NO_ERROR;
21201   ULONG ulAction;
21202   char *zNameCp;
21203   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21204
21205   /* If the second argument to this function is NULL, generate a 
21206   ** temporary file name to use 
21207   */
21208   if( !zName ){
21209     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21210     if( rc!=SQLITE_OK ){
21211       return rc;
21212     }
21213     zName = zTmpname;
21214   }
21215
21216
21217   memset( pFile, 0, sizeof(*pFile) );
21218
21219   OSTRACE2( "OPEN want %d\n", flags );
21220
21221   if( flags & SQLITE_OPEN_READWRITE ){
21222     ulOpenMode |= OPEN_ACCESS_READWRITE;
21223     OSTRACE1( "OPEN read/write\n" );
21224   }else{
21225     ulOpenMode |= OPEN_ACCESS_READONLY;
21226     OSTRACE1( "OPEN read only\n" );
21227   }
21228
21229   if( flags & SQLITE_OPEN_CREATE ){
21230     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21231     OSTRACE1( "OPEN open new/create\n" );
21232   }else{
21233     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21234     OSTRACE1( "OPEN open existing\n" );
21235   }
21236
21237   if( flags & SQLITE_OPEN_MAIN_DB ){
21238     ulOpenMode |= OPEN_SHARE_DENYNONE;
21239     OSTRACE1( "OPEN share read/write\n" );
21240   }else{
21241     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21242     OSTRACE1( "OPEN share read only\n" );
21243   }
21244
21245   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21246     char pathUtf8[CCHMAXPATH];
21247 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21248     ulFileAttribute = FILE_HIDDEN;
21249 #endif
21250     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21251     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21252     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21253   }else{
21254     pFile->pathToDel = NULL;
21255     OSTRACE1( "OPEN normal file attribute\n" );
21256   }
21257
21258   /* always open in random access mode for possibly better speed */
21259   ulOpenMode |= OPEN_FLAGS_RANDOM;
21260   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21261   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21262
21263   zNameCp = convertUtf8PathToCp( zName );
21264   rc = DosOpen( (PSZ)zNameCp,
21265                 &h,
21266                 &ulAction,
21267                 0L,
21268                 ulFileAttribute,
21269                 ulOpenFlags,
21270                 ulOpenMode,
21271                 (PEAOP2)NULL );
21272   free( zNameCp );
21273   if( rc != NO_ERROR ){
21274     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21275               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21276     if( pFile->pathToDel )
21277       free( pFile->pathToDel );
21278     pFile->pathToDel = NULL;
21279     if( flags & SQLITE_OPEN_READWRITE ){
21280       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21281       return os2Open( pVfs, zName, id,
21282                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21283                       pOutFlags );
21284     }else{
21285       return SQLITE_CANTOPEN;
21286     }
21287   }
21288
21289   if( pOutFlags ){
21290     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21291   }
21292
21293   pFile->pMethod = &os2IoMethod;
21294   pFile->h = h;
21295   OpenCounter(+1);
21296   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21297   return SQLITE_OK;
21298 }
21299
21300 /*
21301 ** Delete the named file.
21302 */
21303 static int os2Delete(
21304   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21305   const char *zFilename,                 /* Name of file to delete */
21306   int syncDir                            /* Not used on os2 */
21307 ){
21308   APIRET rc = NO_ERROR;
21309   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21310   SimulateIOError( return SQLITE_IOERR_DELETE );
21311   rc = DosDelete( (PSZ)zFilenameCp );
21312   free( zFilenameCp );
21313   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21314   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21315 }
21316
21317 /*
21318 ** Check the existance and status of a file.
21319 */
21320 static int os2Access(
21321   sqlite3_vfs *pVfs,        /* Not used on os2 */
21322   const char *zFilename,    /* Name of file to check */
21323   int flags,                /* Type of test to make on this file */
21324   int *pOut                 /* Write results here */
21325 ){
21326   FILESTATUS3 fsts3ConfigInfo;
21327   APIRET rc = NO_ERROR;
21328   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21329
21330   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21331   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21332                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21333   free( zFilenameCp );
21334   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21335             fsts3ConfigInfo.attrFile, flags, rc );
21336   switch( flags ){
21337     case SQLITE_ACCESS_READ:
21338     case SQLITE_ACCESS_EXISTS:
21339       rc = (rc == NO_ERROR);
21340       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21341       break;
21342     case SQLITE_ACCESS_READWRITE:
21343       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21344       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21345       break;
21346     default:
21347       assert( !"Invalid flags argument" );
21348   }
21349   *pOut = rc;
21350   return SQLITE_OK;
21351 }
21352
21353
21354 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21355 /*
21356 ** Interfaces for opening a shared library, finding entry points
21357 ** within the shared library, and closing the shared library.
21358 */
21359 /*
21360 ** Interfaces for opening a shared library, finding entry points
21361 ** within the shared library, and closing the shared library.
21362 */
21363 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21364   UCHAR loadErr[256];
21365   HMODULE hmod;
21366   APIRET rc;
21367   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21368   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21369   free(zFilenameCp);
21370   return rc != NO_ERROR ? 0 : (void*)hmod;
21371 }
21372 /*
21373 ** A no-op since the error code is returned on the DosLoadModule call.
21374 ** os2Dlopen returns zero if DosLoadModule is not successful.
21375 */
21376 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21377 /* no-op */
21378 }
21379 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21380   PFN pfn;
21381   APIRET rc;
21382   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21383   if( rc != NO_ERROR ){
21384     /* if the symbol itself was not found, search again for the same
21385      * symbol with an extra underscore, that might be needed depending
21386      * on the calling convention */
21387     char _zSymbol[256] = "_";
21388     strncat(_zSymbol, zSymbol, 255);
21389     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21390   }
21391   return rc != NO_ERROR ? 0 : (void*)pfn;
21392 }
21393 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21394   DosFreeModule((HMODULE)pHandle);
21395 }
21396 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21397   #define os2DlOpen 0
21398   #define os2DlError 0
21399   #define os2DlSym 0
21400   #define os2DlClose 0
21401 #endif
21402
21403
21404 /*
21405 ** Write up to nBuf bytes of randomness into zBuf.
21406 */
21407 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21408   ULONG sizeofULong = sizeof(ULONG);
21409   int n = 0;
21410   if( sizeof(DATETIME) <= nBuf - n ){
21411     DATETIME x;
21412     DosGetDateTime(&x);
21413     memcpy(&zBuf[n], &x, sizeof(x));
21414     n += sizeof(x);
21415   }
21416
21417   if( sizeofULong <= nBuf - n ){
21418     PPIB ppib;
21419     DosGetInfoBlocks(NULL, &ppib);
21420     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21421     n += sizeofULong;
21422   }
21423
21424   if( sizeofULong <= nBuf - n ){
21425     PTIB ptib;
21426     DosGetInfoBlocks(&ptib, NULL);
21427     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21428     n += sizeofULong;
21429   }
21430
21431   /* if we still haven't filled the buffer yet the following will */
21432   /* grab everything once instead of making several calls for a single item */
21433   if( sizeofULong <= nBuf - n ){
21434     ULONG ulSysInfo[QSV_MAX];
21435     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21436
21437     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21438     n += sizeofULong;
21439
21440     if( sizeofULong <= nBuf - n ){
21441       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21442       n += sizeofULong;
21443     }
21444     if( sizeofULong <= nBuf - n ){
21445       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21446       n += sizeofULong;
21447     }
21448     if( sizeofULong <= nBuf - n ){
21449       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21450       n += sizeofULong;
21451     }
21452     if( sizeofULong <= nBuf - n ){
21453       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21454       n += sizeofULong;
21455     }
21456   }
21457
21458   return n;
21459 }
21460
21461 /*
21462 ** Sleep for a little while.  Return the amount of time slept.
21463 ** The argument is the number of microseconds we want to sleep.
21464 ** The return value is the number of microseconds of sleep actually
21465 ** requested from the underlying operating system, a number which
21466 ** might be greater than or equal to the argument, but not less
21467 ** than the argument.
21468 */
21469 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21470   DosSleep( (microsec/1000) );
21471   return microsec;
21472 }
21473
21474 /*
21475 ** The following variable, if set to a non-zero value, becomes the result
21476 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21477 */
21478 #ifdef SQLITE_TEST
21479 SQLITE_API int sqlite3_current_time = 0;
21480 #endif
21481
21482 /*
21483 ** Find the current time (in Universal Coordinated Time).  Write the
21484 ** current time and date as a Julian Day number into *prNow and
21485 ** return 0.  Return 1 if the time and date cannot be found.
21486 */
21487 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21488   double now;
21489   SHORT minute; /* needs to be able to cope with negative timezone offset */
21490   USHORT second, hour,
21491          day, month, year;
21492   DATETIME dt;
21493   DosGetDateTime( &dt );
21494   second = (USHORT)dt.seconds;
21495   minute = (SHORT)dt.minutes + dt.timezone;
21496   hour = (USHORT)dt.hours;
21497   day = (USHORT)dt.day;
21498   month = (USHORT)dt.month;
21499   year = (USHORT)dt.year;
21500
21501   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21502      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21503   /* Calculate the Julian days */
21504   now = day - 32076 +
21505     1461*(year + 4800 + (month - 14)/12)/4 +
21506     367*(month - 2 - (month - 14)/12*12)/12 -
21507     3*((year + 4900 + (month - 14)/12)/100)/4;
21508
21509   /* Add the fractional hours, mins and seconds */
21510   now += (hour + 12.0)/24.0;
21511   now += minute/1440.0;
21512   now += second/86400.0;
21513   *prNow = now;
21514 #ifdef SQLITE_TEST
21515   if( sqlite3_current_time ){
21516     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21517   }
21518 #endif
21519   return 0;
21520 }
21521
21522 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21523   return 0;
21524 }
21525
21526 /*
21527 ** Initialize and deinitialize the operating system interface.
21528 */
21529 SQLITE_API int sqlite3_os_init(void){
21530   static sqlite3_vfs os2Vfs = {
21531     1,                 /* iVersion */
21532     sizeof(os2File),   /* szOsFile */
21533     CCHMAXPATH,        /* mxPathname */
21534     0,                 /* pNext */
21535     "os2",             /* zName */
21536     0,                 /* pAppData */
21537
21538     os2Open,           /* xOpen */
21539     os2Delete,         /* xDelete */
21540     os2Access,         /* xAccess */
21541     os2FullPathname,   /* xFullPathname */
21542     os2DlOpen,         /* xDlOpen */
21543     os2DlError,        /* xDlError */
21544     os2DlSym,          /* xDlSym */
21545     os2DlClose,        /* xDlClose */
21546     os2Randomness,     /* xRandomness */
21547     os2Sleep,          /* xSleep */
21548     os2CurrentTime,    /* xCurrentTime */
21549     os2GetLastError    /* xGetLastError */
21550   };
21551   sqlite3_vfs_register(&os2Vfs, 1);
21552   initUconvObjects();
21553   return SQLITE_OK;
21554 }
21555 SQLITE_API int sqlite3_os_end(void){
21556   freeUconvObjects();
21557   return SQLITE_OK;
21558 }
21559
21560 #endif /* SQLITE_OS_OS2 */
21561
21562 /************** End of os_os2.c **********************************************/
21563 /************** Begin file os_unix.c *****************************************/
21564 /*
21565 ** 2004 May 22
21566 **
21567 ** The author disclaims copyright to this source code.  In place of
21568 ** a legal notice, here is a blessing:
21569 **
21570 **    May you do good and not evil.
21571 **    May you find forgiveness for yourself and forgive others.
21572 **    May you share freely, never taking more than you give.
21573 **
21574 ******************************************************************************
21575 **
21576 ** This file contains code that is specific to Unix systems.
21577 **
21578 ** $Id: os_unix.c,v 1.205 2008/10/14 17:58:38 drh Exp $
21579 */
21580 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21581
21582 /*
21583 ** If SQLITE_ENABLE_LOCKING_STYLE is defined and is non-zero, then several
21584 ** alternative locking implementations are provided:
21585 **
21586 **   * POSIX locking (the default),
21587 **   * No locking,
21588 **   * Dot-file locking,
21589 **   * flock() locking,
21590 **   * AFP locking (OSX only).
21591 **
21592 ** SQLITE_ENABLE_LOCKING_STYLE only works on a Mac. It is turned on by
21593 ** default on a Mac and disabled on all other posix platforms.
21594 */
21595 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21596 #  if defined(__DARWIN__)
21597 #    define SQLITE_ENABLE_LOCKING_STYLE 1
21598 #  else
21599 #    define SQLITE_ENABLE_LOCKING_STYLE 0
21600 #  endif
21601 #endif
21602
21603 /*
21604 ** These #defines should enable >2GB file support on Posix if the
21605 ** underlying operating system supports it.  If the OS lacks
21606 ** large file support, these should be no-ops.
21607 **
21608 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21609 ** on the compiler command line.  This is necessary if you are compiling
21610 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21611 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21612 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21613 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21614 ** portability you should omit LFS.
21615 */
21616 #ifndef SQLITE_DISABLE_LFS
21617 # define _LARGE_FILE       1
21618 # ifndef _FILE_OFFSET_BITS
21619 #   define _FILE_OFFSET_BITS 64
21620 # endif
21621 # define _LARGEFILE_SOURCE 1
21622 #endif
21623
21624 /*
21625 ** standard include files.
21626 */
21627 #include <sys/types.h>
21628 #include <sys/stat.h>
21629 #include <fcntl.h>
21630 #include <unistd.h>
21631 #include <sys/time.h>
21632 #include <errno.h>
21633
21634 #if SQLITE_ENABLE_LOCKING_STYLE
21635 #include <sys/ioctl.h>
21636 #include <sys/param.h>
21637 #include <sys/mount.h>
21638 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21639
21640 /*
21641 ** If we are to be thread-safe, include the pthreads header and define
21642 ** the SQLITE_UNIX_THREADS macro.
21643 */
21644 #if SQLITE_THREADSAFE
21645 # define SQLITE_UNIX_THREADS 1
21646 #endif
21647
21648 /*
21649 ** Default permissions when creating a new file
21650 */
21651 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21652 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21653 #endif
21654
21655 /*
21656 ** Maximum supported path-length.
21657 */
21658 #define MAX_PATHNAME 512
21659
21660
21661 /*
21662 ** The unixFile structure is subclass of sqlite3_file specific for the unix
21663 ** protability layer.
21664 */
21665 typedef struct unixFile unixFile;
21666 struct unixFile {
21667   sqlite3_io_methods const *pMethod;  /* Always the first entry */
21668 #ifdef SQLITE_TEST
21669   /* In test mode, increase the size of this structure a bit so that 
21670   ** it is larger than the struct CrashFile defined in test6.c.
21671   */
21672   char aPadding[32];
21673 #endif
21674   struct openCnt *pOpen;    /* Info about all open fd's on this inode */
21675   struct lockInfo *pLock;   /* Info about locks on this inode */
21676 #if SQLITE_ENABLE_LOCKING_STYLE
21677   void *lockingContext;     /* Locking style specific state */
21678 #endif
21679   int h;                    /* The file descriptor */
21680   unsigned char locktype;   /* The type of lock held on this fd */
21681   int dirfd;                /* File descriptor for the directory */
21682 #if SQLITE_THREADSAFE
21683   pthread_t tid;            /* The thread that "owns" this unixFile */
21684 #endif
21685   int lastErrno;            /* The unix errno from the last I/O error */
21686 };
21687
21688 /*
21689 ** Include code that is common to all os_*.c files
21690 */
21691 /************** Include os_common.h in the middle of os_unix.c ***************/
21692 /************** Begin file os_common.h ***************************************/
21693 /*
21694 ** 2004 May 22
21695 **
21696 ** The author disclaims copyright to this source code.  In place of
21697 ** a legal notice, here is a blessing:
21698 **
21699 **    May you do good and not evil.
21700 **    May you find forgiveness for yourself and forgive others.
21701 **    May you share freely, never taking more than you give.
21702 **
21703 ******************************************************************************
21704 **
21705 ** This file contains macros and a little bit of code that is common to
21706 ** all of the platform-specific files (os_*.c) and is #included into those
21707 ** files.
21708 **
21709 ** This file should be #included by the os_*.c files only.  It is not a
21710 ** general purpose header file.
21711 **
21712 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
21713 */
21714 #ifndef _OS_COMMON_H_
21715 #define _OS_COMMON_H_
21716
21717 /*
21718 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21719 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21720 ** switch.  The following code should catch this problem at compile-time.
21721 */
21722 #ifdef MEMORY_DEBUG
21723 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21724 #endif
21725
21726
21727 /*
21728  * When testing, this global variable stores the location of the
21729  * pending-byte in the database file.
21730  */
21731 #ifdef SQLITE_TEST
21732 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
21733 #endif
21734
21735 #ifdef SQLITE_DEBUG
21736 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21737 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21738 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21739 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21740 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21741 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21742 #define OSTRACE6(X,Y,Z,A,B,C) \
21743     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21744 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21745     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21746 #else
21747 #define OSTRACE1(X)
21748 #define OSTRACE2(X,Y)
21749 #define OSTRACE3(X,Y,Z)
21750 #define OSTRACE4(X,Y,Z,A)
21751 #define OSTRACE5(X,Y,Z,A,B)
21752 #define OSTRACE6(X,Y,Z,A,B,C)
21753 #define OSTRACE7(X,Y,Z,A,B,C,D)
21754 #endif
21755
21756 /*
21757 ** Macros for performance tracing.  Normally turned off.  Only works
21758 ** on i486 hardware.
21759 */
21760 #ifdef SQLITE_PERFORMANCE_TRACE
21761
21762 /* 
21763 ** hwtime.h contains inline assembler code for implementing 
21764 ** high-performance timing routines.
21765 */
21766 /************** Include hwtime.h in the middle of os_common.h ****************/
21767 /************** Begin file hwtime.h ******************************************/
21768 /*
21769 ** 2008 May 27
21770 **
21771 ** The author disclaims copyright to this source code.  In place of
21772 ** a legal notice, here is a blessing:
21773 **
21774 **    May you do good and not evil.
21775 **    May you find forgiveness for yourself and forgive others.
21776 **    May you share freely, never taking more than you give.
21777 **
21778 ******************************************************************************
21779 **
21780 ** This file contains inline asm code for retrieving "high-performance"
21781 ** counters for x86 class CPUs.
21782 **
21783 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
21784 */
21785 #ifndef _HWTIME_H_
21786 #define _HWTIME_H_
21787
21788 /*
21789 ** The following routine only works on pentium-class (or newer) processors.
21790 ** It uses the RDTSC opcode to read the cycle count value out of the
21791 ** processor and returns that value.  This can be used for high-res
21792 ** profiling.
21793 */
21794 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21795       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21796
21797   #if defined(__GNUC__)
21798
21799   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21800      unsigned int lo, hi;
21801      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21802      return (sqlite_uint64)hi << 32 | lo;
21803   }
21804
21805   #elif defined(_MSC_VER)
21806
21807   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21808      __asm {
21809         rdtsc
21810         ret       ; return value at EDX:EAX
21811      }
21812   }
21813
21814   #endif
21815
21816 #elif (defined(__GNUC__) && defined(__x86_64__))
21817
21818   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21819       unsigned long val;
21820       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21821       return val;
21822   }
21823  
21824 #elif (defined(__GNUC__) && defined(__ppc__))
21825
21826   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21827       unsigned long long retval;
21828       unsigned long junk;
21829       __asm__ __volatile__ ("\n\
21830           1:      mftbu   %1\n\
21831                   mftb    %L0\n\
21832                   mftbu   %0\n\
21833                   cmpw    %0,%1\n\
21834                   bne     1b"
21835                   : "=r" (retval), "=r" (junk));
21836       return retval;
21837   }
21838
21839 #else
21840
21841   #error Need implementation of sqlite3Hwtime() for your platform.
21842
21843   /*
21844   ** To compile without implementing sqlite3Hwtime() for your platform,
21845   ** you can remove the above #error and use the following
21846   ** stub function.  You will lose timing support for many
21847   ** of the debugging and testing utilities, but it should at
21848   ** least compile and run.
21849   */
21850 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21851
21852 #endif
21853
21854 #endif /* !defined(_HWTIME_H_) */
21855
21856 /************** End of hwtime.h **********************************************/
21857 /************** Continuing where we left off in os_common.h ******************/
21858
21859 static sqlite_uint64 g_start;
21860 static sqlite_uint64 g_elapsed;
21861 #define TIMER_START       g_start=sqlite3Hwtime()
21862 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21863 #define TIMER_ELAPSED     g_elapsed
21864 #else
21865 #define TIMER_START
21866 #define TIMER_END
21867 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21868 #endif
21869
21870 /*
21871 ** If we compile with the SQLITE_TEST macro set, then the following block
21872 ** of code will give us the ability to simulate a disk I/O error.  This
21873 ** is used for testing the I/O recovery logic.
21874 */
21875 #ifdef SQLITE_TEST
21876 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21877 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21878 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21879 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21880 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21881 SQLITE_API int sqlite3_diskfull_pending = 0;
21882 SQLITE_API int sqlite3_diskfull = 0;
21883 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21884 #define SimulateIOError(CODE)  \
21885   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21886        || sqlite3_io_error_pending-- == 1 )  \
21887               { local_ioerr(); CODE; }
21888 static void local_ioerr(){
21889   IOTRACE(("IOERR\n"));
21890   sqlite3_io_error_hit++;
21891   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21892 }
21893 #define SimulateDiskfullError(CODE) \
21894    if( sqlite3_diskfull_pending ){ \
21895      if( sqlite3_diskfull_pending == 1 ){ \
21896        local_ioerr(); \
21897        sqlite3_diskfull = 1; \
21898        sqlite3_io_error_hit = 1; \
21899        CODE; \
21900      }else{ \
21901        sqlite3_diskfull_pending--; \
21902      } \
21903    }
21904 #else
21905 #define SimulateIOErrorBenign(X)
21906 #define SimulateIOError(A)
21907 #define SimulateDiskfullError(A)
21908 #endif
21909
21910 /*
21911 ** When testing, keep a count of the number of open files.
21912 */
21913 #ifdef SQLITE_TEST
21914 SQLITE_API int sqlite3_open_file_count = 0;
21915 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21916 #else
21917 #define OpenCounter(X)
21918 #endif
21919
21920 #endif /* !defined(_OS_COMMON_H_) */
21921
21922 /************** End of os_common.h *******************************************/
21923 /************** Continuing where we left off in os_unix.c ********************/
21924
21925 /*
21926 ** Define various macros that are missing from some systems.
21927 */
21928 #ifndef O_LARGEFILE
21929 # define O_LARGEFILE 0
21930 #endif
21931 #ifdef SQLITE_DISABLE_LFS
21932 # undef O_LARGEFILE
21933 # define O_LARGEFILE 0
21934 #endif
21935 #ifndef O_NOFOLLOW
21936 # define O_NOFOLLOW 0
21937 #endif
21938 #ifndef O_BINARY
21939 # define O_BINARY 0
21940 #endif
21941
21942 /*
21943 ** The DJGPP compiler environment looks mostly like Unix, but it
21944 ** lacks the fcntl() system call.  So redefine fcntl() to be something
21945 ** that always succeeds.  This means that locking does not occur under
21946 ** DJGPP.  But it is DOS - what did you expect?
21947 */
21948 #ifdef __DJGPP__
21949 # define fcntl(A,B,C) 0
21950 #endif
21951
21952 /*
21953 ** The threadid macro resolves to the thread-id or to 0.  Used for
21954 ** testing and debugging only.
21955 */
21956 #if SQLITE_THREADSAFE
21957 #define threadid pthread_self()
21958 #else
21959 #define threadid 0
21960 #endif
21961
21962 /*
21963 ** Set or check the unixFile.tid field.  This field is set when an unixFile
21964 ** is first opened.  All subsequent uses of the unixFile verify that the
21965 ** same thread is operating on the unixFile.  Some operating systems do
21966 ** not allow locks to be overridden by other threads and that restriction
21967 ** means that sqlite3* database handles cannot be moved from one thread
21968 ** to another.  This logic makes sure a user does not try to do that
21969 ** by mistake.
21970 **
21971 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
21972 ** another as long as we are running on a system that supports threads
21973 ** overriding each others locks (which now the most common behavior)
21974 ** or if no locks are held.  But the unixFile.pLock field needs to be
21975 ** recomputed because its key includes the thread-id.  See the 
21976 ** transferOwnership() function below for additional information
21977 */
21978 #if SQLITE_THREADSAFE
21979 # define SET_THREADID(X)   (X)->tid = pthread_self()
21980 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
21981                             !pthread_equal((X)->tid, pthread_self()))
21982 #else
21983 # define SET_THREADID(X)
21984 # define CHECK_THREADID(X) 0
21985 #endif
21986
21987 /*
21988 ** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
21989 ** section 6.5.2.2 lines 483 through 490 specify that when a process
21990 ** sets or clears a lock, that operation overrides any prior locks set
21991 ** by the same process.  It does not explicitly say so, but this implies
21992 ** that it overrides locks set by the same process using a different
21993 ** file descriptor.  Consider this test case:
21994 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
21995 **
21996 ** Suppose ./file1 and ./file2 are really the same file (because
21997 ** one is a hard or symbolic link to the other) then if you set
21998 ** an exclusive lock on fd1, then try to get an exclusive lock
21999 ** on fd2, it works.  I would have expected the second lock to
22000 ** fail since there was already a lock on the file due to fd1.
22001 ** But not so.  Since both locks came from the same process, the
22002 ** second overrides the first, even though they were on different
22003 ** file descriptors opened on different file names.
22004 **
22005 ** Bummer.  If you ask me, this is broken.  Badly broken.  It means
22006 ** that we cannot use POSIX locks to synchronize file access among
22007 ** competing threads of the same process.  POSIX locks will work fine
22008 ** to synchronize access for threads in separate processes, but not
22009 ** threads within the same process.
22010 **
22011 ** To work around the problem, SQLite has to manage file locks internally
22012 ** on its own.  Whenever a new database is opened, we have to find the
22013 ** specific inode of the database file (the inode is determined by the
22014 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
22015 ** and check for locks already existing on that inode.  When locks are
22016 ** created or removed, we have to look at our own internal record of the
22017 ** locks to see if another thread has previously set a lock on that same
22018 ** inode.
22019 **
22020 ** The sqlite3_file structure for POSIX is no longer just an integer file
22021 ** descriptor.  It is now a structure that holds the integer file
22022 ** descriptor and a pointer to a structure that describes the internal
22023 ** locks on the corresponding inode.  There is one locking structure
22024 ** per inode, so if the same inode is opened twice, both unixFile structures
22025 ** point to the same locking structure.  The locking structure keeps
22026 ** a reference count (so we will know when to delete it) and a "cnt"
22027 ** field that tells us its internal lock status.  cnt==0 means the
22028 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22029 ** cnt>0 means there are cnt shared locks on the file.
22030 **
22031 ** Any attempt to lock or unlock a file first checks the locking
22032 ** structure.  The fcntl() system call is only invoked to set a 
22033 ** POSIX lock if the internal lock structure transitions between
22034 ** a locked and an unlocked state.
22035 **
22036 ** 2004-Jan-11:
22037 ** More recent discoveries about POSIX advisory locks.  (The more
22038 ** I discover, the more I realize the a POSIX advisory locks are
22039 ** an abomination.)
22040 **
22041 ** If you close a file descriptor that points to a file that has locks,
22042 ** all locks on that file that are owned by the current process are
22043 ** released.  To work around this problem, each unixFile structure contains
22044 ** a pointer to an openCnt structure.  There is one openCnt structure
22045 ** per open inode, which means that multiple unixFile can point to a single
22046 ** openCnt.  When an attempt is made to close an unixFile, if there are
22047 ** other unixFile open on the same inode that are holding locks, the call
22048 ** to close() the file descriptor is deferred until all of the locks clear.
22049 ** The openCnt structure keeps a list of file descriptors that need to
22050 ** be closed and that list is walked (and cleared) when the last lock
22051 ** clears.
22052 **
22053 ** First, under Linux threads, because each thread has a separate
22054 ** process ID, lock operations in one thread do not override locks
22055 ** to the same file in other threads.  Linux threads behave like
22056 ** separate processes in this respect.  But, if you close a file
22057 ** descriptor in linux threads, all locks are cleared, even locks
22058 ** on other threads and even though the other threads have different
22059 ** process IDs.  Linux threads is inconsistent in this respect.
22060 ** (I'm beginning to think that linux threads is an abomination too.)
22061 ** The consequence of this all is that the hash table for the lockInfo
22062 ** structure has to include the process id as part of its key because
22063 ** locks in different threads are treated as distinct.  But the 
22064 ** openCnt structure should not include the process id in its
22065 ** key because close() clears lock on all threads, not just the current
22066 ** thread.  Were it not for this goofiness in linux threads, we could
22067 ** combine the lockInfo and openCnt structures into a single structure.
22068 **
22069 ** 2004-Jun-28:
22070 ** On some versions of linux, threads can override each others locks.
22071 ** On others not.  Sometimes you can change the behavior on the same
22072 ** system by setting the LD_ASSUME_KERNEL environment variable.  The
22073 ** POSIX standard is silent as to which behavior is correct, as far
22074 ** as I can tell, so other versions of unix might show the same
22075 ** inconsistency.  There is no little doubt in my mind that posix
22076 ** advisory locks and linux threads are profoundly broken.
22077 **
22078 ** To work around the inconsistencies, we have to test at runtime 
22079 ** whether or not threads can override each others locks.  This test
22080 ** is run once, the first time any lock is attempted.  A static 
22081 ** variable is set to record the results of this test for future
22082 ** use.
22083 */
22084
22085 /*
22086 ** An instance of the following structure serves as the key used
22087 ** to locate a particular lockInfo structure given its inode.
22088 **
22089 ** If threads cannot override each others locks, then we set the
22090 ** lockKey.tid field to the thread ID.  If threads can override
22091 ** each others locks then tid is always set to zero.  tid is omitted
22092 ** if we compile without threading support.
22093 */
22094 struct lockKey {
22095   dev_t dev;       /* Device number */
22096   ino_t ino;       /* Inode number */
22097 #if SQLITE_THREADSAFE
22098   pthread_t tid;   /* Thread ID or zero if threads can override each other */
22099 #endif
22100 };
22101
22102 /*
22103 ** An instance of the following structure is allocated for each open
22104 ** inode on each thread with a different process ID.  (Threads have
22105 ** different process IDs on linux, but not on most other unixes.)
22106 **
22107 ** A single inode can have multiple file descriptors, so each unixFile
22108 ** structure contains a pointer to an instance of this object and this
22109 ** object keeps a count of the number of unixFile pointing to it.
22110 */
22111 struct lockInfo {
22112   struct lockKey key;  /* The lookup key */
22113   int cnt;             /* Number of SHARED locks held */
22114   int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22115   int nRef;            /* Number of pointers to this structure */
22116   struct lockInfo *pNext, *pPrev;   /* List of all lockInfo objects */
22117 };
22118
22119 /*
22120 ** An instance of the following structure serves as the key used
22121 ** to locate a particular openCnt structure given its inode.  This
22122 ** is the same as the lockKey except that the thread ID is omitted.
22123 */
22124 struct openKey {
22125   dev_t dev;   /* Device number */
22126   ino_t ino;   /* Inode number */
22127 };
22128
22129 /*
22130 ** An instance of the following structure is allocated for each open
22131 ** inode.  This structure keeps track of the number of locks on that
22132 ** inode.  If a close is attempted against an inode that is holding
22133 ** locks, the close is deferred until all locks clear by adding the
22134 ** file descriptor to be closed to the pending list.
22135 */
22136 struct openCnt {
22137   struct openKey key;   /* The lookup key */
22138   int nRef;             /* Number of pointers to this structure */
22139   int nLock;            /* Number of outstanding locks */
22140   int nPending;         /* Number of pending close() operations */
22141   int *aPending;        /* Malloced space holding fd's awaiting a close() */
22142   struct openCnt *pNext, *pPrev;   /* List of all openCnt objects */
22143 };
22144
22145 /*
22146 ** List of all lockInfo and openCnt objects.  This used to be a hash
22147 ** table.  But the number of objects is rarely more than a dozen and
22148 ** never exceeds a few thousand.  And lookup is not on a critical
22149 ** path oo a simple linked list will suffice.
22150 */
22151 static struct lockInfo *lockList = 0;
22152 static struct openCnt *openList = 0;
22153
22154 /*
22155 ** The locking styles are associated with the different file locking
22156 ** capabilities supported by different file systems.  
22157 **
22158 ** POSIX locking style fully supports shared and exclusive byte-range locks 
22159 ** AFP locking only supports exclusive byte-range locks
22160 ** FLOCK only supports a single file-global exclusive lock
22161 ** DOTLOCK isn't a true locking style, it refers to the use of a special
22162 **   file named the same as the database file with a '.lock' extension, this
22163 **   can be used on file systems that do not offer any reliable file locking
22164 ** NO locking means that no locking will be attempted, this is only used for
22165 **   read-only file systems currently
22166 ** UNSUPPORTED means that no locking will be attempted, this is only used for
22167 **   file systems that are known to be unsupported
22168 */
22169 #define LOCKING_STYLE_POSIX        1
22170 #define LOCKING_STYLE_NONE         2
22171 #define LOCKING_STYLE_DOTFILE      3
22172 #define LOCKING_STYLE_FLOCK        4
22173 #define LOCKING_STYLE_AFP          5
22174
22175 /*
22176 ** Only set the lastErrno if the error code is a real error and not 
22177 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22178 */
22179 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22180
22181 /*
22182 ** Helper functions to obtain and relinquish the global mutex.
22183 */
22184 static void enterMutex(void){
22185   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22186 }
22187 static void leaveMutex(void){
22188   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22189 }
22190
22191 #if SQLITE_THREADSAFE
22192 /*
22193 ** This variable records whether or not threads can override each others
22194 ** locks.
22195 **
22196 **    0:  No.  Threads cannot override each others locks.
22197 **    1:  Yes.  Threads can override each others locks.
22198 **   -1:  We don't know yet.
22199 **
22200 ** On some systems, we know at compile-time if threads can override each
22201 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22202 ** will be set appropriately.  On other systems, we have to check at
22203 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22204 ** undefined.
22205 **
22206 ** This variable normally has file scope only.  But during testing, we make
22207 ** it a global so that the test code can change its value in order to verify
22208 ** that the right stuff happens in either case.
22209 */
22210 #ifndef SQLITE_THREAD_OVERRIDE_LOCK
22211 # define SQLITE_THREAD_OVERRIDE_LOCK -1
22212 #endif
22213 #ifdef SQLITE_TEST
22214 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22215 #else
22216 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22217 #endif
22218
22219 /*
22220 ** This structure holds information passed into individual test
22221 ** threads by the testThreadLockingBehavior() routine.
22222 */
22223 struct threadTestData {
22224   int fd;                /* File to be locked */
22225   struct flock lock;     /* The locking operation */
22226   int result;            /* Result of the locking operation */
22227 };
22228
22229 #ifdef SQLITE_LOCK_TRACE
22230 /*
22231 ** Print out information about all locking operations.
22232 **
22233 ** This routine is used for troubleshooting locks on multithreaded
22234 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22235 ** command-line option on the compiler.  This code is normally
22236 ** turned off.
22237 */
22238 static int lockTrace(int fd, int op, struct flock *p){
22239   char *zOpName, *zType;
22240   int s;
22241   int savedErrno;
22242   if( op==F_GETLK ){
22243     zOpName = "GETLK";
22244   }else if( op==F_SETLK ){
22245     zOpName = "SETLK";
22246   }else{
22247     s = fcntl(fd, op, p);
22248     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22249     return s;
22250   }
22251   if( p->l_type==F_RDLCK ){
22252     zType = "RDLCK";
22253   }else if( p->l_type==F_WRLCK ){
22254     zType = "WRLCK";
22255   }else if( p->l_type==F_UNLCK ){
22256     zType = "UNLCK";
22257   }else{
22258     assert( 0 );
22259   }
22260   assert( p->l_whence==SEEK_SET );
22261   s = fcntl(fd, op, p);
22262   savedErrno = errno;
22263   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22264      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22265      (int)p->l_pid, s);
22266   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22267     struct flock l2;
22268     l2 = *p;
22269     fcntl(fd, F_GETLK, &l2);
22270     if( l2.l_type==F_RDLCK ){
22271       zType = "RDLCK";
22272     }else if( l2.l_type==F_WRLCK ){
22273       zType = "WRLCK";
22274     }else if( l2.l_type==F_UNLCK ){
22275       zType = "UNLCK";
22276     }else{
22277       assert( 0 );
22278     }
22279     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22280        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22281   }
22282   errno = savedErrno;
22283   return s;
22284 }
22285 #define fcntl lockTrace
22286 #endif /* SQLITE_LOCK_TRACE */
22287
22288 /*
22289 ** The testThreadLockingBehavior() routine launches two separate
22290 ** threads on this routine.  This routine attempts to lock a file
22291 ** descriptor then returns.  The success or failure of that attempt
22292 ** allows the testThreadLockingBehavior() procedure to determine
22293 ** whether or not threads can override each others locks.
22294 */
22295 static void *threadLockingTest(void *pArg){
22296   struct threadTestData *pData = (struct threadTestData*)pArg;
22297   pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
22298   return pArg;
22299 }
22300
22301 /*
22302 ** This procedure attempts to determine whether or not threads
22303 ** can override each others locks then sets the 
22304 ** threadsOverrideEachOthersLocks variable appropriately.
22305 */
22306 static void testThreadLockingBehavior(int fd_orig){
22307   int fd;
22308   struct threadTestData d[2];
22309   pthread_t t[2];
22310
22311   fd = dup(fd_orig);
22312   if( fd<0 ) return;
22313   memset(d, 0, sizeof(d));
22314   d[0].fd = fd;
22315   d[0].lock.l_type = F_RDLCK;
22316   d[0].lock.l_len = 1;
22317   d[0].lock.l_start = 0;
22318   d[0].lock.l_whence = SEEK_SET;
22319   d[1] = d[0];
22320   d[1].lock.l_type = F_WRLCK;
22321   pthread_create(&t[0], 0, threadLockingTest, &d[0]);
22322   pthread_create(&t[1], 0, threadLockingTest, &d[1]);
22323   pthread_join(t[0], 0);
22324   pthread_join(t[1], 0);
22325   close(fd);
22326   threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
22327 }
22328 #endif /* SQLITE_THREADSAFE */
22329
22330 /*
22331 ** Release a lockInfo structure previously allocated by findLockInfo().
22332 */
22333 static void releaseLockInfo(struct lockInfo *pLock){
22334   if( pLock ){
22335     pLock->nRef--;
22336     if( pLock->nRef==0 ){
22337       if( pLock->pPrev ){
22338         assert( pLock->pPrev->pNext==pLock );
22339         pLock->pPrev->pNext = pLock->pNext;
22340       }else{
22341         assert( lockList==pLock );
22342         lockList = pLock->pNext;
22343       }
22344       if( pLock->pNext ){
22345         assert( pLock->pNext->pPrev==pLock );
22346         pLock->pNext->pPrev = pLock->pPrev;
22347       }
22348       sqlite3_free(pLock);
22349     }
22350   }
22351 }
22352
22353 /*
22354 ** Release a openCnt structure previously allocated by findLockInfo().
22355 */
22356 static void releaseOpenCnt(struct openCnt *pOpen){
22357   if( pOpen ){
22358     pOpen->nRef--;
22359     if( pOpen->nRef==0 ){
22360       if( pOpen->pPrev ){
22361         assert( pOpen->pPrev->pNext==pOpen );
22362         pOpen->pPrev->pNext = pOpen->pNext;
22363       }else{
22364         assert( openList==pOpen );
22365         openList = pOpen->pNext;
22366       }
22367       if( pOpen->pNext ){
22368         assert( pOpen->pNext->pPrev==pOpen );
22369         pOpen->pNext->pPrev = pOpen->pPrev;
22370       }
22371       sqlite3_free(pOpen->aPending);
22372       sqlite3_free(pOpen);
22373     }
22374   }
22375 }
22376
22377 #if SQLITE_ENABLE_LOCKING_STYLE
22378 /*
22379 ** Tests a byte-range locking query to see if byte range locks are 
22380 ** supported, if not we fall back to dotlockLockingStyle.
22381 */
22382 static int testLockingStyle(int fd){
22383   struct flock lockInfo;
22384
22385   /* Test byte-range lock using fcntl(). If the call succeeds, 
22386   ** assume that the file-system supports POSIX style locks. 
22387   */
22388   lockInfo.l_len = 1;
22389   lockInfo.l_start = 0;
22390   lockInfo.l_whence = SEEK_SET;
22391   lockInfo.l_type = F_RDLCK;
22392   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
22393     return LOCKING_STYLE_POSIX;
22394   }
22395   
22396   /* Testing for flock() can give false positives.  So if if the above 
22397   ** test fails, then we fall back to using dot-file style locking.
22398   */  
22399   return LOCKING_STYLE_DOTFILE;
22400 }
22401 #endif
22402
22403 /* 
22404 ** If SQLITE_ENABLE_LOCKING_STYLE is defined, this function Examines the 
22405 ** f_fstypename entry in the statfs structure as returned by stat() for 
22406 ** the file system hosting the database file and selects  the appropriate
22407 ** locking style based on its value.  These values and assignments are 
22408 ** based on Darwin/OSX behavior and have not been thoroughly tested on 
22409 ** other systems.
22410 **
22411 ** If SQLITE_ENABLE_LOCKING_STYLE is not defined, this function always
22412 ** returns LOCKING_STYLE_POSIX.
22413 */
22414 static int detectLockingStyle(
22415   sqlite3_vfs *pVfs,
22416   const char *filePath, 
22417   int fd
22418 ){
22419 #if SQLITE_ENABLE_LOCKING_STYLE
22420   struct Mapping {
22421     const char *zFilesystem;
22422     int eLockingStyle;
22423   } aMap[] = {
22424     { "hfs",    LOCKING_STYLE_POSIX },
22425     { "ufs",    LOCKING_STYLE_POSIX },
22426     { "afpfs",  LOCKING_STYLE_AFP },
22427 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
22428     { "smbfs",  LOCKING_STYLE_AFP },
22429 #else
22430     { "smbfs",  LOCKING_STYLE_FLOCK },
22431 #endif
22432     { "msdos",  LOCKING_STYLE_DOTFILE },
22433     { "webdav", LOCKING_STYLE_NONE },
22434     { 0, 0 }
22435   };
22436   int i;
22437   struct statfs fsInfo;
22438
22439   if( !filePath ){
22440     return LOCKING_STYLE_NONE;
22441   }
22442   if( pVfs->pAppData ){
22443     return SQLITE_PTR_TO_INT(pVfs->pAppData);
22444   }
22445
22446   if( statfs(filePath, &fsInfo) != -1 ){
22447     if( fsInfo.f_flags & MNT_RDONLY ){
22448       return LOCKING_STYLE_NONE;
22449     }
22450     for(i=0; aMap[i].zFilesystem; i++){
22451       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
22452         return aMap[i].eLockingStyle;
22453       }
22454     }
22455   }
22456
22457   /* Default case. Handles, amongst others, "nfs". */
22458   return testLockingStyle(fd);  
22459 #endif
22460   return LOCKING_STYLE_POSIX;
22461 }
22462
22463 /*
22464 ** Given a file descriptor, locate lockInfo and openCnt structures that
22465 ** describes that file descriptor.  Create new ones if necessary.  The
22466 ** return values might be uninitialized if an error occurs.
22467 **
22468 ** Return an appropriate error code.
22469 */
22470 static int findLockInfo(
22471   int fd,                      /* The file descriptor used in the key */
22472   struct lockInfo **ppLock,    /* Return the lockInfo structure here */
22473   struct openCnt **ppOpen      /* Return the openCnt structure here */
22474 ){
22475   int rc;
22476   struct lockKey key1;
22477   struct openKey key2;
22478   struct stat statbuf;
22479   struct lockInfo *pLock;
22480   struct openCnt *pOpen;
22481   rc = fstat(fd, &statbuf);
22482   if( rc!=0 ){
22483 #ifdef EOVERFLOW
22484     if( errno==EOVERFLOW ) return SQLITE_NOLFS;
22485 #endif
22486     return SQLITE_IOERR;
22487   }
22488
22489   /* On OS X on an msdos filesystem, the inode number is reported
22490   ** incorrectly for zero-size files.  See ticket #3260.  To work
22491   ** around this problem (we consider it a bug in OS X, not SQLite)
22492   ** we always increase the file size to 1 by writing a single byte
22493   ** prior to accessing the inode number.  The one byte written is
22494   ** an ASCII 'S' character which also happens to be the first byte
22495   ** in the header of every SQLite database.  In this way, if there
22496   ** is a race condition such that another thread has already populated
22497   ** the first page of the database, no damage is done.
22498   */
22499   if( statbuf.st_size==0 ){
22500     write(fd, "S", 1);
22501     rc = fstat(fd, &statbuf);
22502     if( rc!=0 ){
22503       return SQLITE_IOERR;
22504     }
22505   }
22506
22507   memset(&key1, 0, sizeof(key1));
22508   key1.dev = statbuf.st_dev;
22509   key1.ino = statbuf.st_ino;
22510 #if SQLITE_THREADSAFE
22511   if( threadsOverrideEachOthersLocks<0 ){
22512     testThreadLockingBehavior(fd);
22513   }
22514   key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22515 #endif
22516   memset(&key2, 0, sizeof(key2));
22517   key2.dev = statbuf.st_dev;
22518   key2.ino = statbuf.st_ino;
22519   pLock = lockList;
22520   while( pLock && memcmp(&key1, &pLock->key, sizeof(key1)) ){
22521     pLock = pLock->pNext;
22522   }
22523   if( pLock==0 ){
22524     pLock = sqlite3_malloc( sizeof(*pLock) );
22525     if( pLock==0 ){
22526       rc = SQLITE_NOMEM;
22527       goto exit_findlockinfo;
22528     }
22529     pLock->key = key1;
22530     pLock->nRef = 1;
22531     pLock->cnt = 0;
22532     pLock->locktype = 0;
22533     pLock->pNext = lockList;
22534     pLock->pPrev = 0;
22535     if( lockList ) lockList->pPrev = pLock;
22536     lockList = pLock;
22537   }else{
22538     pLock->nRef++;
22539   }
22540   *ppLock = pLock;
22541   if( ppOpen!=0 ){
22542     pOpen = openList;
22543     while( pOpen && memcmp(&key2, &pOpen->key, sizeof(key2)) ){
22544       pOpen = pOpen->pNext;
22545     }
22546     if( pOpen==0 ){
22547       pOpen = sqlite3_malloc( sizeof(*pOpen) );
22548       if( pOpen==0 ){
22549         releaseLockInfo(pLock);
22550         rc = SQLITE_NOMEM;
22551         goto exit_findlockinfo;
22552       }
22553       pOpen->key = key2;
22554       pOpen->nRef = 1;
22555       pOpen->nLock = 0;
22556       pOpen->nPending = 0;
22557       pOpen->aPending = 0;
22558       pOpen->pNext = openList;
22559       pOpen->pPrev = 0;
22560       if( openList ) openList->pPrev = pOpen;
22561       openList = pOpen;
22562     }else{
22563       pOpen->nRef++;
22564     }
22565     *ppOpen = pOpen;
22566   }
22567
22568 exit_findlockinfo:
22569   return rc;
22570 }
22571
22572 #ifdef SQLITE_DEBUG
22573 /*
22574 ** Helper function for printing out trace information from debugging
22575 ** binaries. This returns the string represetation of the supplied
22576 ** integer lock-type.
22577 */
22578 static const char *locktypeName(int locktype){
22579   switch( locktype ){
22580   case NO_LOCK: return "NONE";
22581   case SHARED_LOCK: return "SHARED";
22582   case RESERVED_LOCK: return "RESERVED";
22583   case PENDING_LOCK: return "PENDING";
22584   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22585   }
22586   return "ERROR";
22587 }
22588 #endif
22589
22590 /*
22591 ** If we are currently in a different thread than the thread that the
22592 ** unixFile argument belongs to, then transfer ownership of the unixFile
22593 ** over to the current thread.
22594 **
22595 ** A unixFile is only owned by a thread on systems where one thread is
22596 ** unable to override locks created by a different thread.  RedHat9 is
22597 ** an example of such a system.
22598 **
22599 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
22600 ** If the unixFile is locked and an ownership is wrong, then return
22601 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22602 */
22603 #if SQLITE_THREADSAFE
22604 static int transferOwnership(unixFile *pFile){
22605   int rc;
22606   pthread_t hSelf;
22607   if( threadsOverrideEachOthersLocks ){
22608     /* Ownership transfers not needed on this system */
22609     return SQLITE_OK;
22610   }
22611   hSelf = pthread_self();
22612   if( pthread_equal(pFile->tid, hSelf) ){
22613     /* We are still in the same thread */
22614     OSTRACE1("No-transfer, same thread\n");
22615     return SQLITE_OK;
22616   }
22617   if( pFile->locktype!=NO_LOCK ){
22618     /* We cannot change ownership while we are holding a lock! */
22619     return SQLITE_MISUSE;
22620   }
22621   OSTRACE4("Transfer ownership of %d from %d to %d\n",
22622             pFile->h, pFile->tid, hSelf);
22623   pFile->tid = hSelf;
22624   if (pFile->pLock != NULL) {
22625     releaseLockInfo(pFile->pLock);
22626     rc = findLockInfo(pFile->h, &pFile->pLock, 0);
22627     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22628            locktypeName(pFile->locktype),
22629            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22630     return rc;
22631   } else {
22632     return SQLITE_OK;
22633   }
22634 }
22635 #else
22636   /* On single-threaded builds, ownership transfer is a no-op */
22637 # define transferOwnership(X) SQLITE_OK
22638 #endif
22639
22640 /*
22641 ** Seek to the offset passed as the second argument, then read cnt 
22642 ** bytes into pBuf. Return the number of bytes actually read.
22643 **
22644 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
22645 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
22646 ** one system to another.  Since SQLite does not define USE_PREAD
22647 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
22648 ** See tickets #2741 and #2681.
22649 */
22650 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
22651   int got;
22652   i64 newOffset;
22653   TIMER_START;
22654 #if defined(USE_PREAD)
22655   got = pread(id->h, pBuf, cnt, offset);
22656   SimulateIOError( got = -1 );
22657 #elif defined(USE_PREAD64)
22658   got = pread64(id->h, pBuf, cnt, offset);
22659   SimulateIOError( got = -1 );
22660 #else
22661   newOffset = lseek(id->h, offset, SEEK_SET);
22662   SimulateIOError( newOffset-- );
22663   if( newOffset!=offset ){
22664     return -1;
22665   }
22666   got = read(id->h, pBuf, cnt);
22667 #endif
22668   TIMER_END;
22669   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22670   return got;
22671 }
22672
22673 /*
22674 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22675 ** bytes were read successfully and SQLITE_IOERR if anything goes
22676 ** wrong.
22677 */
22678 static int unixRead(
22679   sqlite3_file *id, 
22680   void *pBuf, 
22681   int amt,
22682   sqlite3_int64 offset
22683 ){
22684   int got;
22685   assert( id );
22686   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
22687   if( got==amt ){
22688     return SQLITE_OK;
22689   }else if( got<0 ){
22690     return SQLITE_IOERR_READ;
22691   }else{
22692     memset(&((char*)pBuf)[got], 0, amt-got);
22693     return SQLITE_IOERR_SHORT_READ;
22694   }
22695 }
22696
22697 /*
22698 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
22699 ** Return the number of bytes actually read.  Update the offset.
22700 */
22701 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
22702   int got;
22703   i64 newOffset;
22704   TIMER_START;
22705 #if defined(USE_PREAD)
22706   got = pwrite(id->h, pBuf, cnt, offset);
22707 #elif defined(USE_PREAD64)
22708   got = pwrite64(id->h, pBuf, cnt, offset);
22709 #else
22710   newOffset = lseek(id->h, offset, SEEK_SET);
22711   if( newOffset!=offset ){
22712     return -1;
22713   }
22714   got = write(id->h, pBuf, cnt);
22715 #endif
22716   TIMER_END;
22717   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
22718   return got;
22719 }
22720
22721
22722 /*
22723 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22724 ** or some other error code on failure.
22725 */
22726 static int unixWrite(
22727   sqlite3_file *id, 
22728   const void *pBuf, 
22729   int amt,
22730   sqlite3_int64 offset 
22731 ){
22732   int wrote = 0;
22733   assert( id );
22734   assert( amt>0 );
22735   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
22736     amt -= wrote;
22737     offset += wrote;
22738     pBuf = &((char*)pBuf)[wrote];
22739   }
22740   SimulateIOError(( wrote=(-1), amt=1 ));
22741   SimulateDiskfullError(( wrote=0, amt=1 ));
22742   if( amt>0 ){
22743     if( wrote<0 ){
22744       return SQLITE_IOERR_WRITE;
22745     }else{
22746       return SQLITE_FULL;
22747     }
22748   }
22749   return SQLITE_OK;
22750 }
22751
22752 #ifdef SQLITE_TEST
22753 /*
22754 ** Count the number of fullsyncs and normal syncs.  This is used to test
22755 ** that syncs and fullsyncs are occuring at the right times.
22756 */
22757 SQLITE_API int sqlite3_sync_count = 0;
22758 SQLITE_API int sqlite3_fullsync_count = 0;
22759 #endif
22760
22761 /*
22762 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
22763 ** Otherwise use fsync() in its place.
22764 */
22765 #ifndef HAVE_FDATASYNC
22766 # define fdatasync fsync
22767 #endif
22768
22769 /*
22770 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
22771 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
22772 ** only available on Mac OS X.  But that could change.
22773 */
22774 #ifdef F_FULLFSYNC
22775 # define HAVE_FULLFSYNC 1
22776 #else
22777 # define HAVE_FULLFSYNC 0
22778 #endif
22779
22780
22781 /*
22782 ** The fsync() system call does not work as advertised on many
22783 ** unix systems.  The following procedure is an attempt to make
22784 ** it work better.
22785 **
22786 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
22787 ** for testing when we want to run through the test suite quickly.
22788 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
22789 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
22790 ** or power failure will likely corrupt the database file.
22791 */
22792 static int full_fsync(int fd, int fullSync, int dataOnly){
22793   int rc;
22794
22795   /* Record the number of times that we do a normal fsync() and 
22796   ** FULLSYNC.  This is used during testing to verify that this procedure
22797   ** gets called with the correct arguments.
22798   */
22799 #ifdef SQLITE_TEST
22800   if( fullSync ) sqlite3_fullsync_count++;
22801   sqlite3_sync_count++;
22802 #endif
22803
22804   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22805   ** no-op
22806   */
22807 #ifdef SQLITE_NO_SYNC
22808   rc = SQLITE_OK;
22809 #else
22810
22811 #if HAVE_FULLFSYNC
22812   if( fullSync ){
22813     rc = fcntl(fd, F_FULLFSYNC, 0);
22814   }else{
22815     rc = 1;
22816   }
22817   /* If the FULLFSYNC failed, fall back to attempting an fsync().
22818    * It shouldn't be possible for fullfsync to fail on the local 
22819    * file system (on OSX), so failure indicates that FULLFSYNC
22820    * isn't supported for this file system. So, attempt an fsync 
22821    * and (for now) ignore the overhead of a superfluous fcntl call.  
22822    * It'd be better to detect fullfsync support once and avoid 
22823    * the fcntl call every time sync is called.
22824    */
22825   if( rc ) rc = fsync(fd);
22826
22827 #else 
22828   if( dataOnly ){
22829     rc = fdatasync(fd);
22830   }else{
22831     rc = fsync(fd);
22832   }
22833 #endif /* HAVE_FULLFSYNC */
22834 #endif /* defined(SQLITE_NO_SYNC) */
22835
22836   return rc;
22837 }
22838
22839 /*
22840 ** Make sure all writes to a particular file are committed to disk.
22841 **
22842 ** If dataOnly==0 then both the file itself and its metadata (file
22843 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
22844 ** file data is synced.
22845 **
22846 ** Under Unix, also make sure that the directory entry for the file
22847 ** has been created by fsync-ing the directory that contains the file.
22848 ** If we do not do this and we encounter a power failure, the directory
22849 ** entry for the journal might not exist after we reboot.  The next
22850 ** SQLite to access the file will not know that the journal exists (because
22851 ** the directory entry for the journal was never created) and the transaction
22852 ** will not roll back - possibly leading to database corruption.
22853 */
22854 static int unixSync(sqlite3_file *id, int flags){
22855   int rc;
22856   unixFile *pFile = (unixFile*)id;
22857
22858   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
22859   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
22860
22861   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
22862   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
22863       || (flags&0x0F)==SQLITE_SYNC_FULL
22864   );
22865
22866   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
22867   ** line is to test that doing so does not cause any problems.
22868   */
22869   SimulateDiskfullError( return SQLITE_FULL );
22870
22871   assert( pFile );
22872   OSTRACE2("SYNC    %-3d\n", pFile->h);
22873   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
22874   SimulateIOError( rc=1 );
22875   if( rc ){
22876     return SQLITE_IOERR_FSYNC;
22877   }
22878   if( pFile->dirfd>=0 ){
22879     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
22880             HAVE_FULLFSYNC, isFullsync);
22881 #ifndef SQLITE_DISABLE_DIRSYNC
22882     /* The directory sync is only attempted if full_fsync is
22883     ** turned off or unavailable.  If a full_fsync occurred above,
22884     ** then the directory sync is superfluous.
22885     */
22886     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
22887        /*
22888        ** We have received multiple reports of fsync() returning
22889        ** errors when applied to directories on certain file systems.
22890        ** A failed directory sync is not a big deal.  So it seems
22891        ** better to ignore the error.  Ticket #1657
22892        */
22893        /* return SQLITE_IOERR; */
22894     }
22895 #endif
22896     close(pFile->dirfd);  /* Only need to sync once, so close the directory */
22897     pFile->dirfd = -1;    /* when we are done. */
22898   }
22899   return SQLITE_OK;
22900 }
22901
22902 /*
22903 ** Truncate an open file to a specified size
22904 */
22905 static int unixTruncate(sqlite3_file *id, i64 nByte){
22906   int rc;
22907   assert( id );
22908   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22909   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
22910   if( rc ){
22911     return SQLITE_IOERR_TRUNCATE;
22912   }else{
22913     return SQLITE_OK;
22914   }
22915 }
22916
22917 /*
22918 ** Determine the current size of a file in bytes
22919 */
22920 static int unixFileSize(sqlite3_file *id, i64 *pSize){
22921   int rc;
22922   struct stat buf;
22923   assert( id );
22924   rc = fstat(((unixFile*)id)->h, &buf);
22925   SimulateIOError( rc=1 );
22926   if( rc!=0 ){
22927     return SQLITE_IOERR_FSTAT;
22928   }
22929   *pSize = buf.st_size;
22930
22931   /* When opening a zero-size database, the findLockInfo() procedure
22932   ** writes a single byte into that file in order to work around a bug
22933   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
22934   ** layers, we need to report this file size as zero even though it is
22935   ** really 1.   Ticket #3260.
22936   */
22937   if( *pSize==1 ) *pSize = 0;
22938
22939
22940   return SQLITE_OK;
22941 }
22942
22943 /*
22944 ** This routine translates a standard POSIX errno code into something
22945 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22946 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22947 ** and a variety of "please close the file descriptor NOW" errors into 
22948 ** SQLITE_IOERR
22949 ** 
22950 ** Errors during initialization of locks, or file system support for locks,
22951 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22952 */
22953 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22954   switch (posixError) {
22955   case 0: 
22956     return SQLITE_OK;
22957     
22958   case EAGAIN:
22959   case ETIMEDOUT:
22960   case EBUSY:
22961   case EINTR:
22962   case ENOLCK:  
22963     /* random NFS retry error, unless during file system support 
22964      * introspection, in which it actually means what it says */
22965     return SQLITE_BUSY;
22966     
22967   case EACCES: 
22968     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22969     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22970         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22971         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22972         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22973       return SQLITE_BUSY;
22974     }
22975     /* else fall through */
22976   case EPERM: 
22977     return SQLITE_PERM;
22978     
22979   case EDEADLK:
22980     return SQLITE_IOERR_BLOCKED;
22981     
22982 #if EOPNOTSUPP!=ENOTSUP
22983   case EOPNOTSUPP: 
22984     /* something went terribly awry, unless during file system support 
22985      * introspection, in which it actually means what it says */
22986 #endif
22987 #ifdef ENOTSUP
22988   case ENOTSUP: 
22989     /* invalid fd, unless during file system support introspection, in which 
22990      * it actually means what it says */
22991 #endif
22992   case EIO:
22993   case EBADF:
22994   case EINVAL:
22995   case ENOTCONN:
22996   case ENODEV:
22997   case ENXIO:
22998   case ENOENT:
22999   case ESTALE:
23000   case ENOSYS:
23001     /* these should force the client to close the file and reconnect */
23002     
23003   default: 
23004     return sqliteIOErr;
23005   }
23006 }
23007
23008 /*
23009 ** This routine checks if there is a RESERVED lock held on the specified
23010 ** file by this or any other process. If such a lock is held, set *pResOut
23011 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23012 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23013 */
23014 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23015   int rc = SQLITE_OK;
23016   int reserved = 0;
23017   unixFile *pFile = (unixFile*)id;
23018
23019   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23020
23021   assert( pFile );
23022   enterMutex(); /* Because pFile->pLock is shared across threads */
23023
23024   /* Check if a thread in this process holds such a lock */
23025   if( pFile->pLock->locktype>SHARED_LOCK ){
23026     reserved = 1;
23027   }
23028
23029   /* Otherwise see if some other process holds it.
23030   */
23031   if( !reserved ){
23032     struct flock lock;
23033     lock.l_whence = SEEK_SET;
23034     lock.l_start = RESERVED_BYTE;
23035     lock.l_len = 1;
23036     lock.l_type = F_WRLCK;
23037     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23038       int tErrno = errno;
23039       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23040       pFile->lastErrno = tErrno;
23041     } else if( lock.l_type!=F_UNLCK ){
23042       reserved = 1;
23043     }
23044   }
23045   
23046   leaveMutex();
23047   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23048
23049   *pResOut = reserved;
23050   return rc;
23051 }
23052
23053 /*
23054 ** Lock the file with the lock specified by parameter locktype - one
23055 ** of the following:
23056 **
23057 **     (1) SHARED_LOCK
23058 **     (2) RESERVED_LOCK
23059 **     (3) PENDING_LOCK
23060 **     (4) EXCLUSIVE_LOCK
23061 **
23062 ** Sometimes when requesting one lock state, additional lock states
23063 ** are inserted in between.  The locking might fail on one of the later
23064 ** transitions leaving the lock state different from what it started but
23065 ** still short of its goal.  The following chart shows the allowed
23066 ** transitions and the inserted intermediate states:
23067 **
23068 **    UNLOCKED -> SHARED
23069 **    SHARED -> RESERVED
23070 **    SHARED -> (PENDING) -> EXCLUSIVE
23071 **    RESERVED -> (PENDING) -> EXCLUSIVE
23072 **    PENDING -> EXCLUSIVE
23073 **
23074 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23075 ** routine to lower a locking level.
23076 */
23077 static int unixLock(sqlite3_file *id, int locktype){
23078   /* The following describes the implementation of the various locks and
23079   ** lock transitions in terms of the POSIX advisory shared and exclusive
23080   ** lock primitives (called read-locks and write-locks below, to avoid
23081   ** confusion with SQLite lock names). The algorithms are complicated
23082   ** slightly in order to be compatible with windows systems simultaneously
23083   ** accessing the same database file, in case that is ever required.
23084   **
23085   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23086   ** byte', each single bytes at well known offsets, and the 'shared byte
23087   ** range', a range of 510 bytes at a well known offset.
23088   **
23089   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23090   ** byte'.  If this is successful, a random byte from the 'shared byte
23091   ** range' is read-locked and the lock on the 'pending byte' released.
23092   **
23093   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23094   ** A RESERVED lock is implemented by grabbing a write-lock on the
23095   ** 'reserved byte'. 
23096   **
23097   ** A process may only obtain a PENDING lock after it has obtained a
23098   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23099   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23100   ** obtained, but existing SHARED locks are allowed to persist. A process
23101   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23102   ** This property is used by the algorithm for rolling back a journal file
23103   ** after a crash.
23104   **
23105   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23106   ** implemented by obtaining a write-lock on the entire 'shared byte
23107   ** range'. Since all other locks require a read-lock on one of the bytes
23108   ** within this range, this ensures that no other locks are held on the
23109   ** database. 
23110   **
23111   ** The reason a single byte cannot be used instead of the 'shared byte
23112   ** range' is that some versions of windows do not support read-locks. By
23113   ** locking a random byte from a range, concurrent SHARED locks may exist
23114   ** even if the locking primitive used is always a write-lock.
23115   */
23116   int rc = SQLITE_OK;
23117   unixFile *pFile = (unixFile*)id;
23118   struct lockInfo *pLock = pFile->pLock;
23119   struct flock lock;
23120   int s;
23121
23122   assert( pFile );
23123   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
23124       locktypeName(locktype), locktypeName(pFile->locktype),
23125       locktypeName(pLock->locktype), pLock->cnt , getpid());
23126
23127   /* If there is already a lock of this type or more restrictive on the
23128   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23129   ** enterMutex() hasn't been called yet.
23130   */
23131   if( pFile->locktype>=locktype ){
23132     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23133             locktypeName(locktype));
23134     return SQLITE_OK;
23135   }
23136
23137   /* Make sure the locking sequence is correct
23138   */
23139   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23140   assert( locktype!=PENDING_LOCK );
23141   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23142
23143   /* This mutex is needed because pFile->pLock is shared across threads
23144   */
23145   enterMutex();
23146
23147   /* Make sure the current thread owns the pFile.
23148   */
23149   rc = transferOwnership(pFile);
23150   if( rc!=SQLITE_OK ){
23151     leaveMutex();
23152     return rc;
23153   }
23154   pLock = pFile->pLock;
23155
23156   /* If some thread using this PID has a lock via a different unixFile*
23157   ** handle that precludes the requested lock, return BUSY.
23158   */
23159   if( (pFile->locktype!=pLock->locktype && 
23160           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23161   ){
23162     rc = SQLITE_BUSY;
23163     goto end_lock;
23164   }
23165
23166   /* If a SHARED lock is requested, and some thread using this PID already
23167   ** has a SHARED or RESERVED lock, then increment reference counts and
23168   ** return SQLITE_OK.
23169   */
23170   if( locktype==SHARED_LOCK && 
23171       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23172     assert( locktype==SHARED_LOCK );
23173     assert( pFile->locktype==0 );
23174     assert( pLock->cnt>0 );
23175     pFile->locktype = SHARED_LOCK;
23176     pLock->cnt++;
23177     pFile->pOpen->nLock++;
23178     goto end_lock;
23179   }
23180
23181   lock.l_len = 1L;
23182
23183   lock.l_whence = SEEK_SET;
23184
23185   /* A PENDING lock is needed before acquiring a SHARED lock and before
23186   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23187   ** be released.
23188   */
23189   if( locktype==SHARED_LOCK 
23190       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23191   ){
23192     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23193     lock.l_start = PENDING_BYTE;
23194     s = fcntl(pFile->h, F_SETLK, &lock);
23195     if( s==(-1) ){
23196       int tErrno = errno;
23197       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23198       if( IS_LOCK_ERROR(rc) ){
23199         pFile->lastErrno = tErrno;
23200       }
23201       goto end_lock;
23202     }
23203   }
23204
23205
23206   /* If control gets to this point, then actually go ahead and make
23207   ** operating system calls for the specified lock.
23208   */
23209   if( locktype==SHARED_LOCK ){
23210     int tErrno = 0;
23211     assert( pLock->cnt==0 );
23212     assert( pLock->locktype==0 );
23213
23214     /* Now get the read-lock */
23215     lock.l_start = SHARED_FIRST;
23216     lock.l_len = SHARED_SIZE;
23217     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23218       tErrno = errno;
23219     }
23220     /* Drop the temporary PENDING lock */
23221     lock.l_start = PENDING_BYTE;
23222     lock.l_len = 1L;
23223     lock.l_type = F_UNLCK;
23224     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23225       if( s != -1 ){
23226         /* This could happen with a network mount */
23227         tErrno = errno; 
23228         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23229         if( IS_LOCK_ERROR(rc) ){
23230           pFile->lastErrno = tErrno;
23231         }
23232         goto end_lock;
23233       }
23234     }
23235     if( s==(-1) ){
23236       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23237       if( IS_LOCK_ERROR(rc) ){
23238         pFile->lastErrno = tErrno;
23239       }
23240     }else{
23241       pFile->locktype = SHARED_LOCK;
23242       pFile->pOpen->nLock++;
23243       pLock->cnt = 1;
23244     }
23245   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23246     /* We are trying for an exclusive lock but another thread in this
23247     ** same process is still holding a shared lock. */
23248     rc = SQLITE_BUSY;
23249   }else{
23250     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23251     ** assumed that there is a SHARED or greater lock on the file
23252     ** already.
23253     */
23254     assert( 0!=pFile->locktype );
23255     lock.l_type = F_WRLCK;
23256     switch( locktype ){
23257       case RESERVED_LOCK:
23258         lock.l_start = RESERVED_BYTE;
23259         break;
23260       case EXCLUSIVE_LOCK:
23261         lock.l_start = SHARED_FIRST;
23262         lock.l_len = SHARED_SIZE;
23263         break;
23264       default:
23265         assert(0);
23266     }
23267     s = fcntl(pFile->h, F_SETLK, &lock);
23268     if( s==(-1) ){
23269       int tErrno = errno;
23270       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23271       if( IS_LOCK_ERROR(rc) ){
23272         pFile->lastErrno = tErrno;
23273       }
23274     }
23275   }
23276   
23277   if( rc==SQLITE_OK ){
23278     pFile->locktype = locktype;
23279     pLock->locktype = locktype;
23280   }else if( locktype==EXCLUSIVE_LOCK ){
23281     pFile->locktype = PENDING_LOCK;
23282     pLock->locktype = PENDING_LOCK;
23283   }
23284
23285 end_lock:
23286   leaveMutex();
23287   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23288       rc==SQLITE_OK ? "ok" : "failed");
23289   return rc;
23290 }
23291
23292 /*
23293 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23294 ** must be either NO_LOCK or SHARED_LOCK.
23295 **
23296 ** If the locking level of the file descriptor is already at or below
23297 ** the requested locking level, this routine is a no-op.
23298 */
23299 static int unixUnlock(sqlite3_file *id, int locktype){
23300   struct lockInfo *pLock;
23301   struct flock lock;
23302   int rc = SQLITE_OK;
23303   unixFile *pFile = (unixFile*)id;
23304   int h;
23305
23306   assert( pFile );
23307   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
23308       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23309
23310   assert( locktype<=SHARED_LOCK );
23311   if( pFile->locktype<=locktype ){
23312     return SQLITE_OK;
23313   }
23314   if( CHECK_THREADID(pFile) ){
23315     return SQLITE_MISUSE;
23316   }
23317   enterMutex();
23318   h = pFile->h;
23319   pLock = pFile->pLock;
23320   assert( pLock->cnt!=0 );
23321   if( pFile->locktype>SHARED_LOCK ){
23322     assert( pLock->locktype==pFile->locktype );
23323     SimulateIOErrorBenign(1);
23324     SimulateIOError( h=(-1) )
23325     SimulateIOErrorBenign(0);
23326     if( locktype==SHARED_LOCK ){
23327       lock.l_type = F_RDLCK;
23328       lock.l_whence = SEEK_SET;
23329       lock.l_start = SHARED_FIRST;
23330       lock.l_len = SHARED_SIZE;
23331       if( fcntl(h, F_SETLK, &lock)==(-1) ){
23332         int tErrno = errno;
23333         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23334         if( IS_LOCK_ERROR(rc) ){
23335           pFile->lastErrno = tErrno;
23336         }
23337                                 goto end_unlock;
23338       }
23339     }
23340     lock.l_type = F_UNLCK;
23341     lock.l_whence = SEEK_SET;
23342     lock.l_start = PENDING_BYTE;
23343     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23344     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23345       pLock->locktype = SHARED_LOCK;
23346     }else{
23347       int tErrno = errno;
23348       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23349       if( IS_LOCK_ERROR(rc) ){
23350         pFile->lastErrno = tErrno;
23351       }
23352                         goto end_unlock;
23353     }
23354   }
23355   if( locktype==NO_LOCK ){
23356     struct openCnt *pOpen;
23357
23358     /* Decrement the shared lock counter.  Release the lock using an
23359     ** OS call only when all threads in this same process have released
23360     ** the lock.
23361     */
23362     pLock->cnt--;
23363     if( pLock->cnt==0 ){
23364       lock.l_type = F_UNLCK;
23365       lock.l_whence = SEEK_SET;
23366       lock.l_start = lock.l_len = 0L;
23367       SimulateIOErrorBenign(1);
23368       SimulateIOError( h=(-1) )
23369       SimulateIOErrorBenign(0);
23370       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23371         pLock->locktype = NO_LOCK;
23372       }else{
23373         int tErrno = errno;
23374         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23375         if( IS_LOCK_ERROR(rc) ){
23376           pFile->lastErrno = tErrno;
23377         }
23378         pLock->cnt = 1;
23379                                 goto end_unlock;
23380       }
23381     }
23382
23383     /* Decrement the count of locks against this same file.  When the
23384     ** count reaches zero, close any other file descriptors whose close
23385     ** was deferred because of outstanding locks.
23386     */
23387     if( rc==SQLITE_OK ){
23388       pOpen = pFile->pOpen;
23389       pOpen->nLock--;
23390       assert( pOpen->nLock>=0 );
23391       if( pOpen->nLock==0 && pOpen->nPending>0 ){
23392         int i;
23393         for(i=0; i<pOpen->nPending; i++){
23394           close(pOpen->aPending[i]);
23395         }
23396         sqlite3_free(pOpen->aPending);
23397         pOpen->nPending = 0;
23398         pOpen->aPending = 0;
23399       }
23400     }
23401   }
23402         
23403 end_unlock:
23404   leaveMutex();
23405   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23406   return rc;
23407 }
23408
23409 /*
23410 ** This function performs the parts of the "close file" operation 
23411 ** common to all locking schemes. It closes the directory and file
23412 ** handles, if they are valid, and sets all fields of the unixFile
23413 ** structure to 0.
23414 */
23415 static int closeUnixFile(sqlite3_file *id){
23416   unixFile *pFile = (unixFile*)id;
23417   if( pFile ){
23418     if( pFile->dirfd>=0 ){
23419       close(pFile->dirfd);
23420     }
23421     if( pFile->h>=0 ){
23422       close(pFile->h);
23423     }
23424     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23425     OpenCounter(-1);
23426     memset(pFile, 0, sizeof(unixFile));
23427   }
23428   return SQLITE_OK;
23429 }
23430
23431 /*
23432 ** Close a file.
23433 */
23434 static int unixClose(sqlite3_file *id){
23435   if( id ){
23436     unixFile *pFile = (unixFile *)id;
23437     unixUnlock(id, NO_LOCK);
23438     enterMutex();
23439     if( pFile->pOpen && pFile->pOpen->nLock ){
23440       /* If there are outstanding locks, do not actually close the file just
23441       ** yet because that would clear those locks.  Instead, add the file
23442       ** descriptor to pOpen->aPending.  It will be automatically closed when
23443       ** the last lock is cleared.
23444       */
23445       int *aNew;
23446       struct openCnt *pOpen = pFile->pOpen;
23447       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
23448       if( aNew==0 ){
23449         /* If a malloc fails, just leak the file descriptor */
23450       }else{
23451         pOpen->aPending = aNew;
23452         pOpen->aPending[pOpen->nPending] = pFile->h;
23453         pOpen->nPending++;
23454         pFile->h = -1;
23455       }
23456     }
23457     releaseLockInfo(pFile->pLock);
23458     releaseOpenCnt(pFile->pOpen);
23459     closeUnixFile(id);
23460     leaveMutex();
23461   }
23462   return SQLITE_OK;
23463 }
23464
23465
23466 #if SQLITE_ENABLE_LOCKING_STYLE
23467 #pragma mark AFP Support
23468
23469 /*
23470  ** The afpLockingContext structure contains all afp lock specific state
23471  */
23472 typedef struct afpLockingContext afpLockingContext;
23473 struct afpLockingContext {
23474   unsigned long long sharedLockByte;
23475   const char *filePath;
23476 };
23477
23478 struct ByteRangeLockPB2
23479 {
23480   unsigned long long offset;        /* offset to first byte to lock */
23481   unsigned long long length;        /* nbr of bytes to lock */
23482   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23483   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23484   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23485   int fd;                           /* file desc to assoc this lock with */
23486 };
23487
23488 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23489
23490 /* 
23491  ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23492  */
23493 static int _AFPFSSetLock(
23494   const char *path, 
23495   unixFile *pFile, 
23496   unsigned long long offset, 
23497   unsigned long long length, 
23498   int setLockFlag
23499 ){
23500   struct ByteRangeLockPB2       pb;
23501   int                     err;
23502   
23503   pb.unLockFlag = setLockFlag ? 0 : 1;
23504   pb.startEndFlag = 0;
23505   pb.offset = offset;
23506   pb.length = length; 
23507   pb.fd = pFile->h;
23508   OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
23509     (setLockFlag?"ON":"OFF"), pFile->h, offset, length);
23510   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23511   if ( err==-1 ) {
23512     int rc;
23513     int tErrno = errno;
23514     OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, tErrno, strerror(tErrno));
23515     rc = sqliteErrorFromPosixError(tErrno, setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); /* error */
23516     if( IS_LOCK_ERROR(rc) ){
23517       pFile->lastErrno = tErrno;
23518     }
23519     return rc;
23520   } else {
23521     return SQLITE_OK;
23522   }
23523 }
23524
23525 /* AFP-style reserved lock checking following the behavior of 
23526 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23527 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23528   int rc = SQLITE_OK;
23529   int reserved = 0;
23530   unixFile *pFile = (unixFile*)id;
23531   
23532   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23533   
23534   assert( pFile );
23535   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23536   
23537   /* Check if a thread in this process holds such a lock */
23538   if( pFile->locktype>SHARED_LOCK ){
23539     reserved = 1;
23540   }
23541   
23542   /* Otherwise see if some other process holds it.
23543    */
23544   if( !reserved ){
23545     /* lock the RESERVED byte */
23546     int lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);  
23547     if( SQLITE_OK==lrc ){
23548       /* if we succeeded in taking the reserved lock, unlock it to restore
23549       ** the original state */
23550       lrc = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1, 0);
23551     } else {
23552       /* if we failed to get the lock then someone else must have it */
23553       reserved = 1;
23554     }
23555     if( IS_LOCK_ERROR(lrc) ){
23556       rc=lrc;
23557     }
23558   }
23559   
23560   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23561   
23562   *pResOut = reserved;
23563   return rc;
23564 }
23565
23566 /* AFP-style locking following the behavior of unixLock, see the unixLock 
23567 ** function comments for details of lock management. */
23568 static int afpLock(sqlite3_file *id, int locktype){
23569   int rc = SQLITE_OK;
23570   unixFile *pFile = (unixFile*)id;
23571   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23572   
23573   assert( pFile );
23574   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
23575          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
23576
23577   /* If there is already a lock of this type or more restrictive on the
23578   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
23579   ** enterMutex() hasn't been called yet.
23580   */
23581   if( pFile->locktype>=locktype ){
23582     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23583            locktypeName(locktype));
23584     return SQLITE_OK;
23585   }
23586
23587   /* Make sure the locking sequence is correct
23588   */
23589   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23590   assert( locktype!=PENDING_LOCK );
23591   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23592   
23593   /* This mutex is needed because pFile->pLock is shared across threads
23594   */
23595   enterMutex();
23596
23597   /* Make sure the current thread owns the pFile.
23598   */
23599   rc = transferOwnership(pFile);
23600   if( rc!=SQLITE_OK ){
23601     leaveMutex();
23602     return rc;
23603   }
23604     
23605   /* A PENDING lock is needed before acquiring a SHARED lock and before
23606   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23607   ** be released.
23608   */
23609   if( locktype==SHARED_LOCK 
23610       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23611   ){
23612     int failed;
23613     failed = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 1);
23614     if (failed) {
23615       rc = failed;
23616       goto afp_end_lock;
23617     }
23618   }
23619   
23620   /* If control gets to this point, then actually go ahead and make
23621   ** operating system calls for the specified lock.
23622   */
23623   if( locktype==SHARED_LOCK ){
23624     int lk, lrc1, lrc2, lrc1Errno;
23625     
23626     /* Now get the read-lock SHARED_LOCK */
23627     /* note that the quality of the randomness doesn't matter that much */
23628     lk = random(); 
23629     context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
23630     lrc1 = _AFPFSSetLock(context->filePath, pFile, 
23631           SHARED_FIRST+context->sharedLockByte, 1, 1);
23632     if( IS_LOCK_ERROR(lrc1) ){
23633       lrc1Errno = pFile->lastErrno;
23634     }
23635     /* Drop the temporary PENDING lock */
23636     lrc2 = _AFPFSSetLock(context->filePath, pFile, PENDING_BYTE, 1, 0);
23637     
23638     if( IS_LOCK_ERROR(lrc1) ) {
23639       pFile->lastErrno = lrc1Errno;
23640       rc = lrc1;
23641       goto afp_end_lock;
23642     } else if( IS_LOCK_ERROR(lrc2) ){
23643       rc = lrc2;
23644       goto afp_end_lock;
23645     } else if( lrc1 != SQLITE_OK ) {
23646       rc = lrc1;
23647     } else {
23648       pFile->locktype = SHARED_LOCK;
23649     }
23650   }else{
23651     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23652     ** assumed that there is a SHARED or greater lock on the file
23653     ** already.
23654     */
23655     int failed = 0;
23656     assert( 0!=pFile->locktype );
23657     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
23658         /* Acquire a RESERVED lock */
23659         failed = _AFPFSSetLock(context->filePath, pFile, RESERVED_BYTE, 1,1);
23660     }
23661     if (!failed && locktype == EXCLUSIVE_LOCK) {
23662       /* Acquire an EXCLUSIVE lock */
23663         
23664       /* Remove the shared lock before trying the range.  we'll need to 
23665       ** reestablish the shared lock if we can't get the  afpUnlock
23666       */
23667       if (!(failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST +
23668                          context->sharedLockByte, 1, 0))) {
23669         /* now attemmpt to get the exclusive lock range */
23670         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23671                                SHARED_SIZE, 1);
23672         if (failed && (failed = _AFPFSSetLock(context->filePath, pFile, 
23673                        SHARED_FIRST + context->sharedLockByte, 1, 1))) {
23674           rc = failed;
23675         }
23676       } else {
23677         rc = failed; 
23678       }
23679     }
23680     if( failed ){
23681       rc = failed;
23682     }
23683   }
23684   
23685   if( rc==SQLITE_OK ){
23686     pFile->locktype = locktype;
23687   }else if( locktype==EXCLUSIVE_LOCK ){
23688     pFile->locktype = PENDING_LOCK;
23689   }
23690   
23691 afp_end_lock:
23692   leaveMutex();
23693   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23694          rc==SQLITE_OK ? "ok" : "failed");
23695   return rc;
23696 }
23697
23698 /*
23699 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23700 ** must be either NO_LOCK or SHARED_LOCK.
23701 **
23702 ** If the locking level of the file descriptor is already at or below
23703 ** the requested locking level, this routine is a no-op.
23704 */
23705 static int afpUnlock(sqlite3_file *id, int locktype) {
23706   int rc = SQLITE_OK;
23707   unixFile *pFile = (unixFile*)id;
23708   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23709
23710   assert( pFile );
23711   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23712          pFile->locktype, getpid());
23713
23714   assert( locktype<=SHARED_LOCK );
23715   if( pFile->locktype<=locktype ){
23716     return SQLITE_OK;
23717   }
23718   if( CHECK_THREADID(pFile) ){
23719     return SQLITE_MISUSE;
23720   }
23721   enterMutex();
23722   int failed = SQLITE_OK;
23723   if( pFile->locktype>SHARED_LOCK ){
23724     if( locktype==SHARED_LOCK ){
23725
23726       /* unlock the exclusive range - then re-establish the shared lock */
23727       if (pFile->locktype==EXCLUSIVE_LOCK) {
23728         failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST, 
23729                                  SHARED_SIZE, 0);
23730         if (!failed) {
23731           /* successfully removed the exclusive lock */
23732           if ((failed = _AFPFSSetLock(context->filePath, pFile, SHARED_FIRST+
23733                             context->sharedLockByte, 1, 1))) {
23734             /* failed to re-establish our shared lock */
23735             rc = failed;
23736           }
23737         } else {
23738           rc = failed;
23739         } 
23740       }
23741     }
23742     if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
23743       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23744                                   PENDING_BYTE, 1, 0))){
23745         /* failed to release the pending lock */
23746         rc = failed; 
23747       }
23748     } 
23749     if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
23750       if ((failed = _AFPFSSetLock(context->filePath, pFile, 
23751                                   RESERVED_BYTE, 1, 0))) {
23752         /* failed to release the reserved lock */
23753         rc = failed;  
23754       }
23755     } 
23756   }
23757   if( locktype==NO_LOCK ){
23758     int failed = _AFPFSSetLock(context->filePath, pFile, 
23759                                SHARED_FIRST + context->sharedLockByte, 1, 0);
23760     if (failed) {
23761       rc = failed;  
23762     }
23763   }
23764   if (rc == SQLITE_OK)
23765     pFile->locktype = locktype;
23766   leaveMutex();
23767   return rc;
23768 }
23769
23770 /*
23771 ** Close a file & cleanup AFP specific locking context 
23772 */
23773 static int afpClose(sqlite3_file *id) {
23774   if( id ){
23775     unixFile *pFile = (unixFile*)id;
23776     afpUnlock(id, NO_LOCK);
23777     sqlite3_free(pFile->lockingContext);
23778   }
23779   return closeUnixFile(id);
23780 }
23781
23782
23783 #pragma mark flock() style locking
23784
23785 /*
23786 ** The flockLockingContext is not used
23787 */
23788 typedef void flockLockingContext;
23789
23790 /* flock-style reserved lock checking following the behavior of 
23791  ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23792 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23793   int rc = SQLITE_OK;
23794   int reserved = 0;
23795   unixFile *pFile = (unixFile*)id;
23796   
23797   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23798   
23799   assert( pFile );
23800   
23801   /* Check if a thread in this process holds such a lock */
23802   if( pFile->locktype>SHARED_LOCK ){
23803     reserved = 1;
23804   }
23805   
23806   /* Otherwise see if some other process holds it. */
23807   if( !reserved ){
23808     /* attempt to get the lock */
23809     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23810     if( !lrc ){
23811       /* got the lock, unlock it */
23812       lrc = flock(pFile->h, LOCK_UN);
23813       if ( lrc ) {
23814         int tErrno = errno;
23815         /* unlock failed with an error */
23816         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23817         if( IS_LOCK_ERROR(lrc) ){
23818           pFile->lastErrno = tErrno;
23819           rc = lrc;
23820         }
23821       }
23822     } else {
23823       int tErrno = errno;
23824       reserved = 1;
23825       /* someone else might have it reserved */
23826       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
23827       if( IS_LOCK_ERROR(lrc) ){
23828         pFile->lastErrno = tErrno;
23829         rc = lrc;
23830       }
23831     }
23832   }
23833   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23834
23835   *pResOut = reserved;
23836   return rc;
23837 }
23838
23839 static int flockLock(sqlite3_file *id, int locktype) {
23840   int rc = SQLITE_OK;
23841   unixFile *pFile = (unixFile*)id;
23842
23843   assert( pFile );
23844
23845   /* if we already have a lock, it is exclusive.  
23846   ** Just adjust level and punt on outta here. */
23847   if (pFile->locktype > NO_LOCK) {
23848     pFile->locktype = locktype;
23849     return SQLITE_OK;
23850   }
23851   
23852   /* grab an exclusive lock */
23853   
23854   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23855     int tErrno = errno;
23856     /* didn't get, must be busy */
23857     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23858     if( IS_LOCK_ERROR(rc) ){
23859       pFile->lastErrno = tErrno;
23860     }
23861   } else {
23862     /* got it, set the type and return ok */
23863     pFile->locktype = locktype;
23864   }
23865   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23866            rc==SQLITE_OK ? "ok" : "failed");
23867   return rc;
23868 }
23869
23870 static int flockUnlock(sqlite3_file *id, int locktype) {
23871   unixFile *pFile = (unixFile*)id;
23872   
23873   assert( pFile );
23874   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23875            pFile->locktype, getpid());
23876   assert( locktype<=SHARED_LOCK );
23877   
23878   /* no-op if possible */
23879   if( pFile->locktype==locktype ){
23880     return SQLITE_OK;
23881   }
23882   
23883   /* shared can just be set because we always have an exclusive */
23884   if (locktype==SHARED_LOCK) {
23885     pFile->locktype = locktype;
23886     return SQLITE_OK;
23887   }
23888   
23889   /* no, really, unlock. */
23890   int rc = flock(pFile->h, LOCK_UN);
23891   if (rc) {
23892     int r, tErrno = errno;
23893     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23894     if( IS_LOCK_ERROR(r) ){
23895       pFile->lastErrno = tErrno;
23896     }
23897     return r;
23898   } else {
23899     pFile->locktype = NO_LOCK;
23900     return SQLITE_OK;
23901   }
23902 }
23903
23904 /*
23905 ** Close a file.
23906 */
23907 static int flockClose(sqlite3_file *id) {
23908   if( id ){
23909     flockUnlock(id, NO_LOCK);
23910   }
23911   return closeUnixFile(id);
23912 }
23913
23914 #pragma mark Old-School .lock file based locking
23915
23916 /* Dotlock-style reserved lock checking following the behavior of 
23917 ** unixCheckReservedLock, see the unixCheckReservedLock function comments */
23918 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23919   int rc = SQLITE_OK;
23920   int reserved = 0;
23921   unixFile *pFile = (unixFile*)id;
23922
23923   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23924   
23925   assert( pFile );
23926
23927   /* Check if a thread in this process holds such a lock */
23928   if( pFile->locktype>SHARED_LOCK ){
23929     reserved = 1;
23930   }
23931   
23932   /* Otherwise see if some other process holds it. */
23933   if( !reserved ){
23934     char *zLockFile = (char *)pFile->lockingContext;
23935     struct stat statBuf;
23936     
23937     if( lstat(zLockFile, &statBuf)==0 ){
23938       /* file exists, someone else has the lock */
23939       reserved = 1;
23940     }else{
23941       /* file does not exist, we could have it if we want it */
23942                         int tErrno = errno;
23943       if( ENOENT != tErrno ){
23944         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23945         pFile->lastErrno = tErrno;
23946       }
23947     }
23948   }
23949   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23950
23951   *pResOut = reserved;
23952   return rc;
23953 }
23954
23955 static int dotlockLock(sqlite3_file *id, int locktype) {
23956   unixFile *pFile = (unixFile*)id;
23957   int fd;
23958   char *zLockFile = (char *)pFile->lockingContext;
23959   int rc=SQLITE_OK;
23960
23961   /* if we already have a lock, it is exclusive.  
23962   ** Just adjust level and punt on outta here. */
23963   if (pFile->locktype > NO_LOCK) {
23964     pFile->locktype = locktype;
23965     
23966     /* Always update the timestamp on the old file */
23967     utimes(zLockFile, NULL);
23968     rc = SQLITE_OK;
23969     goto dotlock_end_lock;
23970   }
23971   
23972   /* check to see if lock file already exists */
23973   struct stat statBuf;
23974   if (lstat(zLockFile,&statBuf) == 0){
23975     rc = SQLITE_BUSY; /* it does, busy */
23976     goto dotlock_end_lock;
23977   }
23978   
23979   /* grab an exclusive lock */
23980   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23981   if( fd<0 ){
23982     /* failed to open/create the file, someone else may have stolen the lock */
23983     int tErrno = errno;
23984     if( EEXIST == tErrno ){
23985       rc = SQLITE_BUSY;
23986     } else {
23987       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23988       if( IS_LOCK_ERROR(rc) ){
23989         pFile->lastErrno = tErrno;
23990       }
23991     }
23992     goto dotlock_end_lock;
23993   } 
23994   close(fd);
23995   
23996   /* got it, set the type and return ok */
23997   pFile->locktype = locktype;
23998
23999  dotlock_end_lock:
24000   return rc;
24001 }
24002
24003 static int dotlockUnlock(sqlite3_file *id, int locktype) {
24004   unixFile *pFile = (unixFile*)id;
24005   char *zLockFile = (char *)pFile->lockingContext;
24006
24007   assert( pFile );
24008   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24009            pFile->locktype, getpid());
24010   assert( locktype<=SHARED_LOCK );
24011   
24012   /* no-op if possible */
24013   if( pFile->locktype==locktype ){
24014     return SQLITE_OK;
24015   }
24016   
24017   /* shared can just be set because we always have an exclusive */
24018   if (locktype==SHARED_LOCK) {
24019     pFile->locktype = locktype;
24020     return SQLITE_OK;
24021   }
24022   
24023   /* no, really, unlock. */
24024   if (unlink(zLockFile) ) {
24025     int rc, tErrno = errno;
24026     if( ENOENT != tErrno ){
24027       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24028     }
24029     if( IS_LOCK_ERROR(rc) ){
24030       pFile->lastErrno = tErrno;
24031     }
24032     return rc; 
24033   }
24034   pFile->locktype = NO_LOCK;
24035   return SQLITE_OK;
24036 }
24037
24038 /*
24039  ** Close a file.
24040  */
24041 static int dotlockClose(sqlite3_file *id) {
24042   if( id ){
24043     unixFile *pFile = (unixFile*)id;
24044     dotlockUnlock(id, NO_LOCK);
24045     sqlite3_free(pFile->lockingContext);
24046   }
24047   return closeUnixFile(id);
24048 }
24049
24050
24051 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24052
24053 /*
24054 ** The nolockLockingContext is void
24055 */
24056 typedef void nolockLockingContext;
24057
24058 static int nolockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24059   *pResOut = 0;
24060   return SQLITE_OK;
24061 }
24062
24063 static int nolockLock(sqlite3_file *id, int locktype) {
24064   return SQLITE_OK;
24065 }
24066
24067 static int nolockUnlock(sqlite3_file *id, int locktype) {
24068   return SQLITE_OK;
24069 }
24070
24071 /*
24072 ** Close a file.
24073 */
24074 static int nolockClose(sqlite3_file *id) {
24075   return closeUnixFile(id);
24076 }
24077
24078
24079 /*
24080 ** Information and control of an open file handle.
24081 */
24082 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24083   switch( op ){
24084     case SQLITE_FCNTL_LOCKSTATE: {
24085       *(int*)pArg = ((unixFile*)id)->locktype;
24086       return SQLITE_OK;
24087     }
24088   }
24089   return SQLITE_ERROR;
24090 }
24091
24092 /*
24093 ** Return the sector size in bytes of the underlying block device for
24094 ** the specified file. This is almost always 512 bytes, but may be
24095 ** larger for some devices.
24096 **
24097 ** SQLite code assumes this function cannot fail. It also assumes that
24098 ** if two files are created in the same file-system directory (i.e.
24099 ** a database and its journal file) that the sector size will be the
24100 ** same for both.
24101 */
24102 static int unixSectorSize(sqlite3_file *id){
24103   return SQLITE_DEFAULT_SECTOR_SIZE;
24104 }
24105
24106 /*
24107 ** Return the device characteristics for the file. This is always 0.
24108 */
24109 static int unixDeviceCharacteristics(sqlite3_file *id){
24110   return 0;
24111 }
24112
24113 /*
24114 ** Initialize the contents of the unixFile structure pointed to by pId.
24115 **
24116 ** When locking extensions are enabled, the filepath and locking style 
24117 ** are needed to determine the unixFile pMethod to use for locking operations.
24118 ** The locking-style specific lockingContext data structure is created 
24119 ** and assigned here also.
24120 */
24121 static int fillInUnixFile(
24122   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
24123   int h,                  /* Open file descriptor of file being opened */
24124   int dirfd,              /* Directory file descriptor */
24125   sqlite3_file *pId,      /* Write to the unixFile structure here */
24126   const char *zFilename,  /* Name of the file being opened */
24127   int noLock              /* Omit locking if true */
24128 ){
24129   int eLockingStyle;
24130   unixFile *pNew = (unixFile *)pId;
24131   int rc = SQLITE_OK;
24132
24133   /* Macro to define the static contents of an sqlite3_io_methods 
24134   ** structure for a unix backend file. Different locking methods
24135   ** require different functions for the xClose, xLock, xUnlock and
24136   ** xCheckReservedLock methods.
24137   */
24138   #define IOMETHODS(xClose, xLock, xUnlock, xCheckReservedLock) {    \
24139     1,                          /* iVersion */                           \
24140     xClose,                     /* xClose */                             \
24141     unixRead,                   /* xRead */                              \
24142     unixWrite,                  /* xWrite */                             \
24143     unixTruncate,               /* xTruncate */                          \
24144     unixSync,                   /* xSync */                              \
24145     unixFileSize,               /* xFileSize */                          \
24146     xLock,                      /* xLock */                              \
24147     xUnlock,                    /* xUnlock */                            \
24148     xCheckReservedLock,         /* xCheckReservedLock */                 \
24149     unixFileControl,            /* xFileControl */                       \
24150     unixSectorSize,             /* xSectorSize */                        \
24151     unixDeviceCharacteristics   /* xDeviceCapabilities */                \
24152   }
24153   static sqlite3_io_methods aIoMethod[] = {
24154     IOMETHODS(unixClose, unixLock, unixUnlock, unixCheckReservedLock) 
24155    ,IOMETHODS(nolockClose, nolockLock, nolockUnlock, nolockCheckReservedLock)
24156 #if SQLITE_ENABLE_LOCKING_STYLE
24157    ,IOMETHODS(dotlockClose, dotlockLock, dotlockUnlock,dotlockCheckReservedLock)
24158    ,IOMETHODS(flockClose, flockLock, flockUnlock, flockCheckReservedLock)
24159    ,IOMETHODS(afpClose, afpLock, afpUnlock, afpCheckReservedLock)
24160 #endif
24161   };
24162   /* The order of the IOMETHODS macros above is important.  It must be the
24163   ** same order as the LOCKING_STYLE numbers
24164   */
24165   assert(LOCKING_STYLE_POSIX==1);
24166   assert(LOCKING_STYLE_NONE==2);
24167   assert(LOCKING_STYLE_DOTFILE==3);
24168   assert(LOCKING_STYLE_FLOCK==4);
24169   assert(LOCKING_STYLE_AFP==5);
24170
24171   assert( pNew->pLock==NULL );
24172   assert( pNew->pOpen==NULL );
24173
24174   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
24175   pNew->h = h;
24176   pNew->dirfd = dirfd;
24177   SET_THREADID(pNew);
24178
24179   if( noLock ){
24180     eLockingStyle = LOCKING_STYLE_NONE;
24181   }else{
24182     eLockingStyle = detectLockingStyle(pVfs, zFilename, h);
24183   }
24184
24185   switch( eLockingStyle ){
24186
24187     case LOCKING_STYLE_POSIX: {
24188       enterMutex();
24189       rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
24190       leaveMutex();
24191       break;
24192     }
24193
24194 #if SQLITE_ENABLE_LOCKING_STYLE
24195     case LOCKING_STYLE_AFP: {
24196       /* AFP locking uses the file path so it needs to be included in
24197       ** the afpLockingContext.
24198       */
24199       afpLockingContext *pCtx;
24200       pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
24201       if( pCtx==0 ){
24202         rc = SQLITE_NOMEM;
24203       }else{
24204         /* NB: zFilename exists and remains valid until the file is closed
24205         ** according to requirement F11141.  So we do not need to make a
24206         ** copy of the filename. */
24207         pCtx->filePath = zFilename;
24208         srandomdev();
24209       }
24210       break;
24211     }
24212
24213     case LOCKING_STYLE_DOTFILE: {
24214       /* Dotfile locking uses the file path so it needs to be included in
24215       ** the dotlockLockingContext 
24216       */
24217       char *zLockFile;
24218       int nFilename;
24219       nFilename = strlen(zFilename) + 6;
24220       zLockFile = (char *)sqlite3_malloc(nFilename);
24221       if( zLockFile==0 ){
24222         rc = SQLITE_NOMEM;
24223       }else{
24224         sqlite3_snprintf(nFilename, zLockFile, "%s.lock", zFilename);
24225       }
24226       pNew->lockingContext = zLockFile;
24227       break;
24228     }
24229
24230     case LOCKING_STYLE_FLOCK: 
24231     case LOCKING_STYLE_NONE: 
24232       break;
24233 #endif
24234   }
24235   
24236   pNew->lastErrno = 0;
24237   if( rc!=SQLITE_OK ){
24238     if( dirfd>=0 ) close(dirfd);
24239     close(h);
24240   }else{
24241     pNew->pMethod = &aIoMethod[eLockingStyle-1];
24242     OpenCounter(+1);
24243   }
24244   return rc;
24245 }
24246
24247 /*
24248 ** Open a file descriptor to the directory containing file zFilename.
24249 ** If successful, *pFd is set to the opened file descriptor and
24250 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
24251 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
24252 ** value.
24253 **
24254 ** If SQLITE_OK is returned, the caller is responsible for closing
24255 ** the file descriptor *pFd using close().
24256 */
24257 static int openDirectory(const char *zFilename, int *pFd){
24258   int ii;
24259   int fd = -1;
24260   char zDirname[MAX_PATHNAME+1];
24261
24262   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
24263   for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
24264   if( ii>0 ){
24265     zDirname[ii] = '\0';
24266     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
24267     if( fd>=0 ){
24268 #ifdef FD_CLOEXEC
24269       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24270 #endif
24271       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
24272     }
24273   }
24274   *pFd = fd;
24275   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
24276 }
24277
24278 /*
24279 ** Create a temporary file name in zBuf.  zBuf must be allocated
24280 ** by the calling process and must be big enough to hold at least
24281 ** pVfs->mxPathname bytes.
24282 */
24283 static int getTempname(int nBuf, char *zBuf){
24284   static const char *azDirs[] = {
24285      0,
24286      "/var/tmp",
24287      "/usr/tmp",
24288      "/tmp",
24289      ".",
24290   };
24291   static const unsigned char zChars[] =
24292     "abcdefghijklmnopqrstuvwxyz"
24293     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24294     "0123456789";
24295   int i, j;
24296   struct stat buf;
24297   const char *zDir = ".";
24298
24299   /* It's odd to simulate an io-error here, but really this is just
24300   ** using the io-error infrastructure to test that SQLite handles this
24301   ** function failing. 
24302   */
24303   SimulateIOError( return SQLITE_IOERR );
24304
24305   azDirs[0] = sqlite3_temp_directory;
24306   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
24307     if( azDirs[i]==0 ) continue;
24308     if( stat(azDirs[i], &buf) ) continue;
24309     if( !S_ISDIR(buf.st_mode) ) continue;
24310     if( access(azDirs[i], 07) ) continue;
24311     zDir = azDirs[i];
24312     break;
24313   }
24314
24315   /* Check that the output buffer is large enough for the temporary file 
24316   ** name. If it is not, return SQLITE_ERROR.
24317   */
24318   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
24319     return SQLITE_ERROR;
24320   }
24321
24322   do{
24323     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
24324     j = strlen(zBuf);
24325     sqlite3_randomness(15, &zBuf[j]);
24326     for(i=0; i<15; i++, j++){
24327       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24328     }
24329     zBuf[j] = 0;
24330   }while( access(zBuf,0)==0 );
24331   return SQLITE_OK;
24332 }
24333
24334
24335 /*
24336 ** Open the file zPath.
24337 ** 
24338 ** Previously, the SQLite OS layer used three functions in place of this
24339 ** one:
24340 **
24341 **     sqlite3OsOpenReadWrite();
24342 **     sqlite3OsOpenReadOnly();
24343 **     sqlite3OsOpenExclusive();
24344 **
24345 ** These calls correspond to the following combinations of flags:
24346 **
24347 **     ReadWrite() ->     (READWRITE | CREATE)
24348 **     ReadOnly()  ->     (READONLY) 
24349 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
24350 **
24351 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
24352 ** true, the file was configured to be automatically deleted when the
24353 ** file handle closed. To achieve the same effect using this new 
24354 ** interface, add the DELETEONCLOSE flag to those specified above for 
24355 ** OpenExclusive().
24356 */
24357 static int unixOpen(
24358   sqlite3_vfs *pVfs, 
24359   const char *zPath, 
24360   sqlite3_file *pFile,
24361   int flags,
24362   int *pOutFlags
24363 ){
24364   int fd = 0;                    /* File descriptor returned by open() */
24365   int dirfd = -1;                /* Directory file descriptor */
24366   int oflags = 0;                /* Flags to pass to open() */
24367   int eType = flags&0xFFFFFF00;  /* Type of file to open */
24368   int noLock;                    /* True to omit locking primitives */
24369
24370   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24371   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24372   int isCreate     = (flags & SQLITE_OPEN_CREATE);
24373   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24374   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24375
24376   /* If creating a master or main-file journal, this function will open
24377   ** a file-descriptor on the directory too. The first time unixSync()
24378   ** is called the directory file descriptor will be fsync()ed and close()d.
24379   */
24380   int isOpenDirectory = (isCreate && 
24381       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
24382   );
24383
24384   /* If argument zPath is a NULL pointer, this function is required to open
24385   ** a temporary file. Use this buffer to store the file name in.
24386   */
24387   char zTmpname[MAX_PATHNAME+1];
24388   const char *zName = zPath;
24389
24390   /* Check the following statements are true: 
24391   **
24392   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
24393   **   (b) if CREATE is set, then READWRITE must also be set, and
24394   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24395   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24396   */
24397   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24398   assert(isCreate==0 || isReadWrite);
24399   assert(isExclusive==0 || isCreate);
24400   assert(isDelete==0 || isCreate);
24401
24402   /* The main DB, main journal, and master journal are never automatically
24403   ** deleted
24404   */
24405   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
24406   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
24407   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
24408
24409   /* Assert that the upper layer has set one of the "file-type" flags. */
24410   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
24411        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
24412        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
24413        || eType==SQLITE_OPEN_TRANSIENT_DB
24414   );
24415
24416   memset(pFile, 0, sizeof(unixFile));
24417
24418   if( !zName ){
24419     int rc;
24420     assert(isDelete && !isOpenDirectory);
24421     rc = getTempname(MAX_PATHNAME+1, zTmpname);
24422     if( rc!=SQLITE_OK ){
24423       return rc;
24424     }
24425     zName = zTmpname;
24426   }
24427
24428   if( isReadonly )  oflags |= O_RDONLY;
24429   if( isReadWrite ) oflags |= O_RDWR;
24430   if( isCreate )    oflags |= O_CREAT;
24431   if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
24432   oflags |= (O_LARGEFILE|O_BINARY);
24433
24434   fd = open(zName, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
24435   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
24436     /* Failed to open the file for read/write access. Try read-only. */
24437     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
24438     flags |= SQLITE_OPEN_READONLY;
24439     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
24440   }
24441   if( fd<0 ){
24442     return SQLITE_CANTOPEN;
24443   }
24444   if( isDelete ){
24445     unlink(zName);
24446   }
24447   if( pOutFlags ){
24448     *pOutFlags = flags;
24449   }
24450
24451   assert(fd!=0);
24452   if( isOpenDirectory ){
24453     int rc = openDirectory(zPath, &dirfd);
24454     if( rc!=SQLITE_OK ){
24455       close(fd);
24456       return rc;
24457     }
24458   }
24459
24460 #ifdef FD_CLOEXEC
24461   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24462 #endif
24463
24464   noLock = eType!=SQLITE_OPEN_MAIN_DB;
24465   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock);
24466 }
24467
24468 /*
24469 ** Delete the file at zPath. If the dirSync argument is true, fsync()
24470 ** the directory after deleting the file.
24471 */
24472 static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
24473   int rc = SQLITE_OK;
24474   SimulateIOError(return SQLITE_IOERR_DELETE);
24475   unlink(zPath);
24476   if( dirSync ){
24477     int fd;
24478     rc = openDirectory(zPath, &fd);
24479     if( rc==SQLITE_OK ){
24480       if( fsync(fd) ){
24481         rc = SQLITE_IOERR_DIR_FSYNC;
24482       }
24483       close(fd);
24484     }
24485   }
24486   return rc;
24487 }
24488
24489 /*
24490 ** Test the existance of or access permissions of file zPath. The
24491 ** test performed depends on the value of flags:
24492 **
24493 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
24494 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
24495 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
24496 **
24497 ** Otherwise return 0.
24498 */
24499 static int unixAccess(
24500   sqlite3_vfs *pVfs, 
24501   const char *zPath, 
24502   int flags, 
24503   int *pResOut
24504 ){
24505   int amode = 0;
24506   SimulateIOError( return SQLITE_IOERR_ACCESS; );
24507   switch( flags ){
24508     case SQLITE_ACCESS_EXISTS:
24509       amode = F_OK;
24510       break;
24511     case SQLITE_ACCESS_READWRITE:
24512       amode = W_OK|R_OK;
24513       break;
24514     case SQLITE_ACCESS_READ:
24515       amode = R_OK;
24516       break;
24517
24518     default:
24519       assert(!"Invalid flags argument");
24520   }
24521   *pResOut = (access(zPath, amode)==0);
24522   return SQLITE_OK;
24523 }
24524
24525
24526 /*
24527 ** Turn a relative pathname into a full pathname. The relative path
24528 ** is stored as a nul-terminated string in the buffer pointed to by
24529 ** zPath. 
24530 **
24531 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
24532 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
24533 ** this buffer before returning.
24534 */
24535 static int unixFullPathname(
24536   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
24537   const char *zPath,            /* Possibly relative input path */
24538   int nOut,                     /* Size of output buffer in bytes */
24539   char *zOut                    /* Output buffer */
24540 ){
24541
24542   /* It's odd to simulate an io-error here, but really this is just
24543   ** using the io-error infrastructure to test that SQLite handles this
24544   ** function failing. This function could fail if, for example, the
24545   ** current working directly has been unlinked.
24546   */
24547   SimulateIOError( return SQLITE_ERROR );
24548
24549   assert( pVfs->mxPathname==MAX_PATHNAME );
24550   zOut[nOut-1] = '\0';
24551   if( zPath[0]=='/' ){
24552     sqlite3_snprintf(nOut, zOut, "%s", zPath);
24553   }else{
24554     int nCwd;
24555     if( getcwd(zOut, nOut-1)==0 ){
24556       return SQLITE_CANTOPEN;
24557     }
24558     nCwd = strlen(zOut);
24559     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
24560   }
24561   return SQLITE_OK;
24562
24563 #if 0
24564   /*
24565   ** Remove "/./" path elements and convert "/A/./" path elements
24566   ** to just "/".
24567   */
24568   if( zFull ){
24569     int i, j;
24570     for(i=j=0; zFull[i]; i++){
24571       if( zFull[i]=='/' ){
24572         if( zFull[i+1]=='/' ) continue;
24573         if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
24574           i += 1;
24575           continue;
24576         }
24577         if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
24578           while( j>0 && zFull[j-1]!='/' ){ j--; }
24579           i += 3;
24580           continue;
24581         }
24582       }
24583       zFull[j++] = zFull[i];
24584     }
24585     zFull[j] = 0;
24586   }
24587 #endif
24588 }
24589
24590
24591 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24592 /*
24593 ** Interfaces for opening a shared library, finding entry points
24594 ** within the shared library, and closing the shared library.
24595 */
24596 #include <dlfcn.h>
24597 static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24598   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
24599 }
24600
24601 /*
24602 ** SQLite calls this function immediately after a call to unixDlSym() or
24603 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
24604 ** message is available, it is written to zBufOut. If no error message
24605 ** is available, zBufOut is left unmodified and SQLite uses a default
24606 ** error message.
24607 */
24608 static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24609   char *zErr;
24610   enterMutex();
24611   zErr = dlerror();
24612   if( zErr ){
24613     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
24614   }
24615   leaveMutex();
24616 }
24617 static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
24618   return dlsym(pHandle, zSymbol);
24619 }
24620 static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
24621   dlclose(pHandle);
24622 }
24623 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24624   #define unixDlOpen  0
24625   #define unixDlError 0
24626   #define unixDlSym   0
24627   #define unixDlClose 0
24628 #endif
24629
24630 /*
24631 ** Write nBuf bytes of random data to the supplied buffer zBuf.
24632 */
24633 static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24634
24635   assert(nBuf>=(sizeof(time_t)+sizeof(int)));
24636
24637   /* We have to initialize zBuf to prevent valgrind from reporting
24638   ** errors.  The reports issued by valgrind are incorrect - we would
24639   ** prefer that the randomness be increased by making use of the
24640   ** uninitialized space in zBuf - but valgrind errors tend to worry
24641   ** some users.  Rather than argue, it seems easier just to initialize
24642   ** the whole array and silence valgrind, even if that means less randomness
24643   ** in the random seed.
24644   **
24645   ** When testing, initializing zBuf[] to zero is all we do.  That means
24646   ** that we always use the same random number sequence.  This makes the
24647   ** tests repeatable.
24648   */
24649   memset(zBuf, 0, nBuf);
24650 #if !defined(SQLITE_TEST)
24651   {
24652     int pid, fd;
24653     fd = open("/dev/urandom", O_RDONLY);
24654     if( fd<0 ){
24655       time_t t;
24656       time(&t);
24657       memcpy(zBuf, &t, sizeof(t));
24658       pid = getpid();
24659       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
24660       assert( sizeof(t)+sizeof(pid)<=nBuf );
24661       nBuf = sizeof(t) + sizeof(pid);
24662     }else{
24663       nBuf = read(fd, zBuf, nBuf);
24664       close(fd);
24665     }
24666   }
24667 #endif
24668   return nBuf;
24669 }
24670
24671
24672 /*
24673 ** Sleep for a little while.  Return the amount of time slept.
24674 ** The argument is the number of microseconds we want to sleep.
24675 ** The return value is the number of microseconds of sleep actually
24676 ** requested from the underlying operating system, a number which
24677 ** might be greater than or equal to the argument, but not less
24678 ** than the argument.
24679 */
24680 static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
24681 #if defined(HAVE_USLEEP) && HAVE_USLEEP
24682   usleep(microseconds);
24683   return microseconds;
24684 #else
24685   int seconds = (microseconds+999999)/1000000;
24686   sleep(seconds);
24687   return seconds*1000000;
24688 #endif
24689 }
24690
24691 /*
24692 ** The following variable, if set to a non-zero value, becomes the result
24693 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24694 */
24695 #ifdef SQLITE_TEST
24696 SQLITE_API int sqlite3_current_time = 0;
24697 #endif
24698
24699 /*
24700 ** Find the current time (in Universal Coordinated Time).  Write the
24701 ** current time and date as a Julian Day number into *prNow and
24702 ** return 0.  Return 1 if the time and date cannot be found.
24703 */
24704 static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
24705 #ifdef NO_GETTOD
24706   time_t t;
24707   time(&t);
24708   *prNow = t/86400.0 + 2440587.5;
24709 #else
24710   struct timeval sNow;
24711   gettimeofday(&sNow, 0);
24712   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
24713 #endif
24714 #ifdef SQLITE_TEST
24715   if( sqlite3_current_time ){
24716     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
24717   }
24718 #endif
24719   return 0;
24720 }
24721
24722 static int unixGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24723   return 0;
24724 }
24725
24726 /*
24727 ** Initialize the operating system interface.
24728 */
24729 SQLITE_API int sqlite3_os_init(void){ 
24730   /* Macro to define the static contents of an sqlite3_vfs structure for
24731   ** the unix backend. The two parameters are the values to use for
24732   ** the sqlite3_vfs.zName and sqlite3_vfs.pAppData fields, respectively.
24733   ** 
24734   */
24735   #define UNIXVFS(zVfsName, pVfsAppData) {                  \
24736     1,                    /* iVersion */                    \
24737     sizeof(unixFile),     /* szOsFile */                    \
24738     MAX_PATHNAME,         /* mxPathname */                  \
24739     0,                    /* pNext */                       \
24740     zVfsName,             /* zName */                       \
24741     (void *)pVfsAppData,  /* pAppData */                    \
24742     unixOpen,             /* xOpen */                       \
24743     unixDelete,           /* xDelete */                     \
24744     unixAccess,           /* xAccess */                     \
24745     unixFullPathname,     /* xFullPathname */               \
24746     unixDlOpen,           /* xDlOpen */                     \
24747     unixDlError,          /* xDlError */                    \
24748     unixDlSym,            /* xDlSym */                      \
24749     unixDlClose,          /* xDlClose */                    \
24750     unixRandomness,       /* xRandomness */                 \
24751     unixSleep,            /* xSleep */                      \
24752     unixCurrentTime,      /* xCurrentTime */                \
24753     unixGetLastError      /* xGetLastError */               \
24754   }
24755
24756   static sqlite3_vfs unixVfs = UNIXVFS("unix", 0);
24757 #if SQLITE_ENABLE_LOCKING_STYLE
24758   int i;
24759   static sqlite3_vfs aVfs[] = {
24760     UNIXVFS("unix-posix",   LOCKING_STYLE_POSIX), 
24761     UNIXVFS("unix-afp",     LOCKING_STYLE_AFP), 
24762     UNIXVFS("unix-flock",   LOCKING_STYLE_FLOCK), 
24763     UNIXVFS("unix-dotfile", LOCKING_STYLE_DOTFILE), 
24764     UNIXVFS("unix-none",    LOCKING_STYLE_NONE)
24765   };
24766   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
24767     sqlite3_vfs_register(&aVfs[i], 0);
24768   }
24769 #endif
24770   sqlite3_vfs_register(&unixVfs, 1);
24771   return SQLITE_OK; 
24772 }
24773
24774 /*
24775 ** Shutdown the operating system interface. This is a no-op for unix.
24776 */
24777 SQLITE_API int sqlite3_os_end(void){ 
24778   return SQLITE_OK; 
24779 }
24780  
24781 #endif /* SQLITE_OS_UNIX */
24782
24783 /************** End of os_unix.c *********************************************/
24784 /************** Begin file os_win.c ******************************************/
24785 /*
24786 ** 2004 May 22
24787 **
24788 ** The author disclaims copyright to this source code.  In place of
24789 ** a legal notice, here is a blessing:
24790 **
24791 **    May you do good and not evil.
24792 **    May you find forgiveness for yourself and forgive others.
24793 **    May you share freely, never taking more than you give.
24794 **
24795 ******************************************************************************
24796 **
24797 ** This file contains code that is specific to windows.
24798 **
24799 ** $Id: os_win.c,v 1.135 2008/10/12 02:27:39 shane Exp $
24800 */
24801 #if SQLITE_OS_WIN               /* This file is used for windows only */
24802
24803
24804 /*
24805 ** A Note About Memory Allocation:
24806 **
24807 ** This driver uses malloc()/free() directly rather than going through
24808 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
24809 ** are designed for use on embedded systems where memory is scarce and
24810 ** malloc failures happen frequently.  Win32 does not typically run on
24811 ** embedded systems, and when it does the developers normally have bigger
24812 ** problems to worry about than running out of memory.  So there is not
24813 ** a compelling need to use the wrappers.
24814 **
24815 ** But there is a good reason to not use the wrappers.  If we use the
24816 ** wrappers then we will get simulated malloc() failures within this
24817 ** driver.  And that causes all kinds of problems for our tests.  We
24818 ** could enhance SQLite to deal with simulated malloc failures within
24819 ** the OS driver, but the code to deal with those failure would not
24820 ** be exercised on Linux (which does not need to malloc() in the driver)
24821 ** and so we would have difficulty writing coverage tests for that
24822 ** code.  Better to leave the code out, we think.
24823 **
24824 ** The point of this discussion is as follows:  When creating a new
24825 ** OS layer for an embedded system, if you use this file as an example,
24826 ** avoid the use of malloc()/free().  Those routines work ok on windows
24827 ** desktops but not so well in embedded systems.
24828 */
24829
24830 #include <winbase.h>
24831
24832 #ifdef __CYGWIN__
24833 # include <sys/cygwin.h>
24834 #endif
24835
24836 /*
24837 ** Macros used to determine whether or not to use threads.
24838 */
24839 #if defined(THREADSAFE) && THREADSAFE
24840 # define SQLITE_W32_THREADS 1
24841 #endif
24842
24843 /*
24844 ** Include code that is common to all os_*.c files
24845 */
24846 /************** Include os_common.h in the middle of os_win.c ****************/
24847 /************** Begin file os_common.h ***************************************/
24848 /*
24849 ** 2004 May 22
24850 **
24851 ** The author disclaims copyright to this source code.  In place of
24852 ** a legal notice, here is a blessing:
24853 **
24854 **    May you do good and not evil.
24855 **    May you find forgiveness for yourself and forgive others.
24856 **    May you share freely, never taking more than you give.
24857 **
24858 ******************************************************************************
24859 **
24860 ** This file contains macros and a little bit of code that is common to
24861 ** all of the platform-specific files (os_*.c) and is #included into those
24862 ** files.
24863 **
24864 ** This file should be #included by the os_*.c files only.  It is not a
24865 ** general purpose header file.
24866 **
24867 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
24868 */
24869 #ifndef _OS_COMMON_H_
24870 #define _OS_COMMON_H_
24871
24872 /*
24873 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24874 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24875 ** switch.  The following code should catch this problem at compile-time.
24876 */
24877 #ifdef MEMORY_DEBUG
24878 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24879 #endif
24880
24881
24882 /*
24883  * When testing, this global variable stores the location of the
24884  * pending-byte in the database file.
24885  */
24886 #ifdef SQLITE_TEST
24887 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
24888 #endif
24889
24890 #ifdef SQLITE_DEBUG
24891 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24892 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
24893 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
24894 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
24895 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
24896 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
24897 #define OSTRACE6(X,Y,Z,A,B,C) \
24898     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
24899 #define OSTRACE7(X,Y,Z,A,B,C,D) \
24900     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
24901 #else
24902 #define OSTRACE1(X)
24903 #define OSTRACE2(X,Y)
24904 #define OSTRACE3(X,Y,Z)
24905 #define OSTRACE4(X,Y,Z,A)
24906 #define OSTRACE5(X,Y,Z,A,B)
24907 #define OSTRACE6(X,Y,Z,A,B,C)
24908 #define OSTRACE7(X,Y,Z,A,B,C,D)
24909 #endif
24910
24911 /*
24912 ** Macros for performance tracing.  Normally turned off.  Only works
24913 ** on i486 hardware.
24914 */
24915 #ifdef SQLITE_PERFORMANCE_TRACE
24916
24917 /* 
24918 ** hwtime.h contains inline assembler code for implementing 
24919 ** high-performance timing routines.
24920 */
24921 /************** Include hwtime.h in the middle of os_common.h ****************/
24922 /************** Begin file hwtime.h ******************************************/
24923 /*
24924 ** 2008 May 27
24925 **
24926 ** The author disclaims copyright to this source code.  In place of
24927 ** a legal notice, here is a blessing:
24928 **
24929 **    May you do good and not evil.
24930 **    May you find forgiveness for yourself and forgive others.
24931 **    May you share freely, never taking more than you give.
24932 **
24933 ******************************************************************************
24934 **
24935 ** This file contains inline asm code for retrieving "high-performance"
24936 ** counters for x86 class CPUs.
24937 **
24938 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
24939 */
24940 #ifndef _HWTIME_H_
24941 #define _HWTIME_H_
24942
24943 /*
24944 ** The following routine only works on pentium-class (or newer) processors.
24945 ** It uses the RDTSC opcode to read the cycle count value out of the
24946 ** processor and returns that value.  This can be used for high-res
24947 ** profiling.
24948 */
24949 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24950       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24951
24952   #if defined(__GNUC__)
24953
24954   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24955      unsigned int lo, hi;
24956      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24957      return (sqlite_uint64)hi << 32 | lo;
24958   }
24959
24960   #elif defined(_MSC_VER)
24961
24962   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24963      __asm {
24964         rdtsc
24965         ret       ; return value at EDX:EAX
24966      }
24967   }
24968
24969   #endif
24970
24971 #elif (defined(__GNUC__) && defined(__x86_64__))
24972
24973   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24974       unsigned long val;
24975       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24976       return val;
24977   }
24978  
24979 #elif (defined(__GNUC__) && defined(__ppc__))
24980
24981   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24982       unsigned long long retval;
24983       unsigned long junk;
24984       __asm__ __volatile__ ("\n\
24985           1:      mftbu   %1\n\
24986                   mftb    %L0\n\
24987                   mftbu   %0\n\
24988                   cmpw    %0,%1\n\
24989                   bne     1b"
24990                   : "=r" (retval), "=r" (junk));
24991       return retval;
24992   }
24993
24994 #else
24995
24996   #error Need implementation of sqlite3Hwtime() for your platform.
24997
24998   /*
24999   ** To compile without implementing sqlite3Hwtime() for your platform,
25000   ** you can remove the above #error and use the following
25001   ** stub function.  You will lose timing support for many
25002   ** of the debugging and testing utilities, but it should at
25003   ** least compile and run.
25004   */
25005 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25006
25007 #endif
25008
25009 #endif /* !defined(_HWTIME_H_) */
25010
25011 /************** End of hwtime.h **********************************************/
25012 /************** Continuing where we left off in os_common.h ******************/
25013
25014 static sqlite_uint64 g_start;
25015 static sqlite_uint64 g_elapsed;
25016 #define TIMER_START       g_start=sqlite3Hwtime()
25017 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25018 #define TIMER_ELAPSED     g_elapsed
25019 #else
25020 #define TIMER_START
25021 #define TIMER_END
25022 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25023 #endif
25024
25025 /*
25026 ** If we compile with the SQLITE_TEST macro set, then the following block
25027 ** of code will give us the ability to simulate a disk I/O error.  This
25028 ** is used for testing the I/O recovery logic.
25029 */
25030 #ifdef SQLITE_TEST
25031 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25032 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25033 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25034 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25035 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25036 SQLITE_API int sqlite3_diskfull_pending = 0;
25037 SQLITE_API int sqlite3_diskfull = 0;
25038 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25039 #define SimulateIOError(CODE)  \
25040   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25041        || sqlite3_io_error_pending-- == 1 )  \
25042               { local_ioerr(); CODE; }
25043 static void local_ioerr(){
25044   IOTRACE(("IOERR\n"));
25045   sqlite3_io_error_hit++;
25046   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25047 }
25048 #define SimulateDiskfullError(CODE) \
25049    if( sqlite3_diskfull_pending ){ \
25050      if( sqlite3_diskfull_pending == 1 ){ \
25051        local_ioerr(); \
25052        sqlite3_diskfull = 1; \
25053        sqlite3_io_error_hit = 1; \
25054        CODE; \
25055      }else{ \
25056        sqlite3_diskfull_pending--; \
25057      } \
25058    }
25059 #else
25060 #define SimulateIOErrorBenign(X)
25061 #define SimulateIOError(A)
25062 #define SimulateDiskfullError(A)
25063 #endif
25064
25065 /*
25066 ** When testing, keep a count of the number of open files.
25067 */
25068 #ifdef SQLITE_TEST
25069 SQLITE_API int sqlite3_open_file_count = 0;
25070 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25071 #else
25072 #define OpenCounter(X)
25073 #endif
25074
25075 #endif /* !defined(_OS_COMMON_H_) */
25076
25077 /************** End of os_common.h *******************************************/
25078 /************** Continuing where we left off in os_win.c *********************/
25079
25080 /*
25081 ** Some microsoft compilers lack this definition.
25082 */
25083 #ifndef INVALID_FILE_ATTRIBUTES
25084 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
25085 #endif
25086
25087 /*
25088 ** Determine if we are dealing with WindowsCE - which has a much
25089 ** reduced API.
25090 */
25091 #if defined(SQLITE_OS_WINCE)
25092 # define AreFileApisANSI() 1
25093 #endif
25094
25095 /*
25096 ** WinCE lacks native support for file locking so we have to fake it
25097 ** with some code of our own.
25098 */
25099 #if SQLITE_OS_WINCE
25100 typedef struct winceLock {
25101   int nReaders;       /* Number of reader locks obtained */
25102   BOOL bPending;      /* Indicates a pending lock has been obtained */
25103   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
25104   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
25105 } winceLock;
25106 #endif
25107
25108 /*
25109 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
25110 ** portability layer.
25111 */
25112 typedef struct winFile winFile;
25113 struct winFile {
25114   const sqlite3_io_methods *pMethod;/* Must be first */
25115   HANDLE h;               /* Handle for accessing the file */
25116   unsigned char locktype; /* Type of lock currently held on this file */
25117   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
25118 #if SQLITE_OS_WINCE
25119   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
25120   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
25121   HANDLE hShared;         /* Shared memory segment used for locking */
25122   winceLock local;        /* Locks obtained by this instance of winFile */
25123   winceLock *shared;      /* Global shared lock memory for the file  */
25124 #endif
25125 };
25126
25127
25128 /*
25129 ** The following variable is (normally) set once and never changes
25130 ** thereafter.  It records whether the operating system is Win95
25131 ** or WinNT.
25132 **
25133 ** 0:   Operating system unknown.
25134 ** 1:   Operating system is Win95.
25135 ** 2:   Operating system is WinNT.
25136 **
25137 ** In order to facilitate testing on a WinNT system, the test fixture
25138 ** can manually set this value to 1 to emulate Win98 behavior.
25139 */
25140 #ifdef SQLITE_TEST
25141 SQLITE_API int sqlite3_os_type = 0;
25142 #else
25143 static int sqlite3_os_type = 0;
25144 #endif
25145
25146 /*
25147 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
25148 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
25149 **
25150 ** Here is an interesting observation:  Win95, Win98, and WinME lack
25151 ** the LockFileEx() API.  But we can still statically link against that
25152 ** API as long as we don't call it win running Win95/98/ME.  A call to
25153 ** this routine is used to determine if the host is Win95/98/ME or
25154 ** WinNT/2K/XP so that we will know whether or not we can safely call
25155 ** the LockFileEx() API.
25156 */
25157 #if SQLITE_OS_WINCE
25158 # define isNT()  (1)
25159 #else
25160   static int isNT(void){
25161     if( sqlite3_os_type==0 ){
25162       OSVERSIONINFO sInfo;
25163       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
25164       GetVersionEx(&sInfo);
25165       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
25166     }
25167     return sqlite3_os_type==2;
25168   }
25169 #endif /* SQLITE_OS_WINCE */
25170
25171 /*
25172 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
25173 **
25174 ** Space to hold the returned string is obtained from malloc.
25175 */
25176 static WCHAR *utf8ToUnicode(const char *zFilename){
25177   int nChar;
25178   WCHAR *zWideFilename;
25179
25180   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
25181   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
25182   if( zWideFilename==0 ){
25183     return 0;
25184   }
25185   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
25186   if( nChar==0 ){
25187     free(zWideFilename);
25188     zWideFilename = 0;
25189   }
25190   return zWideFilename;
25191 }
25192
25193 /*
25194 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
25195 ** obtained from malloc().
25196 */
25197 static char *unicodeToUtf8(const WCHAR *zWideFilename){
25198   int nByte;
25199   char *zFilename;
25200
25201   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
25202   zFilename = malloc( nByte );
25203   if( zFilename==0 ){
25204     return 0;
25205   }
25206   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
25207                               0, 0);
25208   if( nByte == 0 ){
25209     free(zFilename);
25210     zFilename = 0;
25211   }
25212   return zFilename;
25213 }
25214
25215 /*
25216 ** Convert an ansi string to microsoft unicode, based on the
25217 ** current codepage settings for file apis.
25218 ** 
25219 ** Space to hold the returned string is obtained
25220 ** from malloc.
25221 */
25222 static WCHAR *mbcsToUnicode(const char *zFilename){
25223   int nByte;
25224   WCHAR *zMbcsFilename;
25225   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25226
25227   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
25228   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
25229   if( zMbcsFilename==0 ){
25230     return 0;
25231   }
25232   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
25233   if( nByte==0 ){
25234     free(zMbcsFilename);
25235     zMbcsFilename = 0;
25236   }
25237   return zMbcsFilename;
25238 }
25239
25240 /*
25241 ** Convert microsoft unicode to multibyte character string, based on the
25242 ** user's Ansi codepage.
25243 **
25244 ** Space to hold the returned string is obtained from
25245 ** malloc().
25246 */
25247 static char *unicodeToMbcs(const WCHAR *zWideFilename){
25248   int nByte;
25249   char *zFilename;
25250   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
25251
25252   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
25253   zFilename = malloc( nByte );
25254   if( zFilename==0 ){
25255     return 0;
25256   }
25257   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
25258                               0, 0);
25259   if( nByte == 0 ){
25260     free(zFilename);
25261     zFilename = 0;
25262   }
25263   return zFilename;
25264 }
25265
25266 /*
25267 ** Convert multibyte character string to UTF-8.  Space to hold the
25268 ** returned string is obtained from malloc().
25269 */
25270 static char *mbcsToUtf8(const char *zFilename){
25271   char *zFilenameUtf8;
25272   WCHAR *zTmpWide;
25273
25274   zTmpWide = mbcsToUnicode(zFilename);
25275   if( zTmpWide==0 ){
25276     return 0;
25277   }
25278   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
25279   free(zTmpWide);
25280   return zFilenameUtf8;
25281 }
25282
25283 /*
25284 ** Convert UTF-8 to multibyte character string.  Space to hold the 
25285 ** returned string is obtained from malloc().
25286 */
25287 static char *utf8ToMbcs(const char *zFilename){
25288   char *zFilenameMbcs;
25289   WCHAR *zTmpWide;
25290
25291   zTmpWide = utf8ToUnicode(zFilename);
25292   if( zTmpWide==0 ){
25293     return 0;
25294   }
25295   zFilenameMbcs = unicodeToMbcs(zTmpWide);
25296   free(zTmpWide);
25297   return zFilenameMbcs;
25298 }
25299
25300 #if SQLITE_OS_WINCE
25301 /*************************************************************************
25302 ** This section contains code for WinCE only.
25303 */
25304 /*
25305 ** WindowsCE does not have a localtime() function.  So create a
25306 ** substitute.
25307 */
25308 struct tm *__cdecl localtime(const time_t *t)
25309 {
25310   static struct tm y;
25311   FILETIME uTm, lTm;
25312   SYSTEMTIME pTm;
25313   sqlite3_int64 t64;
25314   t64 = *t;
25315   t64 = (t64 + 11644473600)*10000000;
25316   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
25317   uTm.dwHighDateTime= t64 >> 32;
25318   FileTimeToLocalFileTime(&uTm,&lTm);
25319   FileTimeToSystemTime(&lTm,&pTm);
25320   y.tm_year = pTm.wYear - 1900;
25321   y.tm_mon = pTm.wMonth - 1;
25322   y.tm_wday = pTm.wDayOfWeek;
25323   y.tm_mday = pTm.wDay;
25324   y.tm_hour = pTm.wHour;
25325   y.tm_min = pTm.wMinute;
25326   y.tm_sec = pTm.wSecond;
25327   return &y;
25328 }
25329
25330 /* This will never be called, but defined to make the code compile */
25331 #define GetTempPathA(a,b)
25332
25333 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
25334 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
25335 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
25336
25337 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
25338
25339 /*
25340 ** Acquire a lock on the handle h
25341 */
25342 static void winceMutexAcquire(HANDLE h){
25343    DWORD dwErr;
25344    do {
25345      dwErr = WaitForSingleObject(h, INFINITE);
25346    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
25347 }
25348 /*
25349 ** Release a lock acquired by winceMutexAcquire()
25350 */
25351 #define winceMutexRelease(h) ReleaseMutex(h)
25352
25353 /*
25354 ** Create the mutex and shared memory used for locking in the file
25355 ** descriptor pFile
25356 */
25357 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
25358   WCHAR *zTok;
25359   WCHAR *zName = utf8ToUnicode(zFilename);
25360   BOOL bInit = TRUE;
25361
25362   /* Initialize the local lockdata */
25363   ZeroMemory(&pFile->local, sizeof(pFile->local));
25364
25365   /* Replace the backslashes from the filename and lowercase it
25366   ** to derive a mutex name. */
25367   zTok = CharLowerW(zName);
25368   for (;*zTok;zTok++){
25369     if (*zTok == '\\') *zTok = '_';
25370   }
25371
25372   /* Create/open the named mutex */
25373   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
25374   if (!pFile->hMutex){
25375     free(zName);
25376     return FALSE;
25377   }
25378
25379   /* Acquire the mutex before continuing */
25380   winceMutexAcquire(pFile->hMutex);
25381   
25382   /* Since the names of named mutexes, semaphores, file mappings etc are 
25383   ** case-sensitive, take advantage of that by uppercasing the mutex name
25384   ** and using that as the shared filemapping name.
25385   */
25386   CharUpperW(zName);
25387   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
25388                                        PAGE_READWRITE, 0, sizeof(winceLock),
25389                                        zName);  
25390
25391   /* Set a flag that indicates we're the first to create the memory so it 
25392   ** must be zero-initialized */
25393   if (GetLastError() == ERROR_ALREADY_EXISTS){
25394     bInit = FALSE;
25395   }
25396
25397   free(zName);
25398
25399   /* If we succeeded in making the shared memory handle, map it. */
25400   if (pFile->hShared){
25401     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
25402              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
25403     /* If mapping failed, close the shared memory handle and erase it */
25404     if (!pFile->shared){
25405       CloseHandle(pFile->hShared);
25406       pFile->hShared = NULL;
25407     }
25408   }
25409
25410   /* If shared memory could not be created, then close the mutex and fail */
25411   if (pFile->hShared == NULL){
25412     winceMutexRelease(pFile->hMutex);
25413     CloseHandle(pFile->hMutex);
25414     pFile->hMutex = NULL;
25415     return FALSE;
25416   }
25417   
25418   /* Initialize the shared memory if we're supposed to */
25419   if (bInit) {
25420     ZeroMemory(pFile->shared, sizeof(winceLock));
25421   }
25422
25423   winceMutexRelease(pFile->hMutex);
25424   return TRUE;
25425 }
25426
25427 /*
25428 ** Destroy the part of winFile that deals with wince locks
25429 */
25430 static void winceDestroyLock(winFile *pFile){
25431   if (pFile->hMutex){
25432     /* Acquire the mutex */
25433     winceMutexAcquire(pFile->hMutex);
25434
25435     /* The following blocks should probably assert in debug mode, but they
25436        are to cleanup in case any locks remained open */
25437     if (pFile->local.nReaders){
25438       pFile->shared->nReaders --;
25439     }
25440     if (pFile->local.bReserved){
25441       pFile->shared->bReserved = FALSE;
25442     }
25443     if (pFile->local.bPending){
25444       pFile->shared->bPending = FALSE;
25445     }
25446     if (pFile->local.bExclusive){
25447       pFile->shared->bExclusive = FALSE;
25448     }
25449
25450     /* De-reference and close our copy of the shared memory handle */
25451     UnmapViewOfFile(pFile->shared);
25452     CloseHandle(pFile->hShared);
25453
25454     /* Done with the mutex */
25455     winceMutexRelease(pFile->hMutex);    
25456     CloseHandle(pFile->hMutex);
25457     pFile->hMutex = NULL;
25458   }
25459 }
25460
25461 /* 
25462 ** An implementation of the LockFile() API of windows for wince
25463 */
25464 static BOOL winceLockFile(
25465   HANDLE *phFile,
25466   DWORD dwFileOffsetLow,
25467   DWORD dwFileOffsetHigh,
25468   DWORD nNumberOfBytesToLockLow,
25469   DWORD nNumberOfBytesToLockHigh
25470 ){
25471   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25472   BOOL bReturn = FALSE;
25473
25474   if (!pFile->hMutex) return TRUE;
25475   winceMutexAcquire(pFile->hMutex);
25476
25477   /* Wanting an exclusive lock? */
25478   if (dwFileOffsetLow == SHARED_FIRST
25479        && nNumberOfBytesToLockLow == SHARED_SIZE){
25480     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
25481        pFile->shared->bExclusive = TRUE;
25482        pFile->local.bExclusive = TRUE;
25483        bReturn = TRUE;
25484     }
25485   }
25486
25487   /* Want a read-only lock? */
25488   else if ((dwFileOffsetLow >= SHARED_FIRST &&
25489             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
25490             nNumberOfBytesToLockLow == 1){
25491     if (pFile->shared->bExclusive == 0){
25492       pFile->local.nReaders ++;
25493       if (pFile->local.nReaders == 1){
25494         pFile->shared->nReaders ++;
25495       }
25496       bReturn = TRUE;
25497     }
25498   }
25499
25500   /* Want a pending lock? */
25501   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
25502     /* If no pending lock has been acquired, then acquire it */
25503     if (pFile->shared->bPending == 0) {
25504       pFile->shared->bPending = TRUE;
25505       pFile->local.bPending = TRUE;
25506       bReturn = TRUE;
25507     }
25508   }
25509   /* Want a reserved lock? */
25510   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
25511     if (pFile->shared->bReserved == 0) {
25512       pFile->shared->bReserved = TRUE;
25513       pFile->local.bReserved = TRUE;
25514       bReturn = TRUE;
25515     }
25516   }
25517
25518   winceMutexRelease(pFile->hMutex);
25519   return bReturn;
25520 }
25521
25522 /*
25523 ** An implementation of the UnlockFile API of windows for wince
25524 */
25525 static BOOL winceUnlockFile(
25526   HANDLE *phFile,
25527   DWORD dwFileOffsetLow,
25528   DWORD dwFileOffsetHigh,
25529   DWORD nNumberOfBytesToUnlockLow,
25530   DWORD nNumberOfBytesToUnlockHigh
25531 ){
25532   winFile *pFile = HANDLE_TO_WINFILE(phFile);
25533   BOOL bReturn = FALSE;
25534
25535   if (!pFile->hMutex) return TRUE;
25536   winceMutexAcquire(pFile->hMutex);
25537
25538   /* Releasing a reader lock or an exclusive lock */
25539   if (dwFileOffsetLow >= SHARED_FIRST &&
25540        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
25541     /* Did we have an exclusive lock? */
25542     if (pFile->local.bExclusive){
25543       pFile->local.bExclusive = FALSE;
25544       pFile->shared->bExclusive = FALSE;
25545       bReturn = TRUE;
25546     }
25547
25548     /* Did we just have a reader lock? */
25549     else if (pFile->local.nReaders){
25550       pFile->local.nReaders --;
25551       if (pFile->local.nReaders == 0)
25552       {
25553         pFile->shared->nReaders --;
25554       }
25555       bReturn = TRUE;
25556     }
25557   }
25558
25559   /* Releasing a pending lock */
25560   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
25561     if (pFile->local.bPending){
25562       pFile->local.bPending = FALSE;
25563       pFile->shared->bPending = FALSE;
25564       bReturn = TRUE;
25565     }
25566   }
25567   /* Releasing a reserved lock */
25568   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
25569     if (pFile->local.bReserved) {
25570       pFile->local.bReserved = FALSE;
25571       pFile->shared->bReserved = FALSE;
25572       bReturn = TRUE;
25573     }
25574   }
25575
25576   winceMutexRelease(pFile->hMutex);
25577   return bReturn;
25578 }
25579
25580 /*
25581 ** An implementation of the LockFileEx() API of windows for wince
25582 */
25583 static BOOL winceLockFileEx(
25584   HANDLE *phFile,
25585   DWORD dwFlags,
25586   DWORD dwReserved,
25587   DWORD nNumberOfBytesToLockLow,
25588   DWORD nNumberOfBytesToLockHigh,
25589   LPOVERLAPPED lpOverlapped
25590 ){
25591   /* If the caller wants a shared read lock, forward this call
25592   ** to winceLockFile */
25593   if (lpOverlapped->Offset == SHARED_FIRST &&
25594       dwFlags == 1 &&
25595       nNumberOfBytesToLockLow == SHARED_SIZE){
25596     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
25597   }
25598   return FALSE;
25599 }
25600 /*
25601 ** End of the special code for wince
25602 *****************************************************************************/
25603 #endif /* SQLITE_OS_WINCE */
25604
25605 /*****************************************************************************
25606 ** The next group of routines implement the I/O methods specified
25607 ** by the sqlite3_io_methods object.
25608 ******************************************************************************/
25609
25610 /*
25611 ** Close a file.
25612 **
25613 ** It is reported that an attempt to close a handle might sometimes
25614 ** fail.  This is a very unreasonable result, but windows is notorious
25615 ** for being unreasonable so I do not doubt that it might happen.  If
25616 ** the close fails, we pause for 100 milliseconds and try again.  As
25617 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
25618 ** giving up and returning an error.
25619 */
25620 #define MX_CLOSE_ATTEMPT 3
25621 static int winClose(sqlite3_file *id){
25622   int rc, cnt = 0;
25623   winFile *pFile = (winFile*)id;
25624   OSTRACE2("CLOSE %d\n", pFile->h);
25625   do{
25626     rc = CloseHandle(pFile->h);
25627   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
25628 #if SQLITE_OS_WINCE
25629 #define WINCE_DELETION_ATTEMPTS 3
25630   winceDestroyLock(pFile);
25631   if( pFile->zDeleteOnClose ){
25632     int cnt = 0;
25633     while(
25634            DeleteFileW(pFile->zDeleteOnClose)==0
25635         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
25636         && cnt++ < WINCE_DELETION_ATTEMPTS
25637     ){
25638        Sleep(100);  /* Wait a little before trying again */
25639     }
25640     free(pFile->zDeleteOnClose);
25641   }
25642 #endif
25643   OpenCounter(-1);
25644   return rc ? SQLITE_OK : SQLITE_IOERR;
25645 }
25646
25647 /*
25648 ** Some microsoft compilers lack this definition.
25649 */
25650 #ifndef INVALID_SET_FILE_POINTER
25651 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
25652 #endif
25653
25654 /*
25655 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25656 ** bytes were read successfully and SQLITE_IOERR if anything goes
25657 ** wrong.
25658 */
25659 static int winRead(
25660   sqlite3_file *id,          /* File to read from */
25661   void *pBuf,                /* Write content into this buffer */
25662   int amt,                   /* Number of bytes to read */
25663   sqlite3_int64 offset       /* Begin reading at this offset */
25664 ){
25665   LONG upperBits = (offset>>32) & 0x7fffffff;
25666   LONG lowerBits = offset & 0xffffffff;
25667   DWORD rc;
25668   DWORD got;
25669   winFile *pFile = (winFile*)id;
25670   assert( id!=0 );
25671   SimulateIOError(return SQLITE_IOERR_READ);
25672   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
25673   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25674   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
25675     return SQLITE_FULL;
25676   }
25677   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
25678     return SQLITE_IOERR_READ;
25679   }
25680   if( got==(DWORD)amt ){
25681     return SQLITE_OK;
25682   }else{
25683     memset(&((char*)pBuf)[got], 0, amt-got);
25684     return SQLITE_IOERR_SHORT_READ;
25685   }
25686 }
25687
25688 /*
25689 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25690 ** or some other error code on failure.
25691 */
25692 static int winWrite(
25693   sqlite3_file *id,         /* File to write into */
25694   const void *pBuf,         /* The bytes to be written */
25695   int amt,                  /* Number of bytes to write */
25696   sqlite3_int64 offset      /* Offset into the file to begin writing at */
25697 ){
25698   LONG upperBits = (offset>>32) & 0x7fffffff;
25699   LONG lowerBits = offset & 0xffffffff;
25700   DWORD rc;
25701   DWORD wrote;
25702   winFile *pFile = (winFile*)id;
25703   assert( id!=0 );
25704   SimulateIOError(return SQLITE_IOERR_WRITE);
25705   SimulateDiskfullError(return SQLITE_FULL);
25706   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
25707   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25708   if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){
25709     return SQLITE_FULL;
25710   }
25711   assert( amt>0 );
25712   while(
25713      amt>0
25714      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
25715      && wrote>0
25716   ){
25717     amt -= wrote;
25718     pBuf = &((char*)pBuf)[wrote];
25719   }
25720   if( !rc || amt>(int)wrote ){
25721     return SQLITE_FULL;
25722   }
25723   return SQLITE_OK;
25724 }
25725
25726 /*
25727 ** Truncate an open file to a specified size
25728 */
25729 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
25730   DWORD rc;
25731   LONG upperBits = (nByte>>32) & 0x7fffffff;
25732   LONG lowerBits = nByte & 0xffffffff;
25733   winFile *pFile = (winFile*)id;
25734   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
25735   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
25736   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
25737   if( INVALID_SET_FILE_POINTER != rc ){
25738     /* SetEndOfFile will fail if nByte is negative */
25739     if( SetEndOfFile(pFile->h) ){
25740       return SQLITE_OK;
25741     }
25742   }
25743   return SQLITE_IOERR_TRUNCATE;
25744 }
25745
25746 #ifdef SQLITE_TEST
25747 /*
25748 ** Count the number of fullsyncs and normal syncs.  This is used to test
25749 ** that syncs and fullsyncs are occuring at the right times.
25750 */
25751 SQLITE_API int sqlite3_sync_count = 0;
25752 SQLITE_API int sqlite3_fullsync_count = 0;
25753 #endif
25754
25755 /*
25756 ** Make sure all writes to a particular file are committed to disk.
25757 */
25758 static int winSync(sqlite3_file *id, int flags){
25759   winFile *pFile = (winFile*)id;
25760   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
25761 #ifdef SQLITE_TEST
25762   if( flags & SQLITE_SYNC_FULL ){
25763     sqlite3_fullsync_count++;
25764   }
25765   sqlite3_sync_count++;
25766 #endif
25767   if( FlushFileBuffers(pFile->h) ){
25768     return SQLITE_OK;
25769   }else{
25770     return SQLITE_IOERR;
25771   }
25772 }
25773
25774 /*
25775 ** Determine the current size of a file in bytes
25776 */
25777 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
25778   winFile *pFile = (winFile*)id;
25779   DWORD upperBits, lowerBits;
25780   SimulateIOError(return SQLITE_IOERR_FSTAT);
25781   lowerBits = GetFileSize(pFile->h, &upperBits);
25782   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
25783   return SQLITE_OK;
25784 }
25785
25786 /*
25787 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
25788 */
25789 #ifndef LOCKFILE_FAIL_IMMEDIATELY
25790 # define LOCKFILE_FAIL_IMMEDIATELY 1
25791 #endif
25792
25793 /*
25794 ** Acquire a reader lock.
25795 ** Different API routines are called depending on whether or not this
25796 ** is Win95 or WinNT.
25797 */
25798 static int getReadLock(winFile *pFile){
25799   int res;
25800   if( isNT() ){
25801     OVERLAPPED ovlp;
25802     ovlp.Offset = SHARED_FIRST;
25803     ovlp.OffsetHigh = 0;
25804     ovlp.hEvent = 0;
25805     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
25806                      0, SHARED_SIZE, 0, &ovlp);
25807   }else{
25808     int lk;
25809     sqlite3_randomness(sizeof(lk), &lk);
25810     pFile->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
25811     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
25812   }
25813   return res;
25814 }
25815
25816 /*
25817 ** Undo a readlock
25818 */
25819 static int unlockReadLock(winFile *pFile){
25820   int res;
25821   if( isNT() ){
25822     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25823   }else{
25824     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
25825   }
25826   return res;
25827 }
25828
25829 /*
25830 ** Lock the file with the lock specified by parameter locktype - one
25831 ** of the following:
25832 **
25833 **     (1) SHARED_LOCK
25834 **     (2) RESERVED_LOCK
25835 **     (3) PENDING_LOCK
25836 **     (4) EXCLUSIVE_LOCK
25837 **
25838 ** Sometimes when requesting one lock state, additional lock states
25839 ** are inserted in between.  The locking might fail on one of the later
25840 ** transitions leaving the lock state different from what it started but
25841 ** still short of its goal.  The following chart shows the allowed
25842 ** transitions and the inserted intermediate states:
25843 **
25844 **    UNLOCKED -> SHARED
25845 **    SHARED -> RESERVED
25846 **    SHARED -> (PENDING) -> EXCLUSIVE
25847 **    RESERVED -> (PENDING) -> EXCLUSIVE
25848 **    PENDING -> EXCLUSIVE
25849 **
25850 ** This routine will only increase a lock.  The winUnlock() routine
25851 ** erases all locks at once and returns us immediately to locking level 0.
25852 ** It is not possible to lower the locking level one step at a time.  You
25853 ** must go straight to locking level 0.
25854 */
25855 static int winLock(sqlite3_file *id, int locktype){
25856   int rc = SQLITE_OK;    /* Return code from subroutines */
25857   int res = 1;           /* Result of a windows lock call */
25858   int newLocktype;       /* Set pFile->locktype to this value before exiting */
25859   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
25860   winFile *pFile = (winFile*)id;
25861
25862   assert( pFile!=0 );
25863   OSTRACE5("LOCK %d %d was %d(%d)\n",
25864           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
25865
25866   /* If there is already a lock of this type or more restrictive on the
25867   ** OsFile, do nothing. Don't use the end_lock: exit path, as
25868   ** sqlite3OsEnterMutex() hasn't been called yet.
25869   */
25870   if( pFile->locktype>=locktype ){
25871     return SQLITE_OK;
25872   }
25873
25874   /* Make sure the locking sequence is correct
25875   */
25876   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
25877   assert( locktype!=PENDING_LOCK );
25878   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
25879
25880   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
25881   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
25882   ** the PENDING_LOCK byte is temporary.
25883   */
25884   newLocktype = pFile->locktype;
25885   if( pFile->locktype==NO_LOCK
25886    || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
25887   ){
25888     int cnt = 3;
25889     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
25890       /* Try 3 times to get the pending lock.  The pending lock might be
25891       ** held by another reader process who will release it momentarily.
25892       */
25893       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
25894       Sleep(1);
25895     }
25896     gotPendingLock = res;
25897   }
25898
25899   /* Acquire a shared lock
25900   */
25901   if( locktype==SHARED_LOCK && res ){
25902     assert( pFile->locktype==NO_LOCK );
25903     res = getReadLock(pFile);
25904     if( res ){
25905       newLocktype = SHARED_LOCK;
25906     }
25907   }
25908
25909   /* Acquire a RESERVED lock
25910   */
25911   if( locktype==RESERVED_LOCK && res ){
25912     assert( pFile->locktype==SHARED_LOCK );
25913     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25914     if( res ){
25915       newLocktype = RESERVED_LOCK;
25916     }
25917   }
25918
25919   /* Acquire a PENDING lock
25920   */
25921   if( locktype==EXCLUSIVE_LOCK && res ){
25922     newLocktype = PENDING_LOCK;
25923     gotPendingLock = 0;
25924   }
25925
25926   /* Acquire an EXCLUSIVE lock
25927   */
25928   if( locktype==EXCLUSIVE_LOCK && res ){
25929     assert( pFile->locktype>=SHARED_LOCK );
25930     res = unlockReadLock(pFile);
25931     OSTRACE2("unreadlock = %d\n", res);
25932     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
25933     if( res ){
25934       newLocktype = EXCLUSIVE_LOCK;
25935     }else{
25936       OSTRACE2("error-code = %d\n", GetLastError());
25937       getReadLock(pFile);
25938     }
25939   }
25940
25941   /* If we are holding a PENDING lock that ought to be released, then
25942   ** release it now.
25943   */
25944   if( gotPendingLock && locktype==SHARED_LOCK ){
25945     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
25946   }
25947
25948   /* Update the state of the lock has held in the file descriptor then
25949   ** return the appropriate result code.
25950   */
25951   if( res ){
25952     rc = SQLITE_OK;
25953   }else{
25954     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
25955            locktype, newLocktype);
25956     rc = SQLITE_BUSY;
25957   }
25958   pFile->locktype = newLocktype;
25959   return rc;
25960 }
25961
25962 /*
25963 ** This routine checks if there is a RESERVED lock held on the specified
25964 ** file by this or any other process. If such a lock is held, return
25965 ** non-zero, otherwise zero.
25966 */
25967 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
25968   int rc;
25969   winFile *pFile = (winFile*)id;
25970   assert( pFile!=0 );
25971   if( pFile->locktype>=RESERVED_LOCK ){
25972     rc = 1;
25973     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
25974   }else{
25975     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25976     if( rc ){
25977       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
25978     }
25979     rc = !rc;
25980     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
25981   }
25982   *pResOut = rc;
25983   return SQLITE_OK;
25984 }
25985
25986 /*
25987 ** Lower the locking level on file descriptor id to locktype.  locktype
25988 ** must be either NO_LOCK or SHARED_LOCK.
25989 **
25990 ** If the locking level of the file descriptor is already at or below
25991 ** the requested locking level, this routine is a no-op.
25992 **
25993 ** It is not possible for this routine to fail if the second argument
25994 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
25995 ** might return SQLITE_IOERR;
25996 */
25997 static int winUnlock(sqlite3_file *id, int locktype){
25998   int type;
25999   winFile *pFile = (winFile*)id;
26000   int rc = SQLITE_OK;
26001   assert( pFile!=0 );
26002   assert( locktype<=SHARED_LOCK );
26003   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
26004           pFile->locktype, pFile->sharedLockByte);
26005   type = pFile->locktype;
26006   if( type>=EXCLUSIVE_LOCK ){
26007     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
26008     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
26009       /* This should never happen.  We should always be able to
26010       ** reacquire the read lock */
26011       rc = SQLITE_IOERR_UNLOCK;
26012     }
26013   }
26014   if( type>=RESERVED_LOCK ){
26015     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
26016   }
26017   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
26018     unlockReadLock(pFile);
26019   }
26020   if( type>=PENDING_LOCK ){
26021     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
26022   }
26023   pFile->locktype = locktype;
26024   return rc;
26025 }
26026
26027 /*
26028 ** Control and query of the open file handle.
26029 */
26030 static int winFileControl(sqlite3_file *id, int op, void *pArg){
26031   switch( op ){
26032     case SQLITE_FCNTL_LOCKSTATE: {
26033       *(int*)pArg = ((winFile*)id)->locktype;
26034       return SQLITE_OK;
26035     }
26036   }
26037   return SQLITE_ERROR;
26038 }
26039
26040 /*
26041 ** Return the sector size in bytes of the underlying block device for
26042 ** the specified file. This is almost always 512 bytes, but may be
26043 ** larger for some devices.
26044 **
26045 ** SQLite code assumes this function cannot fail. It also assumes that
26046 ** if two files are created in the same file-system directory (i.e.
26047 ** a database and its journal file) that the sector size will be the
26048 ** same for both.
26049 */
26050 static int winSectorSize(sqlite3_file *id){
26051   return SQLITE_DEFAULT_SECTOR_SIZE;
26052 }
26053
26054 /*
26055 ** Return a vector of device characteristics.
26056 */
26057 static int winDeviceCharacteristics(sqlite3_file *id){
26058   return 0;
26059 }
26060
26061 /*
26062 ** This vector defines all the methods that can operate on an
26063 ** sqlite3_file for win32.
26064 */
26065 static const sqlite3_io_methods winIoMethod = {
26066   1,                        /* iVersion */
26067   winClose,
26068   winRead,
26069   winWrite,
26070   winTruncate,
26071   winSync,
26072   winFileSize,
26073   winLock,
26074   winUnlock,
26075   winCheckReservedLock,
26076   winFileControl,
26077   winSectorSize,
26078   winDeviceCharacteristics
26079 };
26080
26081 /***************************************************************************
26082 ** Here ends the I/O methods that form the sqlite3_io_methods object.
26083 **
26084 ** The next block of code implements the VFS methods.
26085 ****************************************************************************/
26086
26087 /*
26088 ** Convert a UTF-8 filename into whatever form the underlying
26089 ** operating system wants filenames in.  Space to hold the result
26090 ** is obtained from malloc and must be freed by the calling
26091 ** function.
26092 */
26093 static void *convertUtf8Filename(const char *zFilename){
26094   void *zConverted = 0;
26095   if( isNT() ){
26096     zConverted = utf8ToUnicode(zFilename);
26097   }else{
26098     zConverted = utf8ToMbcs(zFilename);
26099   }
26100   /* caller will handle out of memory */
26101   return zConverted;
26102 }
26103
26104 /*
26105 ** Create a temporary file name in zBuf.  zBuf must be big enough to
26106 ** hold at pVfs->mxPathname characters.
26107 */
26108 static int getTempname(int nBuf, char *zBuf){
26109   static char zChars[] =
26110     "abcdefghijklmnopqrstuvwxyz"
26111     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26112     "0123456789";
26113   size_t i, j;
26114   char zTempPath[MAX_PATH+1];
26115   if( sqlite3_temp_directory ){
26116     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
26117   }else if( isNT() ){
26118     char *zMulti;
26119     WCHAR zWidePath[MAX_PATH];
26120     GetTempPathW(MAX_PATH-30, zWidePath);
26121     zMulti = unicodeToUtf8(zWidePath);
26122     if( zMulti ){
26123       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
26124       free(zMulti);
26125     }else{
26126       return SQLITE_NOMEM;
26127     }
26128   }else{
26129     char *zUtf8;
26130     char zMbcsPath[MAX_PATH];
26131     GetTempPathA(MAX_PATH-30, zMbcsPath);
26132     zUtf8 = mbcsToUtf8(zMbcsPath);
26133     if( zUtf8 ){
26134       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
26135       free(zUtf8);
26136     }else{
26137       return SQLITE_NOMEM;
26138     }
26139   }
26140   for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
26141   zTempPath[i] = 0;
26142   sqlite3_snprintf(nBuf-30, zBuf,
26143                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
26144   j = strlen(zBuf);
26145   sqlite3_randomness(20, &zBuf[j]);
26146   for(i=0; i<20; i++, j++){
26147     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26148   }
26149   zBuf[j] = 0;
26150   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
26151   return SQLITE_OK; 
26152 }
26153
26154 /*
26155 ** The return value of getLastErrorMsg
26156 ** is zero if the error message fits in the buffer, or non-zero
26157 ** otherwise (if the message was truncated).
26158 */
26159 static int getLastErrorMsg(int nBuf, char *zBuf){
26160   DWORD error = GetLastError();
26161
26162 #if SQLITE_OS_WINCE
26163   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26164 #else
26165   /* FormatMessage returns 0 on failure.  Otherwise it
26166   ** returns the number of TCHARs written to the output
26167   ** buffer, excluding the terminating null char.
26168   */
26169   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
26170                       NULL,
26171                       error,
26172                       0,
26173                       zBuf,
26174                       nBuf-1,
26175                       0))
26176   {
26177     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
26178   }
26179 #endif
26180
26181   return 0;
26182 }
26183
26184
26185 /*
26186 ** Open a file.
26187 */
26188 static int winOpen(
26189   sqlite3_vfs *pVfs,        /* Not used */
26190   const char *zName,        /* Name of the file (UTF-8) */
26191   sqlite3_file *id,         /* Write the SQLite file handle here */
26192   int flags,                /* Open mode flags */
26193   int *pOutFlags            /* Status return flags */
26194 ){
26195   HANDLE h;
26196   DWORD dwDesiredAccess;
26197   DWORD dwShareMode;
26198   DWORD dwCreationDisposition;
26199   DWORD dwFlagsAndAttributes = 0;
26200 #if SQLITE_OS_WINCE
26201   int isTemp = 0;
26202 #endif
26203   winFile *pFile = (winFile*)id;
26204   void *zConverted;                 /* Filename in OS encoding */
26205   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
26206   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
26207
26208   /* If the second argument to this function is NULL, generate a 
26209   ** temporary file name to use 
26210   */
26211   if( !zUtf8Name ){
26212     int rc = getTempname(MAX_PATH+1, zTmpname);
26213     if( rc!=SQLITE_OK ){
26214       return rc;
26215     }
26216     zUtf8Name = zTmpname;
26217   }
26218
26219   /* Convert the filename to the system encoding. */
26220   zConverted = convertUtf8Filename(zUtf8Name);
26221   if( zConverted==0 ){
26222     return SQLITE_NOMEM;
26223   }
26224
26225   if( flags & SQLITE_OPEN_READWRITE ){
26226     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
26227   }else{
26228     dwDesiredAccess = GENERIC_READ;
26229   }
26230   if( flags & SQLITE_OPEN_CREATE ){
26231     dwCreationDisposition = OPEN_ALWAYS;
26232   }else{
26233     dwCreationDisposition = OPEN_EXISTING;
26234   }
26235   if( flags & SQLITE_OPEN_MAIN_DB ){
26236     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
26237   }else{
26238     dwShareMode = 0;
26239   }
26240   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
26241 #if SQLITE_OS_WINCE
26242     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
26243     isTemp = 1;
26244 #else
26245     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
26246                                | FILE_ATTRIBUTE_HIDDEN
26247                                | FILE_FLAG_DELETE_ON_CLOSE;
26248 #endif
26249   }else{
26250     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
26251   }
26252   /* Reports from the internet are that performance is always
26253   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
26254 #if SQLITE_OS_WINCE
26255   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
26256 #endif
26257   if( isNT() ){
26258     h = CreateFileW((WCHAR*)zConverted,
26259        dwDesiredAccess,
26260        dwShareMode,
26261        NULL,
26262        dwCreationDisposition,
26263        dwFlagsAndAttributes,
26264        NULL
26265     );
26266   }else{
26267     h = CreateFileA((char*)zConverted,
26268        dwDesiredAccess,
26269        dwShareMode,
26270        NULL,
26271        dwCreationDisposition,
26272        dwFlagsAndAttributes,
26273        NULL
26274     );
26275   }
26276   if( h==INVALID_HANDLE_VALUE ){
26277     free(zConverted);
26278     if( flags & SQLITE_OPEN_READWRITE ){
26279       return winOpen(0, zName, id, 
26280              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
26281     }else{
26282       return SQLITE_CANTOPEN;
26283     }
26284   }
26285   if( pOutFlags ){
26286     if( flags & SQLITE_OPEN_READWRITE ){
26287       *pOutFlags = SQLITE_OPEN_READWRITE;
26288     }else{
26289       *pOutFlags = SQLITE_OPEN_READONLY;
26290     }
26291   }
26292   memset(pFile, 0, sizeof(*pFile));
26293   pFile->pMethod = &winIoMethod;
26294   pFile->h = h;
26295 #if SQLITE_OS_WINCE
26296   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
26297                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
26298        && !winceCreateLock(zName, pFile)
26299   ){
26300     CloseHandle(h);
26301     free(zConverted);
26302     return SQLITE_CANTOPEN;
26303   }
26304   if( isTemp ){
26305     pFile->zDeleteOnClose = zConverted;
26306   }else
26307 #endif
26308   {
26309     free(zConverted);
26310   }
26311   OpenCounter(+1);
26312   return SQLITE_OK;
26313 }
26314
26315 /*
26316 ** Delete the named file.
26317 **
26318 ** Note that windows does not allow a file to be deleted if some other
26319 ** process has it open.  Sometimes a virus scanner or indexing program
26320 ** will open a journal file shortly after it is created in order to do
26321 ** whatever it does.  While this other process is holding the
26322 ** file open, we will be unable to delete it.  To work around this
26323 ** problem, we delay 100 milliseconds and try to delete again.  Up
26324 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
26325 ** up and returning an error.
26326 */
26327 #define MX_DELETION_ATTEMPTS 5
26328 static int winDelete(
26329   sqlite3_vfs *pVfs,          /* Not used on win32 */
26330   const char *zFilename,      /* Name of file to delete */
26331   int syncDir                 /* Not used on win32 */
26332 ){
26333   int cnt = 0;
26334   DWORD rc;
26335   DWORD error;
26336   void *zConverted = convertUtf8Filename(zFilename);
26337   if( zConverted==0 ){
26338     return SQLITE_NOMEM;
26339   }
26340   SimulateIOError(return SQLITE_IOERR_DELETE);
26341   if( isNT() ){
26342     do{
26343       DeleteFileW(zConverted);
26344     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
26345                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26346            && (++cnt < MX_DELETION_ATTEMPTS)
26347            && (Sleep(100), 1) );
26348   }else{
26349     do{
26350       DeleteFileA(zConverted);
26351     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
26352                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
26353            && (++cnt < MX_DELETION_ATTEMPTS)
26354            && (Sleep(100), 1) );
26355   }
26356   free(zConverted);
26357   OSTRACE2("DELETE \"%s\"\n", zFilename);
26358   return (   (rc == INVALID_FILE_ATTRIBUTES) 
26359           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
26360 }
26361
26362 /*
26363 ** Check the existance and status of a file.
26364 */
26365 static int winAccess(
26366   sqlite3_vfs *pVfs,         /* Not used on win32 */
26367   const char *zFilename,     /* Name of file to check */
26368   int flags,                 /* Type of test to make on this file */
26369   int *pResOut               /* OUT: Result */
26370 ){
26371   DWORD attr;
26372   int rc;
26373   void *zConverted = convertUtf8Filename(zFilename);
26374   if( zConverted==0 ){
26375     return SQLITE_NOMEM;
26376   }
26377   if( isNT() ){
26378     attr = GetFileAttributesW((WCHAR*)zConverted);
26379   }else{
26380     attr = GetFileAttributesA((char*)zConverted);
26381   }
26382   free(zConverted);
26383   switch( flags ){
26384     case SQLITE_ACCESS_READ:
26385     case SQLITE_ACCESS_EXISTS:
26386       rc = attr!=INVALID_FILE_ATTRIBUTES;
26387       break;
26388     case SQLITE_ACCESS_READWRITE:
26389       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
26390       break;
26391     default:
26392       assert(!"Invalid flags argument");
26393   }
26394   *pResOut = rc;
26395   return SQLITE_OK;
26396 }
26397
26398
26399 /*
26400 ** Turn a relative pathname into a full pathname.  Write the full
26401 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
26402 ** bytes in size.
26403 */
26404 static int winFullPathname(
26405   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
26406   const char *zRelative,        /* Possibly relative input path */
26407   int nFull,                    /* Size of output buffer in bytes */
26408   char *zFull                   /* Output buffer */
26409 ){
26410
26411 #if defined(__CYGWIN__)
26412   cygwin_conv_to_full_win32_path(zRelative, zFull);
26413   return SQLITE_OK;
26414 #endif
26415
26416 #if SQLITE_OS_WINCE
26417   /* WinCE has no concept of a relative pathname, or so I am told. */
26418   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
26419   return SQLITE_OK;
26420 #endif
26421
26422 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
26423   int nByte;
26424   void *zConverted;
26425   char *zOut;
26426   zConverted = convertUtf8Filename(zRelative);
26427   if( isNT() ){
26428     WCHAR *zTemp;
26429     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
26430     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26431     if( zTemp==0 ){
26432       free(zConverted);
26433       return SQLITE_NOMEM;
26434     }
26435     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
26436     free(zConverted);
26437     zOut = unicodeToUtf8(zTemp);
26438     free(zTemp);
26439   }else{
26440     char *zTemp;
26441     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
26442     zTemp = malloc( nByte*sizeof(zTemp[0]) );
26443     if( zTemp==0 ){
26444       free(zConverted);
26445       return SQLITE_NOMEM;
26446     }
26447     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
26448     free(zConverted);
26449     zOut = mbcsToUtf8(zTemp);
26450     free(zTemp);
26451   }
26452   if( zOut ){
26453     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
26454     free(zOut);
26455     return SQLITE_OK;
26456   }else{
26457     return SQLITE_NOMEM;
26458   }
26459 #endif
26460 }
26461
26462 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26463 /*
26464 ** Interfaces for opening a shared library, finding entry points
26465 ** within the shared library, and closing the shared library.
26466 */
26467 /*
26468 ** Interfaces for opening a shared library, finding entry points
26469 ** within the shared library, and closing the shared library.
26470 */
26471 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
26472   HANDLE h;
26473   void *zConverted = convertUtf8Filename(zFilename);
26474   if( zConverted==0 ){
26475     return 0;
26476   }
26477   if( isNT() ){
26478     h = LoadLibraryW((WCHAR*)zConverted);
26479   }else{
26480     h = LoadLibraryA((char*)zConverted);
26481   }
26482   free(zConverted);
26483   return (void*)h;
26484 }
26485 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
26486   getLastErrorMsg(nBuf, zBufOut);
26487 }
26488 void *winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
26489 #if SQLITE_OS_WINCE
26490   /* The GetProcAddressA() routine is only available on wince. */
26491   return GetProcAddressA((HANDLE)pHandle, zSymbol);
26492 #else
26493   /* All other windows platforms expect GetProcAddress() to take
26494   ** an Ansi string regardless of the _UNICODE setting */
26495   return GetProcAddress((HANDLE)pHandle, zSymbol);
26496 #endif
26497 }
26498 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
26499   FreeLibrary((HANDLE)pHandle);
26500 }
26501 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
26502   #define winDlOpen  0
26503   #define winDlError 0
26504   #define winDlSym   0
26505   #define winDlClose 0
26506 #endif
26507
26508
26509 /*
26510 ** Write up to nBuf bytes of randomness into zBuf.
26511 */
26512 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26513   int n = 0;
26514   if( sizeof(SYSTEMTIME)<=nBuf-n ){
26515     SYSTEMTIME x;
26516     GetSystemTime(&x);
26517     memcpy(&zBuf[n], &x, sizeof(x));
26518     n += sizeof(x);
26519   }
26520   if( sizeof(DWORD)<=nBuf-n ){
26521     DWORD pid = GetCurrentProcessId();
26522     memcpy(&zBuf[n], &pid, sizeof(pid));
26523     n += sizeof(pid);
26524   }
26525   if( sizeof(DWORD)<=nBuf-n ){
26526     DWORD cnt = GetTickCount();
26527     memcpy(&zBuf[n], &cnt, sizeof(cnt));
26528     n += sizeof(cnt);
26529   }
26530   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
26531     LARGE_INTEGER i;
26532     QueryPerformanceCounter(&i);
26533     memcpy(&zBuf[n], &i, sizeof(i));
26534     n += sizeof(i);
26535   }
26536   return n;
26537 }
26538
26539
26540 /*
26541 ** Sleep for a little while.  Return the amount of time slept.
26542 */
26543 static int winSleep(sqlite3_vfs *pVfs, int microsec){
26544   Sleep((microsec+999)/1000);
26545   return ((microsec+999)/1000)*1000;
26546 }
26547
26548 /*
26549 ** The following variable, if set to a non-zero value, becomes the result
26550 ** returned from sqlite3OsCurrentTime().  This is used for testing.
26551 */
26552 #ifdef SQLITE_TEST
26553 SQLITE_API int sqlite3_current_time = 0;
26554 #endif
26555
26556 /*
26557 ** Find the current time (in Universal Coordinated Time).  Write the
26558 ** current time and date as a Julian Day number into *prNow and
26559 ** return 0.  Return 1 if the time and date cannot be found.
26560 */
26561 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
26562   FILETIME ft;
26563   /* FILETIME structure is a 64-bit value representing the number of 
26564      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
26565   */
26566   double now;
26567 #if SQLITE_OS_WINCE
26568   SYSTEMTIME time;
26569   GetSystemTime(&time);
26570   /* if SystemTimeToFileTime() fails, it returns zero. */
26571   if (!SystemTimeToFileTime(&time,&ft)){
26572     return 1;
26573   }
26574 #else
26575   GetSystemTimeAsFileTime( &ft );
26576 #endif
26577   now = ((double)ft.dwHighDateTime) * 4294967296.0; 
26578   *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
26579 #ifdef SQLITE_TEST
26580   if( sqlite3_current_time ){
26581     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26582   }
26583 #endif
26584   return 0;
26585 }
26586
26587 /*
26588 ** The idea is that this function works like a combination of
26589 ** GetLastError() and FormatMessage() on windows (or errno and
26590 ** strerror_r() on unix). After an error is returned by an OS
26591 ** function, SQLite calls this function with zBuf pointing to
26592 ** a buffer of nBuf bytes. The OS layer should populate the
26593 ** buffer with a nul-terminated UTF-8 encoded error message
26594 ** describing the last IO error to have occured within the calling
26595 ** thread.
26596 **
26597 ** If the error message is too large for the supplied buffer,
26598 ** it should be truncated. The return value of xGetLastError
26599 ** is zero if the error message fits in the buffer, or non-zero
26600 ** otherwise (if the message was truncated). If non-zero is returned,
26601 ** then it is not necessary to include the nul-terminator character
26602 ** in the output buffer.
26603 **
26604 ** Not supplying an error message will have no adverse effect
26605 ** on SQLite. It is fine to have an implementation that never
26606 ** returns an error message:
26607 **
26608 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26609 **     assert(zBuf[0]=='\0');
26610 **     return 0;
26611 **   }
26612 **
26613 ** However if an error message is supplied, it will be incorporated
26614 ** by sqlite into the error message available to the user using
26615 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
26616 */
26617 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
26618   return getLastErrorMsg(nBuf, zBuf);
26619 }
26620
26621 /*
26622 ** Initialize and deinitialize the operating system interface.
26623 */
26624 SQLITE_API int sqlite3_os_init(void){
26625   static sqlite3_vfs winVfs = {
26626     1,                 /* iVersion */
26627     sizeof(winFile),   /* szOsFile */
26628     MAX_PATH,          /* mxPathname */
26629     0,                 /* pNext */
26630     "win32",           /* zName */
26631     0,                 /* pAppData */
26632  
26633     winOpen,           /* xOpen */
26634     winDelete,         /* xDelete */
26635     winAccess,         /* xAccess */
26636     winFullPathname,   /* xFullPathname */
26637     winDlOpen,         /* xDlOpen */
26638     winDlError,        /* xDlError */
26639     winDlSym,          /* xDlSym */
26640     winDlClose,        /* xDlClose */
26641     winRandomness,     /* xRandomness */
26642     winSleep,          /* xSleep */
26643     winCurrentTime,    /* xCurrentTime */
26644     winGetLastError    /* xGetLastError */
26645   };
26646   sqlite3_vfs_register(&winVfs, 1);
26647   return SQLITE_OK; 
26648 }
26649 SQLITE_API int sqlite3_os_end(void){ 
26650   return SQLITE_OK;
26651 }
26652
26653 #endif /* SQLITE_OS_WIN */
26654
26655 /************** End of os_win.c **********************************************/
26656 /************** Begin file bitvec.c ******************************************/
26657 /*
26658 ** 2008 February 16
26659 **
26660 ** The author disclaims copyright to this source code.  In place of
26661 ** a legal notice, here is a blessing:
26662 **
26663 **    May you do good and not evil.
26664 **    May you find forgiveness for yourself and forgive others.
26665 **    May you share freely, never taking more than you give.
26666 **
26667 *************************************************************************
26668 ** This file implements an object that represents a fixed-length
26669 ** bitmap.  Bits are numbered starting with 1.
26670 **
26671 ** A bitmap is used to record what pages a database file have been
26672 ** journalled during a transaction.  Usually only a few pages are
26673 ** journalled.  So the bitmap is usually sparse and has low cardinality.
26674 ** But sometimes (for example when during a DROP of a large table) most
26675 ** or all of the pages get journalled.  In those cases, the bitmap becomes
26676 ** dense.  The algorithm needs to handle both cases well.
26677 **
26678 ** The size of the bitmap is fixed when the object is created.
26679 **
26680 ** All bits are clear when the bitmap is created.  Individual bits
26681 ** may be set or cleared one at a time.
26682 **
26683 ** Test operations are about 100 times more common that set operations.
26684 ** Clear operations are exceedingly rare.  There are usually between
26685 ** 5 and 500 set operations per Bitvec object, though the number of sets can
26686 ** sometimes grow into tens of thousands or larger.  The size of the
26687 ** Bitvec object is the number of pages in the database file at the
26688 ** start of a transaction, and is thus usually less than a few thousand,
26689 ** but can be as large as 2 billion for a really big database.
26690 **
26691 ** @(#) $Id: bitvec.c,v 1.6 2008/06/20 14:59:51 danielk1977 Exp $
26692 */
26693
26694 #define BITVEC_SZ        512
26695 /* Round the union size down to the nearest pointer boundary, since that's how 
26696 ** it will be aligned within the Bitvec struct. */
26697 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec*))*sizeof(Bitvec*))
26698 #define BITVEC_NCHAR     BITVEC_USIZE
26699 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
26700 #define BITVEC_NINT      (BITVEC_USIZE/4)
26701 #define BITVEC_MXHASH    (BITVEC_NINT/2)
26702 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
26703
26704 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
26705
26706 /*
26707 ** A bitmap is an instance of the following structure.
26708 **
26709 ** This bitmap records the existance of zero or more bits
26710 ** with values between 1 and iSize, inclusive.
26711 **
26712 ** There are three possible representations of the bitmap.
26713 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
26714 ** bitmap.  The least significant bit is bit 1.
26715 **
26716 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
26717 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
26718 **
26719 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
26720 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
26721 ** handles up to iDivisor separate values of i.  apSub[0] holds
26722 ** values between 1 and iDivisor.  apSub[1] holds values between
26723 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
26724 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
26725 ** to hold deal with values between 1 and iDivisor.
26726 */
26727 struct Bitvec {
26728   u32 iSize;      /* Maximum bit index */
26729   u32 nSet;       /* Number of bits that are set */
26730   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
26731   union {
26732     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
26733     u32 aHash[BITVEC_NINT];      /* Hash table representation */
26734     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
26735   } u;
26736 };
26737
26738 /*
26739 ** Create a new bitmap object able to handle bits between 0 and iSize,
26740 ** inclusive.  Return a pointer to the new object.  Return NULL if 
26741 ** malloc fails.
26742 */
26743 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
26744   Bitvec *p;
26745   assert( sizeof(*p)==BITVEC_SZ );
26746   p = sqlite3MallocZero( sizeof(*p) );
26747   if( p ){
26748     p->iSize = iSize;
26749   }
26750   return p;
26751 }
26752
26753 /*
26754 ** Check to see if the i-th bit is set.  Return true or false.
26755 ** If p is NULL (if the bitmap has not been created) or if
26756 ** i is out of range, then return false.
26757 */
26758 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
26759   if( p==0 ) return 0;
26760   if( i>p->iSize || i==0 ) return 0;
26761   if( p->iSize<=BITVEC_NBIT ){
26762     i--;
26763     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
26764   }
26765   if( p->iDivisor>0 ){
26766     u32 bin = (i-1)/p->iDivisor;
26767     i = (i-1)%p->iDivisor + 1;
26768     return sqlite3BitvecTest(p->u.apSub[bin], i);
26769   }else{
26770     u32 h = BITVEC_HASH(i);
26771     while( p->u.aHash[h] ){
26772       if( p->u.aHash[h]==i ) return 1;
26773       h++;
26774       if( h>=BITVEC_NINT ) h = 0;
26775     }
26776     return 0;
26777   }
26778 }
26779
26780 /*
26781 ** Set the i-th bit.  Return 0 on success and an error code if
26782 ** anything goes wrong.
26783 */
26784 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
26785   u32 h;
26786   assert( p!=0 );
26787   assert( i>0 );
26788   assert( i<=p->iSize );
26789   if( p->iSize<=BITVEC_NBIT ){
26790     i--;
26791     p->u.aBitmap[i/8] |= 1 << (i&7);
26792     return SQLITE_OK;
26793   }
26794   if( p->iDivisor ){
26795     u32 bin = (i-1)/p->iDivisor;
26796     i = (i-1)%p->iDivisor + 1;
26797     if( p->u.apSub[bin]==0 ){
26798       sqlite3BeginBenignMalloc();
26799       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
26800       sqlite3EndBenignMalloc();
26801       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
26802     }
26803     return sqlite3BitvecSet(p->u.apSub[bin], i);
26804   }
26805   h = BITVEC_HASH(i);
26806   while( p->u.aHash[h] ){
26807     if( p->u.aHash[h]==i ) return SQLITE_OK;
26808     h++;
26809     if( h==BITVEC_NINT ) h = 0;
26810   }
26811   p->nSet++;
26812   if( p->nSet>=BITVEC_MXHASH ){
26813     int j, rc;
26814     u32 aiValues[BITVEC_NINT];
26815     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
26816     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
26817     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
26818     rc = sqlite3BitvecSet(p, i);
26819     for(j=0; j<BITVEC_NINT; j++){
26820       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
26821     }
26822     return rc;
26823   }
26824   p->u.aHash[h] = i;
26825   return SQLITE_OK;
26826 }
26827
26828 /*
26829 ** Clear the i-th bit.  Return 0 on success and an error code if
26830 ** anything goes wrong.
26831 */
26832 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
26833   assert( p!=0 );
26834   assert( i>0 );
26835   if( p->iSize<=BITVEC_NBIT ){
26836     i--;
26837     p->u.aBitmap[i/8] &= ~(1 << (i&7));
26838   }else if( p->iDivisor ){
26839     u32 bin = (i-1)/p->iDivisor;
26840     i = (i-1)%p->iDivisor + 1;
26841     if( p->u.apSub[bin] ){
26842       sqlite3BitvecClear(p->u.apSub[bin], i);
26843     }
26844   }else{
26845     int j;
26846     u32 aiValues[BITVEC_NINT];
26847     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
26848     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
26849     p->nSet = 0;
26850     for(j=0; j<BITVEC_NINT; j++){
26851       if( aiValues[j] && aiValues[j]!=i ){
26852         sqlite3BitvecSet(p, aiValues[j]);
26853       }
26854     }
26855   }
26856 }
26857
26858 /*
26859 ** Destroy a bitmap object.  Reclaim all memory used.
26860 */
26861 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
26862   if( p==0 ) return;
26863   if( p->iDivisor ){
26864     int i;
26865     for(i=0; i<BITVEC_NPTR; i++){
26866       sqlite3BitvecDestroy(p->u.apSub[i]);
26867     }
26868   }
26869   sqlite3_free(p);
26870 }
26871
26872 #ifndef SQLITE_OMIT_BUILTIN_TEST
26873 /*
26874 ** Let V[] be an array of unsigned characters sufficient to hold
26875 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
26876 ** Then the following macros can be used to set, clear, or test
26877 ** individual bits within V.
26878 */
26879 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
26880 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
26881 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
26882
26883 /*
26884 ** This routine runs an extensive test of the Bitvec code.
26885 **
26886 ** The input is an array of integers that acts as a program
26887 ** to test the Bitvec.  The integers are opcodes followed
26888 ** by 0, 1, or 3 operands, depending on the opcode.  Another
26889 ** opcode follows immediately after the last operand.
26890 **
26891 ** There are 6 opcodes numbered from 0 through 5.  0 is the
26892 ** "halt" opcode and causes the test to end.
26893 **
26894 **    0          Halt and return the number of errors
26895 **    1 N S X    Set N bits beginning with S and incrementing by X
26896 **    2 N S X    Clear N bits beginning with S and incrementing by X
26897 **    3 N        Set N randomly chosen bits
26898 **    4 N        Clear N randomly chosen bits
26899 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
26900 **
26901 ** The opcodes 1 through 4 perform set and clear operations are performed
26902 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
26903 ** Opcode 5 works on the linear array only, not on the Bitvec.
26904 ** Opcode 5 is used to deliberately induce a fault in order to
26905 ** confirm that error detection works.
26906 **
26907 ** At the conclusion of the test the linear array is compared
26908 ** against the Bitvec object.  If there are any differences,
26909 ** an error is returned.  If they are the same, zero is returned.
26910 **
26911 ** If a memory allocation error occurs, return -1.
26912 */
26913 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
26914   Bitvec *pBitvec = 0;
26915   unsigned char *pV = 0;
26916   int rc = -1;
26917   int i, nx, pc, op;
26918
26919   /* Allocate the Bitvec to be tested and a linear array of
26920   ** bits to act as the reference */
26921   pBitvec = sqlite3BitvecCreate( sz );
26922   pV = sqlite3_malloc( (sz+7)/8 + 1 );
26923   if( pBitvec==0 || pV==0 ) goto bitvec_end;
26924   memset(pV, 0, (sz+7)/8 + 1);
26925
26926   /* Run the program */
26927   pc = 0;
26928   while( (op = aOp[pc])!=0 ){
26929     switch( op ){
26930       case 1:
26931       case 2:
26932       case 5: {
26933         nx = 4;
26934         i = aOp[pc+2] - 1;
26935         aOp[pc+2] += aOp[pc+3];
26936         break;
26937       }
26938       case 3:
26939       case 4: 
26940       default: {
26941         nx = 2;
26942         sqlite3_randomness(sizeof(i), &i);
26943         break;
26944       }
26945     }
26946     if( (--aOp[pc+1]) > 0 ) nx = 0;
26947     pc += nx;
26948     i = (i & 0x7fffffff)%sz;
26949     if( (op & 1)!=0 ){
26950       SETBIT(pV, (i+1));
26951       if( op!=5 ){
26952         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
26953       }
26954     }else{
26955       CLEARBIT(pV, (i+1));
26956       sqlite3BitvecClear(pBitvec, i+1);
26957     }
26958   }
26959
26960   /* Test to make sure the linear array exactly matches the
26961   ** Bitvec object.  Start with the assumption that they do
26962   ** match (rc==0).  Change rc to non-zero if a discrepancy
26963   ** is found.
26964   */
26965   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
26966           + sqlite3BitvecTest(pBitvec, 0);
26967   for(i=1; i<=sz; i++){
26968     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
26969       rc = i;
26970       break;
26971     }
26972   }
26973
26974   /* Free allocated structure */
26975 bitvec_end:
26976   sqlite3_free(pV);
26977   sqlite3BitvecDestroy(pBitvec);
26978   return rc;
26979 }
26980 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26981
26982 /************** End of bitvec.c **********************************************/
26983 /************** Begin file pcache.c ******************************************/
26984 /*
26985 ** 2008 August 05
26986 **
26987 ** The author disclaims copyright to this source code.  In place of
26988 ** a legal notice, here is a blessing:
26989 **
26990 **    May you do good and not evil.
26991 **    May you find forgiveness for yourself and forgive others.
26992 **    May you share freely, never taking more than you give.
26993 **
26994 *************************************************************************
26995 ** This file implements that page cache.
26996 **
26997 ** @(#) $Id: pcache.c,v 1.33 2008/09/29 11:49:48 danielk1977 Exp $
26998 */
26999
27000 /*
27001 ** A complete page cache is an instance of this structure.
27002 **
27003 ** A cache may only be deleted by its owner and while holding the
27004 ** SQLITE_MUTEX_STATUS_LRU mutex.
27005 */
27006 struct PCache {
27007   /*********************************************************************
27008   ** The first group of elements may be read or written at any time by
27009   ** the cache owner without holding the mutex.  No thread other than the
27010   ** cache owner is permitted to access these elements at any time.
27011   */
27012   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
27013   PgHdr *pSynced;                     /* Last synced page in dirty page list */
27014   int nRef;                           /* Number of pinned pages */
27015   int nPinned;                        /* Number of pinned and/or dirty pages */
27016   int nMax;                           /* Configured cache size */
27017   int nMin;                           /* Configured minimum cache size */
27018   /**********************************************************************
27019   ** The next group of elements are fixed when the cache is created and
27020   ** may not be changed afterwards.  These elements can read at any time by
27021   ** the cache owner or by any thread holding the the mutex.  Non-owner
27022   ** threads must hold the mutex when reading these elements to prevent
27023   ** the entire PCache object from being deleted during the read.
27024   */
27025   int szPage;                         /* Size of every page in this cache */
27026   int szExtra;                        /* Size of extra space for each page */
27027   int bPurgeable;                     /* True if pages are on backing store */
27028   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
27029   void *pStress;                      /* Argument to xStress */
27030   /**********************************************************************
27031   ** The final group of elements can only be accessed while holding the
27032   ** mutex.  Both the cache owner and any other thread must hold the mutex
27033   ** to read or write any of these elements.
27034   */
27035   int nPage;                          /* Total number of pages in apHash */
27036   int nHash;                          /* Number of slots in apHash[] */
27037   PgHdr **apHash;                     /* Hash table for fast lookup by pgno */
27038   PgHdr *pClean;                      /* List of clean pages in use */
27039 };
27040
27041 /*
27042 ** Free slots in the page block allocator
27043 */
27044 typedef struct PgFreeslot PgFreeslot;
27045 struct PgFreeslot {
27046   PgFreeslot *pNext;  /* Next free slot */
27047 };
27048
27049 /*
27050 ** Global data for the page cache.
27051 */
27052 static SQLITE_WSD struct PCacheGlobal {
27053   int isInit;                         /* True when initialized */
27054   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
27055
27056   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
27057   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
27058   int nCurrentPage;                   /* Number of purgeable pages allocated */
27059   PgHdr *pLruHead, *pLruTail;         /* LRU list of unused clean pgs */
27060
27061   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
27062   int szSlot;                         /* Size of each free slot */
27063   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
27064   PgFreeslot *pFree;                  /* Free page blocks */
27065 } pcache = {0};
27066
27067 /*
27068 ** All code in this file should access the global pcache structure via the
27069 ** alias "pcache_g". This ensures that the WSD emulation is used when
27070 ** compiling for systems that do not support real WSD.
27071 */
27072 #define pcache_g (GLOBAL(struct PCacheGlobal, pcache))
27073
27074 /*
27075 ** All global variables used by this module (all of which are grouped 
27076 ** together in global structure "pcache" above) are protected by the static 
27077 ** SQLITE_MUTEX_STATIC_LRU mutex. A pointer to this mutex is stored in
27078 ** variable "pcache.mutex".
27079 **
27080 ** Some elements of the PCache and PgHdr structures are protected by the 
27081 ** SQLITE_MUTEX_STATUS_LRU mutex and other are not.  The protected
27082 ** elements are grouped at the end of the structures and are clearly
27083 ** marked.
27084 **
27085 ** Use the following macros must surround all access (read or write)
27086 ** of protected elements.  The mutex is not recursive and may not be
27087 ** entered more than once.  The pcacheMutexHeld() macro should only be
27088 ** used within an assert() to verify that the mutex is being held.
27089 */
27090 #define pcacheEnterMutex() sqlite3_mutex_enter(pcache_g.mutex)
27091 #define pcacheExitMutex()  sqlite3_mutex_leave(pcache_g.mutex)
27092 #define pcacheMutexHeld()  sqlite3_mutex_held(pcache_g.mutex)
27093
27094 /*
27095 ** Some of the assert() macros in this code are too expensive to run
27096 ** even during normal debugging.  Use them only rarely on long-running
27097 ** tests.  Enable the expensive asserts using the
27098 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
27099 */
27100 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
27101 # define expensive_assert(X)  assert(X)
27102 #else
27103 # define expensive_assert(X)
27104 #endif
27105
27106 /********************************** Linked List Management ********************/
27107
27108 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
27109 /*
27110 ** This routine verifies that the number of entries in the hash table
27111 ** is pCache->nPage.  This routine is used within assert() statements
27112 ** only and is therefore disabled during production builds.
27113 */
27114 static int pcacheCheckHashCount(PCache *pCache){
27115   int i;
27116   int nPage = 0;
27117   for(i=0; i<pCache->nHash; i++){
27118     PgHdr *p;
27119     for(p=pCache->apHash[i]; p; p=p->pNextHash){
27120       nPage++;
27121     }
27122   }
27123   assert( nPage==pCache->nPage );
27124   return 1;
27125 }
27126 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
27127
27128
27129 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
27130 /*
27131 ** Based on the current value of PCache.nRef and the contents of the
27132 ** PCache.pDirty list, return the expected value of the PCache.nPinned
27133 ** counter. This is only used in debugging builds, as follows:
27134 **
27135 **   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27136 */
27137 static int pcachePinnedCount(PCache *pCache){
27138   PgHdr *p;
27139   int nPinned = pCache->nRef;
27140   for(p=pCache->pDirty; p; p=p->pNext){
27141     if( p->nRef==0 ){
27142       nPinned++;
27143     }
27144   }
27145   return nPinned;
27146 }
27147 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
27148
27149
27150 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
27151 /*
27152 ** Check that the pCache->pSynced variable is set correctly. If it
27153 ** is not, either fail an assert or return zero. Otherwise, return
27154 ** non-zero. This is only used in debugging builds, as follows:
27155 **
27156 **   expensive_assert( pcacheCheckSynced(pCache) );
27157 */
27158 static int pcacheCheckSynced(PCache *pCache){
27159   PgHdr *p = pCache->pDirtyTail;
27160   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pPrev){
27161     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
27162   }
27163   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
27164 }
27165 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
27166
27167
27168
27169 /*
27170 ** Remove a page from its hash table (PCache.apHash[]).
27171 */
27172 static void pcacheRemoveFromHash(PgHdr *pPage){
27173   assert( pcacheMutexHeld() );
27174   if( pPage->pPrevHash ){
27175     pPage->pPrevHash->pNextHash = pPage->pNextHash;
27176   }else{
27177     PCache *pCache = pPage->pCache;
27178     u32 h = pPage->pgno % pCache->nHash;
27179     assert( pCache->apHash[h]==pPage );
27180     pCache->apHash[h] = pPage->pNextHash;
27181   }
27182   if( pPage->pNextHash ){
27183     pPage->pNextHash->pPrevHash = pPage->pPrevHash;
27184   }
27185   pPage->pCache->nPage--;
27186   expensive_assert( pcacheCheckHashCount(pPage->pCache) );
27187 }
27188
27189 /*
27190 ** Insert a page into the hash table
27191 **
27192 ** The mutex must be held by the caller.
27193 */
27194 static void pcacheAddToHash(PgHdr *pPage){
27195   PCache *pCache = pPage->pCache;
27196   u32 h = pPage->pgno % pCache->nHash;
27197   assert( pcacheMutexHeld() );
27198   pPage->pNextHash = pCache->apHash[h];
27199   pPage->pPrevHash = 0;
27200   if( pCache->apHash[h] ){
27201     pCache->apHash[h]->pPrevHash = pPage;
27202   }
27203   pCache->apHash[h] = pPage;
27204   pCache->nPage++;
27205   expensive_assert( pcacheCheckHashCount(pCache) );
27206 }
27207
27208 /*
27209 ** Attempt to increase the size the hash table to contain
27210 ** at least nHash buckets.
27211 */
27212 static int pcacheResizeHash(PCache *pCache, int nHash){
27213   PgHdr *p;
27214   PgHdr **pNew;
27215   assert( pcacheMutexHeld() );
27216 #ifdef SQLITE_MALLOC_SOFT_LIMIT
27217   if( nHash*sizeof(PgHdr*)>SQLITE_MALLOC_SOFT_LIMIT ){
27218     nHash = SQLITE_MALLOC_SOFT_LIMIT/sizeof(PgHdr *);
27219   }
27220 #endif
27221   pcacheExitMutex();
27222   pNew = (PgHdr **)sqlite3Malloc(sizeof(PgHdr*)*nHash);
27223   pcacheEnterMutex();
27224   if( !pNew ){
27225     return SQLITE_NOMEM;
27226   }
27227   memset(pNew, 0, sizeof(PgHdr *)*nHash);
27228   sqlite3_free(pCache->apHash);
27229   pCache->apHash = pNew;
27230   pCache->nHash = nHash;
27231   pCache->nPage = 0;
27232  
27233   for(p=pCache->pClean; p; p=p->pNext){
27234     pcacheAddToHash(p);
27235   }
27236   for(p=pCache->pDirty; p; p=p->pNext){
27237     pcacheAddToHash(p);
27238   }
27239   return SQLITE_OK;
27240 }
27241
27242 /*
27243 ** Remove a page from a linked list that is headed by *ppHead.
27244 ** *ppHead is either PCache.pClean or PCache.pDirty.
27245 */
27246 static void pcacheRemoveFromList(PgHdr **ppHead, PgHdr *pPage){
27247   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
27248   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
27249   assert( pcacheMutexHeld() || ppHead!=&pPage->pCache->pClean );
27250
27251   if( pPage->pPrev ){
27252     pPage->pPrev->pNext = pPage->pNext;
27253   }else{
27254     assert( *ppHead==pPage );
27255     *ppHead = pPage->pNext;
27256   }
27257   if( pPage->pNext ){
27258     pPage->pNext->pPrev = pPage->pPrev;
27259   }
27260
27261   if( isDirtyList ){
27262     PCache *pCache = pPage->pCache;
27263     assert( pPage->pNext || pCache->pDirtyTail==pPage );
27264     if( !pPage->pNext ){
27265       pCache->pDirtyTail = pPage->pPrev;
27266     }
27267     if( pCache->pSynced==pPage ){
27268       PgHdr *pSynced = pPage->pPrev;
27269       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
27270         pSynced = pSynced->pPrev;
27271       }
27272       pCache->pSynced = pSynced;
27273     }
27274   }
27275 }
27276
27277 /*
27278 ** Add a page from a linked list that is headed by *ppHead.
27279 ** *ppHead is either PCache.pClean or PCache.pDirty.
27280 */
27281 static void pcacheAddToList(PgHdr **ppHead, PgHdr *pPage){
27282   int isDirtyList = (ppHead==&pPage->pCache->pDirty);
27283   assert( ppHead==&pPage->pCache->pClean || ppHead==&pPage->pCache->pDirty );
27284
27285   if( (*ppHead) ){
27286     (*ppHead)->pPrev = pPage;
27287   }
27288   pPage->pNext = *ppHead;
27289   pPage->pPrev = 0;
27290   *ppHead = pPage;
27291
27292   if( isDirtyList ){
27293     PCache *pCache = pPage->pCache;
27294     if( !pCache->pDirtyTail ){
27295       assert( pPage->pNext==0 );
27296       pCache->pDirtyTail = pPage;
27297     }
27298     if( !pCache->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
27299       pCache->pSynced = pPage;
27300     }
27301   }
27302 }
27303
27304 /*
27305 ** Remove a page from the global LRU list
27306 */
27307 static void pcacheRemoveFromLruList(PgHdr *pPage){
27308   assert( sqlite3_mutex_held(pcache_g.mutex) );
27309   assert( (pPage->flags&PGHDR_DIRTY)==0 );
27310   if( pPage->pCache->bPurgeable==0 ) return;
27311   if( pPage->pNextLru ){
27312     assert( pcache_g.pLruTail!=pPage );
27313     pPage->pNextLru->pPrevLru = pPage->pPrevLru;
27314   }else{
27315     assert( pcache_g.pLruTail==pPage );
27316     pcache_g.pLruTail = pPage->pPrevLru;
27317   }
27318   if( pPage->pPrevLru ){
27319     assert( pcache_g.pLruHead!=pPage );
27320     pPage->pPrevLru->pNextLru = pPage->pNextLru;
27321   }else{
27322     assert( pcache_g.pLruHead==pPage );
27323     pcache_g.pLruHead = pPage->pNextLru;
27324   }
27325 }
27326
27327 /*
27328 ** Add a page to the global LRU list.  The page is normally added
27329 ** to the front of the list so that it will be the last page recycled.
27330 ** However, if the PGHDR_REUSE_UNLIKELY bit is set, the page is added
27331 ** to the end of the LRU list so that it will be the next to be recycled.
27332 */
27333 static void pcacheAddToLruList(PgHdr *pPage){
27334   assert( sqlite3_mutex_held(pcache_g.mutex) );
27335   assert( (pPage->flags&PGHDR_DIRTY)==0 );
27336   if( pPage->pCache->bPurgeable==0 ) return;
27337   if( pcache_g.pLruTail && (pPage->flags & PGHDR_REUSE_UNLIKELY)!=0 ){
27338     /* If reuse is unlikely.  Put the page at the end of the LRU list
27339     ** where it will be recycled sooner rather than later. 
27340     */
27341     assert( pcache_g.pLruHead );
27342     pPage->pNextLru = 0;
27343     pPage->pPrevLru = pcache_g.pLruTail;
27344     pcache_g.pLruTail->pNextLru = pPage;
27345     pcache_g.pLruTail = pPage;
27346     pPage->flags &= ~PGHDR_REUSE_UNLIKELY;
27347   }else{
27348     /* If reuse is possible. the page goes at the beginning of the LRU
27349     ** list so that it will be the last to be recycled.
27350     */
27351     if( pcache_g.pLruHead ){
27352       pcache_g.pLruHead->pPrevLru = pPage;
27353     }
27354     pPage->pNextLru = pcache_g.pLruHead;
27355     pcache_g.pLruHead = pPage;
27356     pPage->pPrevLru = 0;
27357     if( pcache_g.pLruTail==0 ){
27358       pcache_g.pLruTail = pPage;
27359     }
27360   }
27361 }
27362
27363 /*********************************************** Memory Allocation ***********
27364 **
27365 ** Initialize the page cache memory pool.
27366 **
27367 ** This must be called at start-time when no page cache lines are
27368 ** checked out. This function is not threadsafe.
27369 */
27370 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
27371   PgFreeslot *p;
27372   sz &= ~7;
27373   pcache_g.szSlot = sz;
27374   pcache_g.pStart = pBuf;
27375   pcache_g.pFree = 0;
27376   while( n-- ){
27377     p = (PgFreeslot*)pBuf;
27378     p->pNext = pcache_g.pFree;
27379     pcache_g.pFree = p;
27380     pBuf = (void*)&((char*)pBuf)[sz];
27381   }
27382   pcache_g.pEnd = pBuf;
27383 }
27384
27385 /*
27386 ** Allocate a page cache line.  Look in the page cache memory pool first
27387 ** and use an element from it first if available.  If nothing is available
27388 ** in the page cache memory pool, go to the general purpose memory allocator.
27389 */
27390 static void *pcacheMalloc(int sz, PCache *pCache){
27391   assert( sqlite3_mutex_held(pcache_g.mutex) );
27392   if( sz<=pcache_g.szSlot && pcache_g.pFree ){
27393     PgFreeslot *p = pcache_g.pFree;
27394     pcache_g.pFree = p->pNext;
27395     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, sz);
27396     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
27397     return (void*)p;
27398   }else{
27399     void *p;
27400
27401     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
27402     ** global pcache mutex and unlock the pager-cache object pCache. This is 
27403     ** so that if the attempt to allocate a new buffer causes the the 
27404     ** configured soft-heap-limit to be breached, it will be possible to
27405     ** reclaim memory from this pager-cache.
27406     */
27407     pcacheExitMutex();
27408     p = sqlite3Malloc(sz);
27409     pcacheEnterMutex();
27410
27411     if( p ){
27412       sz = sqlite3MallocSize(p);
27413       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
27414     }
27415     return p;
27416   }
27417 }
27418 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
27419   void *p;
27420   pcacheEnterMutex();
27421   p = pcacheMalloc(sz, 0);
27422   pcacheExitMutex();
27423   return p;
27424 }
27425
27426 /*
27427 ** Release a pager memory allocation
27428 */
27429 static void pcacheFree(void *p){
27430   assert( sqlite3_mutex_held(pcache_g.mutex) );
27431   if( p==0 ) return;
27432   if( p>=pcache_g.pStart && p<pcache_g.pEnd ){
27433     PgFreeslot *pSlot;
27434     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
27435     pSlot = (PgFreeslot*)p;
27436     pSlot->pNext = pcache_g.pFree;
27437     pcache_g.pFree = pSlot;
27438   }else{
27439     int iSize = sqlite3MallocSize(p);
27440     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
27441     sqlite3_free(p);
27442   }
27443 }
27444 SQLITE_PRIVATE void sqlite3PageFree(void *p){
27445   pcacheEnterMutex();
27446   pcacheFree(p);
27447   pcacheExitMutex();
27448 }
27449
27450 /*
27451 ** Allocate a new page.
27452 */
27453 static PgHdr *pcachePageAlloc(PCache *pCache){
27454   PgHdr *p;
27455   int sz = sizeof(*p) + pCache->szPage + pCache->szExtra;
27456   assert( sqlite3_mutex_held(pcache_g.mutex) );
27457   p = pcacheMalloc(sz, pCache);
27458   if( p==0 ) return 0;
27459   memset(p, 0, sizeof(PgHdr));
27460   p->pData = (void*)&p[1];
27461   p->pExtra = (void*)&((char*)p->pData)[pCache->szPage];
27462   if( pCache->bPurgeable ){
27463     pcache_g.nCurrentPage++;
27464   }
27465   return p;
27466 }
27467
27468 /*
27469 ** Deallocate a page
27470 */
27471 static void pcachePageFree(PgHdr *p){
27472   assert( sqlite3_mutex_held(pcache_g.mutex) );
27473   if( p->pCache->bPurgeable ){
27474     pcache_g.nCurrentPage--;
27475   }
27476   pcacheFree(p->apSave[0]);
27477   pcacheFree(p->apSave[1]);
27478   pcacheFree(p);
27479 }
27480
27481 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
27482 /*
27483 ** Return the number of bytes that will be returned to the heap when
27484 ** the argument is passed to pcachePageFree().
27485 */
27486 static int pcachePageSize(PgHdr *p){
27487   assert( sqlite3_mutex_held(pcache_g.mutex) );
27488   assert( !pcache_g.pStart );
27489   assert( p->apSave[0]==0 );
27490   assert( p->apSave[1]==0 );
27491   assert( p && p->pCache );
27492   return sqlite3MallocSize(p);
27493 }
27494 #endif
27495
27496 /*
27497 ** Attempt to 'recycle' a page from the global LRU list. Only clean,
27498 ** unreferenced pages from purgeable caches are eligible for recycling.
27499 **
27500 ** This function removes page pcache.pLruTail from the global LRU list,
27501 ** and from the hash-table and PCache.pClean list of the owner pcache.
27502 ** There should be no other references to the page.
27503 **
27504 ** A pointer to the recycled page is returned, or NULL if no page is
27505 ** eligible for recycling.
27506 */
27507 static PgHdr *pcacheRecyclePage(void){
27508   PgHdr *p = 0;
27509   assert( sqlite3_mutex_held(pcache_g.mutex) );
27510
27511   if( (p=pcache_g.pLruTail) ){
27512     assert( (p->flags&PGHDR_DIRTY)==0 );
27513     pcacheRemoveFromLruList(p);
27514     pcacheRemoveFromHash(p);
27515     pcacheRemoveFromList(&p->pCache->pClean, p);
27516   }
27517
27518   return p;
27519 }
27520
27521 /*
27522 ** Obtain space for a page. Try to recycle an old page if the limit on the 
27523 ** number of pages has been reached. If the limit has not been reached or
27524 ** there are no pages eligible for recycling, allocate a new page.
27525 **
27526 ** Return a pointer to the new page, or NULL if an OOM condition occurs.
27527 */
27528 static int pcacheRecycleOrAlloc(PCache *pCache, PgHdr **ppPage){
27529   PgHdr *p = 0;
27530
27531   int szPage = pCache->szPage;
27532   int szExtra = pCache->szExtra;
27533
27534   assert( pcache_g.isInit );
27535   assert( sqlite3_mutex_held(pcache_g.mutex) );
27536
27537   *ppPage = 0;
27538
27539   /* If we have reached either the global or the local limit for 
27540   ** pinned+dirty pages, and there is at least one dirty page,
27541   ** invoke the xStress callback to cause a page to become clean.
27542   */
27543   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27544   expensive_assert( pcacheCheckSynced(pCache) );
27545   if( pCache->xStress
27546    && pCache->pDirty
27547    && (pCache->nPinned>=(pcache_g.nMaxPage+pCache->nMin-pcache_g.nMinPage)
27548            || pCache->nPinned>=pCache->nMax)
27549   ){
27550     PgHdr *pPg;
27551     assert(pCache->pDirtyTail);
27552
27553     for(pPg=pCache->pSynced; 
27554         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
27555         pPg=pPg->pPrev
27556     );
27557     if( !pPg ){
27558       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pPrev);
27559     }
27560     if( pPg ){
27561       int rc;
27562       pcacheExitMutex();
27563       rc = pCache->xStress(pCache->pStress, pPg);
27564       pcacheEnterMutex();
27565       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
27566         return rc;
27567       }
27568     }
27569   }
27570
27571   /* If either the local or the global page limit has been reached, 
27572   ** try to recycle a page. 
27573   */
27574   if( pCache->bPurgeable && (pCache->nPage>=pCache->nMax-1 ||
27575                              pcache_g.nCurrentPage>=pcache_g.nMaxPage) ){
27576     p = pcacheRecyclePage();
27577   }
27578
27579   /* If a page has been recycled but it is the wrong size, free it. */
27580   if( p && (p->pCache->szPage!=szPage || p->pCache->szPage!=szExtra) ){
27581     pcachePageFree(p);
27582     p = 0;
27583   }
27584
27585   if( !p ){
27586     p = pcachePageAlloc(pCache);
27587   }
27588
27589   *ppPage = p;
27590   return (p?SQLITE_OK:SQLITE_NOMEM);
27591 }
27592
27593 /*************************************************** General Interfaces ******
27594 **
27595 ** Initialize and shutdown the page cache subsystem. Neither of these 
27596 ** functions are threadsafe.
27597 */
27598 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
27599   assert( pcache_g.isInit==0 );
27600   memset(&pcache_g, 0, sizeof(pcache));
27601   if( sqlite3GlobalConfig.bCoreMutex ){
27602     /* No need to check the return value of sqlite3_mutex_alloc(). 
27603     ** Allocating a static mutex cannot fail.
27604     */
27605     pcache_g.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
27606   }
27607   pcache_g.isInit = 1;
27608   return SQLITE_OK;
27609 }
27610 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
27611   memset(&pcache_g, 0, sizeof(pcache));
27612 }
27613
27614 /*
27615 ** Return the size in bytes of a PCache object.
27616 */
27617 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
27618
27619 /*
27620 ** Create a new PCache object.  Storage space to hold the object
27621 ** has already been allocated and is passed in as the p pointer.
27622 */
27623 SQLITE_PRIVATE void sqlite3PcacheOpen(
27624   int szPage,                  /* Size of every page */
27625   int szExtra,                 /* Extra space associated with each page */
27626   int bPurgeable,              /* True if pages are on backing store */
27627   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
27628   void *pStress,               /* Argument to xStress */
27629   PCache *p                    /* Preallocated space for the PCache */
27630 ){
27631   assert( pcache_g.isInit );
27632   memset(p, 0, sizeof(PCache));
27633   p->szPage = szPage;
27634   p->szExtra = szExtra;
27635   p->bPurgeable = bPurgeable;
27636   p->xStress = xStress;
27637   p->pStress = pStress;
27638   p->nMax = 100;
27639   p->nMin = 10;
27640
27641   pcacheEnterMutex();
27642   if( bPurgeable ){
27643     pcache_g.nMaxPage += p->nMax;
27644     pcache_g.nMinPage += p->nMin;
27645   }
27646
27647   pcacheExitMutex();
27648 }
27649
27650 /*
27651 ** Change the page size for PCache object.  This can only happen
27652 ** when the cache is empty.
27653 */
27654 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
27655   assert(pCache->nPage==0);
27656   pCache->szPage = szPage;
27657 }
27658
27659 /*
27660 ** Try to obtain a page from the cache.
27661 */
27662 SQLITE_PRIVATE int sqlite3PcacheFetch(
27663   PCache *pCache,       /* Obtain the page from this cache */
27664   Pgno pgno,            /* Page number to obtain */
27665   int createFlag,       /* If true, create page if it does not exist already */
27666   PgHdr **ppPage        /* Write the page here */
27667 ){
27668   int rc = SQLITE_OK;
27669   PgHdr *pPage = 0;
27670
27671   assert( pcache_g.isInit );
27672   assert( pCache!=0 );
27673   assert( pgno>0 );
27674   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27675
27676   pcacheEnterMutex();
27677
27678   /* Search the hash table for the requested page. Exit early if it is found. */
27679   if( pCache->apHash ){
27680     u32 h = pgno % pCache->nHash;
27681     for(pPage=pCache->apHash[h]; pPage; pPage=pPage->pNextHash){
27682       if( pPage->pgno==pgno ){
27683         if( pPage->nRef==0 ){
27684           if( 0==(pPage->flags&PGHDR_DIRTY) ){
27685             pcacheRemoveFromLruList(pPage);
27686             pCache->nPinned++;
27687           }
27688           pCache->nRef++;
27689         }
27690         pPage->nRef++;
27691         break;
27692       }
27693     }
27694   }
27695
27696   if( !pPage && createFlag ){
27697     if( pCache->nHash<=pCache->nPage ){
27698       rc = pcacheResizeHash(pCache, pCache->nHash<256 ? 256 : pCache->nHash*2);
27699     }
27700     if( rc==SQLITE_OK ){
27701       rc = pcacheRecycleOrAlloc(pCache, &pPage);
27702     }
27703     if( rc==SQLITE_OK ){
27704       pPage->pPager = 0;
27705       pPage->flags = 0;
27706       pPage->pDirty = 0;
27707       pPage->pgno = pgno;
27708       pPage->pCache = pCache;
27709       pPage->nRef = 1;
27710       pCache->nRef++;
27711       pCache->nPinned++;
27712       pcacheAddToList(&pCache->pClean, pPage);
27713       pcacheAddToHash(pPage);
27714     }
27715   }
27716
27717   pcacheExitMutex();
27718
27719   *ppPage = pPage;
27720   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27721   assert( pPage || !createFlag || rc!=SQLITE_OK );
27722   return rc;
27723 }
27724
27725 /*
27726 ** Dereference a page.  When the reference count reaches zero,
27727 ** move the page to the LRU list if it is clean.
27728 */
27729 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
27730   assert( p->nRef>0 );
27731   p->nRef--;
27732   if( p->nRef==0 ){
27733     PCache *pCache = p->pCache;
27734     pCache->nRef--;
27735     if( (p->flags&PGHDR_DIRTY)==0 ){
27736       pCache->nPinned--;
27737       pcacheEnterMutex();
27738       if( pcache_g.nCurrentPage>pcache_g.nMaxPage ){
27739         pcacheRemoveFromList(&pCache->pClean, p);
27740         pcacheRemoveFromHash(p);
27741         pcachePageFree(p);
27742       }else{
27743         pcacheAddToLruList(p);
27744       }
27745       pcacheExitMutex();
27746     }else{
27747       /* Move the page to the head of the caches dirty list. */
27748       pcacheRemoveFromList(&pCache->pDirty, p);
27749       pcacheAddToList(&pCache->pDirty, p);
27750     }
27751   }
27752 }
27753
27754 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
27755   assert(p->nRef>0);
27756   p->nRef++;
27757 }
27758
27759 /*
27760 ** Drop a page from the cache. There must be exactly one reference to the
27761 ** page. This function deletes that reference, so after it returns the
27762 ** page pointed to by p is invalid.
27763 */
27764 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
27765   PCache *pCache;
27766   assert( p->nRef==1 );
27767   assert( 0==(p->flags&PGHDR_DIRTY) );
27768   pCache = p->pCache;
27769   pCache->nRef--;
27770   pCache->nPinned--;
27771   pcacheEnterMutex();
27772   pcacheRemoveFromList(&pCache->pClean, p);
27773   pcacheRemoveFromHash(p);
27774   pcachePageFree(p);
27775   pcacheExitMutex();
27776 }
27777
27778 /*
27779 ** Make sure the page is marked as dirty.  If it isn't dirty already,
27780 ** make it so.
27781 */
27782 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
27783   PCache *pCache;
27784   p->flags &= ~PGHDR_DONT_WRITE;
27785   if( p->flags & PGHDR_DIRTY ) return;
27786   assert( (p->flags & PGHDR_DIRTY)==0 );
27787   assert( p->nRef>0 );
27788   pCache = p->pCache;
27789   pcacheEnterMutex();
27790   pcacheRemoveFromList(&pCache->pClean, p);
27791   pcacheAddToList(&pCache->pDirty, p);
27792   pcacheExitMutex();
27793   p->flags |= PGHDR_DIRTY;
27794 }
27795
27796 static void pcacheMakeClean(PgHdr *p){
27797   PCache *pCache = p->pCache;
27798   assert( p->apSave[0]==0 && p->apSave[1]==0 );
27799   assert( p->flags & PGHDR_DIRTY );
27800   pcacheRemoveFromList(&pCache->pDirty, p);
27801   pcacheAddToList(&pCache->pClean, p);
27802   p->flags &= ~PGHDR_DIRTY;
27803   if( p->nRef==0 ){
27804     pcacheAddToLruList(p);
27805     pCache->nPinned--;
27806   }
27807   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27808 }
27809
27810 /*
27811 ** Make sure the page is marked as clean.  If it isn't clean already,
27812 ** make it so.
27813 */
27814 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
27815   if( (p->flags & PGHDR_DIRTY) ){
27816     pcacheEnterMutex();
27817     pcacheMakeClean(p);
27818     pcacheExitMutex();
27819   }
27820 }
27821
27822 /*
27823 ** Make every page in the cache clean.
27824 */
27825 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
27826   PgHdr *p;
27827   pcacheEnterMutex();
27828   while( (p = pCache->pDirty)!=0 ){
27829     assert( p->apSave[0]==0 && p->apSave[1]==0 );
27830     pcacheRemoveFromList(&pCache->pDirty, p);
27831     p->flags &= ~PGHDR_DIRTY;
27832     pcacheAddToList(&pCache->pClean, p);
27833     if( p->nRef==0 ){
27834       pcacheAddToLruList(p);
27835       pCache->nPinned--;
27836     }
27837   }
27838   sqlite3PcacheAssertFlags(pCache, 0, PGHDR_DIRTY);
27839   expensive_assert( pCache->nPinned==pcachePinnedCount(pCache) );
27840   pcacheExitMutex();
27841 }
27842
27843 /*
27844 ** Change the page number of page p to newPgno. If newPgno is 0, then the
27845 ** page object is added to the clean-list and the PGHDR_REUSE_UNLIKELY 
27846 ** flag set.
27847 */
27848 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
27849   assert( p->nRef>0 );
27850   pcacheEnterMutex();
27851   pcacheRemoveFromHash(p);
27852   p->pgno = newPgno;
27853   if( newPgno==0 ){
27854     pcacheFree(p->apSave[0]);
27855     pcacheFree(p->apSave[1]);
27856     p->apSave[0] = 0;
27857     p->apSave[1] = 0;
27858     if( (p->flags & PGHDR_DIRTY) ){
27859       pcacheMakeClean(p);
27860     }
27861     p->flags = PGHDR_REUSE_UNLIKELY;
27862   }
27863   pcacheAddToHash(p);
27864   pcacheExitMutex();
27865 }
27866
27867 /*
27868 ** Remove all content from a page cache
27869 */
27870 static void pcacheClear(PCache *pCache){
27871   PgHdr *p, *pNext;
27872   assert( sqlite3_mutex_held(pcache_g.mutex) );
27873   for(p=pCache->pClean; p; p=pNext){
27874     pNext = p->pNext;
27875     pcacheRemoveFromLruList(p);
27876     pcachePageFree(p);
27877   }
27878   for(p=pCache->pDirty; p; p=pNext){
27879     pNext = p->pNext;
27880     pcachePageFree(p);
27881   }
27882   pCache->pClean = 0;
27883   pCache->pDirty = 0;
27884   pCache->pDirtyTail = 0;
27885   pCache->nPage = 0;
27886   pCache->nPinned = 0;
27887   memset(pCache->apHash, 0, pCache->nHash*sizeof(pCache->apHash[0]));
27888 }
27889
27890
27891 /*
27892 ** Drop every cache entry whose page number is greater than "pgno".
27893 */
27894 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
27895   PgHdr *p, *pNext;
27896   PgHdr *pDirty = pCache->pDirty;
27897   pcacheEnterMutex();
27898   for(p=pCache->pClean; p||pDirty; p=pNext){
27899     if( !p ){
27900       p = pDirty;
27901       pDirty = 0;
27902     }
27903     pNext = p->pNext;
27904     if( p->pgno>pgno ){
27905       if( p->nRef==0 ){
27906         pcacheRemoveFromHash(p);
27907         if( p->flags&PGHDR_DIRTY ){
27908           pcacheRemoveFromList(&pCache->pDirty, p);
27909           pCache->nPinned--;
27910         }else{
27911           pcacheRemoveFromList(&pCache->pClean, p);
27912           pcacheRemoveFromLruList(p);
27913         }
27914         pcachePageFree(p);
27915       }else{
27916         /* If there are references to the page, it cannot be freed. In this
27917         ** case, zero the page content instead.
27918         */
27919         memset(p->pData, 0, pCache->szPage);
27920       }
27921     }
27922   }
27923   pcacheExitMutex();
27924 }
27925
27926 /*
27927 ** If there are currently more than pcache.nMaxPage pages allocated, try
27928 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
27929 */
27930 static void pcacheEnforceMaxPage(void){
27931   PgHdr *p;
27932   assert( sqlite3_mutex_held(pcache_g.mutex) );
27933   while( pcache_g.nCurrentPage>pcache_g.nMaxPage && (p = pcacheRecyclePage()) ){
27934     pcachePageFree(p);
27935   }
27936 }
27937
27938 /*
27939 ** Close a cache.
27940 */
27941 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
27942   pcacheEnterMutex();
27943
27944   /* Free all the pages used by this pager and remove them from the LRU list. */
27945   pcacheClear(pCache);
27946   if( pCache->bPurgeable ){
27947     pcache_g.nMaxPage -= pCache->nMax;
27948     pcache_g.nMinPage -= pCache->nMin;
27949     pcacheEnforceMaxPage();
27950   }
27951   sqlite3_free(pCache->apHash);
27952   pcacheExitMutex();
27953 }
27954
27955 /*
27956 ** Preserve the content of the page.  It is assumed that the content
27957 ** has not been preserved already.
27958 **
27959 ** If idJournal==0 then this is for the overall transaction.
27960 ** If idJournal==1 then this is for the statement journal.
27961 **
27962 ** This routine is used for in-memory databases only.
27963 **
27964 ** Return SQLITE_OK or SQLITE_NOMEM if a memory allocation fails.
27965 */
27966 SQLITE_PRIVATE int sqlite3PcachePreserve(PgHdr *p, int idJournal){
27967   void *x;
27968   int sz;
27969   assert( p->pCache->bPurgeable==0 );
27970   assert( p->apSave[idJournal]==0 );
27971   sz = p->pCache->szPage;
27972   p->apSave[idJournal] = x = sqlite3PageMalloc( sz );
27973   if( x==0 ) return SQLITE_NOMEM;
27974   memcpy(x, p->pData, sz);
27975   return SQLITE_OK;
27976 }
27977
27978 /*
27979 ** Commit a change previously preserved.
27980 */
27981 SQLITE_PRIVATE void sqlite3PcacheCommit(PCache *pCache, int idJournal){
27982   PgHdr *p;
27983   int mask = idJournal==0 ? ~PGHDR_IN_JOURNAL : 0xffffff;
27984   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
27985   for(p=pCache->pDirty; p; p=p->pNext){
27986     if( p->apSave[idJournal] ){
27987       pcacheFree(p->apSave[idJournal]);
27988       p->apSave[idJournal] = 0;
27989     }
27990     p->flags &= mask;
27991   }
27992   pcacheExitMutex();
27993 }
27994
27995 /*
27996 ** Rollback a change previously preserved.
27997 */
27998 SQLITE_PRIVATE void sqlite3PcacheRollback(
27999   PCache *pCache,                  /* Pager cache */
28000   int idJournal,                   /* Which copy to rollback to */
28001   void (*xReiniter)(PgHdr*)        /* Called on each rolled back page */
28002 ){
28003   PgHdr *p;
28004   int sz;
28005   int mask = idJournal==0 ? ~PGHDR_IN_JOURNAL : 0xffffff;
28006   pcacheEnterMutex();     /* Mutex is required to call pcacheFree() */
28007   sz = pCache->szPage;
28008   for(p=pCache->pDirty; p; p=p->pNext){
28009     if( p->apSave[idJournal] ){
28010       memcpy(p->pData, p->apSave[idJournal], sz);
28011       pcacheFree(p->apSave[idJournal]);
28012       p->apSave[idJournal] = 0;
28013       if( xReiniter ){
28014         xReiniter(p);
28015       }
28016     }
28017     p->flags &= mask;
28018   }
28019   pcacheExitMutex();
28020 }
28021
28022 #ifndef NDEBUG
28023 /* 
28024 ** Assert flags settings on all pages.  Debugging only.
28025 */
28026 SQLITE_PRIVATE void sqlite3PcacheAssertFlags(PCache *pCache, int trueMask, int falseMask){
28027   PgHdr *p;
28028   for(p=pCache->pDirty; p; p=p->pNext){
28029     assert( (p->flags&trueMask)==trueMask );
28030     assert( (p->flags&falseMask)==0 );
28031   }
28032   for(p=pCache->pClean; p; p=p->pNext){
28033     assert( (p->flags&trueMask)==trueMask );
28034     assert( (p->flags&falseMask)==0 );
28035   }
28036 }
28037 #endif
28038
28039 /* 
28040 ** Discard the contents of the cache.
28041 */
28042 SQLITE_PRIVATE int sqlite3PcacheClear(PCache *pCache){
28043   assert(pCache->nRef==0);
28044   pcacheEnterMutex();
28045   pcacheClear(pCache);
28046   pcacheExitMutex();
28047   return SQLITE_OK;
28048 }
28049
28050 /*
28051 ** Merge two lists of pages connected by pDirty and in pgno order.
28052 ** Do not both fixing the pPrevDirty pointers.
28053 */
28054 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
28055   PgHdr result, *pTail;
28056   pTail = &result;
28057   while( pA && pB ){
28058     if( pA->pgno<pB->pgno ){
28059       pTail->pDirty = pA;
28060       pTail = pA;
28061       pA = pA->pDirty;
28062     }else{
28063       pTail->pDirty = pB;
28064       pTail = pB;
28065       pB = pB->pDirty;
28066     }
28067   }
28068   if( pA ){
28069     pTail->pDirty = pA;
28070   }else if( pB ){
28071     pTail->pDirty = pB;
28072   }else{
28073     pTail->pDirty = 0;
28074   }
28075   return result.pDirty;
28076 }
28077
28078 /*
28079 ** Sort the list of pages in accending order by pgno.  Pages are
28080 ** connected by pDirty pointers.  The pPrevDirty pointers are
28081 ** corrupted by this sort.
28082 */
28083 #define N_SORT_BUCKET_ALLOC 25
28084 #define N_SORT_BUCKET       25
28085 #ifdef SQLITE_TEST
28086   int sqlite3_pager_n_sort_bucket = 0;
28087   #undef N_SORT_BUCKET
28088   #define N_SORT_BUCKET \
28089    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
28090 #endif
28091 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
28092   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
28093   int i;
28094   memset(a, 0, sizeof(a));
28095   while( pIn ){
28096     p = pIn;
28097     pIn = p->pDirty;
28098     p->pDirty = 0;
28099     for(i=0; i<N_SORT_BUCKET-1; i++){
28100       if( a[i]==0 ){
28101         a[i] = p;
28102         break;
28103       }else{
28104         p = pcacheMergeDirtyList(a[i], p);
28105         a[i] = 0;
28106       }
28107     }
28108     if( i==N_SORT_BUCKET-1 ){
28109       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
28110       ** elements in the input list. This is possible, but impractical.
28111       ** Testing this line is the point of global variable
28112       ** sqlite3_pager_n_sort_bucket.
28113       */
28114       a[i] = pcacheMergeDirtyList(a[i], p);
28115     }
28116   }
28117   p = a[0];
28118   for(i=1; i<N_SORT_BUCKET; i++){
28119     p = pcacheMergeDirtyList(p, a[i]);
28120   }
28121   return p;
28122 }
28123
28124 /*
28125 ** Return a list of all dirty pages in the cache, sorted by page number.
28126 */
28127 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
28128   PgHdr *p;
28129   for(p=pCache->pDirty; p; p=p->pNext){
28130     p->pDirty = p->pNext;
28131   }
28132   return pcacheSortDirtyList(pCache->pDirty);
28133 }
28134
28135 /* 
28136 ** Return the total number of outstanding page references.
28137 */
28138 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
28139   return pCache->nRef;
28140 }
28141
28142 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
28143   return p->nRef;
28144 }
28145
28146 /* 
28147 ** Return the total number of pages in the cache.
28148 */
28149 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
28150   assert( pCache->nPage>=0 );
28151   return pCache->nPage;
28152 }
28153
28154 #ifdef SQLITE_CHECK_PAGES
28155 /*
28156 ** This function is used by the pager.c module to iterate through all 
28157 ** pages in the cache. At present, this is only required if the
28158 ** SQLITE_CHECK_PAGES macro (used for debugging) is specified.
28159 */
28160 SQLITE_PRIVATE void sqlite3PcacheIterate(PCache *pCache, void (*xIter)(PgHdr *)){
28161   PgHdr *p;
28162   for(p=pCache->pClean; p; p=p->pNext){
28163     xIter(p);
28164   }
28165   for(p=pCache->pDirty; p; p=p->pNext){
28166     xIter(p);
28167   }
28168 }
28169 #endif
28170
28171 /* 
28172 ** Set flags on all pages in the page cache 
28173 */
28174 SQLITE_PRIVATE void sqlite3PcacheClearFlags(PCache *pCache, int mask){
28175   PgHdr *p;
28176
28177   /* Obtain the global mutex before modifying any PgHdr.flags variables 
28178   ** or traversing the LRU list.
28179   */ 
28180   pcacheEnterMutex();
28181
28182   mask = ~mask;
28183   for(p=pCache->pDirty; p; p=p->pNext){
28184     p->flags &= mask;
28185   }
28186   for(p=pCache->pClean; p; p=p->pNext){
28187     p->flags &= mask;
28188   }
28189
28190   if( 0==(mask&PGHDR_NEED_SYNC) ){
28191     pCache->pSynced = pCache->pDirtyTail;
28192     assert( !pCache->pSynced || (pCache->pSynced->flags&PGHDR_NEED_SYNC)==0 );
28193   }
28194
28195   pcacheExitMutex();
28196 }
28197
28198 /*
28199 ** Set the suggested cache-size value.
28200 */
28201 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
28202   return pCache->nMax;
28203 }
28204
28205 /*
28206 ** Set the suggested cache-size value.
28207 */
28208 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
28209   if( mxPage<10 ){
28210     mxPage = 10;
28211   }
28212   if( pCache->bPurgeable ){
28213     pcacheEnterMutex();
28214     pcache_g.nMaxPage -= pCache->nMax;
28215     pcache_g.nMaxPage += mxPage;
28216     pcacheEnforceMaxPage();
28217     pcacheExitMutex();
28218   }
28219   pCache->nMax = mxPage;
28220 }
28221
28222 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
28223 /*
28224 ** This function is called to free superfluous dynamically allocated memory
28225 ** held by the pager system. Memory in use by any SQLite pager allocated
28226 ** by the current thread may be sqlite3_free()ed.
28227 **
28228 ** nReq is the number of bytes of memory required. Once this much has
28229 ** been released, the function returns. The return value is the total number 
28230 ** of bytes of memory released.
28231 */
28232 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
28233   int nFree = 0;
28234   if( pcache_g.pStart==0 ){
28235     PgHdr *p;
28236     pcacheEnterMutex();
28237     while( (nReq<0 || nFree<nReq) && (p=pcacheRecyclePage()) ){
28238       nFree += pcachePageSize(p);
28239       pcachePageFree(p);
28240     }
28241     pcacheExitMutex();
28242   }
28243   return nFree;
28244 }
28245 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
28246
28247 #ifdef SQLITE_TEST
28248 SQLITE_PRIVATE void sqlite3PcacheStats(
28249   int *pnCurrent,
28250   int *pnMax,
28251   int *pnMin,
28252   int *pnRecyclable
28253 ){
28254   PgHdr *p;
28255   int nRecyclable = 0;
28256   for(p=pcache_g.pLruHead; p; p=p->pNextLru){
28257     nRecyclable++;
28258   }
28259
28260   *pnCurrent = pcache_g.nCurrentPage;
28261   *pnMax = pcache_g.nMaxPage;
28262   *pnMin = pcache_g.nMinPage;
28263   *pnRecyclable = nRecyclable;
28264 }
28265 #endif
28266
28267 /************** End of pcache.c **********************************************/
28268 /************** Begin file pager.c *******************************************/
28269 /*
28270 ** 2001 September 15
28271 **
28272 ** The author disclaims copyright to this source code.  In place of
28273 ** a legal notice, here is a blessing:
28274 **
28275 **    May you do good and not evil.
28276 **    May you find forgiveness for yourself and forgive others.
28277 **    May you share freely, never taking more than you give.
28278 **
28279 *************************************************************************
28280 ** This is the implementation of the page cache subsystem or "pager".
28281 ** 
28282 ** The pager is used to access a database disk file.  It implements
28283 ** atomic commit and rollback through the use of a journal file that
28284 ** is separate from the database file.  The pager also implements file
28285 ** locking to prevent two processes from writing the same database
28286 ** file simultaneously, or one process from reading the database while
28287 ** another is writing.
28288 **
28289 ** @(#) $Id: pager.c,v 1.497 2008/10/07 11:51:20 danielk1977 Exp $
28290 */
28291 #ifndef SQLITE_OMIT_DISKIO
28292
28293 /*
28294 ** Macros for troubleshooting.  Normally turned off
28295 */
28296 #if 0
28297 #define sqlite3DebugPrintf printf
28298 #define PAGERTRACE1(X)       sqlite3DebugPrintf(X)
28299 #define PAGERTRACE2(X,Y)     sqlite3DebugPrintf(X,Y)
28300 #define PAGERTRACE3(X,Y,Z)   sqlite3DebugPrintf(X,Y,Z)
28301 #define PAGERTRACE4(X,Y,Z,W) sqlite3DebugPrintf(X,Y,Z,W)
28302 #define PAGERTRACE5(X,Y,Z,W,V) sqlite3DebugPrintf(X,Y,Z,W,V)
28303 #else
28304 #define PAGERTRACE1(X)
28305 #define PAGERTRACE2(X,Y)
28306 #define PAGERTRACE3(X,Y,Z)
28307 #define PAGERTRACE4(X,Y,Z,W)
28308 #define PAGERTRACE5(X,Y,Z,W,V)
28309 #endif
28310
28311 /*
28312 ** The following two macros are used within the PAGERTRACEX() macros above
28313 ** to print out file-descriptors. 
28314 **
28315 ** PAGERID() takes a pointer to a Pager struct as its argument. The
28316 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
28317 ** struct as its argument.
28318 */
28319 #define PAGERID(p) ((int)(p->fd))
28320 #define FILEHANDLEID(fd) ((int)fd)
28321
28322 /*
28323 ** The page cache as a whole is always in one of the following
28324 ** states:
28325 **
28326 **   PAGER_UNLOCK        The page cache is not currently reading or 
28327 **                       writing the database file.  There is no
28328 **                       data held in memory.  This is the initial
28329 **                       state.
28330 **
28331 **   PAGER_SHARED        The page cache is reading the database.
28332 **                       Writing is not permitted.  There can be
28333 **                       multiple readers accessing the same database
28334 **                       file at the same time.
28335 **
28336 **   PAGER_RESERVED      This process has reserved the database for writing
28337 **                       but has not yet made any changes.  Only one process
28338 **                       at a time can reserve the database.  The original
28339 **                       database file has not been modified so other
28340 **                       processes may still be reading the on-disk
28341 **                       database file.
28342 **
28343 **   PAGER_EXCLUSIVE     The page cache is writing the database.
28344 **                       Access is exclusive.  No other processes or
28345 **                       threads can be reading or writing while one
28346 **                       process is writing.
28347 **
28348 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
28349 **                       after all dirty pages have been written to the
28350 **                       database file and the file has been synced to
28351 **                       disk. All that remains to do is to remove or
28352 **                       truncate the journal file and the transaction 
28353 **                       will be committed.
28354 **
28355 ** The page cache comes up in PAGER_UNLOCK.  The first time a
28356 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
28357 ** After all pages have been released using sqlite_page_unref(),
28358 ** the state transitions back to PAGER_UNLOCK.  The first time
28359 ** that sqlite3PagerWrite() is called, the state transitions to
28360 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
28361 ** called on an outstanding page which means that the pager must
28362 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
28363 ** PAGER_RESERVED means that there is an open rollback journal.
28364 ** The transition to PAGER_EXCLUSIVE occurs before any changes
28365 ** are made to the database file, though writes to the rollback
28366 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
28367 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
28368 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
28369 */
28370 #define PAGER_UNLOCK      0
28371 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
28372 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
28373 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
28374 #define PAGER_SYNCED      5
28375
28376 /*
28377 ** If the SQLITE_BUSY_RESERVED_LOCK macro is set to true at compile-time,
28378 ** then failed attempts to get a reserved lock will invoke the busy callback.
28379 ** This is off by default.  To see why, consider the following scenario:
28380 ** 
28381 ** Suppose thread A already has a shared lock and wants a reserved lock.
28382 ** Thread B already has a reserved lock and wants an exclusive lock.  If
28383 ** both threads are using their busy callbacks, it might be a long time
28384 ** be for one of the threads give up and allows the other to proceed.
28385 ** But if the thread trying to get the reserved lock gives up quickly
28386 ** (if it never invokes its busy callback) then the contention will be
28387 ** resolved quickly.
28388 */
28389 #ifndef SQLITE_BUSY_RESERVED_LOCK
28390 # define SQLITE_BUSY_RESERVED_LOCK 0
28391 #endif
28392
28393 /*
28394 ** This macro rounds values up so that if the value is an address it
28395 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
28396 */
28397 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
28398
28399 /*
28400 ** A macro used for invoking the codec if there is one
28401 */
28402 #ifdef SQLITE_HAS_CODEC
28403 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
28404 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
28405 #else
28406 # define CODEC1(P,D,N,X) /* NO-OP */
28407 # define CODEC2(P,D,N,X) ((char*)D)
28408 #endif
28409
28410 /*
28411 ** A open page cache is an instance of the following structure.
28412 **
28413 ** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
28414 ** or SQLITE_FULL. Once one of the first three errors occurs, it persists
28415 ** and is returned as the result of every major pager API call.  The
28416 ** SQLITE_FULL return code is slightly different. It persists only until the
28417 ** next successful rollback is performed on the pager cache. Also,
28418 ** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
28419 ** APIs, they may still be used successfully.
28420 */
28421 struct Pager {
28422   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
28423   u8 journalOpen;             /* True if journal file descriptors is valid */
28424   u8 journalStarted;          /* True if header of journal is synced */
28425   u8 useJournal;              /* Use a rollback journal on this file */
28426   u8 noReadlock;              /* Do not bother to obtain readlocks */
28427   u8 stmtOpen;                /* True if the statement subjournal is open */
28428   u8 stmtInUse;               /* True we are in a statement subtransaction */
28429   u8 stmtAutoopen;            /* Open stmt journal when main journal is opened*/
28430   u8 noSync;                  /* Do not sync the journal if true */
28431   u8 fullSync;                /* Do extra syncs of the journal for robustness */
28432   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
28433   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
28434   u8 tempFile;                /* zFilename is a temporary file */
28435   u8 readOnly;                /* True for a read-only database */
28436   u8 needSync;                /* True if an fsync() is needed on the journal */
28437   u8 dirtyCache;              /* True if cached pages have changed */
28438   u8 alwaysRollback;          /* Disable DontRollback() for all pages */
28439   u8 memDb;                   /* True to inhibit all file I/O */
28440   u8 setMaster;               /* True if a m-j name has been written to jrnl */
28441   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
28442   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
28443   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
28444   u8 dbModified;              /* True if there are any changes to the Db */
28445   u8 changeCountDone;         /* Set after incrementing the change-counter */
28446   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
28447   int errCode;                /* One of several kinds of errors */
28448   int dbSize;                 /* Number of pages in the file */
28449   int origDbSize;             /* dbSize before the current change */
28450   int stmtSize;               /* Size of database (in pages) at stmt_begin() */
28451   int nRec;                   /* Number of pages written to the journal */
28452   u32 cksumInit;              /* Quasi-random value added to every checksum */
28453   int stmtNRec;               /* Number of records in stmt subjournal */
28454   int nExtra;                 /* Add this many bytes to each in-memory page */
28455   int pageSize;               /* Number of bytes in a page */
28456   int nPage;                  /* Total number of in-memory pages */
28457   int mxPage;                 /* Maximum number of pages to hold in cache */
28458   Pgno mxPgno;                /* Maximum allowed size of the database */
28459   Bitvec *pInJournal;         /* One bit for each page in the database file */
28460   Bitvec *pInStmt;            /* One bit for each page in the database */
28461   Bitvec *pAlwaysRollback;    /* One bit for each page marked always-rollback */
28462   char *zFilename;            /* Name of the database file */
28463   char *zJournal;             /* Name of the journal file */
28464   char *zDirectory;           /* Directory hold database and journal files */
28465   sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
28466   sqlite3_file *stfd;         /* File descriptor for the statement subjournal*/
28467   BusyHandler *pBusyHandler;  /* Pointer to sqlite.busyHandler */
28468   i64 journalOff;             /* Current byte offset in the journal file */
28469   i64 journalHdr;             /* Byte offset to previous journal header */
28470   i64 stmtHdrOff;             /* First journal header written this statement */
28471   i64 stmtCksum;              /* cksumInit when statement was started */
28472   i64 stmtJSize;              /* Size of journal at stmt_begin() */
28473   int sectorSize;             /* Assumed sector size during rollback */
28474 #ifdef SQLITE_TEST
28475   int nHit, nMiss;            /* Cache hits and missing */
28476   int nRead, nWrite;          /* Database pages read/written */
28477 #endif
28478   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
28479 #ifdef SQLITE_HAS_CODEC
28480   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
28481   void *pCodecArg;            /* First argument to xCodec() */
28482 #endif
28483   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
28484   char dbFileVers[16];        /* Changes whenever database file changes */
28485   i64 journalSizeLimit;       /* Size limit for persistent journal files */
28486   PCache *pPCache;            /* Pointer to page cache object */
28487 };
28488
28489 /*
28490 ** The following global variables hold counters used for
28491 ** testing purposes only.  These variables do not exist in
28492 ** a non-testing build.  These variables are not thread-safe.
28493 */
28494 #ifdef SQLITE_TEST
28495 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
28496 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
28497 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
28498 # define PAGER_INCR(v)  v++
28499 #else
28500 # define PAGER_INCR(v)
28501 #endif
28502
28503
28504
28505 /*
28506 ** Journal files begin with the following magic string.  The data
28507 ** was obtained from /dev/random.  It is used only as a sanity check.
28508 **
28509 ** Since version 2.8.0, the journal format contains additional sanity
28510 ** checking information.  If the power fails while the journal is begin
28511 ** written, semi-random garbage data might appear in the journal
28512 ** file after power is restored.  If an attempt is then made
28513 ** to roll the journal back, the database could be corrupted.  The additional
28514 ** sanity checking data is an attempt to discover the garbage in the
28515 ** journal and ignore it.
28516 **
28517 ** The sanity checking information for the new journal format consists
28518 ** of a 32-bit checksum on each page of data.  The checksum covers both
28519 ** the page number and the pPager->pageSize bytes of data for the page.
28520 ** This cksum is initialized to a 32-bit random value that appears in the
28521 ** journal file right after the header.  The random initializer is important,
28522 ** because garbage data that appears at the end of a journal is likely
28523 ** data that was once in other files that have now been deleted.  If the
28524 ** garbage data came from an obsolete journal file, the checksums might
28525 ** be correct.  But by initializing the checksum to random value which
28526 ** is different for every journal, we minimize that risk.
28527 */
28528 static const unsigned char aJournalMagic[] = {
28529   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
28530 };
28531
28532 /*
28533 ** The size of the header and of each page in the journal is determined
28534 ** by the following macros.
28535 */
28536 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
28537
28538 /*
28539 ** The journal header size for this pager. In the future, this could be
28540 ** set to some value read from the disk controller. The important
28541 ** characteristic is that it is the same size as a disk sector.
28542 */
28543 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
28544
28545 /*
28546 ** The macro MEMDB is true if we are dealing with an in-memory database.
28547 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
28548 ** the value of MEMDB will be a constant and the compiler will optimize
28549 ** out code that would never execute.
28550 */
28551 #ifdef SQLITE_OMIT_MEMORYDB
28552 # define MEMDB 0
28553 #else
28554 # define MEMDB pPager->memDb
28555 #endif
28556
28557 /*
28558 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
28559 ** reserved for working around a windows/posix incompatibility). It is
28560 ** used in the journal to signify that the remainder of the journal file 
28561 ** is devoted to storing a master journal name - there are no more pages to
28562 ** roll back. See comments for function writeMasterJournal() for details.
28563 */
28564 /* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
28565 #define PAGER_MJ_PGNO(x) ((PENDING_BYTE/((x)->pageSize))+1)
28566
28567 /*
28568 ** The maximum legal page number is (2^31 - 1).
28569 */
28570 #define PAGER_MAX_PGNO 2147483647
28571
28572 /*
28573 ** Return true if page *pPg has already been written to the statement
28574 ** journal (or statement snapshot has been created, if *pPg is part
28575 ** of an in-memory database).
28576 */
28577 static int pageInStatement(PgHdr *pPg){
28578   Pager *pPager = pPg->pPager;
28579   if( MEMDB ){
28580     return pPg->apSave[1]!=0;
28581   }else{
28582     return sqlite3BitvecTest(pPager->pInStmt, pPg->pgno);
28583   }
28584 }
28585
28586 /*
28587 ** Read a 32-bit integer from the given file descriptor.  Store the integer
28588 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
28589 ** error code is something goes wrong.
28590 **
28591 ** All values are stored on disk as big-endian.
28592 */
28593 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
28594   unsigned char ac[4];
28595   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
28596   if( rc==SQLITE_OK ){
28597     *pRes = sqlite3Get4byte(ac);
28598   }
28599   return rc;
28600 }
28601
28602 /*
28603 ** Write a 32-bit integer into a string buffer in big-endian byte order.
28604 */
28605 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
28606
28607 /*
28608 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
28609 ** on success or an error code is something goes wrong.
28610 */
28611 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
28612   char ac[4];
28613   put32bits(ac, val);
28614   return sqlite3OsWrite(fd, ac, 4, offset);
28615 }
28616
28617 /*
28618 ** If file pFd is open, call sqlite3OsUnlock() on it.
28619 */
28620 static int osUnlock(sqlite3_file *pFd, int eLock){
28621   if( !pFd->pMethods ){
28622     return SQLITE_OK;
28623   }
28624   return sqlite3OsUnlock(pFd, eLock);
28625 }
28626
28627 /*
28628 ** This function determines whether or not the atomic-write optimization
28629 ** can be used with this pager. The optimization can be used if:
28630 **
28631 **  (a) the value returned by OsDeviceCharacteristics() indicates that
28632 **      a database page may be written atomically, and
28633 **  (b) the value returned by OsSectorSize() is less than or equal
28634 **      to the page size.
28635 **
28636 ** If the optimization cannot be used, 0 is returned. If it can be used,
28637 ** then the value returned is the size of the journal file when it
28638 ** contains rollback data for exactly one page.
28639 */
28640 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
28641 static int jrnlBufferSize(Pager *pPager){
28642   int dc;           /* Device characteristics */
28643   int nSector;      /* Sector size */
28644   int szPage;        /* Page size */
28645   sqlite3_file *fd = pPager->fd;
28646
28647   if( fd->pMethods ){
28648     dc = sqlite3OsDeviceCharacteristics(fd);
28649     nSector = sqlite3OsSectorSize(fd);
28650     szPage = pPager->pageSize;
28651   }
28652
28653   assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
28654   assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
28655
28656   if( !fd->pMethods || 
28657        (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
28658     return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
28659   }
28660   return 0;
28661 }
28662 #endif
28663
28664 /*
28665 ** This function should be called when an error occurs within the pager
28666 ** code. The first argument is a pointer to the pager structure, the
28667 ** second the error-code about to be returned by a pager API function. 
28668 ** The value returned is a copy of the second argument to this function. 
28669 **
28670 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
28671 ** the error becomes persistent. Until the persisten error is cleared,
28672 ** subsequent API calls on this Pager will immediately return the same 
28673 ** error code.
28674 **
28675 ** A persistent error indicates that the contents of the pager-cache 
28676 ** cannot be trusted. This state can be cleared by completely discarding 
28677 ** the contents of the pager-cache. If a transaction was active when
28678 ** the persistent error occured, then the rollback journal may need
28679 ** to be replayed.
28680 */
28681 static void pager_unlock(Pager *pPager);
28682 static int pager_error(Pager *pPager, int rc){
28683   int rc2 = rc & 0xff;
28684   assert(
28685        pPager->errCode==SQLITE_FULL ||
28686        pPager->errCode==SQLITE_OK ||
28687        (pPager->errCode & 0xff)==SQLITE_IOERR
28688   );
28689   if(
28690     rc2==SQLITE_FULL ||
28691     rc2==SQLITE_IOERR ||
28692     rc2==SQLITE_CORRUPT
28693   ){
28694     pPager->errCode = rc;
28695     if( pPager->state==PAGER_UNLOCK 
28696      && sqlite3PcacheRefCount(pPager->pPCache)==0 
28697     ){
28698       /* If the pager is already unlocked, call pager_unlock() now to
28699       ** clear the error state and ensure that the pager-cache is 
28700       ** completely empty.
28701       */
28702       pager_unlock(pPager);
28703     }
28704   }
28705   return rc;
28706 }
28707
28708 /*
28709 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
28710 ** on the cache using a hash function.  This is used for testing
28711 ** and debugging only.
28712 */
28713 #ifdef SQLITE_CHECK_PAGES
28714 /*
28715 ** Return a 32-bit hash of the page data for pPage.
28716 */
28717 static u32 pager_datahash(int nByte, unsigned char *pData){
28718   u32 hash = 0;
28719   int i;
28720   for(i=0; i<nByte; i++){
28721     hash = (hash*1039) + pData[i];
28722   }
28723   return hash;
28724 }
28725 static u32 pager_pagehash(PgHdr *pPage){
28726   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
28727 }
28728 static u32 pager_set_pagehash(PgHdr *pPage){
28729   pPage->pageHash = pager_pagehash(pPage);
28730 }
28731
28732 /*
28733 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
28734 ** is defined, and NDEBUG is not defined, an assert() statement checks
28735 ** that the page is either dirty or still matches the calculated page-hash.
28736 */
28737 #define CHECK_PAGE(x) checkPage(x)
28738 static void checkPage(PgHdr *pPg){
28739   Pager *pPager = pPg->pPager;
28740   assert( !pPg->pageHash || pPager->errCode || MEMDB 
28741       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
28742 }
28743
28744 #else
28745 #define pager_datahash(X,Y)  0
28746 #define pager_pagehash(X)  0
28747 #define CHECK_PAGE(x)
28748 #endif  /* SQLITE_CHECK_PAGES */
28749
28750 /*
28751 ** When this is called the journal file for pager pPager must be open.
28752 ** The master journal file name is read from the end of the file and 
28753 ** written into memory supplied by the caller. 
28754 **
28755 ** zMaster must point to a buffer of at least nMaster bytes allocated by
28756 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
28757 ** enough space to write the master journal name). If the master journal
28758 ** name in the journal is longer than nMaster bytes (including a
28759 ** nul-terminator), then this is handled as if no master journal name
28760 ** were present in the journal.
28761 **
28762 ** If no master journal file name is present zMaster[0] is set to 0 and
28763 ** SQLITE_OK returned.
28764 */
28765 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, int nMaster){
28766   int rc;
28767   u32 len;
28768   i64 szJ;
28769   u32 cksum;
28770   u32 u;                   /* Unsigned loop counter */
28771   unsigned char aMagic[8]; /* A buffer to hold the magic header */
28772
28773   zMaster[0] = '\0';
28774
28775   rc = sqlite3OsFileSize(pJrnl, &szJ);
28776   if( rc!=SQLITE_OK || szJ<16 ) return rc;
28777
28778   rc = read32bits(pJrnl, szJ-16, &len);
28779   if( rc!=SQLITE_OK ) return rc;
28780
28781   if( len>=nMaster ){
28782     return SQLITE_OK;
28783   }
28784
28785   rc = read32bits(pJrnl, szJ-12, &cksum);
28786   if( rc!=SQLITE_OK ) return rc;
28787
28788   rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
28789   if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;
28790
28791   rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
28792   if( rc!=SQLITE_OK ){
28793     return rc;
28794   }
28795   zMaster[len] = '\0';
28796
28797   /* See if the checksum matches the master journal name */
28798   for(u=0; u<len; u++){
28799     cksum -= zMaster[u];
28800    }
28801   if( cksum ){
28802     /* If the checksum doesn't add up, then one or more of the disk sectors
28803     ** containing the master journal filename is corrupted. This means
28804     ** definitely roll back, so just return SQLITE_OK and report a (nul)
28805     ** master-journal filename.
28806     */
28807     zMaster[0] = '\0';
28808   }
28809    
28810   return SQLITE_OK;
28811 }
28812
28813 /*
28814 ** Seek the journal file descriptor to the next sector boundary where a
28815 ** journal header may be read or written. Pager.journalOff is updated with
28816 ** the new seek offset.
28817 **
28818 ** i.e for a sector size of 512:
28819 **
28820 ** Input Offset              Output Offset
28821 ** ---------------------------------------
28822 ** 0                         0
28823 ** 512                       512
28824 ** 100                       512
28825 ** 2000                      2048
28826 ** 
28827 */
28828 static void seekJournalHdr(Pager *pPager){
28829   i64 offset = 0;
28830   i64 c = pPager->journalOff;
28831   if( c ){
28832     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
28833   }
28834   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
28835   assert( offset>=c );
28836   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
28837   pPager->journalOff = offset;
28838 }
28839
28840 /*
28841 ** Write zeros over the header of the journal file.  This has the
28842 ** effect of invalidating the journal file and committing the
28843 ** transaction.
28844 */
28845 static int zeroJournalHdr(Pager *pPager, int doTruncate){
28846   int rc = SQLITE_OK;
28847   static const char zeroHdr[28] = {0};
28848
28849   if( pPager->journalOff ){
28850     i64 iLimit = pPager->journalSizeLimit;
28851
28852     IOTRACE(("JZEROHDR %p\n", pPager))
28853     if( doTruncate || iLimit==0 ){
28854       rc = sqlite3OsTruncate(pPager->jfd, 0);
28855     }else{
28856       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
28857     }
28858     if( rc==SQLITE_OK && !pPager->noSync ){
28859       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
28860     }
28861
28862     /* At this point the transaction is committed but the write lock 
28863     ** is still held on the file. If there is a size limit configured for 
28864     ** the persistent journal and the journal file currently consumes more
28865     ** space than that limit allows for, truncate it now. There is no need
28866     ** to sync the file following this operation.
28867     */
28868     if( rc==SQLITE_OK && iLimit>0 ){
28869       i64 sz;
28870       rc = sqlite3OsFileSize(pPager->jfd, &sz);
28871       if( rc==SQLITE_OK && sz>iLimit ){
28872         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
28873       }
28874     }
28875   }
28876   return rc;
28877 }
28878
28879 /*
28880 ** The journal file must be open when this routine is called. A journal
28881 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
28882 ** current location.
28883 **
28884 ** The format for the journal header is as follows:
28885 ** - 8 bytes: Magic identifying journal format.
28886 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
28887 ** - 4 bytes: Random number used for page hash.
28888 ** - 4 bytes: Initial database page count.
28889 ** - 4 bytes: Sector size used by the process that wrote this journal.
28890 ** - 4 bytes: Database page size.
28891 ** 
28892 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
28893 */
28894 static int writeJournalHdr(Pager *pPager){
28895   int rc = SQLITE_OK;
28896   char *zHeader = pPager->pTmpSpace;
28897   int nHeader = pPager->pageSize;
28898   int nWrite;
28899
28900   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
28901     nHeader = JOURNAL_HDR_SZ(pPager);
28902   }
28903
28904   if( pPager->stmtHdrOff==0 ){
28905     pPager->stmtHdrOff = pPager->journalOff;
28906   }
28907
28908   seekJournalHdr(pPager);
28909   pPager->journalHdr = pPager->journalOff;
28910
28911   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
28912
28913   /* 
28914   ** Write the nRec Field - the number of page records that follow this
28915   ** journal header. Normally, zero is written to this value at this time.
28916   ** After the records are added to the journal (and the journal synced, 
28917   ** if in full-sync mode), the zero is overwritten with the true number
28918   ** of records (see syncJournal()).
28919   **
28920   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
28921   ** reading the journal this value tells SQLite to assume that the
28922   ** rest of the journal file contains valid page records. This assumption
28923   ** is dangerous, as if a failure occured whilst writing to the journal
28924   ** file it may contain some garbage data. There are two scenarios
28925   ** where this risk can be ignored:
28926   **
28927   **   * When the pager is in no-sync mode. Corruption can follow a
28928   **     power failure in this case anyway.
28929   **
28930   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
28931   **     that garbage data is never appended to the journal file.
28932   */
28933   assert(pPager->fd->pMethods||pPager->noSync);
28934   if( (pPager->noSync) 
28935    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
28936   ){
28937     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
28938   }else{
28939     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
28940   }
28941
28942   /* The random check-hash initialiser */ 
28943   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
28944   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
28945   /* The initial database size */
28946   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbSize);
28947   /* The assumed sector size for this process */
28948   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
28949   if( pPager->journalHdr==0 ){
28950     /* The page size */
28951     put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
28952   }
28953
28954   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
28955     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
28956     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
28957     pPager->journalOff += nHeader;
28958   }
28959
28960   return rc;
28961 }
28962
28963 /*
28964 ** The journal file must be open when this is called. A journal header file
28965 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
28966 ** file. See comments above function writeJournalHdr() for a description of
28967 ** the journal header format.
28968 **
28969 ** If the header is read successfully, *nRec is set to the number of
28970 ** page records following this header and *dbSize is set to the size of the
28971 ** database before the transaction began, in pages. Also, pPager->cksumInit
28972 ** is set to the value read from the journal header. SQLITE_OK is returned
28973 ** in this case.
28974 **
28975 ** If the journal header file appears to be corrupted, SQLITE_DONE is
28976 ** returned and *nRec and *dbSize are not set.  If JOURNAL_HDR_SZ bytes
28977 ** cannot be read from the journal file an error code is returned.
28978 */
28979 static int readJournalHdr(
28980   Pager *pPager, 
28981   i64 journalSize,
28982   u32 *pNRec, 
28983   u32 *pDbSize
28984 ){
28985   int rc;
28986   unsigned char aMagic[8]; /* A buffer to hold the magic header */
28987   i64 jrnlOff;
28988   int iPageSize;
28989
28990   seekJournalHdr(pPager);
28991   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
28992     return SQLITE_DONE;
28993   }
28994   jrnlOff = pPager->journalOff;
28995
28996   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
28997   if( rc ) return rc;
28998   jrnlOff += sizeof(aMagic);
28999
29000   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
29001     return SQLITE_DONE;
29002   }
29003
29004   rc = read32bits(pPager->jfd, jrnlOff, pNRec);
29005   if( rc ) return rc;
29006
29007   rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);
29008   if( rc ) return rc;
29009
29010   rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
29011   if( rc ) return rc;
29012
29013   rc = read32bits(pPager->jfd, jrnlOff+16, (u32 *)&iPageSize);
29014   if( rc==SQLITE_OK 
29015    && iPageSize>=512 
29016    && iPageSize<=SQLITE_MAX_PAGE_SIZE 
29017    && ((iPageSize-1)&iPageSize)==0 
29018   ){
29019     u16 pagesize = iPageSize;
29020     rc = sqlite3PagerSetPagesize(pPager, &pagesize);
29021   }
29022   if( rc ) return rc;
29023
29024   /* Update the assumed sector-size to match the value used by 
29025   ** the process that created this journal. If this journal was
29026   ** created by a process other than this one, then this routine
29027   ** is being called from within pager_playback(). The local value
29028   ** of Pager.sectorSize is restored at the end of that routine.
29029   */
29030   rc = read32bits(pPager->jfd, jrnlOff+12, (u32 *)&pPager->sectorSize);
29031   if( rc ) return rc;
29032
29033   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
29034   return SQLITE_OK;
29035 }
29036
29037
29038 /*
29039 ** Write the supplied master journal name into the journal file for pager
29040 ** pPager at the current location. The master journal name must be the last
29041 ** thing written to a journal file. If the pager is in full-sync mode, the
29042 ** journal file descriptor is advanced to the next sector boundary before
29043 ** anything is written. The format is:
29044 **
29045 ** + 4 bytes: PAGER_MJ_PGNO.
29046 ** + N bytes: length of master journal name.
29047 ** + 4 bytes: N
29048 ** + 4 bytes: Master journal name checksum.
29049 ** + 8 bytes: aJournalMagic[].
29050 **
29051 ** The master journal page checksum is the sum of the bytes in the master
29052 ** journal name.
29053 **
29054 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
29055 ** this call is a no-op.
29056 */
29057 static int writeMasterJournal(Pager *pPager, const char *zMaster){
29058   int rc;
29059   int len; 
29060   int i; 
29061   i64 jrnlOff;
29062   i64 jrnlSize;
29063   u32 cksum = 0;
29064   char zBuf[sizeof(aJournalMagic)+2*4];
29065
29066   if( !zMaster || pPager->setMaster) return SQLITE_OK;
29067   pPager->setMaster = 1;
29068
29069   len = strlen(zMaster);
29070   for(i=0; i<len; i++){
29071     cksum += zMaster[i];
29072   }
29073
29074   /* If in full-sync mode, advance to the next disk sector before writing
29075   ** the master journal name. This is in case the previous page written to
29076   ** the journal has already been synced.
29077   */
29078   if( pPager->fullSync ){
29079     seekJournalHdr(pPager);
29080   }
29081   jrnlOff = pPager->journalOff;
29082   pPager->journalOff += (len+20);
29083
29084   rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
29085   if( rc!=SQLITE_OK ) return rc;
29086   jrnlOff += 4;
29087
29088   rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);
29089   if( rc!=SQLITE_OK ) return rc;
29090   jrnlOff += len;
29091
29092   put32bits(zBuf, len);
29093   put32bits(&zBuf[4], cksum);
29094   memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
29095   rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
29096   jrnlOff += 8+sizeof(aJournalMagic);
29097   pPager->needSync = !pPager->noSync;
29098
29099   /* If the pager is in peristent-journal mode, then the physical 
29100   ** journal-file may extend past the end of the master-journal name
29101   ** and 8 bytes of magic data just written to the file. This is 
29102   ** dangerous because the code to rollback a hot-journal file
29103   ** will not be able to find the master-journal name to determine 
29104   ** whether or not the journal is hot. 
29105   **
29106   ** Easiest thing to do in this scenario is to truncate the journal 
29107   ** file to the required size.
29108   */ 
29109   if( (rc==SQLITE_OK)
29110    && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
29111    && jrnlSize>jrnlOff
29112   ){
29113     rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
29114   }
29115   return rc;
29116 }
29117
29118 /*
29119 ** Find a page in the hash table given its page number.  Return
29120 ** a pointer to the page or NULL if not found.
29121 */
29122 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
29123   PgHdr *p;
29124   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
29125   return p;
29126 }
29127
29128 /*
29129 ** Clear the in-memory cache.  This routine
29130 ** sets the state of the pager back to what it was when it was first
29131 ** opened.  Any outstanding pages are invalidated and subsequent attempts
29132 ** to access those pages will likely result in a coredump.
29133 */
29134 static void pager_reset(Pager *pPager){
29135   if( pPager->errCode ) return;
29136   sqlite3PcacheClear(pPager->pPCache);
29137 }
29138
29139 /*
29140 ** Unlock the database file. 
29141 **
29142 ** If the pager is currently in error state, discard the contents of 
29143 ** the cache and reset the Pager structure internal state. If there is
29144 ** an open journal-file, then the next time a shared-lock is obtained
29145 ** on the pager file (by this or any other process), it will be
29146 ** treated as a hot-journal and rolled back.
29147 */
29148 static void pager_unlock(Pager *pPager){
29149   if( !pPager->exclusiveMode ){
29150     if( !MEMDB ){
29151       int rc = osUnlock(pPager->fd, NO_LOCK);
29152       if( rc ) pPager->errCode = rc;
29153       pPager->dbSize = -1;
29154       IOTRACE(("UNLOCK %p\n", pPager))
29155
29156       /* Always close the journal file when dropping the database lock.
29157       ** Otherwise, another connection with journal_mode=delete might
29158       ** delete the file out from under us.
29159       */
29160       if( pPager->journalOpen ){
29161         sqlite3OsClose(pPager->jfd);
29162         pPager->journalOpen = 0;
29163         sqlite3BitvecDestroy(pPager->pInJournal);
29164         pPager->pInJournal = 0;
29165         sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29166         pPager->pAlwaysRollback = 0;
29167       }
29168
29169       /* If Pager.errCode is set, the contents of the pager cache cannot be
29170       ** trusted. Now that the pager file is unlocked, the contents of the
29171       ** cache can be discarded and the error code safely cleared.
29172       */
29173       if( pPager->errCode ){
29174         if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;
29175         pager_reset(pPager);
29176         if( pPager->stmtOpen ){
29177           sqlite3OsClose(pPager->stfd);
29178           sqlite3BitvecDestroy(pPager->pInStmt);
29179           pPager->pInStmt = 0;
29180         }
29181         pPager->stmtOpen = 0;
29182         pPager->stmtInUse = 0;
29183         pPager->journalOff = 0;
29184         pPager->journalStarted = 0;
29185         pPager->stmtAutoopen = 0;
29186         pPager->origDbSize = 0;
29187       }
29188     }
29189
29190     if( !MEMDB || pPager->errCode==SQLITE_OK ){
29191       pPager->state = PAGER_UNLOCK;
29192       pPager->changeCountDone = 0;
29193     }
29194   }
29195 }
29196
29197 /*
29198 ** Execute a rollback if a transaction is active and unlock the 
29199 ** database file. If the pager has already entered the error state, 
29200 ** do not attempt the rollback.
29201 */
29202 static void pagerUnlockAndRollback(Pager *p){
29203   if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
29204     sqlite3BeginBenignMalloc();
29205     sqlite3PagerRollback(p);
29206     sqlite3EndBenignMalloc();
29207   }
29208   pager_unlock(p);
29209 }
29210
29211 /*
29212 ** This routine ends a transaction.  A transaction is ended by either
29213 ** a COMMIT or a ROLLBACK.
29214 **
29215 ** When this routine is called, the pager has the journal file open and
29216 ** a RESERVED or EXCLUSIVE lock on the database.  This routine will release
29217 ** the database lock and acquires a SHARED lock in its place if that is
29218 ** the appropriate thing to do.  Release locks usually is appropriate,
29219 ** unless we are in exclusive access mode or unless this is a 
29220 ** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.
29221 **
29222 ** The journal file is either deleted or truncated.
29223 **
29224 ** TODO: Consider keeping the journal file open for temporary databases.
29225 ** This might give a performance improvement on windows where opening
29226 ** a file is an expensive operation.
29227 */
29228 static int pager_end_transaction(Pager *pPager, int hasMaster){
29229   int rc = SQLITE_OK;
29230   int rc2 = SQLITE_OK;
29231   assert( !MEMDB );
29232   if( pPager->state<PAGER_RESERVED ){
29233     return SQLITE_OK;
29234   }
29235   sqlite3PagerStmtCommit(pPager);
29236   if( pPager->stmtOpen && !pPager->exclusiveMode ){
29237     sqlite3OsClose(pPager->stfd);
29238     pPager->stmtOpen = 0;
29239   }
29240   if( pPager->journalOpen ){
29241     if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
29242          && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
29243       pPager->journalOff = 0;
29244       pPager->journalStarted = 0;
29245     }else if( pPager->exclusiveMode 
29246      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
29247     ){
29248       rc = zeroJournalHdr(pPager, hasMaster);
29249       pager_error(pPager, rc);
29250       pPager->journalOff = 0;
29251       pPager->journalStarted = 0;
29252     }else{
29253       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
29254       sqlite3OsClose(pPager->jfd);
29255       pPager->journalOpen = 0;
29256       if( rc==SQLITE_OK && !pPager->tempFile ){
29257         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
29258       }
29259     }
29260     sqlite3BitvecDestroy(pPager->pInJournal);
29261     pPager->pInJournal = 0;
29262     sqlite3BitvecDestroy(pPager->pAlwaysRollback);
29263     pPager->pAlwaysRollback = 0;
29264     sqlite3PcacheCleanAll(pPager->pPCache);
29265 #ifdef SQLITE_CHECK_PAGES
29266     sqlite3PcacheIterate(pPager->pPCache, pager_set_pagehash);
29267 #endif
29268     sqlite3PcacheClearFlags(pPager->pPCache,
29269        PGHDR_IN_JOURNAL | PGHDR_NEED_SYNC
29270     );
29271     pPager->dirtyCache = 0;
29272     pPager->nRec = 0;
29273   }else{
29274     assert( pPager->pInJournal==0 );
29275   }
29276
29277   if( !pPager->exclusiveMode ){
29278     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
29279     pPager->state = PAGER_SHARED;
29280   }else if( pPager->state==PAGER_SYNCED ){
29281     pPager->state = PAGER_EXCLUSIVE;
29282   }
29283   pPager->origDbSize = 0;
29284   pPager->setMaster = 0;
29285   pPager->needSync = 0;
29286   /* lruListSetFirstSynced(pPager); */
29287   pPager->dbSize = -1;
29288   pPager->dbModified = 0;
29289
29290   return (rc==SQLITE_OK?rc2:rc);
29291 }
29292
29293 /*
29294 ** Compute and return a checksum for the page of data.
29295 **
29296 ** This is not a real checksum.  It is really just the sum of the 
29297 ** random initial value and the page number.  We experimented with
29298 ** a checksum of the entire data, but that was found to be too slow.
29299 **
29300 ** Note that the page number is stored at the beginning of data and
29301 ** the checksum is stored at the end.  This is important.  If journal
29302 ** corruption occurs due to a power failure, the most likely scenario
29303 ** is that one end or the other of the record will be changed.  It is
29304 ** much less likely that the two ends of the journal record will be
29305 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
29306 ** though fast and simple, catches the mostly likely kind of corruption.
29307 **
29308 ** FIX ME:  Consider adding every 200th (or so) byte of the data to the
29309 ** checksum.  That way if a single page spans 3 or more disk sectors and
29310 ** only the middle sector is corrupt, we will still have a reasonable
29311 ** chance of failing the checksum and thus detecting the problem.
29312 */
29313 static u32 pager_cksum(Pager *pPager, const u8 *aData){
29314   u32 cksum = pPager->cksumInit;
29315   int i = pPager->pageSize-200;
29316   while( i>0 ){
29317     cksum += aData[i];
29318     i -= 200;
29319   }
29320   return cksum;
29321 }
29322
29323 /* Forward declaration */
29324 static void makeClean(PgHdr*);
29325
29326 /*
29327 ** Read a single page from the journal file opened on file descriptor
29328 ** jfd.  Playback this one page.
29329 **
29330 ** The isMainJrnl flag is true if this is the main rollback journal and
29331 ** false for the statement journal.  The main rollback journal uses
29332 ** checksums - the statement journal does not.
29333 */
29334 static int pager_playback_one_page(
29335   Pager *pPager,       /* The pager being played back */
29336   sqlite3_file *jfd,   /* The file that is the journal being rolled back */
29337   i64 offset,          /* Offset of the page within the journal */
29338   int isMainJrnl       /* True for main rollback journal. False for Stmt jrnl */
29339 ){
29340   int rc;
29341   PgHdr *pPg;                   /* An existing page in the cache */
29342   Pgno pgno;                    /* The page number of a page in journal */
29343   u32 cksum;                    /* Checksum used for sanity checking */
29344   u8 *aData = (u8 *)pPager->pTmpSpace;   /* Temp storage for a page */
29345
29346   /* isMainJrnl should be true for the main journal and false for
29347   ** statement journals.  Verify that this is always the case
29348   */
29349   assert( jfd == (isMainJrnl ? pPager->jfd : pPager->stfd) );
29350   assert( aData );
29351
29352   rc = read32bits(jfd, offset, &pgno);
29353   if( rc!=SQLITE_OK ) return rc;
29354   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, offset+4);
29355   if( rc!=SQLITE_OK ) return rc;
29356   pPager->journalOff += pPager->pageSize + 4;
29357
29358   /* Sanity checking on the page.  This is more important that I originally
29359   ** thought.  If a power failure occurs while the journal is being written,
29360   ** it could cause invalid data to be written into the journal.  We need to
29361   ** detect this invalid data (with high probability) and ignore it.
29362   */
29363   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
29364     return SQLITE_DONE;
29365   }
29366   if( pgno>(unsigned)pPager->dbSize ){
29367     return SQLITE_OK;
29368   }
29369   if( isMainJrnl ){
29370     rc = read32bits(jfd, offset+pPager->pageSize+4, &cksum);
29371     if( rc ) return rc;
29372     pPager->journalOff += 4;
29373     if( pager_cksum(pPager, aData)!=cksum ){
29374       return SQLITE_DONE;
29375     }
29376   }
29377
29378   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
29379
29380   /* If the pager is in RESERVED state, then there must be a copy of this
29381   ** page in the pager cache. In this case just update the pager cache,
29382   ** not the database file. The page is left marked dirty in this case.
29383   **
29384   ** An exception to the above rule: If the database is in no-sync mode
29385   ** and a page is moved during an incremental vacuum then the page may
29386   ** not be in the pager cache. Later: if a malloc() or IO error occurs
29387   ** during a Movepage() call, then the page may not be in the cache
29388   ** either. So the condition described in the above paragraph is not
29389   ** assert()able.
29390   **
29391   ** If in EXCLUSIVE state, then we update the pager cache if it exists
29392   ** and the main file. The page is then marked not dirty.
29393   **
29394   ** Ticket #1171:  The statement journal might contain page content that is
29395   ** different from the page content at the start of the transaction.
29396   ** This occurs when a page is changed prior to the start of a statement
29397   ** then changed again within the statement.  When rolling back such a
29398   ** statement we must not write to the original database unless we know
29399   ** for certain that original page contents are synced into the main rollback
29400   ** journal.  Otherwise, a power loss might leave modified data in the
29401   ** database file without an entry in the rollback journal that can
29402   ** restore the database to its original form.  Two conditions must be
29403   ** met before writing to the database files. (1) the database must be
29404   ** locked.  (2) we know that the original page content is fully synced
29405   ** in the main journal either because the page is not in cache or else
29406   ** the page is marked as needSync==0.
29407   **
29408   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
29409   ** is possible to fail a statement on a database that does not yet exist.
29410   ** Do not attempt to write if database file has never been opened.
29411   */
29412   pPg = pager_lookup(pPager, pgno);
29413   PAGERTRACE4("PLAYBACK %d page %d hash(%08x)\n",
29414                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData));
29415   if( (pPager->state>=PAGER_EXCLUSIVE)
29416    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
29417    && (pPager->fd->pMethods)
29418   ){
29419     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
29420     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
29421   }
29422   if( pPg ){
29423     /* No page should ever be explicitly rolled back that is in use, except
29424     ** for page 1 which is held in use in order to keep the lock on the
29425     ** database active. However such a page may be rolled back as a result
29426     ** of an internal error resulting in an automatic call to
29427     ** sqlite3PagerRollback().
29428     */
29429     void *pData;
29430     pData = pPg->pData;
29431     memcpy(pData, aData, pPager->pageSize);
29432     if( pPager->xReiniter ){
29433       pPager->xReiniter(pPg);
29434     }
29435     if( isMainJrnl ) makeClean(pPg);
29436 #ifdef SQLITE_CHECK_PAGES
29437     pPg->pageHash = pager_pagehash(pPg);
29438 #endif
29439     /* If this was page 1, then restore the value of Pager.dbFileVers.
29440     ** Do this before any decoding. */
29441     if( pgno==1 ){
29442       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
29443     }
29444
29445     /* Decode the page just read from disk */
29446     CODEC1(pPager, pData, pPg->pgno, 3);
29447     sqlite3PcacheRelease(pPg);
29448   }
29449   return rc;
29450 }
29451
29452 /*
29453 ** Parameter zMaster is the name of a master journal file. A single journal
29454 ** file that referred to the master journal file has just been rolled back.
29455 ** This routine checks if it is possible to delete the master journal file,
29456 ** and does so if it is.
29457 **
29458 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
29459 ** available for use within this function.
29460 **
29461 **
29462 ** The master journal file contains the names of all child journals.
29463 ** To tell if a master journal can be deleted, check to each of the
29464 ** children.  If all children are either missing or do not refer to
29465 ** a different master journal, then this master journal can be deleted.
29466 */
29467 static int pager_delmaster(Pager *pPager, const char *zMaster){
29468   sqlite3_vfs *pVfs = pPager->pVfs;
29469   int rc;
29470   int master_open = 0;
29471   sqlite3_file *pMaster;
29472   sqlite3_file *pJournal;
29473   char *zMasterJournal = 0; /* Contents of master journal file */
29474   i64 nMasterJournal;       /* Size of master journal file */
29475
29476   /* Open the master journal file exclusively in case some other process
29477   ** is running this routine also. Not that it makes too much difference.
29478   */
29479   pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
29480   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
29481   if( !pMaster ){
29482     rc = SQLITE_NOMEM;
29483   }else{
29484     int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
29485     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
29486   }
29487   if( rc!=SQLITE_OK ) goto delmaster_out;
29488   master_open = 1;
29489
29490   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
29491   if( rc!=SQLITE_OK ) goto delmaster_out;
29492
29493   if( nMasterJournal>0 ){
29494     char *zJournal;
29495     char *zMasterPtr = 0;
29496     int nMasterPtr = pPager->pVfs->mxPathname+1;
29497
29498     /* Load the entire master journal file into space obtained from
29499     ** sqlite3_malloc() and pointed to by zMasterJournal. 
29500     */
29501     zMasterJournal = (char *)sqlite3Malloc(nMasterJournal + nMasterPtr);
29502     if( !zMasterJournal ){
29503       rc = SQLITE_NOMEM;
29504       goto delmaster_out;
29505     }
29506     zMasterPtr = &zMasterJournal[nMasterJournal];
29507     rc = sqlite3OsRead(pMaster, zMasterJournal, nMasterJournal, 0);
29508     if( rc!=SQLITE_OK ) goto delmaster_out;
29509
29510     zJournal = zMasterJournal;
29511     while( (zJournal-zMasterJournal)<nMasterJournal ){
29512       int exists;
29513       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
29514       if( rc!=SQLITE_OK ){
29515         goto delmaster_out;
29516       }
29517       if( exists ){
29518         /* One of the journals pointed to by the master journal exists.
29519         ** Open it and check if it points at the master journal. If
29520         ** so, return without deleting the master journal file.
29521         */
29522         int c;
29523         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
29524         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
29525         if( rc!=SQLITE_OK ){
29526           goto delmaster_out;
29527         }
29528
29529         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
29530         sqlite3OsClose(pJournal);
29531         if( rc!=SQLITE_OK ){
29532           goto delmaster_out;
29533         }
29534
29535         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
29536         if( c ){
29537           /* We have a match. Do not delete the master journal file. */
29538           goto delmaster_out;
29539         }
29540       }
29541       zJournal += (strlen(zJournal)+1);
29542     }
29543   }
29544   
29545   rc = sqlite3OsDelete(pVfs, zMaster, 0);
29546
29547 delmaster_out:
29548   if( zMasterJournal ){
29549     sqlite3_free(zMasterJournal);
29550   }  
29551   if( master_open ){
29552     sqlite3OsClose(pMaster);
29553   }
29554   sqlite3_free(pMaster);
29555   return rc;
29556 }
29557
29558
29559 static void pager_truncate_cache(Pager *pPager);
29560
29561 /*
29562 ** Truncate the main file of the given pager to the number of pages
29563 ** indicated. Also truncate the cached representation of the file.
29564 **
29565 ** Might might be the case that the file on disk is smaller than nPage.
29566 ** This can happen, for example, if we are in the middle of a transaction
29567 ** which has extended the file size and the new pages are still all held
29568 ** in cache, then an INSERT or UPDATE does a statement rollback.  Some
29569 ** operating system implementations can get confused if you try to
29570 ** truncate a file to some size that is larger than it currently is,
29571 ** so detect this case and write a single zero byte to the end of the new
29572 ** file instead.
29573 */
29574 static int pager_truncate(Pager *pPager, int nPage){
29575   int rc = SQLITE_OK;
29576   if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
29577     i64 currentSize, newSize;
29578     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
29579     newSize = pPager->pageSize*(i64)nPage;
29580     if( rc==SQLITE_OK && currentSize!=newSize ){
29581       if( currentSize>newSize ){
29582         rc = sqlite3OsTruncate(pPager->fd, newSize);
29583       }else{
29584         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
29585       }
29586     }
29587   }
29588   if( rc==SQLITE_OK ){
29589     pPager->dbSize = nPage;
29590     pager_truncate_cache(pPager);
29591   }
29592   return rc;
29593 }
29594
29595 /*
29596 ** Set the sectorSize for the given pager.
29597 **
29598 ** The sector size is at least as big as the sector size reported
29599 ** by sqlite3OsSectorSize().  The minimum sector size is 512.
29600 */
29601 static void setSectorSize(Pager *pPager){
29602   assert(pPager->fd->pMethods||pPager->tempFile);
29603   if( !pPager->tempFile ){
29604     /* Sector size doesn't matter for temporary files. Also, the file
29605     ** may not have been opened yet, in whcih case the OsSectorSize()
29606     ** call will segfault.
29607     */
29608     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
29609   }
29610   if( pPager->sectorSize<512 ){
29611     pPager->sectorSize = 512;
29612   }
29613 }
29614
29615 /*
29616 ** Playback the journal and thus restore the database file to
29617 ** the state it was in before we started making changes.  
29618 **
29619 ** The journal file format is as follows: 
29620 **
29621 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
29622 **  (2)  4 byte big-endian integer which is the number of valid page records
29623 **       in the journal.  If this value is 0xffffffff, then compute the
29624 **       number of page records from the journal size.
29625 **  (3)  4 byte big-endian integer which is the initial value for the 
29626 **       sanity checksum.
29627 **  (4)  4 byte integer which is the number of pages to truncate the
29628 **       database to during a rollback.
29629 **  (5)  4 byte big-endian integer which is the sector size.  The header
29630 **       is this many bytes in size.
29631 **  (6)  4 byte big-endian integer which is the page case.
29632 **  (7)  4 byte integer which is the number of bytes in the master journal
29633 **       name.  The value may be zero (indicate that there is no master
29634 **       journal.)
29635 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
29636 **       and might be shorter than the value read from (5).  If the first byte
29637 **       of the name is \000 then there is no master journal.  The master
29638 **       journal name is stored in UTF-8.
29639 **  (9)  Zero or more pages instances, each as follows:
29640 **        +  4 byte page number.
29641 **        +  pPager->pageSize bytes of data.
29642 **        +  4 byte checksum
29643 **
29644 ** When we speak of the journal header, we mean the first 8 items above.
29645 ** Each entry in the journal is an instance of the 9th item.
29646 **
29647 ** Call the value from the second bullet "nRec".  nRec is the number of
29648 ** valid page entries in the journal.  In most cases, you can compute the
29649 ** value of nRec from the size of the journal file.  But if a power
29650 ** failure occurred while the journal was being written, it could be the
29651 ** case that the size of the journal file had already been increased but
29652 ** the extra entries had not yet made it safely to disk.  In such a case,
29653 ** the value of nRec computed from the file size would be too large.  For
29654 ** that reason, we always use the nRec value in the header.
29655 **
29656 ** If the nRec value is 0xffffffff it means that nRec should be computed
29657 ** from the file size.  This value is used when the user selects the
29658 ** no-sync option for the journal.  A power failure could lead to corruption
29659 ** in this case.  But for things like temporary table (which will be
29660 ** deleted when the power is restored) we don't care.  
29661 **
29662 ** If the file opened as the journal file is not a well-formed
29663 ** journal file then all pages up to the first corrupted page are rolled
29664 ** back (or no pages if the journal header is corrupted). The journal file
29665 ** is then deleted and SQLITE_OK returned, just as if no corruption had
29666 ** been encountered.
29667 **
29668 ** If an I/O or malloc() error occurs, the journal-file is not deleted
29669 ** and an error code is returned.
29670 */
29671 static int pager_playback(Pager *pPager, int isHot){
29672   sqlite3_vfs *pVfs = pPager->pVfs;
29673   i64 szJ;                 /* Size of the journal file in bytes */
29674   u32 nRec;                /* Number of Records in the journal */
29675   u32 u;                   /* Unsigned loop counter */
29676   Pgno mxPg = 0;           /* Size of the original file in pages */
29677   int rc;                  /* Result code of a subroutine */
29678   int res = 1;             /* Value returned by sqlite3OsAccess() */
29679   char *zMaster = 0;       /* Name of master journal file if any */
29680
29681   /* Figure out how many records are in the journal.  Abort early if
29682   ** the journal is empty.
29683   */
29684   assert( pPager->journalOpen );
29685   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
29686   if( rc!=SQLITE_OK || szJ==0 ){
29687     goto end_playback;
29688   }
29689
29690   /* Read the master journal name from the journal, if it is present.
29691   ** If a master journal file name is specified, but the file is not
29692   ** present on disk, then the journal is not hot and does not need to be
29693   ** played back.
29694   */
29695   zMaster = pPager->pTmpSpace;
29696   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
29697   if( rc==SQLITE_OK && zMaster[0] ){
29698     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
29699   }
29700   zMaster = 0;
29701   if( rc!=SQLITE_OK || !res ){
29702     goto end_playback;
29703   }
29704   pPager->journalOff = 0;
29705
29706   /* This loop terminates either when the readJournalHdr() call returns
29707   ** SQLITE_DONE or an IO error occurs. */
29708   while( 1 ){
29709
29710     /* Read the next journal header from the journal file.  If there are
29711     ** not enough bytes left in the journal file for a complete header, or
29712     ** it is corrupted, then a process must of failed while writing it.
29713     ** This indicates nothing more needs to be rolled back.
29714     */
29715     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
29716     if( rc!=SQLITE_OK ){ 
29717       if( rc==SQLITE_DONE ){
29718         rc = SQLITE_OK;
29719       }
29720       goto end_playback;
29721     }
29722
29723     /* If nRec is 0xffffffff, then this journal was created by a process
29724     ** working in no-sync mode. This means that the rest of the journal
29725     ** file consists of pages, there are no more journal headers. Compute
29726     ** the value of nRec based on this assumption.
29727     */
29728     if( nRec==0xffffffff ){
29729       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
29730       nRec = (szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager);
29731     }
29732
29733     /* If nRec is 0 and this rollback is of a transaction created by this
29734     ** process and if this is the final header in the journal, then it means
29735     ** that this part of the journal was being filled but has not yet been
29736     ** synced to disk.  Compute the number of pages based on the remaining
29737     ** size of the file.
29738     **
29739     ** The third term of the test was added to fix ticket #2565.
29740     */
29741     if( nRec==0 && !isHot &&
29742         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
29743       nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager);
29744     }
29745
29746     /* If this is the first header read from the journal, truncate the
29747     ** database file back to its original size.
29748     */
29749     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
29750       rc = pager_truncate(pPager, mxPg);
29751       if( rc!=SQLITE_OK ){
29752         goto end_playback;
29753       }
29754     }
29755
29756     /* Copy original pages out of the journal and back into the database file.
29757     */
29758     for(u=0; u<nRec; u++){
29759       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29760       if( rc!=SQLITE_OK ){
29761         if( rc==SQLITE_DONE ){
29762           rc = SQLITE_OK;
29763           pPager->journalOff = szJ;
29764           break;
29765         }else{
29766           /* If we are unable to rollback, then the database is probably
29767           ** going to end up being corrupt.  It is corrupt to us, anyhow.
29768           ** Perhaps the next process to come along can fix it....
29769           */
29770           rc = SQLITE_CORRUPT_BKPT;
29771           goto end_playback;
29772         }
29773       }
29774     }
29775   }
29776   /*NOTREACHED*/
29777   assert( 0 );
29778
29779 end_playback:
29780   if( rc==SQLITE_OK ){
29781     zMaster = pPager->pTmpSpace;
29782     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
29783   }
29784   if( rc==SQLITE_OK ){
29785     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
29786   }
29787   if( rc==SQLITE_OK && zMaster[0] && res ){
29788     /* If there was a master journal and this routine will return success,
29789     ** see if it is possible to delete the master journal.
29790     */
29791     rc = pager_delmaster(pPager, zMaster);
29792   }
29793
29794   /* The Pager.sectorSize variable may have been updated while rolling
29795   ** back a journal created by a process with a different sector size
29796   ** value. Reset it to the correct value for this process.
29797   */
29798   setSectorSize(pPager);
29799   return rc;
29800 }
29801
29802 /*
29803 ** Playback the statement journal.
29804 **
29805 ** This is similar to playing back the transaction journal but with
29806 ** a few extra twists.
29807 **
29808 **    (1)  The number of pages in the database file at the start of
29809 **         the statement is stored in pPager->stmtSize, not in the
29810 **         journal file itself.
29811 **
29812 **    (2)  In addition to playing back the statement journal, also
29813 **         playback all pages of the transaction journal beginning
29814 **         at offset pPager->stmtJSize.
29815 */
29816 static int pager_stmt_playback(Pager *pPager){
29817   i64 szJ;                 /* Size of the full journal */
29818   i64 hdrOff;
29819   int nRec;                /* Number of Records */
29820   int i;                   /* Loop counter */
29821   int rc;
29822
29823   szJ = pPager->journalOff;
29824
29825   /* Set hdrOff to be the offset just after the end of the last journal
29826   ** page written before the first journal-header for this statement
29827   ** transaction was written, or the end of the file if no journal
29828   ** header was written.
29829   */
29830   hdrOff = pPager->stmtHdrOff;
29831   assert( pPager->fullSync || !hdrOff );
29832   if( !hdrOff ){
29833     hdrOff = szJ;
29834   }
29835   
29836   /* Truncate the database back to its original size.
29837   */
29838   rc = pager_truncate(pPager, pPager->stmtSize);
29839   assert( pPager->state>=PAGER_SHARED );
29840
29841   /* Figure out how many records are in the statement journal.
29842   */
29843   assert( pPager->stmtInUse && pPager->journalOpen );
29844   nRec = pPager->stmtNRec;
29845   
29846   /* Copy original pages out of the statement journal and back into the
29847   ** database file.  Note that the statement journal omits checksums from
29848   ** each record since power-failure recovery is not important to statement
29849   ** journals.
29850   */
29851   for(i=0; i<nRec; i++){
29852     i64 offset = i*(4+pPager->pageSize);
29853     rc = pager_playback_one_page(pPager, pPager->stfd, offset, 0);
29854     assert( rc!=SQLITE_DONE );
29855     if( rc!=SQLITE_OK ) goto end_stmt_playback;
29856   }
29857
29858   /* Now roll some pages back from the transaction journal. Pager.stmtJSize
29859   ** was the size of the journal file when this statement was started, so
29860   ** everything after that needs to be rolled back, either into the
29861   ** database, the memory cache, or both.
29862   **
29863   ** If it is not zero, then Pager.stmtHdrOff is the offset to the start
29864   ** of the first journal header written during this statement transaction.
29865   */
29866   pPager->journalOff = pPager->stmtJSize;
29867   pPager->cksumInit = pPager->stmtCksum;
29868   while( pPager->journalOff < hdrOff ){
29869     rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29870     assert( rc!=SQLITE_DONE );
29871     if( rc!=SQLITE_OK ) goto end_stmt_playback;
29872   }
29873
29874   while( pPager->journalOff < szJ ){
29875     u32 nJRec;         /* Number of Journal Records */
29876     u32 dummy;
29877     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
29878     if( rc!=SQLITE_OK ){
29879       assert( rc!=SQLITE_DONE );
29880       goto end_stmt_playback;
29881     }
29882     if( nJRec==0 ){
29883       nJRec = (szJ - pPager->journalOff) / (pPager->pageSize+8);
29884     }
29885     for(i=nJRec-1; i>=0 && pPager->journalOff < szJ; i--){
29886       rc = pager_playback_one_page(pPager, pPager->jfd, pPager->journalOff, 1);
29887       assert( rc!=SQLITE_DONE );
29888       if( rc!=SQLITE_OK ) goto end_stmt_playback;
29889     }
29890   }
29891
29892   pPager->journalOff = szJ;
29893   
29894 end_stmt_playback:
29895   if( rc==SQLITE_OK) {
29896     pPager->journalOff = szJ;
29897     /* pager_reload_cache(pPager); */
29898   }
29899   return rc;
29900 }
29901
29902 /*
29903 ** Change the maximum number of in-memory pages that are allowed.
29904 */
29905 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
29906   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
29907 }
29908
29909 /*
29910 ** Adjust the robustness of the database to damage due to OS crashes
29911 ** or power failures by changing the number of syncs()s when writing
29912 ** the rollback journal.  There are three levels:
29913 **
29914 **    OFF       sqlite3OsSync() is never called.  This is the default
29915 **              for temporary and transient files.
29916 **
29917 **    NORMAL    The journal is synced once before writes begin on the
29918 **              database.  This is normally adequate protection, but
29919 **              it is theoretically possible, though very unlikely,
29920 **              that an inopertune power failure could leave the journal
29921 **              in a state which would cause damage to the database
29922 **              when it is rolled back.
29923 **
29924 **    FULL      The journal is synced twice before writes begin on the
29925 **              database (with some additional information - the nRec field
29926 **              of the journal header - being written in between the two
29927 **              syncs).  If we assume that writing a
29928 **              single disk sector is atomic, then this mode provides
29929 **              assurance that the journal will not be corrupted to the
29930 **              point of causing damage to the database during rollback.
29931 **
29932 ** Numeric values associated with these states are OFF==1, NORMAL=2,
29933 ** and FULL=3.
29934 */
29935 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
29936 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
29937   pPager->noSync =  level==1 || pPager->tempFile || MEMDB;
29938   pPager->fullSync = level==3 && !pPager->tempFile;
29939   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
29940   if( pPager->noSync ) pPager->needSync = 0;
29941 }
29942 #endif
29943
29944 /*
29945 ** The following global variable is incremented whenever the library
29946 ** attempts to open a temporary file.  This information is used for
29947 ** testing and analysis only.  
29948 */
29949 #ifdef SQLITE_TEST
29950 SQLITE_API int sqlite3_opentemp_count = 0;
29951 #endif
29952
29953 /*
29954 ** Open a temporary file. 
29955 **
29956 ** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
29957 ** other error code if we fail. The OS will automatically delete the temporary
29958 ** file when it is closed.
29959 */
29960 static int sqlite3PagerOpentemp(
29961   Pager *pPager,        /* The pager object */
29962   sqlite3_file *pFile,  /* Write the file descriptor here */
29963   int vfsFlags          /* Flags passed through to the VFS */
29964 ){
29965   int rc;
29966
29967 #ifdef SQLITE_TEST
29968   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
29969 #endif
29970
29971   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
29972             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
29973   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
29974   assert( rc!=SQLITE_OK || pFile->pMethods );
29975   return rc;
29976 }
29977
29978 static int pagerStress(void *,PgHdr *);
29979
29980 /*
29981 ** Create a new page cache and put a pointer to the page cache in *ppPager.
29982 ** The file to be cached need not exist.  The file is not locked until
29983 ** the first call to sqlite3PagerGet() and is only held open until the
29984 ** last page is released using sqlite3PagerUnref().
29985 **
29986 ** If zFilename is NULL then a randomly-named temporary file is created
29987 ** and used as the file to be cached.  The file will be deleted
29988 ** automatically when it is closed.
29989 **
29990 ** If zFilename is ":memory:" then all information is held in cache.
29991 ** It is never written to disk.  This can be used to implement an
29992 ** in-memory database.
29993 */
29994 SQLITE_PRIVATE int sqlite3PagerOpen(
29995   sqlite3_vfs *pVfs,       /* The virtual file system to use */
29996   Pager **ppPager,         /* Return the Pager structure here */
29997   const char *zFilename,   /* Name of the database file to open */
29998   int nExtra,              /* Extra bytes append to each in-memory page */
29999   int flags,               /* flags controlling this file */
30000   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
30001 ){
30002   u8 *pPtr;
30003   Pager *pPager = 0;
30004   int rc = SQLITE_OK;
30005   int i;
30006   int tempFile = 0;
30007   int memDb = 0;
30008   int readOnly = 0;
30009   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
30010   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
30011   int journalFileSize = sqlite3JournalSize(pVfs);
30012   int pcacheSize = sqlite3PcacheSize();
30013   int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
30014   char *zPathname = 0;
30015   int nPathname = 0;
30016
30017   /* The default return is a NULL pointer */
30018   *ppPager = 0;
30019
30020   /* Compute and store the full pathname in an allocated buffer pointed
30021   ** to by zPathname, length nPathname. Or, if this is a temporary file,
30022   ** leave both nPathname and zPathname set to 0.
30023   */
30024   if( zFilename && zFilename[0] ){
30025     nPathname = pVfs->mxPathname+1;
30026     zPathname = sqlite3Malloc(nPathname*2);
30027     if( zPathname==0 ){
30028       return SQLITE_NOMEM;
30029     }
30030 #ifndef SQLITE_OMIT_MEMORYDB
30031     if( strcmp(zFilename,":memory:")==0 ){
30032       memDb = 1;
30033       zPathname[0] = 0;
30034       useJournal = 0;
30035     }else
30036 #endif
30037     {
30038       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
30039     }
30040     if( rc!=SQLITE_OK ){
30041       sqlite3_free(zPathname);
30042       return rc;
30043     }
30044     nPathname = strlen(zPathname);
30045   }
30046
30047   /* Allocate memory for the pager structure */
30048   pPager = sqlite3MallocZero(
30049     sizeof(*pPager) +           /* Pager structure */
30050     pcacheSize      +           /* PCache object */
30051     journalFileSize +           /* The journal file structure */ 
30052     pVfs->szOsFile * 3 +        /* The main db and two journal files */ 
30053     3*nPathname + 40            /* zFilename, zDirectory, zJournal */
30054   );
30055   if( !pPager ){
30056     sqlite3_free(zPathname);
30057     return SQLITE_NOMEM;
30058   }
30059   pPager->pPCache = (PCache *)&pPager[1];
30060   pPtr = ((u8 *)&pPager[1]) + pcacheSize;
30061   pPager->vfsFlags = vfsFlags;
30062   pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
30063   pPager->stfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*1];
30064   pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile*2];
30065   pPager->zFilename = (char*)&pPtr[pVfs->szOsFile*2+journalFileSize];
30066   pPager->zDirectory = &pPager->zFilename[nPathname+1];
30067   pPager->zJournal = &pPager->zDirectory[nPathname+1];
30068   pPager->pVfs = pVfs;
30069   if( zPathname ){
30070     memcpy(pPager->zFilename, zPathname, nPathname+1);
30071     sqlite3_free(zPathname);
30072   }
30073
30074   /* Open the pager file.
30075   */
30076   if( zFilename && zFilename[0] && !memDb ){
30077     if( nPathname>(pVfs->mxPathname - sizeof("-journal")) ){
30078       rc = SQLITE_CANTOPEN;
30079     }else{
30080       int fout = 0;
30081       rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
30082                          pPager->vfsFlags, &fout);
30083       readOnly = (fout&SQLITE_OPEN_READONLY);
30084
30085       /* If the file was successfully opened for read/write access,
30086       ** choose a default page size in case we have to create the
30087       ** database file. The default page size is the maximum of:
30088       **
30089       **    + SQLITE_DEFAULT_PAGE_SIZE,
30090       **    + The value returned by sqlite3OsSectorSize()
30091       **    + The largest page size that can be written atomically.
30092       */
30093       if( rc==SQLITE_OK && !readOnly ){
30094         int iSectorSize = sqlite3OsSectorSize(pPager->fd);
30095         if( szPageDflt<iSectorSize ){
30096           szPageDflt = iSectorSize;
30097         }
30098 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
30099         {
30100           int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
30101           int ii;
30102           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
30103           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
30104           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
30105           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
30106             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
30107           }
30108         }
30109 #endif
30110         if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
30111           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
30112         }
30113       }
30114     }
30115   }else if( !memDb ){
30116     /* If a temporary file is requested, it is not opened immediately.
30117     ** In this case we accept the default page size and delay actually
30118     ** opening the file until the first call to OsWrite().
30119     */ 
30120     tempFile = 1;
30121     pPager->state = PAGER_EXCLUSIVE;
30122   }
30123
30124   if( pPager && rc==SQLITE_OK ){
30125     pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
30126   }
30127
30128   /* If an error occured in either of the blocks above.
30129   ** Free the Pager structure and close the file.
30130   ** Since the pager is not allocated there is no need to set 
30131   ** any Pager.errMask variables.
30132   */
30133   if( !pPager || !pPager->pTmpSpace ){
30134     sqlite3OsClose(pPager->fd);
30135     sqlite3_free(pPager);
30136     return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
30137   }
30138   nExtra = FORCE_ALIGNMENT(nExtra);
30139   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
30140                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
30141
30142   PAGERTRACE3("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename);
30143   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
30144
30145   /* Fill in Pager.zDirectory[] */
30146   memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
30147   for(i=strlen(pPager->zDirectory); i>0 && pPager->zDirectory[i-1]!='/'; i--){}
30148   if( i>0 ) pPager->zDirectory[i-1] = 0;
30149
30150   /* Fill in Pager.zJournal[] */
30151   if( zPathname ){
30152     memcpy(pPager->zJournal, pPager->zFilename, nPathname);
30153     memcpy(&pPager->zJournal[nPathname], "-journal", 9);
30154   }else{
30155     pPager->zJournal = 0;
30156   }
30157
30158   /* pPager->journalOpen = 0; */
30159   pPager->useJournal = useJournal;
30160   pPager->noReadlock = noReadlock && readOnly;
30161   /* pPager->stmtOpen = 0; */
30162   /* pPager->stmtInUse = 0; */
30163   /* pPager->nRef = 0; */
30164   pPager->dbSize = memDb-1;
30165   pPager->pageSize = szPageDflt;
30166   /* pPager->stmtSize = 0; */
30167   /* pPager->stmtJSize = 0; */
30168   /* pPager->nPage = 0; */
30169   pPager->mxPage = 100;
30170   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
30171   /* pPager->state = PAGER_UNLOCK; */
30172   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
30173   /* pPager->errMask = 0; */
30174   pPager->tempFile = tempFile;
30175   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
30176           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
30177   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
30178   pPager->exclusiveMode = tempFile; 
30179   pPager->memDb = memDb;
30180   pPager->readOnly = readOnly;
30181   /* pPager->needSync = 0; */
30182   pPager->noSync = pPager->tempFile || !useJournal;
30183   pPager->fullSync = (pPager->noSync?0:1);
30184   pPager->sync_flags = SQLITE_SYNC_NORMAL;
30185   /* pPager->pFirst = 0; */
30186   /* pPager->pFirstSynced = 0; */
30187   /* pPager->pLast = 0; */
30188   pPager->nExtra = nExtra;
30189   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
30190   assert(pPager->fd->pMethods||memDb||tempFile);
30191   if( !memDb ){
30192     setSectorSize(pPager);
30193   }
30194   /* pPager->pBusyHandler = 0; */
30195   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
30196   *ppPager = pPager;
30197   return SQLITE_OK;
30198 }
30199
30200 /*
30201 ** Set the busy handler function.
30202 */
30203 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
30204   pPager->pBusyHandler = pBusyHandler;
30205 }
30206
30207 /*
30208 ** Set the reinitializer for this pager.  If not NULL, the reinitializer
30209 ** is called when the content of a page in cache is restored to its original
30210 ** value as a result of a rollback.  The callback gives higher-level code
30211 ** an opportunity to restore the EXTRA section to agree with the restored
30212 ** page data.
30213 */
30214 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
30215   pPager->xReiniter = xReinit;
30216 }
30217
30218 /*
30219 ** Set the page size to *pPageSize. If the suggest new page size is
30220 ** inappropriate, then an alternative page size is set to that
30221 ** value before returning.
30222 */
30223 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
30224   int rc = pPager->errCode;
30225   if( rc==SQLITE_OK ){
30226     u16 pageSize = *pPageSize;
30227     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
30228     if( pageSize && pageSize!=pPager->pageSize 
30229      && (pPager->memDb==0 || pPager->dbSize==0)
30230      && sqlite3PcacheRefCount(pPager->pPCache)==0 
30231     ){
30232       char *pNew = (char *)sqlite3PageMalloc(pageSize);
30233       if( !pNew ){
30234         rc = SQLITE_NOMEM;
30235       }else{
30236         pager_reset(pPager);
30237         pPager->pageSize = pageSize;
30238         if( !pPager->memDb ) setSectorSize(pPager);
30239         sqlite3PageFree(pPager->pTmpSpace);
30240         pPager->pTmpSpace = pNew;
30241         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
30242       }
30243     }
30244     *pPageSize = pPager->pageSize;
30245   }
30246   return rc;
30247 }
30248
30249 /*
30250 ** Return a pointer to the "temporary page" buffer held internally
30251 ** by the pager.  This is a buffer that is big enough to hold the
30252 ** entire content of a database page.  This buffer is used internally
30253 ** during rollback and will be overwritten whenever a rollback
30254 ** occurs.  But other modules are free to use it too, as long as
30255 ** no rollbacks are happening.
30256 */
30257 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
30258   return pPager->pTmpSpace;
30259 }
30260
30261 /*
30262 ** Attempt to set the maximum database page count if mxPage is positive. 
30263 ** Make no changes if mxPage is zero or negative.  And never reduce the
30264 ** maximum page count below the current size of the database.
30265 **
30266 ** Regardless of mxPage, return the current maximum page count.
30267 */
30268 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
30269   if( mxPage>0 ){
30270     pPager->mxPgno = mxPage;
30271   }
30272   sqlite3PagerPagecount(pPager, 0);
30273   return pPager->mxPgno;
30274 }
30275
30276 /*
30277 ** The following set of routines are used to disable the simulated
30278 ** I/O error mechanism.  These routines are used to avoid simulated
30279 ** errors in places where we do not care about errors.
30280 **
30281 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
30282 ** and generate no code.
30283 */
30284 #ifdef SQLITE_TEST
30285 SQLITE_API extern int sqlite3_io_error_pending;
30286 SQLITE_API extern int sqlite3_io_error_hit;
30287 static int saved_cnt;
30288 void disable_simulated_io_errors(void){
30289   saved_cnt = sqlite3_io_error_pending;
30290   sqlite3_io_error_pending = -1;
30291 }
30292 void enable_simulated_io_errors(void){
30293   sqlite3_io_error_pending = saved_cnt;
30294 }
30295 #else
30296 # define disable_simulated_io_errors()
30297 # define enable_simulated_io_errors()
30298 #endif
30299
30300 /*
30301 ** Read the first N bytes from the beginning of the file into memory
30302 ** that pDest points to. 
30303 **
30304 ** No error checking is done. The rational for this is that this function 
30305 ** may be called even if the file does not exist or contain a header. In 
30306 ** these cases sqlite3OsRead() will return an error, to which the correct 
30307 ** response is to zero the memory at pDest and continue.  A real IO error 
30308 ** will presumably recur and be picked up later (Todo: Think about this).
30309 */
30310 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
30311   int rc = SQLITE_OK;
30312   memset(pDest, 0, N);
30313   assert(MEMDB||pPager->fd->pMethods||pPager->tempFile);
30314   if( pPager->fd->pMethods ){
30315     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
30316     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
30317     if( rc==SQLITE_IOERR_SHORT_READ ){
30318       rc = SQLITE_OK;
30319     }
30320   }
30321   return rc;
30322 }
30323
30324 /*
30325 ** Return the total number of pages in the disk file associated with
30326 ** pPager. 
30327 **
30328 ** If the PENDING_BYTE lies on the page directly after the end of the
30329 ** file, then consider this page part of the file too. For example, if
30330 ** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
30331 ** file is 4096 bytes, 5 is returned instead of 4.
30332 */
30333 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
30334   i64 n = 0;
30335   int rc;
30336   assert( pPager!=0 );
30337   if( pPager->errCode ){
30338     rc = pPager->errCode;
30339     return rc;
30340   }
30341   if( pPager->dbSize>=0 ){
30342     n = pPager->dbSize;
30343   } else {
30344     assert(pPager->fd->pMethods||pPager->tempFile);
30345     if( (pPager->fd->pMethods)
30346      && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
30347       pager_error(pPager, rc);
30348       return rc;
30349     }
30350     if( n>0 && n<pPager->pageSize ){
30351       n = 1;
30352     }else{
30353       n /= pPager->pageSize;
30354     }
30355     if( pPager->state!=PAGER_UNLOCK ){
30356       pPager->dbSize = n;
30357     }
30358   }
30359   if( n==(PENDING_BYTE/pPager->pageSize) ){
30360     n++;
30361   }
30362   if( n>pPager->mxPgno ){
30363     pPager->mxPgno = n;
30364   }
30365   if( pnPage ){
30366     *pnPage = n;
30367   }
30368   return SQLITE_OK;
30369 }
30370
30371 /*
30372 ** Forward declaration
30373 */
30374 static int syncJournal(Pager*);
30375
30376 /*
30377 ** This routine is used to truncate the cache when a database
30378 ** is truncated.  Drop from the cache all pages whose pgno is
30379 ** larger than pPager->dbSize and is unreferenced.
30380 **
30381 ** Referenced pages larger than pPager->dbSize are zeroed.
30382 **
30383 ** Actually, at the point this routine is called, it would be
30384 ** an error to have a referenced page.  But rather than delete
30385 ** that page and guarantee a subsequent segfault, it seems better
30386 ** to zero it and hope that we error out sanely.
30387 */
30388 static void pager_truncate_cache(Pager *pPager){
30389   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
30390 }
30391
30392 /*
30393 ** Try to obtain a lock on a file.  Invoke the busy callback if the lock
30394 ** is currently not available.  Repeat until the busy callback returns
30395 ** false or until the lock succeeds.
30396 **
30397 ** Return SQLITE_OK on success and an error code if we cannot obtain
30398 ** the lock.
30399 */
30400 static int pager_wait_on_lock(Pager *pPager, int locktype){
30401   int rc;
30402
30403   /* The OS lock values must be the same as the Pager lock values */
30404   assert( PAGER_SHARED==SHARED_LOCK );
30405   assert( PAGER_RESERVED==RESERVED_LOCK );
30406   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
30407
30408   /* If the file is currently unlocked then the size must be unknown */
30409   assert( pPager->state>=PAGER_SHARED || pPager->dbSize<0 || MEMDB );
30410
30411   if( pPager->state>=locktype ){
30412     rc = SQLITE_OK;
30413   }else{
30414     if( pPager->pBusyHandler ) pPager->pBusyHandler->nBusy = 0;
30415     do {
30416       rc = sqlite3OsLock(pPager->fd, locktype);
30417     }while( rc==SQLITE_BUSY && sqlite3InvokeBusyHandler(pPager->pBusyHandler) );
30418     if( rc==SQLITE_OK ){
30419       pPager->state = locktype;
30420       IOTRACE(("LOCK %p %d\n", pPager, locktype))
30421     }
30422   }
30423   return rc;
30424 }
30425
30426 /*
30427 ** Truncate the file to the number of pages specified.
30428 */
30429 SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
30430   int rc = SQLITE_OK;
30431   assert( pPager->state>=PAGER_SHARED || MEMDB );
30432
30433
30434   sqlite3PagerPagecount(pPager, 0);
30435   if( pPager->errCode ){
30436     rc = pPager->errCode;
30437   }else if( nPage<(unsigned)pPager->dbSize ){
30438     if( MEMDB ){
30439       pPager->dbSize = nPage;
30440       pager_truncate_cache(pPager);
30441     }else{
30442       rc = syncJournal(pPager);
30443       if( rc==SQLITE_OK ){
30444         /* Get an exclusive lock on the database before truncating. */
30445         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30446       }
30447       if( rc==SQLITE_OK ){
30448         rc = pager_truncate(pPager, nPage);
30449       }
30450     }
30451   }
30452
30453   return rc;
30454 }
30455
30456 /*
30457 ** Shutdown the page cache.  Free all memory and close all files.
30458 **
30459 ** If a transaction was in progress when this routine is called, that
30460 ** transaction is rolled back.  All outstanding pages are invalidated
30461 ** and their memory is freed.  Any attempt to use a page associated
30462 ** with this page cache after this function returns will likely
30463 ** result in a coredump.
30464 **
30465 ** This function always succeeds. If a transaction is active an attempt
30466 ** is made to roll it back. If an error occurs during the rollback 
30467 ** a hot journal may be left in the filesystem but no error is returned
30468 ** to the caller.
30469 */
30470 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
30471
30472   disable_simulated_io_errors();
30473   sqlite3BeginBenignMalloc();
30474   pPager->errCode = 0;
30475   pPager->exclusiveMode = 0;
30476   pager_reset(pPager);
30477   pagerUnlockAndRollback(pPager);
30478   enable_simulated_io_errors();
30479   sqlite3EndBenignMalloc();
30480   PAGERTRACE2("CLOSE %d\n", PAGERID(pPager));
30481   IOTRACE(("CLOSE %p\n", pPager))
30482   if( pPager->journalOpen ){
30483     sqlite3OsClose(pPager->jfd);
30484   }
30485   sqlite3BitvecDestroy(pPager->pInJournal);
30486   sqlite3BitvecDestroy(pPager->pAlwaysRollback);
30487   if( pPager->stmtOpen ){
30488     sqlite3OsClose(pPager->stfd);
30489   }
30490   sqlite3OsClose(pPager->fd);
30491   /* Temp files are automatically deleted by the OS
30492   ** if( pPager->tempFile ){
30493   **   sqlite3OsDelete(pPager->zFilename);
30494   ** }
30495   */
30496
30497   sqlite3PageFree(pPager->pTmpSpace);
30498   sqlite3PcacheClose(pPager->pPCache);
30499   sqlite3_free(pPager);
30500   return SQLITE_OK;
30501 }
30502
30503 #if !defined(NDEBUG) || defined(SQLITE_TEST)
30504 /*
30505 ** Return the page number for the given page data.
30506 */
30507 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
30508   return p->pgno;
30509 }
30510 #endif
30511
30512 /*
30513 ** Increment the reference count for a page.  The input pointer is
30514 ** a reference to the page data.
30515 */
30516 SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
30517   sqlite3PcacheRef(pPg);
30518   return SQLITE_OK;
30519 }
30520
30521 /*
30522 ** Sync the journal.  In other words, make sure all the pages that have
30523 ** been written to the journal have actually reached the surface of the
30524 ** disk.  It is not safe to modify the original database file until after
30525 ** the journal has been synced.  If the original database is modified before
30526 ** the journal is synced and a power failure occurs, the unsynced journal
30527 ** data would be lost and we would be unable to completely rollback the
30528 ** database changes.  Database corruption would occur.
30529 ** 
30530 ** This routine also updates the nRec field in the header of the journal.
30531 ** (See comments on the pager_playback() routine for additional information.)
30532 ** If the sync mode is FULL, two syncs will occur.  First the whole journal
30533 ** is synced, then the nRec field is updated, then a second sync occurs.
30534 **
30535 ** For temporary databases, we do not care if we are able to rollback
30536 ** after a power failure, so no sync occurs.
30537 **
30538 ** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
30539 ** the database is stored, then OsSync() is never called on the journal
30540 ** file. In this case all that is required is to update the nRec field in
30541 ** the journal header.
30542 **
30543 ** This routine clears the needSync field of every page current held in
30544 ** memory.
30545 */
30546 static int syncJournal(Pager *pPager){
30547   int rc = SQLITE_OK;
30548
30549   /* Sync the journal before modifying the main database
30550   ** (assuming there is a journal and it needs to be synced.)
30551   */
30552   if( pPager->needSync ){
30553     if( !pPager->tempFile ){
30554       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
30555       assert( pPager->journalOpen );
30556
30557       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
30558         /* Write the nRec value into the journal file header. If in
30559         ** full-synchronous mode, sync the journal first. This ensures that
30560         ** all data has really hit the disk before nRec is updated to mark
30561         ** it as a candidate for rollback.
30562         **
30563         ** This is not required if the persistent media supports the
30564         ** SAFE_APPEND property. Because in this case it is not possible 
30565         ** for garbage data to be appended to the file, the nRec field
30566         ** is populated with 0xFFFFFFFF when the journal header is written
30567         ** and never needs to be updated.
30568         */
30569         i64 jrnlOff;
30570         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
30571           PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
30572           IOTRACE(("JSYNC %p\n", pPager))
30573           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
30574           if( rc!=0 ) return rc;
30575         }
30576
30577         jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
30578         IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
30579         rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
30580         if( rc ) return rc;
30581       }
30582       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
30583         PAGERTRACE2("SYNC journal of %d\n", PAGERID(pPager));
30584         IOTRACE(("JSYNC %p\n", pPager))
30585         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
30586           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
30587         );
30588         if( rc!=0 ) return rc;
30589       }
30590       pPager->journalStarted = 1;
30591     }
30592     pPager->needSync = 0;
30593
30594     /* Erase the needSync flag from every page.
30595     */
30596     sqlite3PcacheClearFlags(pPager->pPCache, PGHDR_NEED_SYNC);
30597   }
30598
30599 #ifndef NDEBUG
30600   /* If the Pager.needSync flag is clear then the PgHdr.needSync
30601   ** flag must also be clear for all pages.  Verify that this
30602   ** invariant is true.
30603   */
30604   else{
30605     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_NEED_SYNC);
30606   }
30607 #endif
30608
30609   return rc;
30610 }
30611
30612 /*
30613 ** Given a list of pages (connected by the PgHdr.pDirty pointer) write
30614 ** every one of those pages out to the database file. No calls are made
30615 ** to the page-cache to mark the pages as clean. It is the responsibility
30616 ** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark
30617 ** the pages as clean.
30618 */
30619 static int pager_write_pagelist(PgHdr *pList){
30620   Pager *pPager;
30621   int rc;
30622
30623   if( pList==0 ) return SQLITE_OK;
30624   pPager = pList->pPager;
30625
30626   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
30627   ** database file. If there is already an EXCLUSIVE lock, the following
30628   ** calls to sqlite3OsLock() are no-ops.
30629   **
30630   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
30631   ** through an intermediate state PENDING.   A PENDING lock prevents new
30632   ** readers from attaching to the database but is unsufficient for us to
30633   ** write.  The idea of a PENDING lock is to prevent new readers from
30634   ** coming in while we wait for existing readers to clear.
30635   **
30636   ** While the pager is in the RESERVED state, the original database file
30637   ** is unchanged and we can rollback without having to playback the
30638   ** journal into the original database file.  Once we transition to
30639   ** EXCLUSIVE, it means the database file has been changed and any rollback
30640   ** will require a journal playback.
30641   */
30642   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
30643   if( rc!=SQLITE_OK ){
30644     return rc;
30645   }
30646
30647   while( pList ){
30648
30649     /* If the file has not yet been opened, open it now. */
30650     if( !pPager->fd->pMethods ){
30651       assert(pPager->tempFile);
30652       rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
30653       if( rc ) return rc;
30654     }
30655
30656     /* If there are dirty pages in the page cache with page numbers greater
30657     ** than Pager.dbSize, this means sqlite3PagerTruncate() was called to
30658     ** make the file smaller (presumably by auto-vacuum code). Do not write
30659     ** any such pages to the file.
30660     */
30661     if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
30662       i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
30663       char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);
30664       PAGERTRACE4("STORE %d page %d hash(%08x)\n",
30665                    PAGERID(pPager), pList->pgno, pager_pagehash(pList));
30666       IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
30667       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
30668       PAGER_INCR(sqlite3_pager_writedb_count);
30669       PAGER_INCR(pPager->nWrite);
30670       if( pList->pgno==1 ){
30671         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
30672       }
30673     }
30674 #ifndef NDEBUG
30675     else{
30676       PAGERTRACE3("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno);
30677     }
30678 #endif
30679     if( rc ) return rc;
30680 #ifdef SQLITE_CHECK_PAGES
30681     pList->pageHash = pager_pagehash(pList);
30682 #endif
30683     pList = pList->pDirty;
30684   }
30685
30686   return SQLITE_OK;
30687 }
30688
30689 /*
30690 ** This function is called by the pcache layer when it has reached some
30691 ** soft memory limit. The argument is a pointer to a purgeable Pager 
30692 ** object. This function attempts to make a single dirty page that has no
30693 ** outstanding references (if one exists) clean so that it can be recycled 
30694 ** by the pcache layer.
30695 */
30696 static int pagerStress(void *p, PgHdr *pPg){
30697   Pager *pPager = (Pager *)p;
30698   int rc = SQLITE_OK;
30699
30700   if( pPager->doNotSync ){
30701     return SQLITE_OK;
30702   }
30703
30704   assert( pPg->flags&PGHDR_DIRTY );
30705   if( pPager->errCode==SQLITE_OK ){
30706     if( pPg->flags&PGHDR_NEED_SYNC ){
30707       rc = syncJournal(pPager);
30708       if( rc==SQLITE_OK && pPager->fullSync && 
30709         !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
30710       ){
30711         pPager->nRec = 0;
30712         rc = writeJournalHdr(pPager);
30713       }
30714     }
30715     if( rc==SQLITE_OK ){
30716       pPg->pDirty = 0;
30717       rc = pager_write_pagelist(pPg);
30718     }
30719     if( rc!=SQLITE_OK ){
30720       pager_error(pPager, rc);
30721     }
30722   }
30723
30724   if( rc==SQLITE_OK ){
30725     sqlite3PcacheMakeClean(pPg);
30726   }
30727   return rc;
30728 }
30729
30730
30731 /*
30732 ** Return 1 if there is a hot journal on the given pager.
30733 ** A hot journal is one that needs to be played back.
30734 **
30735 ** If the current size of the database file is 0 but a journal file
30736 ** exists, that is probably an old journal left over from a prior
30737 ** database with the same name.  Just delete the journal.
30738 **
30739 ** Return negative if unable to determine the status of the journal.
30740 **
30741 ** This routine does not open the journal file to examine its
30742 ** content.  Hence, the journal might contain the name of a master
30743 ** journal file that has been deleted, and hence not be hot.  Or
30744 ** the header of the journal might be zeroed out.  This routine
30745 ** does not discover these cases of a non-hot journal - if the
30746 ** journal file exists and is not empty this routine assumes it
30747 ** is hot.  The pager_playback() routine will discover that the
30748 ** journal file is not really hot and will no-op.
30749 */
30750 static int hasHotJournal(Pager *pPager, int *pExists){
30751   sqlite3_vfs *pVfs = pPager->pVfs;
30752   int rc = SQLITE_OK;
30753   int exists;
30754   int locked;
30755   assert( pPager!=0 );
30756   assert( pPager->useJournal );
30757   assert( pPager->fd->pMethods );
30758   *pExists = 0;
30759   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
30760   if( rc==SQLITE_OK && exists ){
30761     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
30762   }
30763   if( rc==SQLITE_OK && exists && !locked ){
30764     int nPage;
30765     rc = sqlite3PagerPagecount(pPager, &nPage);
30766     if( rc==SQLITE_OK ){
30767      if( nPage==0 ){
30768         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
30769       }else{
30770         *pExists = 1;
30771       }
30772     }
30773   }
30774   return rc;
30775 }
30776
30777 /*
30778 ** Read the content of page pPg out of the database file.
30779 */
30780 static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){
30781   int rc;
30782   i64 offset;
30783   assert( MEMDB==0 );
30784   assert(pPager->fd->pMethods||pPager->tempFile);
30785   if( !pPager->fd->pMethods ){
30786     return SQLITE_IOERR_SHORT_READ;
30787   }
30788   offset = (pgno-1)*(i64)pPager->pageSize;
30789   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);
30790   PAGER_INCR(sqlite3_pager_readdb_count);
30791   PAGER_INCR(pPager->nRead);
30792   IOTRACE(("PGIN %p %d\n", pPager, pgno));
30793   if( pgno==1 ){
30794     memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
30795                                               sizeof(pPager->dbFileVers));
30796   }
30797   CODEC1(pPager, pPg->pData, pPg->pgno, 3);
30798   PAGERTRACE4("FETCH %d page %d hash(%08x)\n",
30799                PAGERID(pPager), pPg->pgno, pager_pagehash(pPg));
30800   return rc;
30801 }
30802
30803
30804 /*
30805 ** This function is called to obtain the shared lock required before
30806 ** data may be read from the pager cache. If the shared lock has already
30807 ** been obtained, this function is a no-op.
30808 **
30809 ** Immediately after obtaining the shared lock (if required), this function
30810 ** checks for a hot-journal file. If one is found, an emergency rollback
30811 ** is performed immediately.
30812 */
30813 static int pagerSharedLock(Pager *pPager){
30814   int rc = SQLITE_OK;
30815   int isErrorReset = 0;
30816
30817   /* If this database is opened for exclusive access, has no outstanding 
30818   ** page references and is in an error-state, now is the chance to clear
30819   ** the error. Discard the contents of the pager-cache and treat any
30820   ** open journal file as a hot-journal.
30821   */
30822   if( !MEMDB && pPager->exclusiveMode 
30823    && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
30824   ){
30825     if( pPager->journalOpen ){
30826       isErrorReset = 1;
30827     }
30828     pPager->errCode = SQLITE_OK;
30829     pager_reset(pPager);
30830   }
30831
30832   /* If the pager is still in an error state, do not proceed. The error 
30833   ** state will be cleared at some point in the future when all page 
30834   ** references are dropped and the cache can be discarded.
30835   */
30836   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
30837     return pPager->errCode;
30838   }
30839
30840   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
30841     sqlite3_vfs *pVfs = pPager->pVfs;
30842     if( !MEMDB ){
30843       int isHotJournal;
30844       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
30845       if( !pPager->noReadlock ){
30846         rc = pager_wait_on_lock(pPager, SHARED_LOCK);
30847         if( rc!=SQLITE_OK ){
30848           assert( pPager->state==PAGER_UNLOCK );
30849           return pager_error(pPager, rc);
30850         }
30851         assert( pPager->state>=SHARED_LOCK );
30852       }
30853   
30854       /* If a journal file exists, and there is no RESERVED lock on the
30855       ** database file, then it either needs to be played back or deleted.
30856       */
30857       if( !isErrorReset ){
30858         rc = hasHotJournal(pPager, &isHotJournal);
30859         if( rc!=SQLITE_OK ){
30860           goto failed;
30861         }
30862       }
30863       if( isErrorReset || isHotJournal ){
30864         /* Get an EXCLUSIVE lock on the database file. At this point it is
30865         ** important that a RESERVED lock is not obtained on the way to the
30866         ** EXCLUSIVE lock. If it were, another process might open the
30867         ** database file, detect the RESERVED lock, and conclude that the
30868         ** database is safe to read while this process is still rolling it 
30869         ** back.
30870         ** 
30871         ** Because the intermediate RESERVED lock is not requested, the
30872         ** second process will get to this point in the code and fail to
30873         ** obtain its own EXCLUSIVE lock on the database file.
30874         */
30875         if( pPager->state<EXCLUSIVE_LOCK ){
30876           rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
30877           if( rc!=SQLITE_OK ){
30878             rc = pager_error(pPager, rc);
30879             goto failed;
30880           }
30881           pPager->state = PAGER_EXCLUSIVE;
30882         }
30883  
30884         /* Open the journal for read/write access. This is because in 
30885         ** exclusive-access mode the file descriptor will be kept open and
30886         ** possibly used for a transaction later on. On some systems, the
30887         ** OsTruncate() call used in exclusive-access mode also requires
30888         ** a read/write file handle.
30889         */
30890         if( !isErrorReset && pPager->journalOpen==0 ){
30891           int res;
30892           rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
30893           if( rc==SQLITE_OK ){
30894             if( res ){
30895               int fout = 0;
30896               int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
30897               assert( !pPager->tempFile );
30898               rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
30899               assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
30900               if( fout&SQLITE_OPEN_READONLY ){
30901                 rc = SQLITE_BUSY;
30902                 sqlite3OsClose(pPager->jfd);
30903               }
30904             }else{
30905               /* If the journal does not exist, that means some other process
30906               ** has already rolled it back */
30907               rc = SQLITE_BUSY;
30908             }
30909           }
30910         }
30911         if( rc!=SQLITE_OK ){
30912           if( rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_UNLOCK 
30913            && rc!=SQLITE_IOERR_NOMEM 
30914           ){
30915             rc = SQLITE_BUSY;
30916           }
30917           goto failed;
30918         }
30919         pPager->journalOpen = 1;
30920         pPager->journalStarted = 0;
30921         pPager->journalOff = 0;
30922         pPager->setMaster = 0;
30923         pPager->journalHdr = 0;
30924  
30925         /* Playback and delete the journal.  Drop the database write
30926         ** lock and reacquire the read lock.
30927         */
30928         rc = pager_playback(pPager, 1);
30929         if( rc!=SQLITE_OK ){
30930           rc = pager_error(pPager, rc);
30931           goto failed;
30932         }
30933         assert(pPager->state==PAGER_SHARED || 
30934             (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
30935         );
30936       }
30937
30938       if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
30939         /* The shared-lock has just been acquired on the database file
30940         ** and there are already pages in the cache (from a previous
30941         ** read or write transaction).  Check to see if the database
30942         ** has been modified.  If the database has changed, flush the
30943         ** cache.
30944         **
30945         ** Database changes is detected by looking at 15 bytes beginning
30946         ** at offset 24 into the file.  The first 4 of these 16 bytes are
30947         ** a 32-bit counter that is incremented with each change.  The
30948         ** other bytes change randomly with each file change when
30949         ** a codec is in use.
30950         ** 
30951         ** There is a vanishingly small chance that a change will not be 
30952         ** detected.  The chance of an undetected change is so small that
30953         ** it can be neglected.
30954         */
30955         char dbFileVers[sizeof(pPager->dbFileVers)];
30956         sqlite3PagerPagecount(pPager, 0);
30957
30958         if( pPager->errCode ){
30959           rc = pPager->errCode;
30960           goto failed;
30961         }
30962
30963         if( pPager->dbSize>0 ){
30964           IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
30965           rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
30966           if( rc!=SQLITE_OK ){
30967             goto failed;
30968           }
30969         }else{
30970           memset(dbFileVers, 0, sizeof(dbFileVers));
30971         }
30972
30973         if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
30974           pager_reset(pPager);
30975         }
30976       }
30977     }
30978     assert( pPager->exclusiveMode || pPager->state<=PAGER_SHARED );
30979     if( pPager->state==PAGER_UNLOCK ){
30980       pPager->state = PAGER_SHARED;
30981     }
30982   }
30983
30984  failed:
30985   if( rc!=SQLITE_OK ){
30986     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
30987     pager_unlock(pPager);
30988   }
30989   return rc;
30990 }
30991
30992 /*
30993 ** Make sure we have the content for a page.  If the page was
30994 ** previously acquired with noContent==1, then the content was
30995 ** just initialized to zeros instead of being read from disk.
30996 ** But now we need the real data off of disk.  So make sure we
30997 ** have it.  Read it in if we do not have it already.
30998 */
30999 static int pager_get_content(PgHdr *pPg){
31000   if( pPg->flags&PGHDR_NEED_READ ){
31001     int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
31002     if( rc==SQLITE_OK ){
31003       pPg->flags &= ~PGHDR_NEED_READ;
31004     }else{
31005       return rc;
31006     }
31007   }
31008   return SQLITE_OK;
31009 }
31010
31011 /*
31012 ** If the reference count has reached zero, and the pager is not in the
31013 ** middle of a write transaction or opened in exclusive mode, unlock it.
31014 */ 
31015 static void pagerUnlockIfUnused(Pager *pPager){
31016   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
31017     && (!pPager->exclusiveMode || pPager->journalOff>0) 
31018   ){
31019     pagerUnlockAndRollback(pPager);
31020   }
31021 }
31022
31023 /*
31024 ** Drop a page from the cache using sqlite3PcacheDrop().
31025 **
31026 ** If this means there are now no pages with references to them, a rollback
31027 ** occurs and the lock on the database is removed.
31028 */
31029 static void pagerDropPage(DbPage *pPg){
31030   Pager *pPager = pPg->pPager;
31031   sqlite3PcacheDrop(pPg);
31032   pagerUnlockIfUnused(pPager);
31033 }
31034
31035 /*
31036 ** Acquire a page.
31037 **
31038 ** A read lock on the disk file is obtained when the first page is acquired. 
31039 ** This read lock is dropped when the last page is released.
31040 **
31041 ** This routine works for any page number greater than 0.  If the database
31042 ** file is smaller than the requested page, then no actual disk
31043 ** read occurs and the memory image of the page is initialized to
31044 ** all zeros.  The extra data appended to a page is always initialized
31045 ** to zeros the first time a page is loaded into memory.
31046 **
31047 ** The acquisition might fail for several reasons.  In all cases,
31048 ** an appropriate error code is returned and *ppPage is set to NULL.
31049 **
31050 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
31051 ** to find a page in the in-memory cache first.  If the page is not already
31052 ** in memory, this routine goes to disk to read it in whereas Lookup()
31053 ** just returns 0.  This routine acquires a read-lock the first time it
31054 ** has to go to disk, and could also playback an old journal if necessary.
31055 ** Since Lookup() never goes to disk, it never has to deal with locks
31056 ** or journal files.
31057 **
31058 ** If noContent is false, the page contents are actually read from disk.
31059 ** If noContent is true, it means that we do not care about the contents
31060 ** of the page at this time, so do not do a disk read.  Just fill in the
31061 ** page content with zeros.  But mark the fact that we have not read the
31062 ** content by setting the PgHdr.needRead flag.  Later on, if 
31063 ** sqlite3PagerWrite() is called on this page or if this routine is
31064 ** called again with noContent==0, that means that the content is needed
31065 ** and the disk read should occur at that point.
31066 */
31067 SQLITE_PRIVATE int sqlite3PagerAcquire(
31068   Pager *pPager,      /* The pager open on the database file */
31069   Pgno pgno,          /* Page number to fetch */
31070   DbPage **ppPage,    /* Write a pointer to the page here */
31071   int noContent       /* Do not bother reading content from disk if true */
31072 ){
31073   PgHdr *pPg = 0;
31074   int rc;
31075
31076   assert( pPager->state==PAGER_UNLOCK 
31077        || sqlite3PcacheRefCount(pPager->pPCache)>0 
31078        || pgno==1 
31079   );
31080
31081   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
31082   ** number greater than this, or zero, is requested.
31083   */
31084   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
31085     return SQLITE_CORRUPT_BKPT;
31086   }
31087
31088   /* Make sure we have not hit any critical errors.
31089   */ 
31090   assert( pPager!=0 );
31091   *ppPage = 0;
31092
31093   /* If this is the first page accessed, then get a SHARED lock
31094   ** on the database file. pagerSharedLock() is a no-op if 
31095   ** a database lock is already held.
31096   */
31097   rc = pagerSharedLock(pPager);
31098   if( rc!=SQLITE_OK ){
31099     return rc;
31100   }
31101   assert( pPager->state!=PAGER_UNLOCK );
31102
31103   rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
31104   if( rc!=SQLITE_OK ){
31105     return rc;
31106   }
31107   if( pPg->pPager==0 ){
31108     /* The pager cache has created a new page. Its content needs to 
31109     ** be initialized.
31110     */
31111     int nMax;
31112     PAGER_INCR(pPager->nMiss);
31113     pPg->pPager = pPager;
31114     if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
31115       assert( !MEMDB );
31116       pPg->flags |= PGHDR_IN_JOURNAL;
31117     }
31118     memset(pPg->pExtra, 0, pPager->nExtra);
31119
31120     rc = sqlite3PagerPagecount(pPager, &nMax);
31121     if( rc!=SQLITE_OK ){
31122       sqlite3PagerUnref(pPg);
31123       return rc;
31124     }
31125
31126     if( nMax<(int)pgno || MEMDB || noContent ){
31127       if( pgno>pPager->mxPgno ){
31128         sqlite3PagerUnref(pPg);
31129         return SQLITE_FULL;
31130       }
31131       memset(pPg->pData, 0, pPager->pageSize);
31132       if( noContent ){
31133         pPg->flags |= PGHDR_NEED_READ;
31134       }
31135       IOTRACE(("ZERO %p %d\n", pPager, pgno));
31136     }else{
31137       rc = readDbPage(pPager, pPg, pgno);
31138       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
31139         /* sqlite3PagerUnref(pPg); */
31140         pagerDropPage(pPg);
31141         return rc;
31142       }
31143     }
31144 #ifdef SQLITE_CHECK_PAGES
31145     pPg->pageHash = pager_pagehash(pPg);
31146 #endif
31147   }else{
31148     /* The requested page is in the page cache. */
31149     assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
31150     PAGER_INCR(pPager->nHit);
31151     if( !noContent ){
31152       rc = pager_get_content(pPg);
31153       if( rc ){
31154         sqlite3PagerUnref(pPg);
31155         return rc;
31156       }
31157     }
31158   }
31159
31160   *ppPage = pPg;
31161   return SQLITE_OK;
31162 }
31163
31164 /*
31165 ** Acquire a page if it is already in the in-memory cache.  Do
31166 ** not read the page from disk.  Return a pointer to the page,
31167 ** or 0 if the page is not in cache.
31168 **
31169 ** See also sqlite3PagerGet().  The difference between this routine
31170 ** and sqlite3PagerGet() is that _get() will go to the disk and read
31171 ** in the page if the page is not already in cache.  This routine
31172 ** returns NULL if the page is not in cache or if a disk I/O error 
31173 ** has ever happened.
31174 */
31175 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
31176   PgHdr *pPg = 0;
31177   assert( pPager!=0 );
31178   assert( pgno!=0 );
31179
31180   if( (pPager->state!=PAGER_UNLOCK)
31181    && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
31182   ){
31183     sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
31184   }
31185
31186   return pPg;
31187 }
31188
31189 /*
31190 ** Release a page.
31191 **
31192 ** If the number of references to the page drop to zero, then the
31193 ** page is added to the LRU list.  When all references to all pages
31194 ** are released, a rollback occurs and the lock on the database is
31195 ** removed.
31196 */
31197 SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
31198   if( pPg ){
31199     Pager *pPager = pPg->pPager;
31200     sqlite3PcacheRelease(pPg);
31201     pagerUnlockIfUnused(pPager);
31202   }
31203   return SQLITE_OK;
31204 }
31205
31206 /*
31207 ** Create a journal file for pPager.  There should already be a RESERVED
31208 ** or EXCLUSIVE lock on the database file when this routine is called.
31209 **
31210 ** Return SQLITE_OK if everything.  Return an error code and release the
31211 ** write lock if anything goes wrong.
31212 */
31213 static int pager_open_journal(Pager *pPager){
31214   sqlite3_vfs *pVfs = pPager->pVfs;
31215   int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);
31216
31217   int rc;
31218   assert( !MEMDB );
31219   assert( pPager->state>=PAGER_RESERVED );
31220   assert( pPager->useJournal );
31221   assert( pPager->pInJournal==0 );
31222   sqlite3PagerPagecount(pPager, 0);
31223   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
31224   if( pPager->pInJournal==0 ){
31225     rc = SQLITE_NOMEM;
31226     goto failed_to_open_journal;
31227   }
31228
31229   if( pPager->journalOpen==0 ){
31230     if( pPager->tempFile ){
31231       flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
31232     }else{
31233       flags |= (SQLITE_OPEN_MAIN_JOURNAL);
31234     }
31235 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31236     rc = sqlite3JournalOpen(
31237         pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
31238     );
31239 #else
31240     rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
31241 #endif
31242     assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
31243     pPager->journalOff = 0;
31244     pPager->setMaster = 0;
31245     pPager->journalHdr = 0;
31246     if( rc!=SQLITE_OK ){
31247       if( rc==SQLITE_NOMEM ){
31248         sqlite3OsDelete(pVfs, pPager->zJournal, 0);
31249       }
31250       goto failed_to_open_journal;
31251     }
31252   }
31253   pPager->journalOpen = 1;
31254   pPager->journalStarted = 0;
31255   pPager->needSync = 0;
31256   pPager->nRec = 0;
31257   if( pPager->errCode ){
31258     rc = pPager->errCode;
31259     goto failed_to_open_journal;
31260   }
31261   pPager->origDbSize = pPager->dbSize;
31262
31263   rc = writeJournalHdr(pPager);
31264
31265   if( pPager->stmtAutoopen && rc==SQLITE_OK ){
31266     rc = sqlite3PagerStmtBegin(pPager);
31267   }
31268   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
31269     rc = pager_end_transaction(pPager, 0);
31270     if( rc==SQLITE_OK ){
31271       rc = SQLITE_FULL;
31272     }
31273   }
31274   return rc;
31275
31276 failed_to_open_journal:
31277   sqlite3BitvecDestroy(pPager->pInJournal);
31278   pPager->pInJournal = 0;
31279   return rc;
31280 }
31281
31282 /*
31283 ** Acquire a write-lock on the database.  The lock is removed when
31284 ** the any of the following happen:
31285 **
31286 **   *  sqlite3PagerCommitPhaseTwo() is called.
31287 **   *  sqlite3PagerRollback() is called.
31288 **   *  sqlite3PagerClose() is called.
31289 **   *  sqlite3PagerUnref() is called to on every outstanding page.
31290 **
31291 ** The first parameter to this routine is a pointer to any open page of the
31292 ** database file.  Nothing changes about the page - it is used merely to
31293 ** acquire a pointer to the Pager structure and as proof that there is
31294 ** already a read-lock on the database.
31295 **
31296 ** The second parameter indicates how much space in bytes to reserve for a
31297 ** master journal file-name at the start of the journal when it is created.
31298 **
31299 ** A journal file is opened if this is not a temporary file.  For temporary
31300 ** files, the opening of the journal file is deferred until there is an
31301 ** actual need to write to the journal.
31302 **
31303 ** If the database is already reserved for writing, this routine is a no-op.
31304 **
31305 ** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
31306 ** immediately instead of waiting until we try to flush the cache.  The
31307 ** exFlag is ignored if a transaction is already active.
31308 */
31309 SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
31310   Pager *pPager = pPg->pPager;
31311   int rc = SQLITE_OK;
31312   assert( pPg->nRef>0 );
31313   assert( pPager->state!=PAGER_UNLOCK );
31314   if( pPager->state==PAGER_SHARED ){
31315     assert( pPager->pInJournal==0 );
31316     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
31317     if( MEMDB ){
31318       pPager->state = PAGER_EXCLUSIVE;
31319       pPager->origDbSize = pPager->dbSize;
31320     }else{
31321       rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
31322       if( rc==SQLITE_OK ){
31323         pPager->state = PAGER_RESERVED;
31324         if( exFlag ){
31325           rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
31326         }
31327       }
31328       if( rc!=SQLITE_OK ){
31329         return rc;
31330       }
31331       pPager->dirtyCache = 0;
31332       PAGERTRACE2("TRANSACTION %d\n", PAGERID(pPager));
31333       if( pPager->useJournal && !pPager->tempFile
31334              && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31335         rc = pager_open_journal(pPager);
31336       }
31337     }
31338   }else if( pPager->journalOpen && pPager->journalOff==0 ){
31339     /* This happens when the pager was in exclusive-access mode the last
31340     ** time a (read or write) transaction was successfully concluded
31341     ** by this connection. Instead of deleting the journal file it was 
31342     ** kept open and either was truncated to 0 bytes or its header was
31343     ** overwritten with zeros.
31344     */
31345     assert( pPager->nRec==0 );
31346     assert( pPager->origDbSize==0 );
31347     assert( pPager->pInJournal==0 );
31348     sqlite3PagerPagecount(pPager, 0);
31349     pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
31350     if( !pPager->pInJournal ){
31351       rc = SQLITE_NOMEM;
31352     }else{
31353       pPager->origDbSize = pPager->dbSize;
31354       rc = writeJournalHdr(pPager);
31355     }
31356   }
31357   assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
31358   return rc;
31359 }
31360
31361 /*
31362 ** Make a page dirty.  Set its dirty flag and add it to the dirty
31363 ** page list.
31364 */
31365 static void makeDirty(PgHdr *pPg){
31366   sqlite3PcacheMakeDirty(pPg);
31367 }
31368
31369 /*
31370 ** Make a page clean.  Clear its dirty bit and remove it from the
31371 ** dirty page list.
31372 */
31373 static void makeClean(PgHdr *pPg){
31374   sqlite3PcacheMakeClean(pPg);
31375 }
31376
31377
31378 /*
31379 ** Mark a data page as writeable.  The page is written into the journal 
31380 ** if it is not there already.  This routine must be called before making
31381 ** changes to a page.
31382 **
31383 ** The first time this routine is called, the pager creates a new
31384 ** journal and acquires a RESERVED lock on the database.  If the RESERVED
31385 ** lock could not be acquired, this routine returns SQLITE_BUSY.  The
31386 ** calling routine must check for that return value and be careful not to
31387 ** change any page data until this routine returns SQLITE_OK.
31388 **
31389 ** If the journal file could not be written because the disk is full,
31390 ** then this routine returns SQLITE_FULL and does an immediate rollback.
31391 ** All subsequent write attempts also return SQLITE_FULL until there
31392 ** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
31393 ** reset.
31394 */
31395 static int pager_write(PgHdr *pPg){
31396   void *pData = pPg->pData;
31397   Pager *pPager = pPg->pPager;
31398   int rc = SQLITE_OK;
31399
31400   /* Check for errors
31401   */
31402   if( pPager->errCode ){ 
31403     return pPager->errCode;
31404   }
31405   if( pPager->readOnly ){
31406     return SQLITE_PERM;
31407   }
31408
31409   assert( !pPager->setMaster );
31410
31411   CHECK_PAGE(pPg);
31412
31413   /* If this page was previously acquired with noContent==1, that means
31414   ** we didn't really read in the content of the page.  This can happen
31415   ** (for example) when the page is being moved to the freelist.  But
31416   ** now we are (perhaps) moving the page off of the freelist for
31417   ** reuse and we need to know its original content so that content
31418   ** can be stored in the rollback journal.  So do the read at this
31419   ** time.
31420   */
31421   rc = pager_get_content(pPg);
31422   if( rc ){
31423     return rc;
31424   }
31425
31426   /* Mark the page as dirty.  If the page has already been written
31427   ** to the journal then we can return right away.
31428   */
31429   makeDirty(pPg);
31430   if( (pPg->flags&PGHDR_IN_JOURNAL)
31431    && (pageInStatement(pPg) || pPager->stmtInUse==0) 
31432   ){
31433     pPager->dirtyCache = 1;
31434     pPager->dbModified = 1;
31435   }else{
31436
31437     /* If we get this far, it means that the page needs to be
31438     ** written to the transaction journal or the ckeckpoint journal
31439     ** or both.
31440     **
31441     ** First check to see that the transaction journal exists and
31442     ** create it if it does not.
31443     */
31444     assert( pPager->state!=PAGER_UNLOCK );
31445     rc = sqlite3PagerBegin(pPg, 0);
31446     if( rc!=SQLITE_OK ){
31447       return rc;
31448     }
31449     assert( pPager->state>=PAGER_RESERVED );
31450     if( !pPager->journalOpen && pPager->useJournal
31451           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31452       rc = pager_open_journal(pPager);
31453       if( rc!=SQLITE_OK ) return rc;
31454     }
31455     pPager->dirtyCache = 1;
31456     pPager->dbModified = 1;
31457   
31458     /* The transaction journal now exists and we have a RESERVED or an
31459     ** EXCLUSIVE lock on the main database file.  Write the current page to
31460     ** the transaction journal if it is not there already.
31461     */
31462     if( !(pPg->flags&PGHDR_IN_JOURNAL) && (pPager->journalOpen || MEMDB) ){
31463       if( (int)pPg->pgno <= pPager->origDbSize ){
31464         if( MEMDB ){
31465           PAGERTRACE3("JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31466           rc = sqlite3PcachePreserve(pPg, 0);
31467           if( rc!=SQLITE_OK ){
31468             return rc;
31469           }
31470         }else{
31471           u32 cksum;
31472           char *pData2;
31473
31474           /* We should never write to the journal file the page that
31475           ** contains the database locks.  The following assert verifies
31476           ** that we do not. */
31477           assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
31478           pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31479           cksum = pager_cksum(pPager, (u8*)pData2);
31480           rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
31481           if( rc==SQLITE_OK ){
31482             rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
31483                                 pPager->journalOff + 4);
31484             pPager->journalOff += pPager->pageSize+4;
31485           }
31486           if( rc==SQLITE_OK ){
31487             rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
31488             pPager->journalOff += 4;
31489           }
31490           IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
31491                    pPager->journalOff, pPager->pageSize));
31492           PAGER_INCR(sqlite3_pager_writej_count);
31493           PAGERTRACE5("JOURNAL %d page %d needSync=%d hash(%08x)\n",
31494                PAGERID(pPager), pPg->pgno, 
31495                ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg));
31496
31497           /* An error has occured writing to the journal file. The 
31498           ** transaction will be rolled back by the layer above.
31499           */
31500           if( rc!=SQLITE_OK ){
31501             return rc;
31502           }
31503
31504           pPager->nRec++;
31505           assert( pPager->pInJournal!=0 );
31506           sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
31507           if( !pPager->noSync ){
31508             pPg->flags |= PGHDR_NEED_SYNC;
31509           }
31510           if( pPager->stmtInUse ){
31511             sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31512           }
31513         }
31514       }else{
31515         if( !pPager->journalStarted && !pPager->noSync ){
31516           pPg->flags |= PGHDR_NEED_SYNC;
31517         }
31518         PAGERTRACE4("APPEND %d page %d needSync=%d\n",
31519                 PAGERID(pPager), pPg->pgno,
31520                ((pPg->flags&PGHDR_NEED_SYNC)?1:0));
31521       }
31522       if( pPg->flags&PGHDR_NEED_SYNC ){
31523         pPager->needSync = 1;
31524       }
31525       pPg->flags |= PGHDR_IN_JOURNAL;
31526     }
31527   
31528     /* If the statement journal is open and the page is not in it,
31529     ** then write the current page to the statement journal.  Note that
31530     ** the statement journal format differs from the standard journal format
31531     ** in that it omits the checksums and the header.
31532     */
31533     if( pPager->stmtInUse 
31534      && !pageInStatement(pPg) 
31535      && (int)pPg->pgno<=pPager->stmtSize 
31536     ){
31537       assert( (pPg->flags&PGHDR_IN_JOURNAL) 
31538                  || (int)pPg->pgno>pPager->origDbSize );
31539       if( MEMDB ){
31540         rc = sqlite3PcachePreserve(pPg, 1);
31541         if( rc!=SQLITE_OK ){
31542           return rc;
31543         }
31544         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31545       }else{
31546         i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
31547         char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
31548         rc = write32bits(pPager->stfd, offset, pPg->pgno);
31549         if( rc==SQLITE_OK ){
31550           rc = sqlite3OsWrite(pPager->stfd, pData2, pPager->pageSize, offset+4);
31551         }
31552         PAGERTRACE3("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno);
31553         if( rc!=SQLITE_OK ){
31554           return rc;
31555         }
31556         pPager->stmtNRec++;
31557         assert( pPager->pInStmt!=0 );
31558         sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31559       }
31560     }
31561   }
31562
31563   /* Update the database size and return.
31564   */
31565   assert( pPager->state>=PAGER_SHARED );
31566   if( pPager->dbSize<(int)pPg->pgno ){
31567     pPager->dbSize = pPg->pgno;
31568     if( !MEMDB && pPager->dbSize==PENDING_BYTE/pPager->pageSize ){
31569       pPager->dbSize++;
31570     }
31571   }
31572   return rc;
31573 }
31574
31575 /*
31576 ** This function is used to mark a data-page as writable. It uses 
31577 ** pager_write() to open a journal file (if it is not already open)
31578 ** and write the page *pData to the journal.
31579 **
31580 ** The difference between this function and pager_write() is that this
31581 ** function also deals with the special case where 2 or more pages
31582 ** fit on a single disk sector. In this case all co-resident pages
31583 ** must have been written to the journal file before returning.
31584 */
31585 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
31586   int rc = SQLITE_OK;
31587
31588   PgHdr *pPg = pDbPage;
31589   Pager *pPager = pPg->pPager;
31590   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
31591
31592   if( !MEMDB && nPagePerSector>1 ){
31593     Pgno nPageCount;          /* Total number of pages in database file */
31594     Pgno pg1;                 /* First page of the sector pPg is located on. */
31595     int nPage;                /* Number of pages starting at pg1 to journal */
31596     int ii;
31597     int needSync = 0;
31598
31599     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
31600     ** header to be written between the pages journaled by this function.
31601     */
31602     assert( pPager->doNotSync==0 );
31603     pPager->doNotSync = 1;
31604
31605     /* This trick assumes that both the page-size and sector-size are
31606     ** an integer power of 2. It sets variable pg1 to the identifier
31607     ** of the first page of the sector pPg is located on.
31608     */
31609     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
31610
31611     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
31612     if( pPg->pgno>nPageCount ){
31613       nPage = (pPg->pgno - pg1)+1;
31614     }else if( (pg1+nPagePerSector-1)>nPageCount ){
31615       nPage = nPageCount+1-pg1;
31616     }else{
31617       nPage = nPagePerSector;
31618     }
31619     assert(nPage>0);
31620     assert(pg1<=pPg->pgno);
31621     assert((pg1+nPage)>pPg->pgno);
31622
31623     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
31624       Pgno pg = pg1+ii;
31625       PgHdr *pPage;
31626       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
31627         if( pg!=PAGER_MJ_PGNO(pPager) ){
31628           rc = sqlite3PagerGet(pPager, pg, &pPage);
31629           if( rc==SQLITE_OK ){
31630             rc = pager_write(pPage);
31631             if( pPage->flags&PGHDR_NEED_SYNC ){
31632               needSync = 1;
31633             }
31634             sqlite3PagerUnref(pPage);
31635           }
31636         }
31637       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
31638         if( pPage->flags&PGHDR_NEED_SYNC ){
31639           needSync = 1;
31640         }
31641         sqlite3PagerUnref(pPage);
31642       }
31643     }
31644
31645     /* If the PgHdr.needSync flag is set for any of the nPage pages 
31646     ** starting at pg1, then it needs to be set for all of them. Because
31647     ** writing to any of these nPage pages may damage the others, the
31648     ** journal file must contain sync()ed copies of all of them
31649     ** before any of them can be written out to the database file.
31650     */
31651     if( needSync ){
31652       assert( !MEMDB && pPager->noSync==0 );
31653       for(ii=0; ii<nPage && needSync; ii++){
31654         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
31655         if( pPage ) pPage->flags |= PGHDR_NEED_SYNC;
31656         sqlite3PagerUnref(pPage);
31657       }
31658       assert(pPager->needSync);
31659     }
31660
31661     assert( pPager->doNotSync==1 );
31662     pPager->doNotSync = 0;
31663   }else{
31664     rc = pager_write(pDbPage);
31665   }
31666   return rc;
31667 }
31668
31669 /*
31670 ** Return TRUE if the page given in the argument was previously passed
31671 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
31672 ** to change the content of the page.
31673 */
31674 #ifndef NDEBUG
31675 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
31676   return pPg->flags&PGHDR_DIRTY;
31677 }
31678 #endif
31679
31680 /*
31681 ** A call to this routine tells the pager that it is not necessary to
31682 ** write the information on page pPg back to the disk, even though
31683 ** that page might be marked as dirty.
31684 **
31685 ** The overlying software layer calls this routine when all of the data
31686 ** on the given page is unused.  The pager marks the page as clean so
31687 ** that it does not get written to disk.
31688 **
31689 ** Tests show that this optimization, together with the
31690 ** sqlite3PagerDontRollback() below, more than double the speed
31691 ** of large INSERT operations and quadruple the speed of large DELETEs.
31692 **
31693 ** When this routine is called, set the alwaysRollback flag to true.
31694 ** Subsequent calls to sqlite3PagerDontRollback() for the same page
31695 ** will thereafter be ignored.  This is necessary to avoid a problem
31696 ** where a page with data is added to the freelist during one part of
31697 ** a transaction then removed from the freelist during a later part
31698 ** of the same transaction and reused for some other purpose.  When it
31699 ** is first added to the freelist, this routine is called.  When reused,
31700 ** the sqlite3PagerDontRollback() routine is called.  But because the
31701 ** page contains critical data, we still need to be sure it gets
31702 ** rolled back in spite of the sqlite3PagerDontRollback() call.
31703 */
31704 SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage *pDbPage){
31705   PgHdr *pPg = pDbPage;
31706   Pager *pPager = pPg->pPager;
31707   int rc;
31708
31709   if( MEMDB || pPg->pgno>pPager->origDbSize ){
31710     return SQLITE_OK;
31711   }
31712   if( pPager->pAlwaysRollback==0 ){
31713     assert( pPager->pInJournal );
31714     pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->origDbSize);
31715     if( !pPager->pAlwaysRollback ){
31716       return SQLITE_NOMEM;
31717     }
31718   }
31719   rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);
31720
31721   if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && !pPager->stmtInUse ){
31722     assert( pPager->state>=PAGER_SHARED );
31723     if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
31724       /* If this pages is the last page in the file and the file has grown
31725       ** during the current transaction, then do NOT mark the page as clean.
31726       ** When the database file grows, we must make sure that the last page
31727       ** gets written at least once so that the disk file will be the correct
31728       ** size. If you do not write this page and the size of the file
31729       ** on the disk ends up being too small, that can lead to database
31730       ** corruption during the next transaction.
31731       */
31732     }else{
31733       PAGERTRACE3("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager));
31734       IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
31735       pPg->flags |= PGHDR_DONT_WRITE;
31736 #ifdef SQLITE_CHECK_PAGES
31737       pPg->pageHash = pager_pagehash(pPg);
31738 #endif
31739     }
31740   }
31741   return rc;
31742 }
31743
31744 /*
31745 ** A call to this routine tells the pager that if a rollback occurs,
31746 ** it is not necessary to restore the data on the given page.  This
31747 ** means that the pager does not have to record the given page in the
31748 ** rollback journal.
31749 **
31750 ** If we have not yet actually read the content of this page (if
31751 ** the PgHdr.needRead flag is set) then this routine acts as a promise
31752 ** that we will never need to read the page content in the future.
31753 ** so the needRead flag can be cleared at this point.
31754 */
31755 SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
31756   Pager *pPager = pPg->pPager;
31757
31758   assert( pPager->state>=PAGER_RESERVED );
31759
31760   /* If the journal file is not open, or DontWrite() has been called on
31761   ** this page (DontWrite() sets the alwaysRollback flag), then this
31762   ** function is a no-op.
31763   */
31764   if( pPager->journalOpen==0 
31765    || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
31766    || pPg->pgno>pPager->origDbSize
31767   ){
31768     return;
31769   }
31770   assert( !MEMDB );    /* For a memdb, pPager->journalOpen is always 0 */
31771
31772 #ifdef SQLITE_SECURE_DELETE
31773   if( (pPg->flags & PGHDR_IN_JOURNAL)!=0 || (int)pPg->pgno>pPager->origDbSize ){
31774     return;
31775   }
31776 #endif
31777
31778   /* If SECURE_DELETE is disabled, then there is no way that this
31779   ** routine can be called on a page for which sqlite3PagerDontWrite()
31780   ** has not been previously called during the same transaction.
31781   ** And if DontWrite() has previously been called, the following
31782   ** conditions must be met.
31783   **
31784   ** (Later:)  Not true.  If the database is corrupted by having duplicate
31785   ** pages on the freelist (ex: corrupt9.test) then the following is not
31786   ** necessarily true:
31787   */
31788   /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); */
31789
31790   assert( pPager->pInJournal!=0 );
31791   sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
31792   pPg->flags |= PGHDR_IN_JOURNAL;
31793   pPg->flags &= ~PGHDR_NEED_READ;
31794   if( pPager->stmtInUse ){
31795     assert( pPager->stmtSize >= pPager->origDbSize );
31796     sqlite3BitvecSet(pPager->pInStmt, pPg->pgno);
31797   }
31798   PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager));
31799   IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
31800 }
31801
31802
31803 /*
31804 ** This routine is called to increment the database file change-counter,
31805 ** stored at byte 24 of the pager file.
31806 */
31807 static int pager_incr_changecounter(Pager *pPager, int isDirect){
31808   PgHdr *pPgHdr;
31809   u32 change_counter;
31810   int rc = SQLITE_OK;
31811
31812 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
31813   assert( isDirect==0 );  /* isDirect is only true for atomic writes */
31814 #endif
31815   if( !pPager->changeCountDone ){
31816     /* Open page 1 of the file for writing. */
31817     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
31818     if( rc!=SQLITE_OK ) return rc;
31819
31820     if( !isDirect ){
31821       rc = sqlite3PagerWrite(pPgHdr);
31822       if( rc!=SQLITE_OK ){
31823         sqlite3PagerUnref(pPgHdr);
31824         return rc;
31825       }
31826     }
31827
31828     /* Increment the value just read and write it back to byte 24. */
31829     change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
31830     change_counter++;
31831     put32bits(((char*)pPgHdr->pData)+24, change_counter);
31832
31833 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31834     if( isDirect && pPager->fd->pMethods ){
31835       const void *zBuf = pPgHdr->pData;
31836       rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
31837     }
31838 #endif
31839
31840     /* Release the page reference. */
31841     sqlite3PagerUnref(pPgHdr);
31842     pPager->changeCountDone = 1;
31843   }
31844   return rc;
31845 }
31846
31847 /*
31848 ** Sync the pager file to disk.
31849 */
31850 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
31851   int rc;
31852   if( MEMDB ){
31853     rc = SQLITE_OK;
31854   }else{
31855     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
31856   }
31857   return rc;
31858 }
31859
31860 /*
31861 ** Sync the database file for the pager pPager. zMaster points to the name
31862 ** of a master journal file that should be written into the individual
31863 ** journal file. zMaster may be NULL, which is interpreted as no master
31864 ** journal (a single database transaction).
31865 **
31866 ** This routine ensures that the journal is synced, all dirty pages written
31867 ** to the database file and the database file synced. The only thing that
31868 ** remains to commit the transaction is to delete the journal file (or
31869 ** master journal file if specified).
31870 **
31871 ** Note that if zMaster==NULL, this does not overwrite a previous value
31872 ** passed to an sqlite3PagerCommitPhaseOne() call.
31873 **
31874 ** If parameter nTrunc is non-zero, then the pager file is truncated to
31875 ** nTrunc pages (this is used by auto-vacuum databases).
31876 **
31877 ** If the final parameter - noSync - is true, then the database file itself
31878 ** is not synced. The caller must call sqlite3PagerSync() directly to
31879 ** sync the database file before calling CommitPhaseTwo() to delete the
31880 ** journal file in this case.
31881 */
31882 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
31883   Pager *pPager, 
31884   const char *zMaster, 
31885   Pgno nTrunc,
31886   int noSync
31887 ){
31888   int rc = SQLITE_OK;
31889
31890   if( pPager->errCode ){
31891     return pPager->errCode;
31892   }
31893
31894   /* If no changes have been made, we can leave the transaction early.
31895   */
31896   if( pPager->dbModified==0 &&
31897         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
31898           pPager->exclusiveMode!=0) ){
31899     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
31900     return SQLITE_OK;
31901   }
31902
31903   PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
31904       pPager->zFilename, zMaster, nTrunc);
31905
31906   /* If this is an in-memory db, or no pages have been written to, or this
31907   ** function has already been called, it is a no-op.
31908   */
31909   if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
31910     PgHdr *pPg;
31911
31912 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31913     /* The atomic-write optimization can be used if all of the
31914     ** following are true:
31915     **
31916     **    + The file-system supports the atomic-write property for
31917     **      blocks of size page-size, and
31918     **    + This commit is not part of a multi-file transaction, and
31919     **    + Exactly one page has been modified and store in the journal file.
31920     **
31921     ** If the optimization can be used, then the journal file will never
31922     ** be created for this transaction.
31923     */
31924     int useAtomicWrite;
31925     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
31926     useAtomicWrite = (
31927         !zMaster && 
31928         pPager->journalOpen &&
31929         pPager->journalOff==jrnlBufferSize(pPager) && 
31930         nTrunc==0 && 
31931         (pPg==0 || pPg->pDirty==0)
31932     );
31933     assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
31934     if( useAtomicWrite ){
31935       /* Update the nRec field in the journal file. */
31936       int offset = pPager->journalHdr + sizeof(aJournalMagic);
31937       assert(pPager->nRec==1);
31938       rc = write32bits(pPager->jfd, offset, pPager->nRec);
31939
31940       /* Update the db file change counter. The following call will modify
31941       ** the in-memory representation of page 1 to include the updated
31942       ** change counter and then write page 1 directly to the database
31943       ** file. Because of the atomic-write property of the host file-system, 
31944       ** this is safe.
31945       */
31946       if( rc==SQLITE_OK ){
31947         rc = pager_incr_changecounter(pPager, 1);
31948       }
31949     }else{
31950       rc = sqlite3JournalCreate(pPager->jfd);
31951     }
31952
31953     if( !useAtomicWrite && rc==SQLITE_OK )
31954 #endif
31955
31956     /* If a master journal file name has already been written to the
31957     ** journal file, then no sync is required. This happens when it is
31958     ** written, then the process fails to upgrade from a RESERVED to an
31959     ** EXCLUSIVE lock. The next time the process tries to commit the
31960     ** transaction the m-j name will have already been written.
31961     */
31962     if( !pPager->setMaster ){
31963       rc = pager_incr_changecounter(pPager, 0);
31964       if( rc!=SQLITE_OK ) goto sync_exit;
31965       if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
31966 #ifndef SQLITE_OMIT_AUTOVACUUM
31967         if( nTrunc!=0 ){
31968           /* If this transaction has made the database smaller, then all pages
31969           ** being discarded by the truncation must be written to the journal
31970           ** file.
31971           */
31972           Pgno i;
31973           int iSkip = PAGER_MJ_PGNO(pPager);
31974           for( i=nTrunc+1; i<=pPager->origDbSize; i++ ){
31975             if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
31976               rc = sqlite3PagerGet(pPager, i, &pPg);
31977               if( rc!=SQLITE_OK ) goto sync_exit;
31978               rc = sqlite3PagerWrite(pPg);
31979               sqlite3PagerUnref(pPg);
31980               if( rc!=SQLITE_OK ) goto sync_exit;
31981             }
31982           } 
31983         }
31984 #endif
31985         rc = writeMasterJournal(pPager, zMaster);
31986         if( rc!=SQLITE_OK ) goto sync_exit;
31987         rc = syncJournal(pPager);
31988       }
31989     }
31990     if( rc!=SQLITE_OK ) goto sync_exit;
31991
31992 #ifndef SQLITE_OMIT_AUTOVACUUM
31993     if( nTrunc!=0 ){
31994       rc = sqlite3PagerTruncate(pPager, nTrunc);
31995       if( rc!=SQLITE_OK ) goto sync_exit;
31996     }
31997 #endif
31998
31999     /* Write all dirty pages to the database file */
32000     pPg = sqlite3PcacheDirtyList(pPager->pPCache);
32001     rc = pager_write_pagelist(pPg);
32002     if( rc!=SQLITE_OK ){
32003       assert( rc!=SQLITE_IOERR_BLOCKED );
32004       /* The error might have left the dirty list all fouled up here,
32005       ** but that does not matter because if the if the dirty list did
32006       ** get corrupted, then the transaction will roll back and
32007       ** discard the dirty list.  There is an assert in
32008       ** pager_get_all_dirty_pages() that verifies that no attempt
32009       ** is made to use an invalid dirty list.
32010       */
32011       goto sync_exit;
32012     }
32013     sqlite3PcacheCleanAll(pPager->pPCache);
32014
32015     /* Sync the database file. */
32016     if( !pPager->noSync && !noSync ){
32017       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
32018     }
32019     IOTRACE(("DBSYNC %p\n", pPager))
32020
32021     pPager->state = PAGER_SYNCED;
32022   }else if( MEMDB && nTrunc!=0 ){
32023     rc = sqlite3PagerTruncate(pPager, nTrunc);
32024   }
32025
32026 sync_exit:
32027   if( rc==SQLITE_IOERR_BLOCKED ){
32028     /* pager_incr_changecounter() may attempt to obtain an exclusive
32029      * lock to spill the cache and return IOERR_BLOCKED. But since 
32030      * there is no chance the cache is inconsistent, it is
32031      * better to return SQLITE_BUSY.
32032      */
32033     rc = SQLITE_BUSY;
32034   }
32035   return rc;
32036 }
32037
32038
32039 /*
32040 ** Commit all changes to the database and release the write lock.
32041 **
32042 ** If the commit fails for any reason, a rollback attempt is made
32043 ** and an error code is returned.  If the commit worked, SQLITE_OK
32044 ** is returned.
32045 */
32046 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
32047   int rc = SQLITE_OK;
32048
32049   if( pPager->errCode ){
32050     return pPager->errCode;
32051   }
32052   if( pPager->state<PAGER_RESERVED ){
32053     return SQLITE_ERROR;
32054   }
32055   if( pPager->dbModified==0 &&
32056         (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
32057           pPager->exclusiveMode!=0) ){
32058     assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
32059     return SQLITE_OK;
32060   }
32061   PAGERTRACE2("COMMIT %d\n", PAGERID(pPager));
32062   if( MEMDB ){
32063     sqlite3PcacheCommit(pPager->pPCache, 0);
32064     sqlite3PcacheCleanAll(pPager->pPCache);
32065     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
32066     pPager->state = PAGER_SHARED;
32067   }else{
32068     assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache );
32069     rc = pager_end_transaction(pPager, pPager->setMaster);
32070     rc = pager_error(pPager, rc);
32071   }
32072   return rc;
32073 }
32074
32075 /*
32076 ** Rollback all changes.  The database falls back to PAGER_SHARED mode.
32077 ** All in-memory cache pages revert to their original data contents.
32078 ** The journal is deleted.
32079 **
32080 ** This routine cannot fail unless some other process is not following
32081 ** the correct locking protocol or unless some other
32082 ** process is writing trash into the journal file (SQLITE_CORRUPT) or
32083 ** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
32084 ** codes are returned for all these occasions.  Otherwise,
32085 ** SQLITE_OK is returned.
32086 */
32087 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
32088   int rc = SQLITE_OK;
32089   PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
32090   if( MEMDB ){
32091     sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
32092     sqlite3PcacheRollback(pPager->pPCache, 0, pPager->xReiniter);
32093     sqlite3PcacheCleanAll(pPager->pPCache);
32094     sqlite3PcacheAssertFlags(pPager->pPCache, 0, PGHDR_IN_JOURNAL);
32095     pPager->dbSize = pPager->origDbSize;
32096     pager_truncate_cache(pPager);
32097     pPager->stmtInUse = 0;
32098     pPager->state = PAGER_SHARED;
32099   }else if( !pPager->dirtyCache || !pPager->journalOpen ){
32100     rc = pager_end_transaction(pPager, pPager->setMaster);
32101   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
32102     if( pPager->state>=PAGER_EXCLUSIVE ){
32103       pager_playback(pPager, 0);
32104     }
32105     rc = pPager->errCode;
32106   }else{
32107     if( pPager->state==PAGER_RESERVED ){
32108       int rc2;
32109       rc = pager_playback(pPager, 0);
32110       rc2 = pager_end_transaction(pPager, pPager->setMaster);
32111       if( rc==SQLITE_OK ){
32112         rc = rc2;
32113       }
32114     }else{
32115       rc = pager_playback(pPager, 0);
32116     }
32117
32118     pPager->dbSize = -1;
32119
32120     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
32121     ** cache. So call pager_error() on the way out to make any error 
32122     ** persistent.
32123     */
32124     rc = pager_error(pPager, rc);
32125   }
32126   return rc;
32127 }
32128
32129 /*
32130 ** Return TRUE if the database file is opened read-only.  Return FALSE
32131 ** if the database is (in theory) writable.
32132 */
32133 SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
32134   return pPager->readOnly;
32135 }
32136
32137 /*
32138 ** Return the number of references to the pager.
32139 */
32140 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
32141   return sqlite3PcacheRefCount(pPager->pPCache);
32142 }
32143
32144 /*
32145 ** Return the number of references to the specified page.
32146 */
32147 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
32148   return sqlite3PcachePageRefcount(pPage);
32149 }
32150
32151 #ifdef SQLITE_TEST
32152 /*
32153 ** This routine is used for testing and analysis only.
32154 */
32155 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
32156   static int a[11];
32157   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
32158   a[1] = sqlite3PcachePagecount(pPager->pPCache);
32159   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
32160   a[3] = pPager->dbSize;
32161   a[4] = pPager->state;
32162   a[5] = pPager->errCode;
32163   a[6] = pPager->nHit;
32164   a[7] = pPager->nMiss;
32165   a[8] = 0;  /* Used to be pPager->nOvfl */
32166   a[9] = pPager->nRead;
32167   a[10] = pPager->nWrite;
32168   return a;
32169 }
32170 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
32171   return MEMDB;
32172 }
32173 #endif
32174
32175 /*
32176 ** Set the statement rollback point.
32177 **
32178 ** This routine should be called with the transaction journal already
32179 ** open.  A new statement journal is created that can be used to rollback
32180 ** changes of a single SQL command within a larger transaction.
32181 */
32182 static int pagerStmtBegin(Pager *pPager){
32183   int rc;
32184   assert( !pPager->stmtInUse );
32185   assert( pPager->state>=PAGER_SHARED );
32186   assert( pPager->dbSize>=0 );
32187   PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
32188   if( MEMDB ){
32189     pPager->stmtInUse = 1;
32190     pPager->stmtSize = pPager->dbSize;
32191     return SQLITE_OK;
32192   }
32193   if( !pPager->journalOpen ){
32194     pPager->stmtAutoopen = 1;
32195     return SQLITE_OK;
32196   }
32197   assert( pPager->journalOpen );
32198   assert( pPager->pInStmt==0 );
32199   pPager->pInStmt = sqlite3BitvecCreate(pPager->dbSize);
32200   if( pPager->pInStmt==0 ){
32201     /* sqlite3OsLock(pPager->fd, SHARED_LOCK); */
32202     return SQLITE_NOMEM;
32203   }
32204   pPager->stmtJSize = pPager->journalOff;
32205   pPager->stmtSize = pPager->dbSize;
32206   pPager->stmtHdrOff = 0;
32207   pPager->stmtCksum = pPager->cksumInit;
32208   if( !pPager->stmtOpen ){
32209     rc = sqlite3PagerOpentemp(pPager, pPager->stfd, SQLITE_OPEN_SUBJOURNAL);
32210     if( rc ){
32211       goto stmt_begin_failed;
32212     }
32213     pPager->stmtOpen = 1;
32214     pPager->stmtNRec = 0;
32215   }
32216   pPager->stmtInUse = 1;
32217   return SQLITE_OK;
32218  
32219 stmt_begin_failed:
32220   if( pPager->pInStmt ){
32221     sqlite3BitvecDestroy(pPager->pInStmt);
32222     pPager->pInStmt = 0;
32223   }
32224   return rc;
32225 }
32226 SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
32227   int rc;
32228   rc = pagerStmtBegin(pPager);
32229   return rc;
32230 }
32231
32232 /*
32233 ** Commit a statement.
32234 */
32235 SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
32236   if( pPager->stmtInUse ){
32237     PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
32238     if( !MEMDB ){
32239       sqlite3BitvecDestroy(pPager->pInStmt);
32240       pPager->pInStmt = 0;
32241     }else{
32242       sqlite3PcacheCommit(pPager->pPCache, 1);
32243     }
32244     pPager->stmtNRec = 0;
32245     pPager->stmtInUse = 0;
32246   }
32247   pPager->stmtAutoopen = 0;
32248   return SQLITE_OK;
32249 }
32250
32251 /*
32252 ** Rollback a statement.
32253 */
32254 SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
32255   int rc;
32256   if( pPager->stmtInUse ){
32257     PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
32258     if( MEMDB ){
32259       sqlite3PcacheRollback(pPager->pPCache, 1, pPager->xReiniter);
32260       pPager->dbSize = pPager->stmtSize;
32261       pager_truncate_cache(pPager);
32262       rc = SQLITE_OK;
32263     }else{
32264       rc = pager_stmt_playback(pPager);
32265     }
32266     sqlite3PagerStmtCommit(pPager);
32267   }else{
32268     rc = SQLITE_OK;
32269   }
32270   pPager->stmtAutoopen = 0;
32271   return rc;
32272 }
32273
32274 /*
32275 ** Return the full pathname of the database file.
32276 */
32277 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
32278   return pPager->zFilename;
32279 }
32280
32281 /*
32282 ** Return the VFS structure for the pager.
32283 */
32284 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
32285   return pPager->pVfs;
32286 }
32287
32288 /*
32289 ** Return the file handle for the database file associated
32290 ** with the pager.  This might return NULL if the file has
32291 ** not yet been opened.
32292 */
32293 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
32294   return pPager->fd;
32295 }
32296
32297 /*
32298 ** Return the directory of the database file.
32299 */
32300 SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
32301   return pPager->zDirectory;
32302 }
32303
32304 /*
32305 ** Return the full pathname of the journal file.
32306 */
32307 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
32308   return pPager->zJournal;
32309 }
32310
32311 /*
32312 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
32313 ** if fsync()s are executed normally.
32314 */
32315 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
32316   return pPager->noSync;
32317 }
32318
32319 #ifdef SQLITE_HAS_CODEC
32320 /*
32321 ** Set the codec for this pager
32322 */
32323 SQLITE_PRIVATE void sqlite3PagerSetCodec(
32324   Pager *pPager,
32325   void *(*xCodec)(void*,void*,Pgno,int),
32326   void *pCodecArg
32327 ){
32328   pPager->xCodec = xCodec;
32329   pPager->pCodecArg = pCodecArg;
32330 }
32331 #endif
32332
32333 #ifndef SQLITE_OMIT_AUTOVACUUM
32334 /*
32335 ** Move the page pPg to location pgno in the file.
32336 **
32337 ** There must be no references to the page previously located at
32338 ** pgno (which we call pPgOld) though that page is allowed to be
32339 ** in cache.  If the page previously located at pgno is not already
32340 ** in the rollback journal, it is not put there by by this routine.
32341 **
32342 ** References to the page pPg remain valid. Updating any
32343 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
32344 ** allocated along with the page) is the responsibility of the caller.
32345 **
32346 ** A transaction must be active when this routine is called. It used to be
32347 ** required that a statement transaction was not active, but this restriction
32348 ** has been removed (CREATE INDEX needs to move a page when a statement
32349 ** transaction is active).
32350 **
32351 ** If the fourth argument, isCommit, is non-zero, then this page is being
32352 ** moved as part of a database reorganization just before the transaction 
32353 ** is being committed. In this case, it is guaranteed that the database page 
32354 ** pPg refers to will not be written to again within this transaction.
32355 */
32356 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
32357   PgHdr *pPgOld;  /* The page being overwritten. */
32358   Pgno needSyncPgno = 0;
32359
32360   assert( pPg->nRef>0 );
32361
32362   PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
32363       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno);
32364   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
32365
32366   pager_get_content(pPg);
32367
32368   /* If the journal needs to be sync()ed before page pPg->pgno can
32369   ** be written to, store pPg->pgno in local variable needSyncPgno.
32370   **
32371   ** If the isCommit flag is set, there is no need to remember that
32372   ** the journal needs to be sync()ed before database page pPg->pgno 
32373   ** can be written to. The caller has already promised not to write to it.
32374   */
32375   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
32376     needSyncPgno = pPg->pgno;
32377     assert( (pPg->flags&PGHDR_IN_JOURNAL) || (int)pgno>pPager->origDbSize );
32378     assert( pPg->flags&PGHDR_DIRTY );
32379     assert( pPager->needSync );
32380   }
32381
32382   /* If the cache contains a page with page-number pgno, remove it
32383   ** from its hash chain. Also, if the PgHdr.needSync was set for 
32384   ** page pgno before the 'move' operation, it needs to be retained 
32385   ** for the page moved there.
32386   */
32387   pPg->flags &= ~(PGHDR_NEED_SYNC|PGHDR_IN_JOURNAL);
32388   pPgOld = pager_lookup(pPager, pgno);
32389   assert( !pPgOld || pPgOld->nRef==1 );
32390   if( pPgOld ){
32391     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
32392   }
32393   if( sqlite3BitvecTest(pPager->pInJournal, pgno) ){
32394     assert( !MEMDB );
32395     pPg->flags |= PGHDR_IN_JOURNAL;
32396   }
32397
32398   sqlite3PcacheMove(pPg, pgno);
32399   if( pPgOld ){
32400     sqlite3PcacheMove(pPgOld, 0);
32401     sqlite3PcacheRelease(pPgOld);
32402   }
32403
32404   makeDirty(pPg);
32405   pPager->dirtyCache = 1;
32406   pPager->dbModified = 1;
32407
32408   if( needSyncPgno ){
32409     /* If needSyncPgno is non-zero, then the journal file needs to be 
32410     ** sync()ed before any data is written to database file page needSyncPgno.
32411     ** Currently, no such page exists in the page-cache and the 
32412     ** "is journaled" bitvec flag has been set. This needs to be remedied by
32413     ** loading the page into the pager-cache and setting the PgHdr.needSync 
32414     ** flag.
32415     **
32416     ** If the attempt to load the page into the page-cache fails, (due
32417     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
32418     ** array. Otherwise, if the page is loaded and written again in
32419     ** this transaction, it may be written to the database file before
32420     ** it is synced into the journal file. This way, it may end up in
32421     ** the journal file twice, but that is not a problem.
32422     **
32423     ** The sqlite3PagerGet() call may cause the journal to sync. So make
32424     ** sure the Pager.needSync flag is set too.
32425     */
32426     int rc;
32427     PgHdr *pPgHdr;
32428     assert( pPager->needSync );
32429     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
32430     if( rc!=SQLITE_OK ){
32431       if( pPager->pInJournal && (int)needSyncPgno<=pPager->origDbSize ){
32432         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
32433       }
32434       return rc;
32435     }
32436     pPager->needSync = 1;
32437     assert( pPager->noSync==0 && !MEMDB );
32438     pPgHdr->flags |= PGHDR_NEED_SYNC;
32439     pPgHdr->flags |= PGHDR_IN_JOURNAL;
32440     makeDirty(pPgHdr);
32441     sqlite3PagerUnref(pPgHdr);
32442   }
32443
32444   return SQLITE_OK;
32445 }
32446 #endif
32447
32448 /*
32449 ** Return a pointer to the data for the specified page.
32450 */
32451 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
32452   assert( pPg->nRef>0 || pPg->pPager->memDb );
32453   return pPg->pData;
32454 }
32455
32456 /*
32457 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
32458 ** allocated along with the specified page.
32459 */
32460 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
32461   Pager *pPager = pPg->pPager;
32462   return (pPager?pPg->pExtra:0);
32463 }
32464
32465 /*
32466 ** Get/set the locking-mode for this pager. Parameter eMode must be one
32467 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
32468 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
32469 ** the locking-mode is set to the value specified.
32470 **
32471 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
32472 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
32473 ** locking-mode.
32474 */
32475 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
32476   assert( eMode==PAGER_LOCKINGMODE_QUERY
32477             || eMode==PAGER_LOCKINGMODE_NORMAL
32478             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
32479   assert( PAGER_LOCKINGMODE_QUERY<0 );
32480   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
32481   if( eMode>=0 && !pPager->tempFile ){
32482     pPager->exclusiveMode = eMode;
32483   }
32484   return (int)pPager->exclusiveMode;
32485 }
32486
32487 /*
32488 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
32489 **
32490 **    PAGER_JOURNALMODE_QUERY
32491 **    PAGER_JOURNALMODE_DELETE
32492 **    PAGER_JOURNALMODE_TRUNCATE
32493 **    PAGER_JOURNALMODE_PERSIST
32494 **    PAGER_JOURNALMODE_OFF
32495 **
32496 ** If the parameter is not _QUERY, then the journal-mode is set to the
32497 ** value specified.
32498 **
32499 ** The returned indicate the current (possibly updated)
32500 ** journal-mode.
32501 */
32502 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
32503   assert( eMode==PAGER_JOURNALMODE_QUERY
32504             || eMode==PAGER_JOURNALMODE_DELETE
32505             || eMode==PAGER_JOURNALMODE_TRUNCATE
32506             || eMode==PAGER_JOURNALMODE_PERSIST
32507             || eMode==PAGER_JOURNALMODE_OFF );
32508   assert( PAGER_JOURNALMODE_QUERY<0 );
32509   if( eMode>=0 ){
32510     pPager->journalMode = eMode;
32511   }else{
32512     assert( eMode==PAGER_JOURNALMODE_QUERY );
32513   }
32514   return (int)pPager->journalMode;
32515 }
32516
32517 /*
32518 ** Get/set the size-limit used for persistent journal files.
32519 */
32520 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
32521   if( iLimit>=-1 ){
32522     pPager->journalSizeLimit = iLimit;
32523   }
32524   return pPager->journalSizeLimit;
32525 }
32526
32527 #endif /* SQLITE_OMIT_DISKIO */
32528
32529 /************** End of pager.c ***********************************************/
32530 /************** Begin file btmutex.c *****************************************/
32531 /*
32532 ** 2007 August 27
32533 **
32534 ** The author disclaims copyright to this source code.  In place of
32535 ** a legal notice, here is a blessing:
32536 **
32537 **    May you do good and not evil.
32538 **    May you find forgiveness for yourself and forgive others.
32539 **    May you share freely, never taking more than you give.
32540 **
32541 *************************************************************************
32542 **
32543 ** $Id: btmutex.c,v 1.11 2008/10/07 15:25:48 drh Exp $
32544 **
32545 ** This file contains code used to implement mutexes on Btree objects.
32546 ** This code really belongs in btree.c.  But btree.c is getting too
32547 ** big and we want to break it down some.  This packaged seemed like
32548 ** a good breakout.
32549 */
32550 /************** Include btreeInt.h in the middle of btmutex.c ****************/
32551 /************** Begin file btreeInt.h ****************************************/
32552 /*
32553 ** 2004 April 6
32554 **
32555 ** The author disclaims copyright to this source code.  In place of
32556 ** a legal notice, here is a blessing:
32557 **
32558 **    May you do good and not evil.
32559 **    May you find forgiveness for yourself and forgive others.
32560 **    May you share freely, never taking more than you give.
32561 **
32562 *************************************************************************
32563 ** $Id: btreeInt.h,v 1.34 2008/09/30 17:18:17 drh Exp $
32564 **
32565 ** This file implements a external (disk-based) database using BTrees.
32566 ** For a detailed discussion of BTrees, refer to
32567 **
32568 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
32569 **     "Sorting And Searching", pages 473-480. Addison-Wesley
32570 **     Publishing Company, Reading, Massachusetts.
32571 **
32572 ** The basic idea is that each page of the file contains N database
32573 ** entries and N+1 pointers to subpages.
32574 **
32575 **   ----------------------------------------------------------------
32576 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
32577 **   ----------------------------------------------------------------
32578 **
32579 ** All of the keys on the page that Ptr(0) points to have values less
32580 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
32581 ** values greater than Key(0) and less than Key(1).  All of the keys
32582 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
32583 ** so forth.
32584 **
32585 ** Finding a particular key requires reading O(log(M)) pages from the 
32586 ** disk where M is the number of entries in the tree.
32587 **
32588 ** In this implementation, a single file can hold one or more separate 
32589 ** BTrees.  Each BTree is identified by the index of its root page.  The
32590 ** key and data for any entry are combined to form the "payload".  A
32591 ** fixed amount of payload can be carried directly on the database
32592 ** page.  If the payload is larger than the preset amount then surplus
32593 ** bytes are stored on overflow pages.  The payload for an entry
32594 ** and the preceding pointer are combined to form a "Cell".  Each 
32595 ** page has a small header which contains the Ptr(N) pointer and other
32596 ** information such as the size of key and data.
32597 **
32598 ** FORMAT DETAILS
32599 **
32600 ** The file is divided into pages.  The first page is called page 1,
32601 ** the second is page 2, and so forth.  A page number of zero indicates
32602 ** "no such page".  The page size can be anything between 512 and 65536.
32603 ** Each page can be either a btree page, a freelist page or an overflow
32604 ** page.
32605 **
32606 ** The first page is always a btree page.  The first 100 bytes of the first
32607 ** page contain a special header (the "file header") that describes the file.
32608 ** The format of the file header is as follows:
32609 **
32610 **   OFFSET   SIZE    DESCRIPTION
32611 **      0      16     Header string: "SQLite format 3\000"
32612 **     16       2     Page size in bytes.  
32613 **     18       1     File format write version
32614 **     19       1     File format read version
32615 **     20       1     Bytes of unused space at the end of each page
32616 **     21       1     Max embedded payload fraction
32617 **     22       1     Min embedded payload fraction
32618 **     23       1     Min leaf payload fraction
32619 **     24       4     File change counter
32620 **     28       4     Reserved for future use
32621 **     32       4     First freelist page
32622 **     36       4     Number of freelist pages in the file
32623 **     40      60     15 4-byte meta values passed to higher layers
32624 **
32625 ** All of the integer values are big-endian (most significant byte first).
32626 **
32627 ** The file change counter is incremented when the database is changed
32628 ** This counter allows other processes to know when the file has changed
32629 ** and thus when they need to flush their cache.
32630 **
32631 ** The max embedded payload fraction is the amount of the total usable
32632 ** space in a page that can be consumed by a single cell for standard
32633 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
32634 ** is to limit the maximum cell size so that at least 4 cells will fit
32635 ** on one page.  Thus the default max embedded payload fraction is 64.
32636 **
32637 ** If the payload for a cell is larger than the max payload, then extra
32638 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
32639 ** as many bytes as possible are moved into the overflow pages without letting
32640 ** the cell size drop below the min embedded payload fraction.
32641 **
32642 ** The min leaf payload fraction is like the min embedded payload fraction
32643 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
32644 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
32645 ** not specified in the header.
32646 **
32647 ** Each btree pages is divided into three sections:  The header, the
32648 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
32649 ** file header that occurs before the page header.
32650 **
32651 **      |----------------|
32652 **      | file header    |   100 bytes.  Page 1 only.
32653 **      |----------------|
32654 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
32655 **      |----------------|
32656 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
32657 **      | array          |   |  Grows downward
32658 **      |                |   v
32659 **      |----------------|
32660 **      | unallocated    |
32661 **      | space          |
32662 **      |----------------|   ^  Grows upwards
32663 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
32664 **      | area           |   |  and free space fragments.
32665 **      |----------------|
32666 **
32667 ** The page headers looks like this:
32668 **
32669 **   OFFSET   SIZE     DESCRIPTION
32670 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
32671 **      1       2      byte offset to the first freeblock
32672 **      3       2      number of cells on this page
32673 **      5       2      first byte of the cell content area
32674 **      7       1      number of fragmented free bytes
32675 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
32676 **
32677 ** The flags define the format of this btree page.  The leaf flag means that
32678 ** this page has no children.  The zerodata flag means that this page carries
32679 ** only keys and no data.  The intkey flag means that the key is a integer
32680 ** which is stored in the key size entry of the cell header rather than in
32681 ** the payload area.
32682 **
32683 ** The cell pointer array begins on the first byte after the page header.
32684 ** The cell pointer array contains zero or more 2-byte numbers which are
32685 ** offsets from the beginning of the page to the cell content in the cell
32686 ** content area.  The cell pointers occur in sorted order.  The system strives
32687 ** to keep free space after the last cell pointer so that new cells can
32688 ** be easily added without having to defragment the page.
32689 **
32690 ** Cell content is stored at the very end of the page and grows toward the
32691 ** beginning of the page.
32692 **
32693 ** Unused space within the cell content area is collected into a linked list of
32694 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
32695 ** to the first freeblock is given in the header.  Freeblocks occur in
32696 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
32697 ** any group of 3 or fewer unused bytes in the cell content area cannot
32698 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
32699 ** a fragment.  The total number of bytes in all fragments is recorded.
32700 ** in the page header at offset 7.
32701 **
32702 **    SIZE    DESCRIPTION
32703 **      2     Byte offset of the next freeblock
32704 **      2     Bytes in this freeblock
32705 **
32706 ** Cells are of variable length.  Cells are stored in the cell content area at
32707 ** the end of the page.  Pointers to the cells are in the cell pointer array
32708 ** that immediately follows the page header.  Cells is not necessarily
32709 ** contiguous or in order, but cell pointers are contiguous and in order.
32710 **
32711 ** Cell content makes use of variable length integers.  A variable
32712 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
32713 ** byte are used.  The integer consists of all bytes that have bit 8 set and
32714 ** the first byte with bit 8 clear.  The most significant byte of the integer
32715 ** appears first.  A variable-length integer may not be more than 9 bytes long.
32716 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
32717 ** allows a 64-bit integer to be encoded in 9 bytes.
32718 **
32719 **    0x00                      becomes  0x00000000
32720 **    0x7f                      becomes  0x0000007f
32721 **    0x81 0x00                 becomes  0x00000080
32722 **    0x82 0x00                 becomes  0x00000100
32723 **    0x80 0x7f                 becomes  0x0000007f
32724 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
32725 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
32726 **
32727 ** Variable length integers are used for rowids and to hold the number of
32728 ** bytes of key and data in a btree cell.
32729 **
32730 ** The content of a cell looks like this:
32731 **
32732 **    SIZE    DESCRIPTION
32733 **      4     Page number of the left child. Omitted if leaf flag is set.
32734 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
32735 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
32736 **      *     Payload
32737 **      4     First page of the overflow chain.  Omitted if no overflow
32738 **
32739 ** Overflow pages form a linked list.  Each page except the last is completely
32740 ** filled with data (pagesize - 4 bytes).  The last page can have as little
32741 ** as 1 byte of data.
32742 **
32743 **    SIZE    DESCRIPTION
32744 **      4     Page number of next overflow page
32745 **      *     Data
32746 **
32747 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
32748 ** file header points to the first in a linked list of trunk page.  Each trunk
32749 ** page points to multiple leaf pages.  The content of a leaf page is
32750 ** unspecified.  A trunk page looks like this:
32751 **
32752 **    SIZE    DESCRIPTION
32753 **      4     Page number of next trunk page
32754 **      4     Number of leaf pointers on this page
32755 **      *     zero or more pages numbers of leaves
32756 */
32757
32758 /* Round up a number to the next larger multiple of 8.  This is used
32759 ** to force 8-byte alignment on 64-bit architectures.
32760 */
32761 #define ROUND8(x)   ((x+7)&~7)
32762
32763
32764 /* The following value is the maximum cell size assuming a maximum page
32765 ** size give above.
32766 */
32767 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
32768
32769 /* The maximum number of cells on a single page of the database.  This
32770 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
32771 ** plus 2 bytes for the index to the cell in the page header).  Such
32772 ** small cells will be rare, but they are possible.
32773 */
32774 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
32775
32776 /* Forward declarations */
32777 typedef struct MemPage MemPage;
32778 typedef struct BtLock BtLock;
32779
32780 /*
32781 ** This is a magic string that appears at the beginning of every
32782 ** SQLite database in order to identify the file as a real database.
32783 **
32784 ** You can change this value at compile-time by specifying a
32785 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
32786 ** header must be exactly 16 bytes including the zero-terminator so
32787 ** the string itself should be 15 characters long.  If you change
32788 ** the header, then your custom library will not be able to read 
32789 ** databases generated by the standard tools and the standard tools
32790 ** will not be able to read databases created by your custom library.
32791 */
32792 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
32793 #  define SQLITE_FILE_HEADER "SQLite format 3"
32794 #endif
32795
32796 /*
32797 ** Page type flags.  An ORed combination of these flags appear as the
32798 ** first byte of on-disk image of every BTree page.
32799 */
32800 #define PTF_INTKEY    0x01
32801 #define PTF_ZERODATA  0x02
32802 #define PTF_LEAFDATA  0x04
32803 #define PTF_LEAF      0x08
32804
32805 /*
32806 ** As each page of the file is loaded into memory, an instance of the following
32807 ** structure is appended and initialized to zero.  This structure stores
32808 ** information about the page that is decoded from the raw file page.
32809 **
32810 ** The pParent field points back to the parent page.  This allows us to
32811 ** walk up the BTree from any leaf to the root.  Care must be taken to
32812 ** unref() the parent page pointer when this page is no longer referenced.
32813 ** The pageDestructor() routine handles that chore.
32814 **
32815 ** Access to all fields of this structure is controlled by the mutex
32816 ** stored in MemPage.pBt->mutex.
32817 */
32818 struct MemPage {
32819   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
32820   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
32821   u8 intKey;           /* True if intkey flag is set */
32822   u8 leaf;             /* True if leaf flag is set */
32823   u8 hasData;          /* True if this page stores data */
32824   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
32825   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
32826   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
32827   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
32828   u16 cellOffset;      /* Index in aData of first cell pointer */
32829   u16 nFree;           /* Number of free bytes on the page */
32830   u16 nCell;           /* Number of cells on this page, local and ovfl */
32831   u16 maskPage;        /* Mask for page offset */
32832   struct _OvflCell {   /* Cells that will not fit on aData[] */
32833     u8 *pCell;          /* Pointers to the body of the overflow cell */
32834     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
32835   } aOvfl[5];
32836   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
32837   u8 *aData;           /* Pointer to disk image of the page data */
32838   DbPage *pDbPage;     /* Pager page handle */
32839   Pgno pgno;           /* Page number for this page */
32840 };
32841
32842 /*
32843 ** The in-memory image of a disk page has the auxiliary information appended
32844 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
32845 ** that extra information.
32846 */
32847 #define EXTRA_SIZE sizeof(MemPage)
32848
32849 /* A Btree handle
32850 **
32851 ** A database connection contains a pointer to an instance of
32852 ** this object for every database file that it has open.  This structure
32853 ** is opaque to the database connection.  The database connection cannot
32854 ** see the internals of this structure and only deals with pointers to
32855 ** this structure.
32856 **
32857 ** For some database files, the same underlying database cache might be 
32858 ** shared between multiple connections.  In that case, each contection
32859 ** has it own pointer to this object.  But each instance of this object
32860 ** points to the same BtShared object.  The database cache and the
32861 ** schema associated with the database file are all contained within
32862 ** the BtShared object.
32863 **
32864 ** All fields in this structure are accessed under sqlite3.mutex.
32865 ** The pBt pointer itself may not be changed while there exists cursors 
32866 ** in the referenced BtShared that point back to this Btree since those
32867 ** cursors have to do go through this Btree to find their BtShared and
32868 ** they often do so without holding sqlite3.mutex.
32869 */
32870 struct Btree {
32871   sqlite3 *db;       /* The database connection holding this btree */
32872   BtShared *pBt;     /* Sharable content of this btree */
32873   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
32874   u8 sharable;       /* True if we can share pBt with another db */
32875   u8 locked;         /* True if db currently has pBt locked */
32876   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
32877   Btree *pNext;      /* List of other sharable Btrees from the same db */
32878   Btree *pPrev;      /* Back pointer of the same list */
32879 };
32880
32881 /*
32882 ** Btree.inTrans may take one of the following values.
32883 **
32884 ** If the shared-data extension is enabled, there may be multiple users
32885 ** of the Btree structure. At most one of these may open a write transaction,
32886 ** but any number may have active read transactions.
32887 */
32888 #define TRANS_NONE  0
32889 #define TRANS_READ  1
32890 #define TRANS_WRITE 2
32891
32892 /*
32893 ** An instance of this object represents a single database file.
32894 ** 
32895 ** A single database file can be in use as the same time by two
32896 ** or more database connections.  When two or more connections are
32897 ** sharing the same database file, each connection has it own
32898 ** private Btree object for the file and each of those Btrees points
32899 ** to this one BtShared object.  BtShared.nRef is the number of
32900 ** connections currently sharing this database file.
32901 **
32902 ** Fields in this structure are accessed under the BtShared.mutex
32903 ** mutex, except for nRef and pNext which are accessed under the
32904 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
32905 ** may not be modified once it is initially set as long as nRef>0.
32906 ** The pSchema field may be set once under BtShared.mutex and
32907 ** thereafter is unchanged as long as nRef>0.
32908 */
32909 struct BtShared {
32910   Pager *pPager;        /* The page cache */
32911   sqlite3 *db;          /* Database connection currently using this Btree */
32912   BtCursor *pCursor;    /* A list of all open cursors */
32913   MemPage *pPage1;      /* First page of the database */
32914   u8 inStmt;            /* True if we are in a statement subtransaction */
32915   u8 readOnly;          /* True if the underlying file is readonly */
32916   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
32917 #ifndef SQLITE_OMIT_AUTOVACUUM
32918   u8 autoVacuum;        /* True if auto-vacuum is enabled */
32919   u8 incrVacuum;        /* True if incr-vacuum is enabled */
32920   Pgno nTrunc;          /* Non-zero if the db will be truncated (incr vacuum) */
32921 #endif
32922   u16 pageSize;         /* Total number of bytes on a page */
32923   u16 usableSize;       /* Number of usable bytes on each page */
32924   int maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
32925   int minLocal;         /* Minimum local payload in non-LEAFDATA tables */
32926   int maxLeaf;          /* Maximum local payload in a LEAFDATA table */
32927   int minLeaf;          /* Minimum local payload in a LEAFDATA table */
32928   u8 inTransaction;     /* Transaction state */
32929   int nTransaction;     /* Number of open transactions (read + write) */
32930   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
32931   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
32932   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
32933   BusyHandler busyHdr;  /* The busy handler for this btree */
32934 #ifndef SQLITE_OMIT_SHARED_CACHE
32935   int nRef;             /* Number of references to this structure */
32936   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
32937   BtLock *pLock;        /* List of locks held on this shared-btree struct */
32938   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
32939 #endif
32940   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
32941 };
32942
32943 /*
32944 ** An instance of the following structure is used to hold information
32945 ** about a cell.  The parseCellPtr() function fills in this structure
32946 ** based on information extract from the raw disk page.
32947 */
32948 typedef struct CellInfo CellInfo;
32949 struct CellInfo {
32950   u8 *pCell;     /* Pointer to the start of cell content */
32951   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
32952   u32 nData;     /* Number of bytes of data */
32953   u32 nPayload;  /* Total amount of payload */
32954   u16 nHeader;   /* Size of the cell content header in bytes */
32955   u16 nLocal;    /* Amount of payload held locally */
32956   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
32957   u16 nSize;     /* Size of the cell content on the main b-tree page */
32958 };
32959
32960 /*
32961 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
32962 ** this will be declared corrupt. This value is calculated based on a
32963 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
32964 ** root-node and 3 for all other internal nodes.
32965 **
32966 ** If a tree that appears to be taller than this is encountered, it is
32967 ** assumed that the database is corrupt.
32968 */
32969 #define BTCURSOR_MAX_DEPTH 20
32970
32971 /*
32972 ** A cursor is a pointer to a particular entry within a particular
32973 ** b-tree within a database file.
32974 **
32975 ** The entry is identified by its MemPage and the index in
32976 ** MemPage.aCell[] of the entry.
32977 **
32978 ** When a single database file can shared by two more database connections,
32979 ** but cursors cannot be shared.  Each cursor is associated with a
32980 ** particular database connection identified BtCursor.pBtree.db.
32981 **
32982 ** Fields in this structure are accessed under the BtShared.mutex
32983 ** found at self->pBt->mutex. 
32984 */
32985 struct BtCursor {
32986   Btree *pBtree;            /* The Btree to which this cursor belongs */
32987   BtShared *pBt;            /* The BtShared this cursor points to */
32988   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
32989   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
32990   Pgno pgnoRoot;            /* The root page of this tree */
32991   CellInfo info;            /* A parse of the cell we are pointing at */
32992   u8 wrFlag;                /* True if writable */
32993   u8 atLast;                /* Cursor pointing to the last entry */
32994   u8 validNKey;             /* True if info.nKey is valid */
32995   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
32996   void *pKey;      /* Saved key that was cursor's last known position */
32997   i64 nKey;        /* Size of pKey, or last integer key */
32998   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
32999 #ifndef SQLITE_OMIT_INCRBLOB
33000   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
33001   Pgno *aOverflow;          /* Cache of overflow page locations */
33002 #endif
33003 #ifndef NDEBUG
33004   u8 pagesShuffled;         /* True if Btree pages are rearranged by balance()*/
33005 #endif
33006   i16 iPage;                            /* Index of current page in apPage */
33007   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
33008   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
33009 };
33010
33011 /*
33012 ** Potential values for BtCursor.eState.
33013 **
33014 ** CURSOR_VALID:
33015 **   Cursor points to a valid entry. getPayload() etc. may be called.
33016 **
33017 ** CURSOR_INVALID:
33018 **   Cursor does not point to a valid entry. This can happen (for example) 
33019 **   because the table is empty or because BtreeCursorFirst() has not been
33020 **   called.
33021 **
33022 ** CURSOR_REQUIRESEEK:
33023 **   The table that this cursor was opened on still exists, but has been 
33024 **   modified since the cursor was last used. The cursor position is saved
33025 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
33026 **   this state, restoreCursorPosition() can be called to attempt to
33027 **   seek the cursor to the saved position.
33028 **
33029 ** CURSOR_FAULT:
33030 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
33031 **   on a different connection that shares the BtShared cache with this
33032 **   cursor.  The error has left the cache in an inconsistent state.
33033 **   Do nothing else with this cursor.  Any attempt to use the cursor
33034 **   should return the error code stored in BtCursor.skip
33035 */
33036 #define CURSOR_INVALID           0
33037 #define CURSOR_VALID             1
33038 #define CURSOR_REQUIRESEEK       2
33039 #define CURSOR_FAULT             3
33040
33041 /* The database page the PENDING_BYTE occupies. This page is never used.
33042 ** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
33043 ** should possibly be consolidated (presumably in pager.h).
33044 **
33045 ** If disk I/O is omitted (meaning that the database is stored purely
33046 ** in memory) then there is no pending byte.
33047 */
33048 #ifdef SQLITE_OMIT_DISKIO
33049 # define PENDING_BYTE_PAGE(pBt)  0x7fffffff
33050 #else
33051 # define PENDING_BYTE_PAGE(pBt) ((PENDING_BYTE/(pBt)->pageSize)+1)
33052 #endif
33053
33054 /*
33055 ** A linked list of the following structures is stored at BtShared.pLock.
33056 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
33057 ** is opened on the table with root page BtShared.iTable. Locks are removed
33058 ** from this list when a transaction is committed or rolled back, or when
33059 ** a btree handle is closed.
33060 */
33061 struct BtLock {
33062   Btree *pBtree;        /* Btree handle holding this lock */
33063   Pgno iTable;          /* Root page of table */
33064   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
33065   BtLock *pNext;        /* Next in BtShared.pLock list */
33066 };
33067
33068 /* Candidate values for BtLock.eLock */
33069 #define READ_LOCK     1
33070 #define WRITE_LOCK    2
33071
33072 /*
33073 ** These macros define the location of the pointer-map entry for a 
33074 ** database page. The first argument to each is the number of usable
33075 ** bytes on each page of the database (often 1024). The second is the
33076 ** page number to look up in the pointer map.
33077 **
33078 ** PTRMAP_PAGENO returns the database page number of the pointer-map
33079 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
33080 ** the offset of the requested map entry.
33081 **
33082 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
33083 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
33084 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
33085 ** this test.
33086 */
33087 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
33088 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
33089 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
33090
33091 /*
33092 ** The pointer map is a lookup table that identifies the parent page for
33093 ** each child page in the database file.  The parent page is the page that
33094 ** contains a pointer to the child.  Every page in the database contains
33095 ** 0 or 1 parent pages.  (In this context 'database page' refers
33096 ** to any page that is not part of the pointer map itself.)  Each pointer map
33097 ** entry consists of a single byte 'type' and a 4 byte parent page number.
33098 ** The PTRMAP_XXX identifiers below are the valid types.
33099 **
33100 ** The purpose of the pointer map is to facility moving pages from one
33101 ** position in the file to another as part of autovacuum.  When a page
33102 ** is moved, the pointer in its parent must be updated to point to the
33103 ** new location.  The pointer map is used to locate the parent page quickly.
33104 **
33105 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
33106 **                  used in this case.
33107 **
33108 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
33109 **                  is not used in this case.
33110 **
33111 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
33112 **                   overflow pages. The page number identifies the page that
33113 **                   contains the cell with a pointer to this overflow page.
33114 **
33115 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
33116 **                   overflow pages. The page-number identifies the previous
33117 **                   page in the overflow page list.
33118 **
33119 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
33120 **               identifies the parent page in the btree.
33121 */
33122 #define PTRMAP_ROOTPAGE 1
33123 #define PTRMAP_FREEPAGE 2
33124 #define PTRMAP_OVERFLOW1 3
33125 #define PTRMAP_OVERFLOW2 4
33126 #define PTRMAP_BTREE 5
33127
33128 /* A bunch of assert() statements to check the transaction state variables
33129 ** of handle p (type Btree*) are internally consistent.
33130 */
33131 #define btreeIntegrity(p) \
33132   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
33133   assert( p->pBt->inTransaction>=p->inTrans ); 
33134
33135
33136 /*
33137 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
33138 ** if the database supports auto-vacuum or not. Because it is used
33139 ** within an expression that is an argument to another macro 
33140 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
33141 ** So, this macro is defined instead.
33142 */
33143 #ifndef SQLITE_OMIT_AUTOVACUUM
33144 #define ISAUTOVACUUM (pBt->autoVacuum)
33145 #else
33146 #define ISAUTOVACUUM 0
33147 #endif
33148
33149
33150 /*
33151 ** This structure is passed around through all the sanity checking routines
33152 ** in order to keep track of some global state information.
33153 */
33154 typedef struct IntegrityCk IntegrityCk;
33155 struct IntegrityCk {
33156   BtShared *pBt;    /* The tree being checked out */
33157   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
33158   int nPage;        /* Number of pages in the database */
33159   int *anRef;       /* Number of times each page is referenced */
33160   int mxErr;        /* Stop accumulating errors when this reaches zero */
33161   int nErr;         /* Number of messages written to zErrMsg so far */
33162   int mallocFailed; /* A memory allocation error has occurred */
33163   StrAccum errMsg;  /* Accumulate the error message text here */
33164 };
33165
33166 /*
33167 ** Read or write a two- and four-byte big-endian integer values.
33168 */
33169 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
33170 #define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
33171 #define get4byte sqlite3Get4byte
33172 #define put4byte sqlite3Put4byte
33173
33174 /*
33175 ** Internal routines that should be accessed by the btree layer only.
33176 */
33177 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
33178 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage);
33179 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
33180 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
33181 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
33182 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
33183 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
33184 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
33185
33186 /************** End of btreeInt.h ********************************************/
33187 /************** Continuing where we left off in btmutex.c ********************/
33188 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
33189
33190
33191 /*
33192 ** Enter a mutex on the given BTree object.
33193 **
33194 ** If the object is not sharable, then no mutex is ever required
33195 ** and this routine is a no-op.  The underlying mutex is non-recursive.
33196 ** But we keep a reference count in Btree.wantToLock so the behavior
33197 ** of this interface is recursive.
33198 **
33199 ** To avoid deadlocks, multiple Btrees are locked in the same order
33200 ** by all database connections.  The p->pNext is a list of other
33201 ** Btrees belonging to the same database connection as the p Btree
33202 ** which need to be locked after p.  If we cannot get a lock on
33203 ** p, then first unlock all of the others on p->pNext, then wait
33204 ** for the lock to become available on p, then relock all of the
33205 ** subsequent Btrees that desire a lock.
33206 */
33207 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
33208   Btree *pLater;
33209
33210   /* Some basic sanity checking on the Btree.  The list of Btrees
33211   ** connected by pNext and pPrev should be in sorted order by
33212   ** Btree.pBt value. All elements of the list should belong to
33213   ** the same connection. Only shared Btrees are on the list. */
33214   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
33215   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
33216   assert( p->pNext==0 || p->pNext->db==p->db );
33217   assert( p->pPrev==0 || p->pPrev->db==p->db );
33218   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
33219
33220   /* Check for locking consistency */
33221   assert( !p->locked || p->wantToLock>0 );
33222   assert( p->sharable || p->wantToLock==0 );
33223
33224   /* We should already hold a lock on the database connection */
33225   assert( sqlite3_mutex_held(p->db->mutex) );
33226
33227   if( !p->sharable ) return;
33228   p->wantToLock++;
33229   if( p->locked ) return;
33230
33231   /* In most cases, we should be able to acquire the lock we
33232   ** want without having to go throught the ascending lock
33233   ** procedure that follows.  Just be sure not to block.
33234   */
33235   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
33236     p->locked = 1;
33237     return;
33238   }
33239
33240   /* To avoid deadlock, first release all locks with a larger
33241   ** BtShared address.  Then acquire our lock.  Then reacquire
33242   ** the other BtShared locks that we used to hold in ascending
33243   ** order.
33244   */
33245   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33246     assert( pLater->sharable );
33247     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
33248     assert( !pLater->locked || pLater->wantToLock>0 );
33249     if( pLater->locked ){
33250       sqlite3_mutex_leave(pLater->pBt->mutex);
33251       pLater->locked = 0;
33252     }
33253   }
33254   sqlite3_mutex_enter(p->pBt->mutex);
33255   p->locked = 1;
33256   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
33257     if( pLater->wantToLock ){
33258       sqlite3_mutex_enter(pLater->pBt->mutex);
33259       pLater->locked = 1;
33260     }
33261   }
33262 }
33263
33264 /*
33265 ** Exit the recursive mutex on a Btree.
33266 */
33267 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
33268   if( p->sharable ){
33269     assert( p->wantToLock>0 );
33270     p->wantToLock--;
33271     if( p->wantToLock==0 ){
33272       assert( p->locked );
33273       sqlite3_mutex_leave(p->pBt->mutex);
33274       p->locked = 0;
33275     }
33276   }
33277 }
33278
33279 #ifndef NDEBUG
33280 /*
33281 ** Return true if the BtShared mutex is held on the btree.  
33282 **
33283 ** This routine makes no determination one why or another if the
33284 ** database connection mutex is held.
33285 **
33286 ** This routine is used only from within assert() statements.
33287 */
33288 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
33289   return (p->sharable==0 ||
33290              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
33291 }
33292 #endif
33293
33294
33295 #ifndef SQLITE_OMIT_INCRBLOB
33296 /*
33297 ** Enter and leave a mutex on a Btree given a cursor owned by that
33298 ** Btree.  These entry points are used by incremental I/O and can be
33299 ** omitted if that module is not used.
33300 */
33301 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
33302   sqlite3BtreeEnter(pCur->pBtree);
33303 }
33304 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
33305   sqlite3BtreeLeave(pCur->pBtree);
33306 }
33307 #endif /* SQLITE_OMIT_INCRBLOB */
33308
33309
33310 /*
33311 ** Enter the mutex on every Btree associated with a database
33312 ** connection.  This is needed (for example) prior to parsing
33313 ** a statement since we will be comparing table and column names
33314 ** against all schemas and we do not want those schemas being
33315 ** reset out from under us.
33316 **
33317 ** There is a corresponding leave-all procedures.
33318 **
33319 ** Enter the mutexes in accending order by BtShared pointer address
33320 ** to avoid the possibility of deadlock when two threads with
33321 ** two or more btrees in common both try to lock all their btrees
33322 ** at the same instant.
33323 */
33324 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
33325   int i;
33326   Btree *p, *pLater;
33327   assert( sqlite3_mutex_held(db->mutex) );
33328   for(i=0; i<db->nDb; i++){
33329     p = db->aDb[i].pBt;
33330     if( p && p->sharable ){
33331       p->wantToLock++;
33332       if( !p->locked ){
33333         assert( p->wantToLock==1 );
33334         while( p->pPrev ) p = p->pPrev;
33335         while( p->locked && p->pNext ) p = p->pNext;
33336         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
33337           if( pLater->locked ){
33338             sqlite3_mutex_leave(pLater->pBt->mutex);
33339             pLater->locked = 0;
33340           }
33341         }
33342         while( p ){
33343           sqlite3_mutex_enter(p->pBt->mutex);
33344           p->locked++;
33345           p = p->pNext;
33346         }
33347       }
33348     }
33349   }
33350 }
33351 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
33352   int i;
33353   Btree *p;
33354   assert( sqlite3_mutex_held(db->mutex) );
33355   for(i=0; i<db->nDb; i++){
33356     p = db->aDb[i].pBt;
33357     if( p && p->sharable ){
33358       assert( p->wantToLock>0 );
33359       p->wantToLock--;
33360       if( p->wantToLock==0 ){
33361         assert( p->locked );
33362         sqlite3_mutex_leave(p->pBt->mutex);
33363         p->locked = 0;
33364       }
33365     }
33366   }
33367 }
33368
33369 #ifndef NDEBUG
33370 /*
33371 ** Return true if the current thread holds the database connection
33372 ** mutex and all required BtShared mutexes.
33373 **
33374 ** This routine is used inside assert() statements only.
33375 */
33376 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
33377   int i;
33378   if( !sqlite3_mutex_held(db->mutex) ){
33379     return 0;
33380   }
33381   for(i=0; i<db->nDb; i++){
33382     Btree *p;
33383     p = db->aDb[i].pBt;
33384     if( p && p->sharable &&
33385          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
33386       return 0;
33387     }
33388   }
33389   return 1;
33390 }
33391 #endif /* NDEBUG */
33392
33393 /*
33394 ** Add a new Btree pointer to a BtreeMutexArray. 
33395 ** if the pointer can possibly be shared with
33396 ** another database connection.
33397 **
33398 ** The pointers are kept in sorted order by pBtree->pBt.  That
33399 ** way when we go to enter all the mutexes, we can enter them
33400 ** in order without every having to backup and retry and without
33401 ** worrying about deadlock.
33402 **
33403 ** The number of shared btrees will always be small (usually 0 or 1)
33404 ** so an insertion sort is an adequate algorithm here.
33405 */
33406 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
33407   int i, j;
33408   BtShared *pBt;
33409   if( pBtree==0 || pBtree->sharable==0 ) return;
33410 #ifndef NDEBUG
33411   {
33412     for(i=0; i<pArray->nMutex; i++){
33413       assert( pArray->aBtree[i]!=pBtree );
33414     }
33415   }
33416 #endif
33417   assert( pArray->nMutex>=0 );
33418   assert( pArray->nMutex<sizeof(pArray->aBtree)/sizeof(pArray->aBtree[0])-1 );
33419   pBt = pBtree->pBt;
33420   for(i=0; i<pArray->nMutex; i++){
33421     assert( pArray->aBtree[i]!=pBtree );
33422     if( pArray->aBtree[i]->pBt>pBt ){
33423       for(j=pArray->nMutex; j>i; j--){
33424         pArray->aBtree[j] = pArray->aBtree[j-1];
33425       }
33426       pArray->aBtree[i] = pBtree;
33427       pArray->nMutex++;
33428       return;
33429     }
33430   }
33431   pArray->aBtree[pArray->nMutex++] = pBtree;
33432 }
33433
33434 /*
33435 ** Enter the mutex of every btree in the array.  This routine is
33436 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
33437 ** exited at the end of the same function.
33438 */
33439 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
33440   int i;
33441   for(i=0; i<pArray->nMutex; i++){
33442     Btree *p = pArray->aBtree[i];
33443     /* Some basic sanity checking */
33444     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33445     assert( !p->locked || p->wantToLock>0 );
33446
33447     /* We should already hold a lock on the database connection */
33448     assert( sqlite3_mutex_held(p->db->mutex) );
33449
33450     p->wantToLock++;
33451     if( !p->locked && p->sharable ){
33452       sqlite3_mutex_enter(p->pBt->mutex);
33453       p->locked = 1;
33454     }
33455   }
33456 }
33457
33458 /*
33459 ** Leave the mutex of every btree in the group.
33460 */
33461 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
33462   int i;
33463   for(i=0; i<pArray->nMutex; i++){
33464     Btree *p = pArray->aBtree[i];
33465     /* Some basic sanity checking */
33466     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
33467     assert( p->locked || !p->sharable );
33468     assert( p->wantToLock>0 );
33469
33470     /* We should already hold a lock on the database connection */
33471     assert( sqlite3_mutex_held(p->db->mutex) );
33472
33473     p->wantToLock--;
33474     if( p->wantToLock==0 && p->locked ){
33475       sqlite3_mutex_leave(p->pBt->mutex);
33476       p->locked = 0;
33477     }
33478   }
33479 }
33480
33481
33482 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
33483
33484 /************** End of btmutex.c *********************************************/
33485 /************** Begin file btree.c *******************************************/
33486 /*
33487 ** 2004 April 6
33488 **
33489 ** The author disclaims copyright to this source code.  In place of
33490 ** a legal notice, here is a blessing:
33491 **
33492 **    May you do good and not evil.
33493 **    May you find forgiveness for yourself and forgive others.
33494 **    May you share freely, never taking more than you give.
33495 **
33496 *************************************************************************
33497 ** $Id: btree.c,v 1.525 2008/10/08 17:58:49 danielk1977 Exp $
33498 **
33499 ** This file implements a external (disk-based) database using BTrees.
33500 ** See the header comment on "btreeInt.h" for additional information.
33501 ** Including a description of file format and an overview of operation.
33502 */
33503
33504 /*
33505 ** The header string that appears at the beginning of every
33506 ** SQLite database.
33507 */
33508 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
33509
33510 /*
33511 ** Set this global variable to 1 to enable tracing using the TRACE
33512 ** macro.
33513 */
33514 #if 0
33515 int sqlite3BtreeTrace=0;  /* True to enable tracing */
33516 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33517 #else
33518 # define TRACE(X)
33519 #endif
33520
33521 /*
33522 ** Sometimes we need a small amount of code such as a variable initialization
33523 ** to setup for a later assert() statement.  We do not want this code to
33524 ** appear when assert() is disabled.  The following macro is therefore
33525 ** used to contain that setup code.  The "VVA" acronym stands for
33526 ** "Verification, Validation, and Accreditation".  In other words, the
33527 ** code within VVA_ONLY() will only run during verification processes.
33528 */
33529 #ifndef NDEBUG
33530 # define VVA_ONLY(X)  X
33531 #else
33532 # define VVA_ONLY(X)
33533 #endif
33534
33535
33536
33537 #ifndef SQLITE_OMIT_SHARED_CACHE
33538 /*
33539 ** A list of BtShared objects that are eligible for participation
33540 ** in shared cache.  This variable has file scope during normal builds,
33541 ** but the test harness needs to access it so we make it global for 
33542 ** test builds.
33543 */
33544 #ifdef SQLITE_TEST
33545 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33546 #else
33547 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
33548 #endif
33549 #endif /* SQLITE_OMIT_SHARED_CACHE */
33550
33551 #ifndef SQLITE_OMIT_SHARED_CACHE
33552 /*
33553 ** Enable or disable the shared pager and schema features.
33554 **
33555 ** This routine has no effect on existing database connections.
33556 ** The shared cache setting effects only future calls to
33557 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
33558 */
33559 SQLITE_API int sqlite3_enable_shared_cache(int enable){
33560   sqlite3GlobalConfig.sharedCacheEnabled = enable;
33561   return SQLITE_OK;
33562 }
33563 #endif
33564
33565
33566 /*
33567 ** Forward declaration
33568 */
33569 static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
33570
33571
33572 #ifdef SQLITE_OMIT_SHARED_CACHE
33573   /*
33574   ** The functions queryTableLock(), lockTable() and unlockAllTables()
33575   ** manipulate entries in the BtShared.pLock linked list used to store
33576   ** shared-cache table level locks. If the library is compiled with the
33577   ** shared-cache feature disabled, then there is only ever one user
33578   ** of each BtShared structure and so this locking is not necessary. 
33579   ** So define the lock related functions as no-ops.
33580   */
33581   #define queryTableLock(a,b,c) SQLITE_OK
33582   #define lockTable(a,b,c) SQLITE_OK
33583   #define unlockAllTables(a)
33584 #endif
33585
33586 #ifndef SQLITE_OMIT_SHARED_CACHE
33587 /*
33588 ** Query to see if btree handle p may obtain a lock of type eLock 
33589 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
33590 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
33591 ** SQLITE_LOCKED if not.
33592 */
33593 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
33594   BtShared *pBt = p->pBt;
33595   BtLock *pIter;
33596
33597   assert( sqlite3BtreeHoldsMutex(p) );
33598   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
33599   assert( p->db!=0 );
33600   
33601   /* This is a no-op if the shared-cache is not enabled */
33602   if( !p->sharable ){
33603     return SQLITE_OK;
33604   }
33605
33606   /* If some other connection is holding an exclusive lock, the
33607   ** requested lock may not be obtained.
33608   */
33609   if( pBt->pExclusive && pBt->pExclusive!=p ){
33610     return SQLITE_LOCKED;
33611   }
33612
33613   /* This (along with lockTable()) is where the ReadUncommitted flag is
33614   ** dealt with. If the caller is querying for a read-lock and the flag is
33615   ** set, it is unconditionally granted - even if there are write-locks
33616   ** on the table. If a write-lock is requested, the ReadUncommitted flag
33617   ** is not considered.
33618   **
33619   ** In function lockTable(), if a read-lock is demanded and the 
33620   ** ReadUncommitted flag is set, no entry is added to the locks list 
33621   ** (BtShared.pLock).
33622   **
33623   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
33624   ** not create or respect table locks. The locking procedure for a 
33625   ** write-cursor does not change.
33626   */
33627   if( 
33628     0==(p->db->flags&SQLITE_ReadUncommitted) || 
33629     eLock==WRITE_LOCK ||
33630     iTab==MASTER_ROOT
33631   ){
33632     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
33633       if( pIter->pBtree!=p && pIter->iTable==iTab && 
33634           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
33635         return SQLITE_LOCKED;
33636       }
33637     }
33638   }
33639   return SQLITE_OK;
33640 }
33641 #endif /* !SQLITE_OMIT_SHARED_CACHE */
33642
33643 #ifndef SQLITE_OMIT_SHARED_CACHE
33644 /*
33645 ** Add a lock on the table with root-page iTable to the shared-btree used
33646 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
33647 ** WRITE_LOCK.
33648 **
33649 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
33650 ** SQLITE_NOMEM may also be returned.
33651 */
33652 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
33653   BtShared *pBt = p->pBt;
33654   BtLock *pLock = 0;
33655   BtLock *pIter;
33656
33657   assert( sqlite3BtreeHoldsMutex(p) );
33658   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
33659   assert( p->db!=0 );
33660
33661   /* This is a no-op if the shared-cache is not enabled */
33662   if( !p->sharable ){
33663     return SQLITE_OK;
33664   }
33665
33666   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
33667
33668   /* If the read-uncommitted flag is set and a read-lock is requested,
33669   ** return early without adding an entry to the BtShared.pLock list. See
33670   ** comment in function queryTableLock() for more info on handling 
33671   ** the ReadUncommitted flag.
33672   */
33673   if( 
33674     (p->db->flags&SQLITE_ReadUncommitted) && 
33675     (eLock==READ_LOCK) &&
33676     iTable!=MASTER_ROOT
33677   ){
33678     return SQLITE_OK;
33679   }
33680
33681   /* First search the list for an existing lock on this table. */
33682   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
33683     if( pIter->iTable==iTable && pIter->pBtree==p ){
33684       pLock = pIter;
33685       break;
33686     }
33687   }
33688
33689   /* If the above search did not find a BtLock struct associating Btree p
33690   ** with table iTable, allocate one and link it into the list.
33691   */
33692   if( !pLock ){
33693     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
33694     if( !pLock ){
33695       return SQLITE_NOMEM;
33696     }
33697     pLock->iTable = iTable;
33698     pLock->pBtree = p;
33699     pLock->pNext = pBt->pLock;
33700     pBt->pLock = pLock;
33701   }
33702
33703   /* Set the BtLock.eLock variable to the maximum of the current lock
33704   ** and the requested lock. This means if a write-lock was already held
33705   ** and a read-lock requested, we don't incorrectly downgrade the lock.
33706   */
33707   assert( WRITE_LOCK>READ_LOCK );
33708   if( eLock>pLock->eLock ){
33709     pLock->eLock = eLock;
33710   }
33711
33712   return SQLITE_OK;
33713 }
33714 #endif /* !SQLITE_OMIT_SHARED_CACHE */
33715
33716 #ifndef SQLITE_OMIT_SHARED_CACHE
33717 /*
33718 ** Release all the table locks (locks obtained via calls to the lockTable()
33719 ** procedure) held by Btree handle p.
33720 */
33721 static void unlockAllTables(Btree *p){
33722   BtShared *pBt = p->pBt;
33723   BtLock **ppIter = &pBt->pLock;
33724
33725   assert( sqlite3BtreeHoldsMutex(p) );
33726   assert( p->sharable || 0==*ppIter );
33727
33728   while( *ppIter ){
33729     BtLock *pLock = *ppIter;
33730     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
33731     if( pLock->pBtree==p ){
33732       *ppIter = pLock->pNext;
33733       sqlite3_free(pLock);
33734     }else{
33735       ppIter = &pLock->pNext;
33736     }
33737   }
33738
33739   if( pBt->pExclusive==p ){
33740     pBt->pExclusive = 0;
33741   }
33742 }
33743 #endif /* SQLITE_OMIT_SHARED_CACHE */
33744
33745 static void releasePage(MemPage *pPage);  /* Forward reference */
33746
33747 /*
33748 ** Verify that the cursor holds a mutex on the BtShared
33749 */
33750 #ifndef NDEBUG
33751 static int cursorHoldsMutex(BtCursor *p){
33752   return sqlite3_mutex_held(p->pBt->mutex);
33753 }
33754 #endif
33755
33756
33757 #ifndef SQLITE_OMIT_INCRBLOB
33758 /*
33759 ** Invalidate the overflow page-list cache for cursor pCur, if any.
33760 */
33761 static void invalidateOverflowCache(BtCursor *pCur){
33762   assert( cursorHoldsMutex(pCur) );
33763   sqlite3_free(pCur->aOverflow);
33764   pCur->aOverflow = 0;
33765 }
33766
33767 /*
33768 ** Invalidate the overflow page-list cache for all cursors opened
33769 ** on the shared btree structure pBt.
33770 */
33771 static void invalidateAllOverflowCache(BtShared *pBt){
33772   BtCursor *p;
33773   assert( sqlite3_mutex_held(pBt->mutex) );
33774   for(p=pBt->pCursor; p; p=p->pNext){
33775     invalidateOverflowCache(p);
33776   }
33777 }
33778 #else
33779   #define invalidateOverflowCache(x)
33780   #define invalidateAllOverflowCache(x)
33781 #endif
33782
33783 /*
33784 ** Save the current cursor position in the variables BtCursor.nKey 
33785 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
33786 */
33787 static int saveCursorPosition(BtCursor *pCur){
33788   int rc;
33789
33790   assert( CURSOR_VALID==pCur->eState );
33791   assert( 0==pCur->pKey );
33792   assert( cursorHoldsMutex(pCur) );
33793
33794   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
33795
33796   /* If this is an intKey table, then the above call to BtreeKeySize()
33797   ** stores the integer key in pCur->nKey. In this case this value is
33798   ** all that is required. Otherwise, if pCur is not open on an intKey
33799   ** table, then malloc space for and store the pCur->nKey bytes of key 
33800   ** data.
33801   */
33802   if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
33803     void *pKey = sqlite3Malloc(pCur->nKey);
33804     if( pKey ){
33805       rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
33806       if( rc==SQLITE_OK ){
33807         pCur->pKey = pKey;
33808       }else{
33809         sqlite3_free(pKey);
33810       }
33811     }else{
33812       rc = SQLITE_NOMEM;
33813     }
33814   }
33815   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
33816
33817   if( rc==SQLITE_OK ){
33818     int i;
33819     for(i=0; i<=pCur->iPage; i++){
33820       releasePage(pCur->apPage[i]);
33821       pCur->apPage[i] = 0;
33822     }
33823     pCur->iPage = -1;
33824     pCur->eState = CURSOR_REQUIRESEEK;
33825   }
33826
33827   invalidateOverflowCache(pCur);
33828   return rc;
33829 }
33830
33831 /*
33832 ** Save the positions of all cursors except pExcept open on the table 
33833 ** with root-page iRoot. Usually, this is called just before cursor
33834 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
33835 */
33836 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
33837   BtCursor *p;
33838   assert( sqlite3_mutex_held(pBt->mutex) );
33839   assert( pExcept==0 || pExcept->pBt==pBt );
33840   for(p=pBt->pCursor; p; p=p->pNext){
33841     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
33842         p->eState==CURSOR_VALID ){
33843       int rc = saveCursorPosition(p);
33844       if( SQLITE_OK!=rc ){
33845         return rc;
33846       }
33847     }
33848   }
33849   return SQLITE_OK;
33850 }
33851
33852 /*
33853 ** Clear the current cursor position.
33854 */
33855 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
33856   assert( cursorHoldsMutex(pCur) );
33857   sqlite3_free(pCur->pKey);
33858   pCur->pKey = 0;
33859   pCur->eState = CURSOR_INVALID;
33860 }
33861
33862 /*
33863 ** Restore the cursor to the position it was in (or as close to as possible)
33864 ** when saveCursorPosition() was called. Note that this call deletes the 
33865 ** saved position info stored by saveCursorPosition(), so there can be
33866 ** at most one effective restoreCursorPosition() call after each 
33867 ** saveCursorPosition().
33868 */
33869 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
33870   int rc;
33871   assert( cursorHoldsMutex(pCur) );
33872   assert( pCur->eState>=CURSOR_REQUIRESEEK );
33873   if( pCur->eState==CURSOR_FAULT ){
33874     return pCur->skip;
33875   }
33876   pCur->eState = CURSOR_INVALID;
33877   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
33878   if( rc==SQLITE_OK ){
33879     sqlite3_free(pCur->pKey);
33880     pCur->pKey = 0;
33881     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
33882   }
33883   return rc;
33884 }
33885
33886 #define restoreCursorPosition(p) \
33887   (p->eState>=CURSOR_REQUIRESEEK ? \
33888          sqlite3BtreeRestoreCursorPosition(p) : \
33889          SQLITE_OK)
33890
33891 /*
33892 ** Determine whether or not a cursor has moved from the position it
33893 ** was last placed at.  Cursor can move when the row they are pointing
33894 ** at is deleted out from under them.
33895 **
33896 ** This routine returns an error code if something goes wrong.  The
33897 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
33898 */
33899 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
33900   int rc;
33901
33902   rc = restoreCursorPosition(pCur);
33903   if( rc ){
33904     *pHasMoved = 1;
33905     return rc;
33906   }
33907   if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
33908     *pHasMoved = 1;
33909   }else{
33910     *pHasMoved = 0;
33911   }
33912   return SQLITE_OK;
33913 }
33914
33915 #ifndef SQLITE_OMIT_AUTOVACUUM
33916 /*
33917 ** Given a page number of a regular database page, return the page
33918 ** number for the pointer-map page that contains the entry for the
33919 ** input page number.
33920 */
33921 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
33922   int nPagesPerMapPage, iPtrMap, ret;
33923   assert( sqlite3_mutex_held(pBt->mutex) );
33924   nPagesPerMapPage = (pBt->usableSize/5)+1;
33925   iPtrMap = (pgno-2)/nPagesPerMapPage;
33926   ret = (iPtrMap*nPagesPerMapPage) + 2; 
33927   if( ret==PENDING_BYTE_PAGE(pBt) ){
33928     ret++;
33929   }
33930   return ret;
33931 }
33932
33933 /*
33934 ** Write an entry into the pointer map.
33935 **
33936 ** This routine updates the pointer map entry for page number 'key'
33937 ** so that it maps to type 'eType' and parent page number 'pgno'.
33938 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
33939 */
33940 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
33941   DbPage *pDbPage;  /* The pointer map page */
33942   u8 *pPtrmap;      /* The pointer map data */
33943   Pgno iPtrmap;     /* The pointer map page number */
33944   int offset;       /* Offset in pointer map page */
33945   int rc;
33946
33947   assert( sqlite3_mutex_held(pBt->mutex) );
33948   /* The master-journal page number must never be used as a pointer map page */
33949   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
33950
33951   assert( pBt->autoVacuum );
33952   if( key==0 ){
33953     return SQLITE_CORRUPT_BKPT;
33954   }
33955   iPtrmap = PTRMAP_PAGENO(pBt, key);
33956   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
33957   if( rc!=SQLITE_OK ){
33958     return rc;
33959   }
33960   offset = PTRMAP_PTROFFSET(iPtrmap, key);
33961   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
33962
33963   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
33964     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
33965     rc = sqlite3PagerWrite(pDbPage);
33966     if( rc==SQLITE_OK ){
33967       pPtrmap[offset] = eType;
33968       put4byte(&pPtrmap[offset+1], parent);
33969     }
33970   }
33971
33972   sqlite3PagerUnref(pDbPage);
33973   return rc;
33974 }
33975
33976 /*
33977 ** Read an entry from the pointer map.
33978 **
33979 ** This routine retrieves the pointer map entry for page 'key', writing
33980 ** the type and parent page number to *pEType and *pPgno respectively.
33981 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
33982 */
33983 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
33984   DbPage *pDbPage;   /* The pointer map page */
33985   int iPtrmap;       /* Pointer map page index */
33986   u8 *pPtrmap;       /* Pointer map page data */
33987   int offset;        /* Offset of entry in pointer map */
33988   int rc;
33989
33990   assert( sqlite3_mutex_held(pBt->mutex) );
33991
33992   iPtrmap = PTRMAP_PAGENO(pBt, key);
33993   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
33994   if( rc!=0 ){
33995     return rc;
33996   }
33997   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
33998
33999   offset = PTRMAP_PTROFFSET(iPtrmap, key);
34000   assert( pEType!=0 );
34001   *pEType = pPtrmap[offset];
34002   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
34003
34004   sqlite3PagerUnref(pDbPage);
34005   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
34006   return SQLITE_OK;
34007 }
34008
34009 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
34010   #define ptrmapPut(w,x,y,z) SQLITE_OK
34011   #define ptrmapGet(w,x,y,z) SQLITE_OK
34012   #define ptrmapPutOvfl(y,z) SQLITE_OK
34013 #endif
34014
34015 /*
34016 ** Given a btree page and a cell index (0 means the first cell on
34017 ** the page, 1 means the second cell, and so forth) return a pointer
34018 ** to the cell content.
34019 **
34020 ** This routine works only for pages that do not contain overflow cells.
34021 */
34022 #define findCell(P,I) \
34023   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
34024
34025 /*
34026 ** This a more complex version of findCell() that works for
34027 ** pages that do contain overflow cells.  See insert
34028 */
34029 static u8 *findOverflowCell(MemPage *pPage, int iCell){
34030   int i;
34031   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34032   for(i=pPage->nOverflow-1; i>=0; i--){
34033     int k;
34034     struct _OvflCell *pOvfl;
34035     pOvfl = &pPage->aOvfl[i];
34036     k = pOvfl->idx;
34037     if( k<=iCell ){
34038       if( k==iCell ){
34039         return pOvfl->pCell;
34040       }
34041       iCell--;
34042     }
34043   }
34044   return findCell(pPage, iCell);
34045 }
34046
34047 /*
34048 ** Parse a cell content block and fill in the CellInfo structure.  There
34049 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
34050 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
34051 ** takes a pointer to the body of the cell as its second argument.
34052 **
34053 ** Within this file, the parseCell() macro can be called instead of
34054 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
34055 */
34056 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
34057   MemPage *pPage,         /* Page containing the cell */
34058   u8 *pCell,              /* Pointer to the cell text. */
34059   CellInfo *pInfo         /* Fill in this structure */
34060 ){
34061   int n;                  /* Number bytes in cell content header */
34062   u32 nPayload;           /* Number of bytes of cell payload */
34063
34064   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34065
34066   pInfo->pCell = pCell;
34067   assert( pPage->leaf==0 || pPage->leaf==1 );
34068   n = pPage->childPtrSize;
34069   assert( n==4-4*pPage->leaf );
34070   if( pPage->intKey ){
34071     if( pPage->hasData ){
34072       n += getVarint32(&pCell[n], nPayload);
34073     }else{
34074       nPayload = 0;
34075     }
34076     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
34077     pInfo->nData = nPayload;
34078   }else{
34079     pInfo->nData = 0;
34080     n += getVarint32(&pCell[n], nPayload);
34081     pInfo->nKey = nPayload;
34082   }
34083   pInfo->nPayload = nPayload;
34084   pInfo->nHeader = n;
34085   if( likely(nPayload<=pPage->maxLocal) ){
34086     /* This is the (easy) common case where the entire payload fits
34087     ** on the local page.  No overflow is required.
34088     */
34089     int nSize;          /* Total size of cell content in bytes */
34090     nSize = nPayload + n;
34091     pInfo->nLocal = nPayload;
34092     pInfo->iOverflow = 0;
34093     if( (nSize & ~3)==0 ){
34094       nSize = 4;        /* Minimum cell size is 4 */
34095     }
34096     pInfo->nSize = nSize;
34097   }else{
34098     /* If the payload will not fit completely on the local page, we have
34099     ** to decide how much to store locally and how much to spill onto
34100     ** overflow pages.  The strategy is to minimize the amount of unused
34101     ** space on overflow pages while keeping the amount of local storage
34102     ** in between minLocal and maxLocal.
34103     **
34104     ** Warning:  changing the way overflow payload is distributed in any
34105     ** way will result in an incompatible file format.
34106     */
34107     int minLocal;  /* Minimum amount of payload held locally */
34108     int maxLocal;  /* Maximum amount of payload held locally */
34109     int surplus;   /* Overflow payload available for local storage */
34110
34111     minLocal = pPage->minLocal;
34112     maxLocal = pPage->maxLocal;
34113     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
34114     if( surplus <= maxLocal ){
34115       pInfo->nLocal = surplus;
34116     }else{
34117       pInfo->nLocal = minLocal;
34118     }
34119     pInfo->iOverflow = pInfo->nLocal + n;
34120     pInfo->nSize = pInfo->iOverflow + 4;
34121   }
34122 }
34123 #define parseCell(pPage, iCell, pInfo) \
34124   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
34125 SQLITE_PRIVATE void sqlite3BtreeParseCell(
34126   MemPage *pPage,         /* Page containing the cell */
34127   int iCell,              /* The cell index.  First cell is 0 */
34128   CellInfo *pInfo         /* Fill in this structure */
34129 ){
34130   parseCell(pPage, iCell, pInfo);
34131 }
34132
34133 /*
34134 ** Compute the total number of bytes that a Cell needs in the cell
34135 ** data area of the btree-page.  The return number includes the cell
34136 ** data header and the local payload, but not any overflow page or
34137 ** the space used by the cell pointer.
34138 */
34139 #ifndef NDEBUG
34140 static u16 cellSize(MemPage *pPage, int iCell){
34141   CellInfo info;
34142   sqlite3BtreeParseCell(pPage, iCell, &info);
34143   return info.nSize;
34144 }
34145 #endif
34146 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
34147   CellInfo info;
34148   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34149   return info.nSize;
34150 }
34151
34152 #ifndef SQLITE_OMIT_AUTOVACUUM
34153 /*
34154 ** If the cell pCell, part of page pPage contains a pointer
34155 ** to an overflow page, insert an entry into the pointer-map
34156 ** for the overflow page.
34157 */
34158 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
34159   CellInfo info;
34160   assert( pCell!=0 );
34161   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
34162   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
34163   if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
34164     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
34165     return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
34166   }
34167   return SQLITE_OK;
34168 }
34169 /*
34170 ** If the cell with index iCell on page pPage contains a pointer
34171 ** to an overflow page, insert an entry into the pointer-map
34172 ** for the overflow page.
34173 */
34174 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
34175   u8 *pCell;
34176   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34177   pCell = findOverflowCell(pPage, iCell);
34178   return ptrmapPutOvflPtr(pPage, pCell);
34179 }
34180 #endif
34181
34182
34183 /*
34184 ** Defragment the page given.  All Cells are moved to the
34185 ** end of the page and all free space is collected into one
34186 ** big FreeBlk that occurs in between the header and cell
34187 ** pointer array and the cell content area.
34188 */
34189 static void defragmentPage(MemPage *pPage){
34190   int i;                     /* Loop counter */
34191   int pc;                    /* Address of a i-th cell */
34192   int addr;                  /* Offset of first byte after cell pointer array */
34193   int hdr;                   /* Offset to the page header */
34194   int size;                  /* Size of a cell */
34195   int usableSize;            /* Number of usable bytes on a page */
34196   int cellOffset;            /* Offset to the cell pointer array */
34197   int cbrk;                  /* Offset to the cell content area */
34198   int nCell;                 /* Number of cells on the page */
34199   unsigned char *data;       /* The page data */
34200   unsigned char *temp;       /* Temp area for cell content */
34201
34202   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34203   assert( pPage->pBt!=0 );
34204   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
34205   assert( pPage->nOverflow==0 );
34206   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34207   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
34208   data = pPage->aData;
34209   hdr = pPage->hdrOffset;
34210   cellOffset = pPage->cellOffset;
34211   nCell = pPage->nCell;
34212   assert( nCell==get2byte(&data[hdr+3]) );
34213   usableSize = pPage->pBt->usableSize;
34214   cbrk = get2byte(&data[hdr+5]);
34215   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
34216   cbrk = usableSize;
34217   for(i=0; i<nCell; i++){
34218     u8 *pAddr;     /* The i-th cell pointer */
34219     pAddr = &data[cellOffset + i*2];
34220     pc = get2byte(pAddr);
34221     assert( pc<pPage->pBt->usableSize );
34222     size = cellSizePtr(pPage, &temp[pc]);
34223     cbrk -= size;
34224     memcpy(&data[cbrk], &temp[pc], size);
34225     put2byte(pAddr, cbrk);
34226   }
34227   assert( cbrk>=cellOffset+2*nCell );
34228   put2byte(&data[hdr+5], cbrk);
34229   data[hdr+1] = 0;
34230   data[hdr+2] = 0;
34231   data[hdr+7] = 0;
34232   addr = cellOffset+2*nCell;
34233   memset(&data[addr], 0, cbrk-addr);
34234 }
34235
34236 /*
34237 ** Allocate nByte bytes of space on a page.
34238 **
34239 ** Return the index into pPage->aData[] of the first byte of
34240 ** the new allocation.  The caller guarantees that there is enough
34241 ** space.  This routine will never fail.
34242 **
34243 ** If the page contains nBytes of free space but does not contain
34244 ** nBytes of contiguous free space, then this routine automatically
34245 ** calls defragementPage() to consolidate all free space before 
34246 ** allocating the new chunk.
34247 */
34248 static int allocateSpace(MemPage *pPage, int nByte){
34249   int addr, pc, hdr;
34250   int size;
34251   int nFrag;
34252   int top;
34253   int nCell;
34254   int cellOffset;
34255   unsigned char *data;
34256   
34257   data = pPage->aData;
34258   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34259   assert( pPage->pBt );
34260   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34261   assert( nByte>=0 );  /* Minimum cell size is 4 */
34262   assert( pPage->nFree>=nByte );
34263   assert( pPage->nOverflow==0 );
34264   pPage->nFree -= nByte;
34265   hdr = pPage->hdrOffset;
34266
34267   nFrag = data[hdr+7];
34268   if( nFrag<60 ){
34269     /* Search the freelist looking for a slot big enough to satisfy the
34270     ** space request. */
34271     addr = hdr+1;
34272     while( (pc = get2byte(&data[addr]))>0 ){
34273       size = get2byte(&data[pc+2]);
34274       if( size>=nByte ){
34275         if( size<nByte+4 ){
34276           memcpy(&data[addr], &data[pc], 2);
34277           data[hdr+7] = nFrag + size - nByte;
34278           return pc;
34279         }else{
34280           put2byte(&data[pc+2], size-nByte);
34281           return pc + size - nByte;
34282         }
34283       }
34284       addr = pc;
34285     }
34286   }
34287
34288   /* Allocate memory from the gap in between the cell pointer array
34289   ** and the cell content area.
34290   */
34291   top = get2byte(&data[hdr+5]);
34292   nCell = get2byte(&data[hdr+3]);
34293   cellOffset = pPage->cellOffset;
34294   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
34295     defragmentPage(pPage);
34296     top = get2byte(&data[hdr+5]);
34297   }
34298   top -= nByte;
34299   assert( cellOffset + 2*nCell <= top );
34300   put2byte(&data[hdr+5], top);
34301   return top;
34302 }
34303
34304 /*
34305 ** Return a section of the pPage->aData to the freelist.
34306 ** The first byte of the new free block is pPage->aDisk[start]
34307 ** and the size of the block is "size" bytes.
34308 **
34309 ** Most of the effort here is involved in coalesing adjacent
34310 ** free blocks into a single big free block.
34311 */
34312 static void freeSpace(MemPage *pPage, int start, int size){
34313   int addr, pbegin, hdr;
34314   unsigned char *data = pPage->aData;
34315
34316   assert( pPage->pBt!=0 );
34317   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34318   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
34319   assert( (start + size)<=pPage->pBt->usableSize );
34320   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34321   assert( size>=0 );   /* Minimum cell size is 4 */
34322
34323 #ifdef SQLITE_SECURE_DELETE
34324   /* Overwrite deleted information with zeros when the SECURE_DELETE 
34325   ** option is enabled at compile-time */
34326   memset(&data[start], 0, size);
34327 #endif
34328
34329   /* Add the space back into the linked list of freeblocks */
34330   hdr = pPage->hdrOffset;
34331   addr = hdr + 1;
34332   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
34333     assert( pbegin<=pPage->pBt->usableSize-4 );
34334     assert( pbegin>addr );
34335     addr = pbegin;
34336   }
34337   assert( pbegin<=pPage->pBt->usableSize-4 );
34338   assert( pbegin>addr || pbegin==0 );
34339   put2byte(&data[addr], start);
34340   put2byte(&data[start], pbegin);
34341   put2byte(&data[start+2], size);
34342   pPage->nFree += size;
34343
34344   /* Coalesce adjacent free blocks */
34345   addr = pPage->hdrOffset + 1;
34346   while( (pbegin = get2byte(&data[addr]))>0 ){
34347     int pnext, psize;
34348     assert( pbegin>addr );
34349     assert( pbegin<=pPage->pBt->usableSize-4 );
34350     pnext = get2byte(&data[pbegin]);
34351     psize = get2byte(&data[pbegin+2]);
34352     if( pbegin + psize + 3 >= pnext && pnext>0 ){
34353       int frag = pnext - (pbegin+psize);
34354       assert( frag<=data[pPage->hdrOffset+7] );
34355       data[pPage->hdrOffset+7] -= frag;
34356       put2byte(&data[pbegin], get2byte(&data[pnext]));
34357       put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
34358     }else{
34359       addr = pbegin;
34360     }
34361   }
34362
34363   /* If the cell content area begins with a freeblock, remove it. */
34364   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
34365     int top;
34366     pbegin = get2byte(&data[hdr+1]);
34367     memcpy(&data[hdr+1], &data[pbegin], 2);
34368     top = get2byte(&data[hdr+5]);
34369     put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
34370   }
34371 }
34372
34373 /*
34374 ** Decode the flags byte (the first byte of the header) for a page
34375 ** and initialize fields of the MemPage structure accordingly.
34376 **
34377 ** Only the following combinations are supported.  Anything different
34378 ** indicates a corrupt database files:
34379 **
34380 **         PTF_ZERODATA
34381 **         PTF_ZERODATA | PTF_LEAF
34382 **         PTF_LEAFDATA | PTF_INTKEY
34383 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
34384 */
34385 static int decodeFlags(MemPage *pPage, int flagByte){
34386   BtShared *pBt;     /* A copy of pPage->pBt */
34387
34388   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
34389   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34390   pPage->leaf = flagByte>>3;  assert( PTF_LEAF == 1<<3 );
34391   flagByte &= ~PTF_LEAF;
34392   pPage->childPtrSize = 4-4*pPage->leaf;
34393   pBt = pPage->pBt;
34394   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
34395     pPage->intKey = 1;
34396     pPage->hasData = pPage->leaf;
34397     pPage->maxLocal = pBt->maxLeaf;
34398     pPage->minLocal = pBt->minLeaf;
34399   }else if( flagByte==PTF_ZERODATA ){
34400     pPage->intKey = 0;
34401     pPage->hasData = 0;
34402     pPage->maxLocal = pBt->maxLocal;
34403     pPage->minLocal = pBt->minLocal;
34404   }else{
34405     return SQLITE_CORRUPT_BKPT;
34406   }
34407   return SQLITE_OK;
34408 }
34409
34410 /*
34411 ** Initialize the auxiliary information for a disk block.
34412 **
34413 ** Return SQLITE_OK on success.  If we see that the page does
34414 ** not contain a well-formed database page, then return 
34415 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
34416 ** guarantee that the page is well-formed.  It only shows that
34417 ** we failed to detect any corruption.
34418 */
34419 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage){
34420
34421   assert( pPage->pBt!=0 );
34422   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34423   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
34424   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
34425   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
34426
34427   if( !pPage->isInit ){
34428     int pc;            /* Address of a freeblock within pPage->aData[] */
34429     int hdr;           /* Offset to beginning of page header */
34430     u8 *data;          /* Equal to pPage->aData */
34431     BtShared *pBt;        /* The main btree structure */
34432     int usableSize;    /* Amount of usable space on each page */
34433     int cellOffset;    /* Offset from start of page to first cell pointer */
34434     int nFree;         /* Number of unused bytes on the page */
34435     int top;           /* First byte of the cell content area */
34436
34437     pBt = pPage->pBt;
34438
34439     hdr = pPage->hdrOffset;
34440     data = pPage->aData;
34441     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
34442     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34443     pPage->maskPage = pBt->pageSize - 1;
34444     pPage->nOverflow = 0;
34445     usableSize = pBt->usableSize;
34446     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
34447     top = get2byte(&data[hdr+5]);
34448     pPage->nCell = get2byte(&data[hdr+3]);
34449     if( pPage->nCell>MX_CELL(pBt) ){
34450       /* To many cells for a single page.  The page must be corrupt */
34451       return SQLITE_CORRUPT_BKPT;
34452     }
34453   
34454     /* Compute the total free space on the page */
34455     pc = get2byte(&data[hdr+1]);
34456     nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
34457     while( pc>0 ){
34458       int next, size;
34459       if( pc>usableSize-4 ){
34460         /* Free block is off the page */
34461         return SQLITE_CORRUPT_BKPT; 
34462       }
34463       next = get2byte(&data[pc]);
34464       size = get2byte(&data[pc+2]);
34465       if( next>0 && next<=pc+size+3 ){
34466         /* Free blocks must be in accending order */
34467         return SQLITE_CORRUPT_BKPT; 
34468       }
34469       nFree += size;
34470       pc = next;
34471     }
34472     pPage->nFree = nFree;
34473     if( nFree>=usableSize ){
34474       /* Free space cannot exceed total page size */
34475       return SQLITE_CORRUPT_BKPT; 
34476     }
34477
34478 #if 0
34479   /* Check that all the offsets in the cell offset array are within range. 
34480   ** 
34481   ** Omitting this consistency check and using the pPage->maskPage mask
34482   ** to prevent overrunning the page buffer in findCell() results in a
34483   ** 2.5% performance gain.
34484   */
34485   {
34486     u8 *pOff;        /* Iterator used to check all cell offsets are in range */
34487     u8 *pEnd;        /* Pointer to end of cell offset array */
34488     u8 mask;         /* Mask of bits that must be zero in MSB of cell offsets */
34489     mask = ~(((u8)(pBt->pageSize>>8))-1);
34490     pEnd = &data[cellOffset + pPage->nCell*2];
34491     for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
34492     if( pOff!=pEnd ){
34493       return SQLITE_CORRUPT_BKPT;
34494     }
34495   }
34496 #endif
34497
34498     pPage->isInit = 1;
34499   }
34500   return SQLITE_OK;
34501 }
34502
34503 /*
34504 ** Set up a raw page so that it looks like a database page holding
34505 ** no entries.
34506 */
34507 static void zeroPage(MemPage *pPage, int flags){
34508   unsigned char *data = pPage->aData;
34509   BtShared *pBt = pPage->pBt;
34510   int hdr = pPage->hdrOffset;
34511   int first;
34512
34513   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
34514   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
34515   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
34516   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
34517   assert( sqlite3_mutex_held(pBt->mutex) );
34518   /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
34519   data[hdr] = flags;
34520   first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
34521   memset(&data[hdr+1], 0, 4);
34522   data[hdr+7] = 0;
34523   put2byte(&data[hdr+5], pBt->usableSize);
34524   pPage->nFree = pBt->usableSize - first;
34525   decodeFlags(pPage, flags);
34526   pPage->hdrOffset = hdr;
34527   pPage->cellOffset = first;
34528   pPage->nOverflow = 0;
34529   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
34530   pPage->maskPage = pBt->pageSize - 1;
34531   pPage->nCell = 0;
34532   pPage->isInit = 1;
34533 }
34534
34535
34536 /*
34537 ** Convert a DbPage obtained from the pager into a MemPage used by
34538 ** the btree layer.
34539 */
34540 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
34541   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
34542   pPage->aData = sqlite3PagerGetData(pDbPage);
34543   pPage->pDbPage = pDbPage;
34544   pPage->pBt = pBt;
34545   pPage->pgno = pgno;
34546   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
34547   return pPage; 
34548 }
34549
34550 /*
34551 ** Get a page from the pager.  Initialize the MemPage.pBt and
34552 ** MemPage.aData elements if needed.
34553 **
34554 ** If the noContent flag is set, it means that we do not care about
34555 ** the content of the page at this time.  So do not go to the disk
34556 ** to fetch the content.  Just fill in the content with zeros for now.
34557 ** If in the future we call sqlite3PagerWrite() on this page, that
34558 ** means we have started to be concerned about content and the disk
34559 ** read should occur at that point.
34560 */
34561 SQLITE_PRIVATE int sqlite3BtreeGetPage(
34562   BtShared *pBt,       /* The btree */
34563   Pgno pgno,           /* Number of the page to fetch */
34564   MemPage **ppPage,    /* Return the page in this parameter */
34565   int noContent        /* Do not load page content if true */
34566 ){
34567   int rc;
34568   DbPage *pDbPage;
34569
34570   assert( sqlite3_mutex_held(pBt->mutex) );
34571   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
34572   if( rc ) return rc;
34573   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
34574   return SQLITE_OK;
34575 }
34576
34577 /*
34578 ** Return the size of the database file in pages.  Or return -1 if
34579 ** there is any kind of error.
34580 */
34581 static int pagerPagecount(Pager *pPager){
34582   int rc;
34583   int nPage;
34584   rc = sqlite3PagerPagecount(pPager, &nPage);
34585   return (rc==SQLITE_OK?nPage:-1);
34586 }
34587
34588 /*
34589 ** Get a page from the pager and initialize it.  This routine
34590 ** is just a convenience wrapper around separate calls to
34591 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
34592 */
34593 static int getAndInitPage(
34594   BtShared *pBt,          /* The database file */
34595   Pgno pgno,           /* Number of the page to get */
34596   MemPage **ppPage     /* Write the page pointer here */
34597 ){
34598   int rc;
34599   DbPage *pDbPage;
34600   MemPage *pPage;
34601
34602   assert( sqlite3_mutex_held(pBt->mutex) );
34603   if( pgno==0 ){
34604     return SQLITE_CORRUPT_BKPT; 
34605   }
34606
34607   /* It is often the case that the page we want is already in cache.
34608   ** If so, get it directly.  This saves us from having to call
34609   ** pagerPagecount() to make sure pgno is within limits, which results
34610   ** in a measureable performance improvements.
34611   */
34612   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
34613   if( pDbPage ){
34614     /* Page is already in cache */
34615     *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
34616     rc = SQLITE_OK;
34617   }else{
34618     /* Page not in cache.  Acquire it. */
34619     if( pgno>pagerPagecount(pBt->pPager) ){
34620       return SQLITE_CORRUPT_BKPT; 
34621     }
34622     rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
34623     if( rc ) return rc;
34624     pPage = *ppPage;
34625   }
34626   if( !pPage->isInit ){
34627     rc = sqlite3BtreeInitPage(pPage);
34628   }
34629   if( rc!=SQLITE_OK ){
34630     releasePage(pPage);
34631     *ppPage = 0;
34632   }
34633   return rc;
34634 }
34635
34636 /*
34637 ** Release a MemPage.  This should be called once for each prior
34638 ** call to sqlite3BtreeGetPage.
34639 */
34640 static void releasePage(MemPage *pPage){
34641   if( pPage ){
34642     assert( pPage->aData );
34643     assert( pPage->pBt );
34644     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
34645     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
34646     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34647     sqlite3PagerUnref(pPage->pDbPage);
34648   }
34649 }
34650
34651 /*
34652 ** During a rollback, when the pager reloads information into the cache
34653 ** so that the cache is restored to its original state at the start of
34654 ** the transaction, for each page restored this routine is called.
34655 **
34656 ** This routine needs to reset the extra data section at the end of the
34657 ** page to agree with the restored data.
34658 */
34659 static void pageReinit(DbPage *pData){
34660   MemPage *pPage;
34661   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
34662   if( pPage->isInit ){
34663     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
34664     pPage->isInit = 0;
34665     if( sqlite3PagerPageRefcount(pData)>0 ){
34666       sqlite3BtreeInitPage(pPage);
34667     }
34668   }
34669 }
34670
34671 /*
34672 ** Invoke the busy handler for a btree.
34673 */
34674 static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
34675   BtShared *pBt = (BtShared*)pArg;
34676   assert( pBt->db );
34677   assert( sqlite3_mutex_held(pBt->db->mutex) );
34678   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
34679 }
34680
34681 /*
34682 ** Open a database file.
34683 ** 
34684 ** zFilename is the name of the database file.  If zFilename is NULL
34685 ** a new database with a random name is created.  This randomly named
34686 ** database file will be deleted when sqlite3BtreeClose() is called.
34687 ** If zFilename is ":memory:" then an in-memory database is created
34688 ** that is automatically destroyed when it is closed.
34689 */
34690 SQLITE_PRIVATE int sqlite3BtreeOpen(
34691   const char *zFilename,  /* Name of the file containing the BTree database */
34692   sqlite3 *db,            /* Associated database handle */
34693   Btree **ppBtree,        /* Pointer to new Btree object written here */
34694   int flags,              /* Options */
34695   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
34696 ){
34697   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
34698   BtShared *pBt = 0;      /* Shared part of btree structure */
34699   Btree *p;               /* Handle to return */
34700   int rc = SQLITE_OK;
34701   int nReserve;
34702   unsigned char zDbHeader[100];
34703
34704   /* Set the variable isMemdb to true for an in-memory database, or 
34705   ** false for a file-based database. This symbol is only required if
34706   ** either of the shared-data or autovacuum features are compiled 
34707   ** into the library.
34708   */
34709 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
34710   #ifdef SQLITE_OMIT_MEMORYDB
34711     const int isMemdb = 0;
34712   #else
34713     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
34714   #endif
34715 #endif
34716
34717   assert( db!=0 );
34718   assert( sqlite3_mutex_held(db->mutex) );
34719
34720   pVfs = db->pVfs;
34721   p = sqlite3MallocZero(sizeof(Btree));
34722   if( !p ){
34723     return SQLITE_NOMEM;
34724   }
34725   p->inTrans = TRANS_NONE;
34726   p->db = db;
34727
34728 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34729   /*
34730   ** If this Btree is a candidate for shared cache, try to find an
34731   ** existing BtShared object that we can share with
34732   */
34733   if( isMemdb==0
34734    && (db->flags & SQLITE_Vtab)==0
34735    && zFilename && zFilename[0]
34736   ){
34737     if( sqlite3GlobalConfig.sharedCacheEnabled ){
34738       int nFullPathname = pVfs->mxPathname+1;
34739       char *zFullPathname = sqlite3Malloc(nFullPathname);
34740       sqlite3_mutex *mutexShared;
34741       p->sharable = 1;
34742       db->flags |= SQLITE_SharedCache;
34743       if( !zFullPathname ){
34744         sqlite3_free(p);
34745         return SQLITE_NOMEM;
34746       }
34747       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
34748       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34749       sqlite3_mutex_enter(mutexShared);
34750       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
34751         assert( pBt->nRef>0 );
34752         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
34753                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
34754           p->pBt = pBt;
34755           pBt->nRef++;
34756           break;
34757         }
34758       }
34759       sqlite3_mutex_leave(mutexShared);
34760       sqlite3_free(zFullPathname);
34761     }
34762 #ifdef SQLITE_DEBUG
34763     else{
34764       /* In debug mode, we mark all persistent databases as sharable
34765       ** even when they are not.  This exercises the locking code and
34766       ** gives more opportunity for asserts(sqlite3_mutex_held())
34767       ** statements to find locking problems.
34768       */
34769       p->sharable = 1;
34770     }
34771 #endif
34772   }
34773 #endif
34774   if( pBt==0 ){
34775     /*
34776     ** The following asserts make sure that structures used by the btree are
34777     ** the right size.  This is to guard against size changes that result
34778     ** when compiling on a different architecture.
34779     */
34780     assert( sizeof(i64)==8 || sizeof(i64)==4 );
34781     assert( sizeof(u64)==8 || sizeof(u64)==4 );
34782     assert( sizeof(u32)==4 );
34783     assert( sizeof(u16)==2 );
34784     assert( sizeof(Pgno)==4 );
34785   
34786     pBt = sqlite3MallocZero( sizeof(*pBt) );
34787     if( pBt==0 ){
34788       rc = SQLITE_NOMEM;
34789       goto btree_open_out;
34790     }
34791     pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
34792     pBt->busyHdr.pArg = pBt;
34793     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
34794                           EXTRA_SIZE, flags, vfsFlags);
34795     if( rc==SQLITE_OK ){
34796       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
34797     }
34798     if( rc!=SQLITE_OK ){
34799       goto btree_open_out;
34800     }
34801     sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
34802     p->pBt = pBt;
34803   
34804     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
34805     pBt->pCursor = 0;
34806     pBt->pPage1 = 0;
34807     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
34808     pBt->pageSize = get2byte(&zDbHeader[16]);
34809     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
34810          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
34811       pBt->pageSize = 0;
34812       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34813 #ifndef SQLITE_OMIT_AUTOVACUUM
34814       /* If the magic name ":memory:" will create an in-memory database, then
34815       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
34816       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
34817       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
34818       ** regular file-name. In this case the auto-vacuum applies as per normal.
34819       */
34820       if( zFilename && !isMemdb ){
34821         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
34822         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
34823       }
34824 #endif
34825       nReserve = 0;
34826     }else{
34827       nReserve = zDbHeader[20];
34828       pBt->pageSizeFixed = 1;
34829 #ifndef SQLITE_OMIT_AUTOVACUUM
34830       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
34831       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
34832 #endif
34833     }
34834     pBt->usableSize = pBt->pageSize - nReserve;
34835     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
34836     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
34837    
34838 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34839     /* Add the new BtShared object to the linked list sharable BtShareds.
34840     */
34841     if( p->sharable ){
34842       sqlite3_mutex *mutexShared;
34843       pBt->nRef = 1;
34844       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34845       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
34846         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
34847         if( pBt->mutex==0 ){
34848           rc = SQLITE_NOMEM;
34849           db->mallocFailed = 0;
34850           goto btree_open_out;
34851         }
34852       }
34853       sqlite3_mutex_enter(mutexShared);
34854       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
34855       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
34856       sqlite3_mutex_leave(mutexShared);
34857     }
34858 #endif
34859   }
34860
34861 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
34862   /* If the new Btree uses a sharable pBtShared, then link the new
34863   ** Btree into the list of all sharable Btrees for the same connection.
34864   ** The list is kept in ascending order by pBt address.
34865   */
34866   if( p->sharable ){
34867     int i;
34868     Btree *pSib;
34869     for(i=0; i<db->nDb; i++){
34870       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
34871         while( pSib->pPrev ){ pSib = pSib->pPrev; }
34872         if( p->pBt<pSib->pBt ){
34873           p->pNext = pSib;
34874           p->pPrev = 0;
34875           pSib->pPrev = p;
34876         }else{
34877           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
34878             pSib = pSib->pNext;
34879           }
34880           p->pNext = pSib->pNext;
34881           p->pPrev = pSib;
34882           if( p->pNext ){
34883             p->pNext->pPrev = p;
34884           }
34885           pSib->pNext = p;
34886         }
34887         break;
34888       }
34889     }
34890   }
34891 #endif
34892   *ppBtree = p;
34893
34894 btree_open_out:
34895   if( rc!=SQLITE_OK ){
34896     if( pBt && pBt->pPager ){
34897       sqlite3PagerClose(pBt->pPager);
34898     }
34899     sqlite3_free(pBt);
34900     sqlite3_free(p);
34901     *ppBtree = 0;
34902   }
34903   return rc;
34904 }
34905
34906 /*
34907 ** Decrement the BtShared.nRef counter.  When it reaches zero,
34908 ** remove the BtShared structure from the sharing list.  Return
34909 ** true if the BtShared.nRef counter reaches zero and return
34910 ** false if it is still positive.
34911 */
34912 static int removeFromSharingList(BtShared *pBt){
34913 #ifndef SQLITE_OMIT_SHARED_CACHE
34914   sqlite3_mutex *pMaster;
34915   BtShared *pList;
34916   int removed = 0;
34917
34918   assert( sqlite3_mutex_notheld(pBt->mutex) );
34919   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
34920   sqlite3_mutex_enter(pMaster);
34921   pBt->nRef--;
34922   if( pBt->nRef<=0 ){
34923     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
34924       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
34925     }else{
34926       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
34927       while( ALWAYS(pList) && pList->pNext!=pBt ){
34928         pList=pList->pNext;
34929       }
34930       if( ALWAYS(pList) ){
34931         pList->pNext = pBt->pNext;
34932       }
34933     }
34934     if( SQLITE_THREADSAFE ){
34935       sqlite3_mutex_free(pBt->mutex);
34936     }
34937     removed = 1;
34938   }
34939   sqlite3_mutex_leave(pMaster);
34940   return removed;
34941 #else
34942   return 1;
34943 #endif
34944 }
34945
34946 /*
34947 ** Make sure pBt->pTmpSpace points to an allocation of 
34948 ** MX_CELL_SIZE(pBt) bytes.
34949 */
34950 static void allocateTempSpace(BtShared *pBt){
34951   if( !pBt->pTmpSpace ){
34952     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
34953   }
34954 }
34955
34956 /*
34957 ** Free the pBt->pTmpSpace allocation
34958 */
34959 static void freeTempSpace(BtShared *pBt){
34960   sqlite3PageFree( pBt->pTmpSpace);
34961   pBt->pTmpSpace = 0;
34962 }
34963
34964 /*
34965 ** Close an open database and invalidate all cursors.
34966 */
34967 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
34968   BtShared *pBt = p->pBt;
34969   BtCursor *pCur;
34970
34971   /* Close all cursors opened via this handle.  */
34972   assert( sqlite3_mutex_held(p->db->mutex) );
34973   sqlite3BtreeEnter(p);
34974   pBt->db = p->db;
34975   pCur = pBt->pCursor;
34976   while( pCur ){
34977     BtCursor *pTmp = pCur;
34978     pCur = pCur->pNext;
34979     if( pTmp->pBtree==p ){
34980       sqlite3BtreeCloseCursor(pTmp);
34981     }
34982   }
34983
34984   /* Rollback any active transaction and free the handle structure.
34985   ** The call to sqlite3BtreeRollback() drops any table-locks held by
34986   ** this handle.
34987   */
34988   sqlite3BtreeRollback(p);
34989   sqlite3BtreeLeave(p);
34990
34991   /* If there are still other outstanding references to the shared-btree
34992   ** structure, return now. The remainder of this procedure cleans 
34993   ** up the shared-btree.
34994   */
34995   assert( p->wantToLock==0 && p->locked==0 );
34996   if( !p->sharable || removeFromSharingList(pBt) ){
34997     /* The pBt is no longer on the sharing list, so we can access
34998     ** it without having to hold the mutex.
34999     **
35000     ** Clean out and delete the BtShared object.
35001     */
35002     assert( !pBt->pCursor );
35003     sqlite3PagerClose(pBt->pPager);
35004     if( pBt->xFreeSchema && pBt->pSchema ){
35005       pBt->xFreeSchema(pBt->pSchema);
35006     }
35007     sqlite3_free(pBt->pSchema);
35008     freeTempSpace(pBt);
35009     sqlite3_free(pBt);
35010   }
35011
35012 #ifndef SQLITE_OMIT_SHARED_CACHE
35013   assert( p->wantToLock==0 );
35014   assert( p->locked==0 );
35015   if( p->pPrev ) p->pPrev->pNext = p->pNext;
35016   if( p->pNext ) p->pNext->pPrev = p->pPrev;
35017 #endif
35018
35019   sqlite3_free(p);
35020   return SQLITE_OK;
35021 }
35022
35023 /*
35024 ** Change the limit on the number of pages allowed in the cache.
35025 **
35026 ** The maximum number of cache pages is set to the absolute
35027 ** value of mxPage.  If mxPage is negative, the pager will
35028 ** operate asynchronously - it will not stop to do fsync()s
35029 ** to insure data is written to the disk surface before
35030 ** continuing.  Transactions still work if synchronous is off,
35031 ** and the database cannot be corrupted if this program
35032 ** crashes.  But if the operating system crashes or there is
35033 ** an abrupt power failure when synchronous is off, the database
35034 ** could be left in an inconsistent and unrecoverable state.
35035 ** Synchronous is on by default so database corruption is not
35036 ** normally a worry.
35037 */
35038 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
35039   BtShared *pBt = p->pBt;
35040   assert( sqlite3_mutex_held(p->db->mutex) );
35041   sqlite3BtreeEnter(p);
35042   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
35043   sqlite3BtreeLeave(p);
35044   return SQLITE_OK;
35045 }
35046
35047 /*
35048 ** Change the way data is synced to disk in order to increase or decrease
35049 ** how well the database resists damage due to OS crashes and power
35050 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
35051 ** there is a high probability of damage)  Level 2 is the default.  There
35052 ** is a very low but non-zero probability of damage.  Level 3 reduces the
35053 ** probability of damage to near zero but with a write performance reduction.
35054 */
35055 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
35056 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
35057   BtShared *pBt = p->pBt;
35058   assert( sqlite3_mutex_held(p->db->mutex) );
35059   sqlite3BtreeEnter(p);
35060   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
35061   sqlite3BtreeLeave(p);
35062   return SQLITE_OK;
35063 }
35064 #endif
35065
35066 /*
35067 ** Return TRUE if the given btree is set to safety level 1.  In other
35068 ** words, return TRUE if no sync() occurs on the disk files.
35069 */
35070 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
35071   BtShared *pBt = p->pBt;
35072   int rc;
35073   assert( sqlite3_mutex_held(p->db->mutex) );  
35074   sqlite3BtreeEnter(p);
35075   assert( pBt && pBt->pPager );
35076   rc = sqlite3PagerNosync(pBt->pPager);
35077   sqlite3BtreeLeave(p);
35078   return rc;
35079 }
35080
35081 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
35082 /*
35083 ** Change the default pages size and the number of reserved bytes per page.
35084 **
35085 ** The page size must be a power of 2 between 512 and 65536.  If the page
35086 ** size supplied does not meet this constraint then the page size is not
35087 ** changed.
35088 **
35089 ** Page sizes are constrained to be a power of two so that the region
35090 ** of the database file used for locking (beginning at PENDING_BYTE,
35091 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
35092 ** at the beginning of a page.
35093 **
35094 ** If parameter nReserve is less than zero, then the number of reserved
35095 ** bytes per page is left unchanged.
35096 */
35097 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
35098   int rc = SQLITE_OK;
35099   BtShared *pBt = p->pBt;
35100   sqlite3BtreeEnter(p);
35101   if( pBt->pageSizeFixed ){
35102     sqlite3BtreeLeave(p);
35103     return SQLITE_READONLY;
35104   }
35105   if( nReserve<0 ){
35106     nReserve = pBt->pageSize - pBt->usableSize;
35107   }
35108   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
35109         ((pageSize-1)&pageSize)==0 ){
35110     assert( (pageSize & 7)==0 );
35111     assert( !pBt->pPage1 && !pBt->pCursor );
35112     pBt->pageSize = pageSize;
35113     freeTempSpace(pBt);
35114     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35115   }
35116   pBt->usableSize = pBt->pageSize - nReserve;
35117   sqlite3BtreeLeave(p);
35118   return rc;
35119 }
35120
35121 /*
35122 ** Return the currently defined page size
35123 */
35124 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
35125   return p->pBt->pageSize;
35126 }
35127 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
35128   int n;
35129   sqlite3BtreeEnter(p);
35130   n = p->pBt->pageSize - p->pBt->usableSize;
35131   sqlite3BtreeLeave(p);
35132   return n;
35133 }
35134
35135 /*
35136 ** Set the maximum page count for a database if mxPage is positive.
35137 ** No changes are made if mxPage is 0 or negative.
35138 ** Regardless of the value of mxPage, return the maximum page count.
35139 */
35140 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
35141   int n;
35142   sqlite3BtreeEnter(p);
35143   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
35144   sqlite3BtreeLeave(p);
35145   return n;
35146 }
35147 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
35148
35149 /*
35150 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
35151 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
35152 ** is disabled. The default value for the auto-vacuum property is 
35153 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
35154 */
35155 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
35156 #ifdef SQLITE_OMIT_AUTOVACUUM
35157   return SQLITE_READONLY;
35158 #else
35159   BtShared *pBt = p->pBt;
35160   int rc = SQLITE_OK;
35161   int av = (autoVacuum?1:0);
35162
35163   sqlite3BtreeEnter(p);
35164   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
35165     rc = SQLITE_READONLY;
35166   }else{
35167     pBt->autoVacuum = av;
35168   }
35169   sqlite3BtreeLeave(p);
35170   return rc;
35171 #endif
35172 }
35173
35174 /*
35175 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
35176 ** enabled 1 is returned. Otherwise 0.
35177 */
35178 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
35179 #ifdef SQLITE_OMIT_AUTOVACUUM
35180   return BTREE_AUTOVACUUM_NONE;
35181 #else
35182   int rc;
35183   sqlite3BtreeEnter(p);
35184   rc = (
35185     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
35186     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
35187     BTREE_AUTOVACUUM_INCR
35188   );
35189   sqlite3BtreeLeave(p);
35190   return rc;
35191 #endif
35192 }
35193
35194
35195 /*
35196 ** Get a reference to pPage1 of the database file.  This will
35197 ** also acquire a readlock on that file.
35198 **
35199 ** SQLITE_OK is returned on success.  If the file is not a
35200 ** well-formed database file, then SQLITE_CORRUPT is returned.
35201 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
35202 ** is returned if we run out of memory. 
35203 */
35204 static int lockBtree(BtShared *pBt){
35205   int rc;
35206   MemPage *pPage1;
35207   int nPage;
35208
35209   assert( sqlite3_mutex_held(pBt->mutex) );
35210   if( pBt->pPage1 ) return SQLITE_OK;
35211   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
35212   if( rc!=SQLITE_OK ) return rc;
35213
35214   /* Do some checking to help insure the file we opened really is
35215   ** a valid database file. 
35216   */
35217   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35218   if( rc!=SQLITE_OK ){
35219     goto page1_init_failed;
35220   }else if( nPage>0 ){
35221     int pageSize;
35222     int usableSize;
35223     u8 *page1 = pPage1->aData;
35224     rc = SQLITE_NOTADB;
35225     if( memcmp(page1, zMagicHeader, 16)!=0 ){
35226       goto page1_init_failed;
35227     }
35228     if( page1[18]>1 ){
35229       pBt->readOnly = 1;
35230     }
35231     if( page1[19]>1 ){
35232       goto page1_init_failed;
35233     }
35234
35235     /* The maximum embedded fraction must be exactly 25%.  And the minimum
35236     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
35237     ** The original design allowed these amounts to vary, but as of
35238     ** version 3.6.0, we require them to be fixed.
35239     */
35240     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
35241       goto page1_init_failed;
35242     }
35243     pageSize = get2byte(&page1[16]);
35244     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
35245         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
35246     ){
35247       goto page1_init_failed;
35248     }
35249     assert( (pageSize & 7)==0 );
35250     usableSize = pageSize - page1[20];
35251     if( pageSize!=pBt->pageSize ){
35252       /* After reading the first page of the database assuming a page size
35253       ** of BtShared.pageSize, we have discovered that the page-size is
35254       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
35255       ** zero and return SQLITE_OK. The caller will call this function
35256       ** again with the correct page-size.
35257       */
35258       releasePage(pPage1);
35259       pBt->usableSize = usableSize;
35260       pBt->pageSize = pageSize;
35261       freeTempSpace(pBt);
35262       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
35263       return SQLITE_OK;
35264     }
35265     if( usableSize<500 ){
35266       goto page1_init_failed;
35267     }
35268     pBt->pageSize = pageSize;
35269     pBt->usableSize = usableSize;
35270 #ifndef SQLITE_OMIT_AUTOVACUUM
35271     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
35272     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
35273 #endif
35274   }
35275
35276   /* maxLocal is the maximum amount of payload to store locally for
35277   ** a cell.  Make sure it is small enough so that at least minFanout
35278   ** cells can will fit on one page.  We assume a 10-byte page header.
35279   ** Besides the payload, the cell must store:
35280   **     2-byte pointer to the cell
35281   **     4-byte child pointer
35282   **     9-byte nKey value
35283   **     4-byte nData value
35284   **     4-byte overflow page pointer
35285   ** So a cell consists of a 2-byte poiner, a header which is as much as
35286   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
35287   ** page pointer.
35288   */
35289   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
35290   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
35291   pBt->maxLeaf = pBt->usableSize - 35;
35292   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
35293   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
35294   pBt->pPage1 = pPage1;
35295   return SQLITE_OK;
35296
35297 page1_init_failed:
35298   releasePage(pPage1);
35299   pBt->pPage1 = 0;
35300   return rc;
35301 }
35302
35303 /*
35304 ** This routine works like lockBtree() except that it also invokes the
35305 ** busy callback if there is lock contention.
35306 */
35307 static int lockBtreeWithRetry(Btree *pRef){
35308   int rc = SQLITE_OK;
35309
35310   assert( sqlite3BtreeHoldsMutex(pRef) );
35311   if( pRef->inTrans==TRANS_NONE ){
35312     u8 inTransaction = pRef->pBt->inTransaction;
35313     btreeIntegrity(pRef);
35314     rc = sqlite3BtreeBeginTrans(pRef, 0);
35315     pRef->pBt->inTransaction = inTransaction;
35316     pRef->inTrans = TRANS_NONE;
35317     if( rc==SQLITE_OK ){
35318       pRef->pBt->nTransaction--;
35319     }
35320     btreeIntegrity(pRef);
35321   }
35322   return rc;
35323 }
35324        
35325
35326 /*
35327 ** If there are no outstanding cursors and we are not in the middle
35328 ** of a transaction but there is a read lock on the database, then
35329 ** this routine unrefs the first page of the database file which 
35330 ** has the effect of releasing the read lock.
35331 **
35332 ** If there are any outstanding cursors, this routine is a no-op.
35333 **
35334 ** If there is a transaction in progress, this routine is a no-op.
35335 */
35336 static void unlockBtreeIfUnused(BtShared *pBt){
35337   assert( sqlite3_mutex_held(pBt->mutex) );
35338   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
35339     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
35340       assert( pBt->pPage1->aData );
35341 #if 0
35342       if( pBt->pPage1->aData==0 ){
35343         MemPage *pPage = pBt->pPage1;
35344         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
35345         pPage->pBt = pBt;
35346         pPage->pgno = 1;
35347       }
35348 #endif
35349       releasePage(pBt->pPage1);
35350     }
35351     pBt->pPage1 = 0;
35352     pBt->inStmt = 0;
35353   }
35354 }
35355
35356 /*
35357 ** Create a new database by initializing the first page of the
35358 ** file.
35359 */
35360 static int newDatabase(BtShared *pBt){
35361   MemPage *pP1;
35362   unsigned char *data;
35363   int rc;
35364   int nPage;
35365
35366   assert( sqlite3_mutex_held(pBt->mutex) );
35367   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
35368   if( rc!=SQLITE_OK || nPage>0 ){
35369     return rc;
35370   }
35371   pP1 = pBt->pPage1;
35372   assert( pP1!=0 );
35373   data = pP1->aData;
35374   rc = sqlite3PagerWrite(pP1->pDbPage);
35375   if( rc ) return rc;
35376   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
35377   assert( sizeof(zMagicHeader)==16 );
35378   put2byte(&data[16], pBt->pageSize);
35379   data[18] = 1;
35380   data[19] = 1;
35381   data[20] = pBt->pageSize - pBt->usableSize;
35382   data[21] = 64;
35383   data[22] = 32;
35384   data[23] = 32;
35385   memset(&data[24], 0, 100-24);
35386   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
35387   pBt->pageSizeFixed = 1;
35388 #ifndef SQLITE_OMIT_AUTOVACUUM
35389   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
35390   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
35391   put4byte(&data[36 + 4*4], pBt->autoVacuum);
35392   put4byte(&data[36 + 7*4], pBt->incrVacuum);
35393 #endif
35394   return SQLITE_OK;
35395 }
35396
35397 /*
35398 ** Attempt to start a new transaction. A write-transaction
35399 ** is started if the second argument is nonzero, otherwise a read-
35400 ** transaction.  If the second argument is 2 or more and exclusive
35401 ** transaction is started, meaning that no other process is allowed
35402 ** to access the database.  A preexisting transaction may not be
35403 ** upgraded to exclusive by calling this routine a second time - the
35404 ** exclusivity flag only works for a new transaction.
35405 **
35406 ** A write-transaction must be started before attempting any 
35407 ** changes to the database.  None of the following routines 
35408 ** will work unless a transaction is started first:
35409 **
35410 **      sqlite3BtreeCreateTable()
35411 **      sqlite3BtreeCreateIndex()
35412 **      sqlite3BtreeClearTable()
35413 **      sqlite3BtreeDropTable()
35414 **      sqlite3BtreeInsert()
35415 **      sqlite3BtreeDelete()
35416 **      sqlite3BtreeUpdateMeta()
35417 **
35418 ** If an initial attempt to acquire the lock fails because of lock contention
35419 ** and the database was previously unlocked, then invoke the busy handler
35420 ** if there is one.  But if there was previously a read-lock, do not
35421 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
35422 ** returned when there is already a read-lock in order to avoid a deadlock.
35423 **
35424 ** Suppose there are two processes A and B.  A has a read lock and B has
35425 ** a reserved lock.  B tries to promote to exclusive but is blocked because
35426 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
35427 ** One or the other of the two processes must give way or there can be
35428 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
35429 ** when A already has a read lock, we encourage A to give up and let B
35430 ** proceed.
35431 */
35432 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
35433   BtShared *pBt = p->pBt;
35434   int rc = SQLITE_OK;
35435
35436   sqlite3BtreeEnter(p);
35437   pBt->db = p->db;
35438   btreeIntegrity(p);
35439
35440   /* If the btree is already in a write-transaction, or it
35441   ** is already in a read-transaction and a read-transaction
35442   ** is requested, this is a no-op.
35443   */
35444   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
35445     goto trans_begun;
35446   }
35447
35448   /* Write transactions are not possible on a read-only database */
35449   if( pBt->readOnly && wrflag ){
35450     rc = SQLITE_READONLY;
35451     goto trans_begun;
35452   }
35453
35454   /* If another database handle has already opened a write transaction 
35455   ** on this shared-btree structure and a second write transaction is
35456   ** requested, return SQLITE_BUSY.
35457   */
35458   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
35459     rc = SQLITE_BUSY;
35460     goto trans_begun;
35461   }
35462
35463 #ifndef SQLITE_OMIT_SHARED_CACHE
35464   if( wrflag>1 ){
35465     BtLock *pIter;
35466     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
35467       if( pIter->pBtree!=p ){
35468         rc = SQLITE_BUSY;
35469         goto trans_begun;
35470       }
35471     }
35472   }
35473 #endif
35474
35475   do {
35476     if( pBt->pPage1==0 ){
35477       do{
35478         rc = lockBtree(pBt);
35479       }while( pBt->pPage1==0 && rc==SQLITE_OK );
35480     }
35481
35482     if( rc==SQLITE_OK && wrflag ){
35483       if( pBt->readOnly ){
35484         rc = SQLITE_READONLY;
35485       }else{
35486         rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
35487         if( rc==SQLITE_OK ){
35488           rc = newDatabase(pBt);
35489         }
35490       }
35491     }
35492   
35493     if( rc==SQLITE_OK ){
35494       if( wrflag ) pBt->inStmt = 0;
35495     }else{
35496       unlockBtreeIfUnused(pBt);
35497     }
35498   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
35499           sqlite3BtreeInvokeBusyHandler(pBt, 0) );
35500
35501   if( rc==SQLITE_OK ){
35502     if( p->inTrans==TRANS_NONE ){
35503       pBt->nTransaction++;
35504     }
35505     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
35506     if( p->inTrans>pBt->inTransaction ){
35507       pBt->inTransaction = p->inTrans;
35508     }
35509 #ifndef SQLITE_OMIT_SHARED_CACHE
35510     if( wrflag>1 ){
35511       assert( !pBt->pExclusive );
35512       pBt->pExclusive = p;
35513     }
35514 #endif
35515   }
35516
35517
35518 trans_begun:
35519   btreeIntegrity(p);
35520   sqlite3BtreeLeave(p);
35521   return rc;
35522 }
35523
35524
35525 #ifndef SQLITE_OMIT_AUTOVACUUM
35526
35527 /*
35528 ** Set the pointer-map entries for all children of page pPage. Also, if
35529 ** pPage contains cells that point to overflow pages, set the pointer
35530 ** map entries for the overflow pages as well.
35531 */
35532 static int setChildPtrmaps(MemPage *pPage){
35533   int i;                             /* Counter variable */
35534   int nCell;                         /* Number of cells in page pPage */
35535   int rc;                            /* Return code */
35536   BtShared *pBt = pPage->pBt;
35537   int isInitOrig = pPage->isInit;
35538   Pgno pgno = pPage->pgno;
35539
35540   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35541   rc = sqlite3BtreeInitPage(pPage);
35542   if( rc!=SQLITE_OK ){
35543     goto set_child_ptrmaps_out;
35544   }
35545   nCell = pPage->nCell;
35546
35547   for(i=0; i<nCell; i++){
35548     u8 *pCell = findCell(pPage, i);
35549
35550     rc = ptrmapPutOvflPtr(pPage, pCell);
35551     if( rc!=SQLITE_OK ){
35552       goto set_child_ptrmaps_out;
35553     }
35554
35555     if( !pPage->leaf ){
35556       Pgno childPgno = get4byte(pCell);
35557       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35558       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
35559     }
35560   }
35561
35562   if( !pPage->leaf ){
35563     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
35564     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
35565   }
35566
35567 set_child_ptrmaps_out:
35568   pPage->isInit = isInitOrig;
35569   return rc;
35570 }
35571
35572 /*
35573 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
35574 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
35575 ** iTo. Parameter eType describes the type of pointer to be modified, as 
35576 ** follows:
35577 **
35578 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
35579 **                   page of pPage.
35580 **
35581 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
35582 **                   page pointed to by one of the cells on pPage.
35583 **
35584 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
35585 **                   overflow page in the list.
35586 */
35587 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
35588   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
35589   if( eType==PTRMAP_OVERFLOW2 ){
35590     /* The pointer is always the first 4 bytes of the page in this case.  */
35591     if( get4byte(pPage->aData)!=iFrom ){
35592       return SQLITE_CORRUPT_BKPT;
35593     }
35594     put4byte(pPage->aData, iTo);
35595   }else{
35596     int isInitOrig = pPage->isInit;
35597     int i;
35598     int nCell;
35599
35600     sqlite3BtreeInitPage(pPage);
35601     nCell = pPage->nCell;
35602
35603     for(i=0; i<nCell; i++){
35604       u8 *pCell = findCell(pPage, i);
35605       if( eType==PTRMAP_OVERFLOW1 ){
35606         CellInfo info;
35607         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
35608         if( info.iOverflow ){
35609           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
35610             put4byte(&pCell[info.iOverflow], iTo);
35611             break;
35612           }
35613         }
35614       }else{
35615         if( get4byte(pCell)==iFrom ){
35616           put4byte(pCell, iTo);
35617           break;
35618         }
35619       }
35620     }
35621   
35622     if( i==nCell ){
35623       if( eType!=PTRMAP_BTREE || 
35624           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
35625         return SQLITE_CORRUPT_BKPT;
35626       }
35627       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
35628     }
35629
35630     pPage->isInit = isInitOrig;
35631   }
35632   return SQLITE_OK;
35633 }
35634
35635
35636 /*
35637 ** Move the open database page pDbPage to location iFreePage in the 
35638 ** database. The pDbPage reference remains valid.
35639 */
35640 static int relocatePage(
35641   BtShared *pBt,           /* Btree */
35642   MemPage *pDbPage,        /* Open page to move */
35643   u8 eType,                /* Pointer map 'type' entry for pDbPage */
35644   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
35645   Pgno iFreePage,          /* The location to move pDbPage to */
35646   int isCommit
35647 ){
35648   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
35649   Pgno iDbPage = pDbPage->pgno;
35650   Pager *pPager = pBt->pPager;
35651   int rc;
35652
35653   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
35654       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
35655   assert( sqlite3_mutex_held(pBt->mutex) );
35656   assert( pDbPage->pBt==pBt );
35657
35658   /* Move page iDbPage from its current location to page number iFreePage */
35659   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
35660       iDbPage, iFreePage, iPtrPage, eType));
35661   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
35662   if( rc!=SQLITE_OK ){
35663     return rc;
35664   }
35665   pDbPage->pgno = iFreePage;
35666
35667   /* If pDbPage was a btree-page, then it may have child pages and/or cells
35668   ** that point to overflow pages. The pointer map entries for all these
35669   ** pages need to be changed.
35670   **
35671   ** If pDbPage is an overflow page, then the first 4 bytes may store a
35672   ** pointer to a subsequent overflow page. If this is the case, then
35673   ** the pointer map needs to be updated for the subsequent overflow page.
35674   */
35675   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
35676     rc = setChildPtrmaps(pDbPage);
35677     if( rc!=SQLITE_OK ){
35678       return rc;
35679     }
35680   }else{
35681     Pgno nextOvfl = get4byte(pDbPage->aData);
35682     if( nextOvfl!=0 ){
35683       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
35684       if( rc!=SQLITE_OK ){
35685         return rc;
35686       }
35687     }
35688   }
35689
35690   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
35691   ** that it points at iFreePage. Also fix the pointer map entry for
35692   ** iPtrPage.
35693   */
35694   if( eType!=PTRMAP_ROOTPAGE ){
35695     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
35696     if( rc!=SQLITE_OK ){
35697       return rc;
35698     }
35699     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
35700     if( rc!=SQLITE_OK ){
35701       releasePage(pPtrPage);
35702       return rc;
35703     }
35704     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
35705     releasePage(pPtrPage);
35706     if( rc==SQLITE_OK ){
35707       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
35708     }
35709   }
35710   return rc;
35711 }
35712
35713 /* Forward declaration required by incrVacuumStep(). */
35714 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
35715
35716 /*
35717 ** Perform a single step of an incremental-vacuum. If successful,
35718 ** return SQLITE_OK. If there is no work to do (and therefore no
35719 ** point in calling this function again), return SQLITE_DONE.
35720 **
35721 ** More specificly, this function attempts to re-organize the 
35722 ** database so that the last page of the file currently in use
35723 ** is no longer in use.
35724 **
35725 ** If the nFin parameter is non-zero, the implementation assumes
35726 ** that the caller will keep calling incrVacuumStep() until
35727 ** it returns SQLITE_DONE or an error, and that nFin is the
35728 ** number of pages the database file will contain after this 
35729 ** process is complete.
35730 */
35731 static int incrVacuumStep(BtShared *pBt, Pgno nFin){
35732   Pgno iLastPg;             /* Last page in the database */
35733   Pgno nFreeList;           /* Number of pages still on the free-list */
35734
35735   assert( sqlite3_mutex_held(pBt->mutex) );
35736   iLastPg = pBt->nTrunc;
35737   if( iLastPg==0 ){
35738     iLastPg = pagerPagecount(pBt->pPager);
35739   }
35740
35741   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
35742     int rc;
35743     u8 eType;
35744     Pgno iPtrPage;
35745
35746     nFreeList = get4byte(&pBt->pPage1->aData[36]);
35747     if( nFreeList==0 || nFin==iLastPg ){
35748       return SQLITE_DONE;
35749     }
35750
35751     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
35752     if( rc!=SQLITE_OK ){
35753       return rc;
35754     }
35755     if( eType==PTRMAP_ROOTPAGE ){
35756       return SQLITE_CORRUPT_BKPT;
35757     }
35758
35759     if( eType==PTRMAP_FREEPAGE ){
35760       if( nFin==0 ){
35761         /* Remove the page from the files free-list. This is not required
35762         ** if nFin is non-zero. In that case, the free-list will be
35763         ** truncated to zero after this function returns, so it doesn't 
35764         ** matter if it still contains some garbage entries.
35765         */
35766         Pgno iFreePg;
35767         MemPage *pFreePg;
35768         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
35769         if( rc!=SQLITE_OK ){
35770           return rc;
35771         }
35772         assert( iFreePg==iLastPg );
35773         releasePage(pFreePg);
35774       }
35775     } else {
35776       Pgno iFreePg;             /* Index of free page to move pLastPg to */
35777       MemPage *pLastPg;
35778
35779       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
35780       if( rc!=SQLITE_OK ){
35781         return rc;
35782       }
35783
35784       /* If nFin is zero, this loop runs exactly once and page pLastPg
35785       ** is swapped with the first free page pulled off the free list.
35786       **
35787       ** On the other hand, if nFin is greater than zero, then keep
35788       ** looping until a free-page located within the first nFin pages
35789       ** of the file is found.
35790       */
35791       do {
35792         MemPage *pFreePg;
35793         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
35794         if( rc!=SQLITE_OK ){
35795           releasePage(pLastPg);
35796           return rc;
35797         }
35798         releasePage(pFreePg);
35799       }while( nFin!=0 && iFreePg>nFin );
35800       assert( iFreePg<iLastPg );
35801       
35802       rc = sqlite3PagerWrite(pLastPg->pDbPage);
35803       if( rc==SQLITE_OK ){
35804         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
35805       }
35806       releasePage(pLastPg);
35807       if( rc!=SQLITE_OK ){
35808         return rc;
35809       }
35810     }
35811   }
35812
35813   pBt->nTrunc = iLastPg - 1;
35814   while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
35815     pBt->nTrunc--;
35816   }
35817   return SQLITE_OK;
35818 }
35819
35820 /*
35821 ** A write-transaction must be opened before calling this function.
35822 ** It performs a single unit of work towards an incremental vacuum.
35823 **
35824 ** If the incremental vacuum is finished after this function has run,
35825 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
35826 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
35827 */
35828 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
35829   int rc;
35830   BtShared *pBt = p->pBt;
35831
35832   sqlite3BtreeEnter(p);
35833   pBt->db = p->db;
35834   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
35835   if( !pBt->autoVacuum ){
35836     rc = SQLITE_DONE;
35837   }else{
35838     invalidateAllOverflowCache(pBt);
35839     rc = incrVacuumStep(pBt, 0);
35840   }
35841   sqlite3BtreeLeave(p);
35842   return rc;
35843 }
35844
35845 /*
35846 ** This routine is called prior to sqlite3PagerCommit when a transaction
35847 ** is commited for an auto-vacuum database.
35848 **
35849 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
35850 ** the database file should be truncated to during the commit process. 
35851 ** i.e. the database has been reorganized so that only the first *pnTrunc
35852 ** pages are in use.
35853 */
35854 static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
35855   int rc = SQLITE_OK;
35856   Pager *pPager = pBt->pPager;
35857   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
35858
35859   assert( sqlite3_mutex_held(pBt->mutex) );
35860   invalidateAllOverflowCache(pBt);
35861   assert(pBt->autoVacuum);
35862   if( !pBt->incrVacuum ){
35863     Pgno nFin = 0;
35864
35865     if( pBt->nTrunc==0 ){
35866       Pgno nFree;
35867       Pgno nPtrmap;
35868       const int pgsz = pBt->pageSize;
35869       int nOrig = pagerPagecount(pBt->pPager);
35870
35871       if( PTRMAP_ISPAGE(pBt, nOrig) ){
35872         return SQLITE_CORRUPT_BKPT;
35873       }
35874       if( nOrig==PENDING_BYTE_PAGE(pBt) ){
35875         nOrig--;
35876       }
35877       nFree = get4byte(&pBt->pPage1->aData[36]);
35878       nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
35879       nFin = nOrig - nFree - nPtrmap;
35880       if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
35881         nFin--;
35882       }
35883       while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
35884         nFin--;
35885       }
35886     }
35887
35888     while( rc==SQLITE_OK ){
35889       rc = incrVacuumStep(pBt, nFin);
35890     }
35891     if( rc==SQLITE_DONE ){
35892       assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
35893       rc = SQLITE_OK;
35894       if( pBt->nTrunc && nFin ){
35895         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
35896         put4byte(&pBt->pPage1->aData[32], 0);
35897         put4byte(&pBt->pPage1->aData[36], 0);
35898         pBt->nTrunc = nFin;
35899       }
35900     }
35901     if( rc!=SQLITE_OK ){
35902       sqlite3PagerRollback(pPager);
35903     }
35904   }
35905
35906   if( rc==SQLITE_OK ){
35907     *pnTrunc = pBt->nTrunc;
35908     pBt->nTrunc = 0;
35909   }
35910   assert( nRef==sqlite3PagerRefcount(pPager) );
35911   return rc;
35912 }
35913
35914 #endif
35915
35916 /*
35917 ** This routine does the first phase of a two-phase commit.  This routine
35918 ** causes a rollback journal to be created (if it does not already exist)
35919 ** and populated with enough information so that if a power loss occurs
35920 ** the database can be restored to its original state by playing back
35921 ** the journal.  Then the contents of the journal are flushed out to
35922 ** the disk.  After the journal is safely on oxide, the changes to the
35923 ** database are written into the database file and flushed to oxide.
35924 ** At the end of this call, the rollback journal still exists on the
35925 ** disk and we are still holding all locks, so the transaction has not
35926 ** committed.  See sqlite3BtreeCommit() for the second phase of the
35927 ** commit process.
35928 **
35929 ** This call is a no-op if no write-transaction is currently active on pBt.
35930 **
35931 ** Otherwise, sync the database file for the btree pBt. zMaster points to
35932 ** the name of a master journal file that should be written into the
35933 ** individual journal file, or is NULL, indicating no master journal file 
35934 ** (single database transaction).
35935 **
35936 ** When this is called, the master journal should already have been
35937 ** created, populated with this journal pointer and synced to disk.
35938 **
35939 ** Once this is routine has returned, the only thing required to commit
35940 ** the write-transaction for this database file is to delete the journal.
35941 */
35942 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
35943   int rc = SQLITE_OK;
35944   if( p->inTrans==TRANS_WRITE ){
35945     BtShared *pBt = p->pBt;
35946     Pgno nTrunc = 0;
35947     sqlite3BtreeEnter(p);
35948     pBt->db = p->db;
35949 #ifndef SQLITE_OMIT_AUTOVACUUM
35950     if( pBt->autoVacuum ){
35951       rc = autoVacuumCommit(pBt, &nTrunc); 
35952       if( rc!=SQLITE_OK ){
35953         sqlite3BtreeLeave(p);
35954         return rc;
35955       }
35956     }
35957 #endif
35958     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
35959     sqlite3BtreeLeave(p);
35960   }
35961   return rc;
35962 }
35963
35964 /*
35965 ** Commit the transaction currently in progress.
35966 **
35967 ** This routine implements the second phase of a 2-phase commit.  The
35968 ** sqlite3BtreeSync() routine does the first phase and should be invoked
35969 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
35970 ** all the work of writing information out to disk and flushing the
35971 ** contents so that they are written onto the disk platter.  All this
35972 ** routine has to do is delete or truncate the rollback journal
35973 ** (which causes the transaction to commit) and drop locks.
35974 **
35975 ** This will release the write lock on the database file.  If there
35976 ** are no active cursors, it also releases the read lock.
35977 */
35978 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
35979   BtShared *pBt = p->pBt;
35980
35981   sqlite3BtreeEnter(p);
35982   pBt->db = p->db;
35983   btreeIntegrity(p);
35984
35985   /* If the handle has a write-transaction open, commit the shared-btrees 
35986   ** transaction and set the shared state to TRANS_READ.
35987   */
35988   if( p->inTrans==TRANS_WRITE ){
35989     int rc;
35990     assert( pBt->inTransaction==TRANS_WRITE );
35991     assert( pBt->nTransaction>0 );
35992     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
35993     if( rc!=SQLITE_OK ){
35994       sqlite3BtreeLeave(p);
35995       return rc;
35996     }
35997     pBt->inTransaction = TRANS_READ;
35998     pBt->inStmt = 0;
35999   }
36000   unlockAllTables(p);
36001
36002   /* If the handle has any kind of transaction open, decrement the transaction
36003   ** count of the shared btree. If the transaction count reaches 0, set
36004   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
36005   ** will unlock the pager.
36006   */
36007   if( p->inTrans!=TRANS_NONE ){
36008     pBt->nTransaction--;
36009     if( 0==pBt->nTransaction ){
36010       pBt->inTransaction = TRANS_NONE;
36011     }
36012   }
36013
36014   /* Set the handles current transaction state to TRANS_NONE and unlock
36015   ** the pager if this call closed the only read or write transaction.
36016   */
36017   p->inTrans = TRANS_NONE;
36018   unlockBtreeIfUnused(pBt);
36019
36020   btreeIntegrity(p);
36021   sqlite3BtreeLeave(p);
36022   return SQLITE_OK;
36023 }
36024
36025 /*
36026 ** Do both phases of a commit.
36027 */
36028 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
36029   int rc;
36030   sqlite3BtreeEnter(p);
36031   rc = sqlite3BtreeCommitPhaseOne(p, 0);
36032   if( rc==SQLITE_OK ){
36033     rc = sqlite3BtreeCommitPhaseTwo(p);
36034   }
36035   sqlite3BtreeLeave(p);
36036   return rc;
36037 }
36038
36039 #ifndef NDEBUG
36040 /*
36041 ** Return the number of write-cursors open on this handle. This is for use
36042 ** in assert() expressions, so it is only compiled if NDEBUG is not
36043 ** defined.
36044 **
36045 ** For the purposes of this routine, a write-cursor is any cursor that
36046 ** is capable of writing to the databse.  That means the cursor was
36047 ** originally opened for writing and the cursor has not be disabled
36048 ** by having its state changed to CURSOR_FAULT.
36049 */
36050 static int countWriteCursors(BtShared *pBt){
36051   BtCursor *pCur;
36052   int r = 0;
36053   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
36054     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
36055   }
36056   return r;
36057 }
36058 #endif
36059
36060 /*
36061 ** This routine sets the state to CURSOR_FAULT and the error
36062 ** code to errCode for every cursor on BtShared that pBtree
36063 ** references.
36064 **
36065 ** Every cursor is tripped, including cursors that belong
36066 ** to other database connections that happen to be sharing
36067 ** the cache with pBtree.
36068 **
36069 ** This routine gets called when a rollback occurs.
36070 ** All cursors using the same cache must be tripped
36071 ** to prevent them from trying to use the btree after
36072 ** the rollback.  The rollback may have deleted tables
36073 ** or moved root pages, so it is not sufficient to
36074 ** save the state of the cursor.  The cursor must be
36075 ** invalidated.
36076 */
36077 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
36078   BtCursor *p;
36079   sqlite3BtreeEnter(pBtree);
36080   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
36081     sqlite3BtreeClearCursor(p);
36082     p->eState = CURSOR_FAULT;
36083     p->skip = errCode;
36084   }
36085   sqlite3BtreeLeave(pBtree);
36086 }
36087
36088 /*
36089 ** Rollback the transaction in progress.  All cursors will be
36090 ** invalided by this operation.  Any attempt to use a cursor
36091 ** that was open at the beginning of this operation will result
36092 ** in an error.
36093 **
36094 ** This will release the write lock on the database file.  If there
36095 ** are no active cursors, it also releases the read lock.
36096 */
36097 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
36098   int rc;
36099   BtShared *pBt = p->pBt;
36100   MemPage *pPage1;
36101
36102   sqlite3BtreeEnter(p);
36103   pBt->db = p->db;
36104   rc = saveAllCursors(pBt, 0, 0);
36105 #ifndef SQLITE_OMIT_SHARED_CACHE
36106   if( rc!=SQLITE_OK ){
36107     /* This is a horrible situation. An IO or malloc() error occured whilst
36108     ** trying to save cursor positions. If this is an automatic rollback (as
36109     ** the result of a constraint, malloc() failure or IO error) then 
36110     ** the cache may be internally inconsistent (not contain valid trees) so
36111     ** we cannot simply return the error to the caller. Instead, abort 
36112     ** all queries that may be using any of the cursors that failed to save.
36113     */
36114     sqlite3BtreeTripAllCursors(p, rc);
36115   }
36116 #endif
36117   btreeIntegrity(p);
36118   unlockAllTables(p);
36119
36120   if( p->inTrans==TRANS_WRITE ){
36121     int rc2;
36122
36123 #ifndef SQLITE_OMIT_AUTOVACUUM
36124     pBt->nTrunc = 0;
36125 #endif
36126
36127     assert( TRANS_WRITE==pBt->inTransaction );
36128     rc2 = sqlite3PagerRollback(pBt->pPager);
36129     if( rc2!=SQLITE_OK ){
36130       rc = rc2;
36131     }
36132
36133     /* The rollback may have destroyed the pPage1->aData value.  So
36134     ** call sqlite3BtreeGetPage() on page 1 again to make
36135     ** sure pPage1->aData is set correctly. */
36136     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
36137       releasePage(pPage1);
36138     }
36139     assert( countWriteCursors(pBt)==0 );
36140     pBt->inTransaction = TRANS_READ;
36141   }
36142
36143   if( p->inTrans!=TRANS_NONE ){
36144     assert( pBt->nTransaction>0 );
36145     pBt->nTransaction--;
36146     if( 0==pBt->nTransaction ){
36147       pBt->inTransaction = TRANS_NONE;
36148     }
36149   }
36150
36151   p->inTrans = TRANS_NONE;
36152   pBt->inStmt = 0;
36153   unlockBtreeIfUnused(pBt);
36154
36155   btreeIntegrity(p);
36156   sqlite3BtreeLeave(p);
36157   return rc;
36158 }
36159
36160 /*
36161 ** Start a statement subtransaction.  The subtransaction can
36162 ** can be rolled back independently of the main transaction.
36163 ** You must start a transaction before starting a subtransaction.
36164 ** The subtransaction is ended automatically if the main transaction
36165 ** commits or rolls back.
36166 **
36167 ** Only one subtransaction may be active at a time.  It is an error to try
36168 ** to start a new subtransaction if another subtransaction is already active.
36169 **
36170 ** Statement subtransactions are used around individual SQL statements
36171 ** that are contained within a BEGIN...COMMIT block.  If a constraint
36172 ** error occurs within the statement, the effect of that one statement
36173 ** can be rolled back without having to rollback the entire transaction.
36174 */
36175 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
36176   int rc;
36177   BtShared *pBt = p->pBt;
36178   sqlite3BtreeEnter(p);
36179   pBt->db = p->db;
36180   if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
36181     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
36182   }else{
36183     assert( pBt->inTransaction==TRANS_WRITE );
36184     rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
36185     pBt->inStmt = 1;
36186   }
36187   sqlite3BtreeLeave(p);
36188   return rc;
36189 }
36190
36191
36192 /*
36193 ** Commit the statment subtransaction currently in progress.  If no
36194 ** subtransaction is active, this is a no-op.
36195 */
36196 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
36197   int rc;
36198   BtShared *pBt = p->pBt;
36199   sqlite3BtreeEnter(p);
36200   pBt->db = p->db;
36201   if( pBt->inStmt && !pBt->readOnly ){
36202     rc = sqlite3PagerStmtCommit(pBt->pPager);
36203   }else{
36204     rc = SQLITE_OK;
36205   }
36206   pBt->inStmt = 0;
36207   sqlite3BtreeLeave(p);
36208   return rc;
36209 }
36210
36211 /*
36212 ** Rollback the active statement subtransaction.  If no subtransaction
36213 ** is active this routine is a no-op.
36214 **
36215 ** All cursors will be invalidated by this operation.  Any attempt
36216 ** to use a cursor that was open at the beginning of this operation
36217 ** will result in an error.
36218 */
36219 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
36220   int rc = SQLITE_OK;
36221   BtShared *pBt = p->pBt;
36222   sqlite3BtreeEnter(p);
36223   pBt->db = p->db;
36224   if( pBt->inStmt && !pBt->readOnly ){
36225     rc = sqlite3PagerStmtRollback(pBt->pPager);
36226     pBt->inStmt = 0;
36227   }
36228   sqlite3BtreeLeave(p);
36229   return rc;
36230 }
36231
36232 /*
36233 ** Create a new cursor for the BTree whose root is on the page
36234 ** iTable.  The act of acquiring a cursor gets a read lock on 
36235 ** the database file.
36236 **
36237 ** If wrFlag==0, then the cursor can only be used for reading.
36238 ** If wrFlag==1, then the cursor can be used for reading or for
36239 ** writing if other conditions for writing are also met.  These
36240 ** are the conditions that must be met in order for writing to
36241 ** be allowed:
36242 **
36243 ** 1:  The cursor must have been opened with wrFlag==1
36244 **
36245 ** 2:  Other database connections that share the same pager cache
36246 **     but which are not in the READ_UNCOMMITTED state may not have
36247 **     cursors open with wrFlag==0 on the same table.  Otherwise
36248 **     the changes made by this write cursor would be visible to
36249 **     the read cursors in the other database connection.
36250 **
36251 ** 3:  The database must be writable (not on read-only media)
36252 **
36253 ** 4:  There must be an active transaction.
36254 **
36255 ** No checking is done to make sure that page iTable really is the
36256 ** root page of a b-tree.  If it is not, then the cursor acquired
36257 ** will not work correctly.
36258 **
36259 ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory 
36260 ** pointed to by pCur have been zeroed by the caller.
36261 */
36262 static int btreeCursor(
36263   Btree *p,                              /* The btree */
36264   int iTable,                            /* Root page of table to open */
36265   int wrFlag,                            /* 1 to write. 0 read-only */
36266   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
36267   BtCursor *pCur                         /* Space for new cursor */
36268 ){
36269   int rc;
36270   BtShared *pBt = p->pBt;
36271
36272   assert( sqlite3BtreeHoldsMutex(p) );
36273   if( wrFlag ){
36274     if( pBt->readOnly ){
36275       return SQLITE_READONLY;
36276     }
36277     if( checkReadLocks(p, iTable, 0, 0) ){
36278       return SQLITE_LOCKED;
36279     }
36280   }
36281
36282   if( pBt->pPage1==0 ){
36283     rc = lockBtreeWithRetry(p);
36284     if( rc!=SQLITE_OK ){
36285       return rc;
36286     }
36287     if( pBt->readOnly && wrFlag ){
36288       return SQLITE_READONLY;
36289     }
36290   }
36291   pCur->pgnoRoot = (Pgno)iTable;
36292   if( iTable==1 && pagerPagecount(pBt->pPager)==0 ){
36293     rc = SQLITE_EMPTY;
36294     goto create_cursor_exception;
36295   }
36296   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
36297   if( rc!=SQLITE_OK ){
36298     goto create_cursor_exception;
36299   }
36300
36301   /* Now that no other errors can occur, finish filling in the BtCursor
36302   ** variables, link the cursor into the BtShared list and set *ppCur (the
36303   ** output argument to this function).
36304   */
36305   pCur->pKeyInfo = pKeyInfo;
36306   pCur->pBtree = p;
36307   pCur->pBt = pBt;
36308   pCur->wrFlag = wrFlag;
36309   pCur->pNext = pBt->pCursor;
36310   if( pCur->pNext ){
36311     pCur->pNext->pPrev = pCur;
36312   }
36313   pBt->pCursor = pCur;
36314   pCur->eState = CURSOR_INVALID;
36315
36316   return SQLITE_OK;
36317
36318 create_cursor_exception:
36319   releasePage(pCur->apPage[0]);
36320   unlockBtreeIfUnused(pBt);
36321   return rc;
36322 }
36323 SQLITE_PRIVATE int sqlite3BtreeCursor(
36324   Btree *p,                                   /* The btree */
36325   int iTable,                                 /* Root page of table to open */
36326   int wrFlag,                                 /* 1 to write. 0 read-only */
36327   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
36328   BtCursor *pCur                              /* Write new cursor here */
36329 ){
36330   int rc;
36331   sqlite3BtreeEnter(p);
36332   p->pBt->db = p->db;
36333   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
36334   sqlite3BtreeLeave(p);
36335   return rc;
36336 }
36337 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
36338   return sizeof(BtCursor);
36339 }
36340
36341
36342
36343 /*
36344 ** Close a cursor.  The read lock on the database file is released
36345 ** when the last cursor is closed.
36346 */
36347 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
36348   Btree *pBtree = pCur->pBtree;
36349   if( pBtree ){
36350     int i;
36351     BtShared *pBt = pCur->pBt;
36352     sqlite3BtreeEnter(pBtree);
36353     pBt->db = pBtree->db;
36354     sqlite3BtreeClearCursor(pCur);
36355     if( pCur->pPrev ){
36356       pCur->pPrev->pNext = pCur->pNext;
36357     }else{
36358       pBt->pCursor = pCur->pNext;
36359     }
36360     if( pCur->pNext ){
36361       pCur->pNext->pPrev = pCur->pPrev;
36362     }
36363     for(i=0; i<=pCur->iPage; i++){
36364       releasePage(pCur->apPage[i]);
36365     }
36366     unlockBtreeIfUnused(pBt);
36367     invalidateOverflowCache(pCur);
36368     /* sqlite3_free(pCur); */
36369     sqlite3BtreeLeave(pBtree);
36370   }
36371   return SQLITE_OK;
36372 }
36373
36374 /*
36375 ** Make a temporary cursor by filling in the fields of pTempCur.
36376 ** The temporary cursor is not on the cursor list for the Btree.
36377 */
36378 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
36379   int i;
36380   assert( cursorHoldsMutex(pCur) );
36381   memcpy(pTempCur, pCur, sizeof(BtCursor));
36382   pTempCur->pNext = 0;
36383   pTempCur->pPrev = 0;
36384   for(i=0; i<=pTempCur->iPage; i++){
36385     sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
36386   }
36387 }
36388
36389 /*
36390 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
36391 ** function above.
36392 */
36393 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
36394   int i;
36395   assert( cursorHoldsMutex(pCur) );
36396   for(i=0; i<=pCur->iPage; i++){
36397     sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
36398   }
36399 }
36400
36401 /*
36402 ** Make sure the BtCursor* given in the argument has a valid
36403 ** BtCursor.info structure.  If it is not already valid, call
36404 ** sqlite3BtreeParseCell() to fill it in.
36405 **
36406 ** BtCursor.info is a cache of the information in the current cell.
36407 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
36408 **
36409 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
36410 ** compiler to crash when getCellInfo() is implemented as a macro.
36411 ** But there is a measureable speed advantage to using the macro on gcc
36412 ** (when less compiler optimizations like -Os or -O0 are used and the
36413 ** compiler is not doing agressive inlining.)  So we use a real function
36414 ** for MSVC and a macro for everything else.  Ticket #2457.
36415 */
36416 #ifndef NDEBUG
36417   static void assertCellInfo(BtCursor *pCur){
36418     CellInfo info;
36419     int iPage = pCur->iPage;
36420     memset(&info, 0, sizeof(info));
36421     sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
36422     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
36423   }
36424 #else
36425   #define assertCellInfo(x)
36426 #endif
36427 #ifdef _MSC_VER
36428   /* Use a real function in MSVC to work around bugs in that compiler. */
36429   static void getCellInfo(BtCursor *pCur){
36430     if( pCur->info.nSize==0 ){
36431       int iPage = pCur->iPage;
36432       sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
36433       pCur->validNKey = 1;
36434     }else{
36435       assertCellInfo(pCur);
36436     }
36437   }
36438 #else /* if not _MSC_VER */
36439   /* Use a macro in all other compilers so that the function is inlined */
36440 #define getCellInfo(pCur)                                                      \
36441   if( pCur->info.nSize==0 ){                                                   \
36442     int iPage = pCur->iPage;                                                   \
36443     sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
36444     pCur->validNKey = 1;                                                       \
36445   }else{                                                                       \
36446     assertCellInfo(pCur);                                                      \
36447   }
36448 #endif /* _MSC_VER */
36449
36450 /*
36451 ** Set *pSize to the size of the buffer needed to hold the value of
36452 ** the key for the current entry.  If the cursor is not pointing
36453 ** to a valid entry, *pSize is set to 0. 
36454 **
36455 ** For a table with the INTKEY flag set, this routine returns the key
36456 ** itself, not the number of bytes in the key.
36457 */
36458 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
36459   int rc;
36460
36461   assert( cursorHoldsMutex(pCur) );
36462   rc = restoreCursorPosition(pCur);
36463   if( rc==SQLITE_OK ){
36464     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36465     if( pCur->eState==CURSOR_INVALID ){
36466       *pSize = 0;
36467     }else{
36468       getCellInfo(pCur);
36469       *pSize = pCur->info.nKey;
36470     }
36471   }
36472   return rc;
36473 }
36474
36475 /*
36476 ** Set *pSize to the number of bytes of data in the entry the
36477 ** cursor currently points to.  Always return SQLITE_OK.
36478 ** Failure is not possible.  If the cursor is not currently
36479 ** pointing to an entry (which can happen, for example, if
36480 ** the database is empty) then *pSize is set to 0.
36481 */
36482 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
36483   int rc;
36484
36485   assert( cursorHoldsMutex(pCur) );
36486   rc = restoreCursorPosition(pCur);
36487   if( rc==SQLITE_OK ){
36488     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
36489     if( pCur->eState==CURSOR_INVALID ){
36490       /* Not pointing at a valid entry - set *pSize to 0. */
36491       *pSize = 0;
36492     }else{
36493       getCellInfo(pCur);
36494       *pSize = pCur->info.nData;
36495     }
36496   }
36497   return rc;
36498 }
36499
36500 /*
36501 ** Given the page number of an overflow page in the database (parameter
36502 ** ovfl), this function finds the page number of the next page in the 
36503 ** linked list of overflow pages. If possible, it uses the auto-vacuum
36504 ** pointer-map data instead of reading the content of page ovfl to do so. 
36505 **
36506 ** If an error occurs an SQLite error code is returned. Otherwise:
36507 **
36508 ** Unless pPgnoNext is NULL, the page number of the next overflow 
36509 ** page in the linked list is written to *pPgnoNext. If page ovfl
36510 ** is the last page in its linked list, *pPgnoNext is set to zero. 
36511 **
36512 ** If ppPage is not NULL, *ppPage is set to the MemPage* handle
36513 ** for page ovfl. The underlying pager page may have been requested
36514 ** with the noContent flag set, so the page data accessable via
36515 ** this handle may not be trusted.
36516 */
36517 static int getOverflowPage(
36518   BtShared *pBt, 
36519   Pgno ovfl,                   /* Overflow page */
36520   MemPage **ppPage,            /* OUT: MemPage handle */
36521   Pgno *pPgnoNext              /* OUT: Next overflow page number */
36522 ){
36523   Pgno next = 0;
36524   int rc;
36525
36526   assert( sqlite3_mutex_held(pBt->mutex) );
36527   /* One of these must not be NULL. Otherwise, why call this function? */
36528   assert(ppPage || pPgnoNext);
36529
36530   /* If pPgnoNext is NULL, then this function is being called to obtain
36531   ** a MemPage* reference only. No page-data is required in this case.
36532   */
36533   if( !pPgnoNext ){
36534     return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
36535   }
36536
36537 #ifndef SQLITE_OMIT_AUTOVACUUM
36538   /* Try to find the next page in the overflow list using the
36539   ** autovacuum pointer-map pages. Guess that the next page in 
36540   ** the overflow list is page number (ovfl+1). If that guess turns 
36541   ** out to be wrong, fall back to loading the data of page 
36542   ** number ovfl to determine the next page number.
36543   */
36544   if( pBt->autoVacuum ){
36545     Pgno pgno;
36546     Pgno iGuess = ovfl+1;
36547     u8 eType;
36548
36549     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
36550       iGuess++;
36551     }
36552
36553     if( iGuess<=pagerPagecount(pBt->pPager) ){
36554       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
36555       if( rc!=SQLITE_OK ){
36556         return rc;
36557       }
36558       if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
36559         next = iGuess;
36560       }
36561     }
36562   }
36563 #endif
36564
36565   if( next==0 || ppPage ){
36566     MemPage *pPage = 0;
36567
36568     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
36569     assert(rc==SQLITE_OK || pPage==0);
36570     if( next==0 && rc==SQLITE_OK ){
36571       next = get4byte(pPage->aData);
36572     }
36573
36574     if( ppPage ){
36575       *ppPage = pPage;
36576     }else{
36577       releasePage(pPage);
36578     }
36579   }
36580   *pPgnoNext = next;
36581
36582   return rc;
36583 }
36584
36585 /*
36586 ** Copy data from a buffer to a page, or from a page to a buffer.
36587 **
36588 ** pPayload is a pointer to data stored on database page pDbPage.
36589 ** If argument eOp is false, then nByte bytes of data are copied
36590 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
36591 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
36592 ** of data are copied from the buffer pBuf to pPayload.
36593 **
36594 ** SQLITE_OK is returned on success, otherwise an error code.
36595 */
36596 static int copyPayload(
36597   void *pPayload,           /* Pointer to page data */
36598   void *pBuf,               /* Pointer to buffer */
36599   int nByte,                /* Number of bytes to copy */
36600   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
36601   DbPage *pDbPage           /* Page containing pPayload */
36602 ){
36603   if( eOp ){
36604     /* Copy data from buffer to page (a write operation) */
36605     int rc = sqlite3PagerWrite(pDbPage);
36606     if( rc!=SQLITE_OK ){
36607       return rc;
36608     }
36609     memcpy(pPayload, pBuf, nByte);
36610   }else{
36611     /* Copy data from page to buffer (a read operation) */
36612     memcpy(pBuf, pPayload, nByte);
36613   }
36614   return SQLITE_OK;
36615 }
36616
36617 /*
36618 ** This function is used to read or overwrite payload information
36619 ** for the entry that the pCur cursor is pointing to. If the eOp
36620 ** parameter is 0, this is a read operation (data copied into
36621 ** buffer pBuf). If it is non-zero, a write (data copied from
36622 ** buffer pBuf).
36623 **
36624 ** A total of "amt" bytes are read or written beginning at "offset".
36625 ** Data is read to or from the buffer pBuf.
36626 **
36627 ** This routine does not make a distinction between key and data.
36628 ** It just reads or writes bytes from the payload area.  Data might 
36629 ** appear on the main page or be scattered out on multiple overflow 
36630 ** pages.
36631 **
36632 ** If the BtCursor.isIncrblobHandle flag is set, and the current
36633 ** cursor entry uses one or more overflow pages, this function
36634 ** allocates space for and lazily popluates the overflow page-list 
36635 ** cache array (BtCursor.aOverflow). Subsequent calls use this
36636 ** cache to make seeking to the supplied offset more efficient.
36637 **
36638 ** Once an overflow page-list cache has been allocated, it may be
36639 ** invalidated if some other cursor writes to the same table, or if
36640 ** the cursor is moved to a different row. Additionally, in auto-vacuum
36641 ** mode, the following events may invalidate an overflow page-list cache.
36642 **
36643 **   * An incremental vacuum,
36644 **   * A commit in auto_vacuum="full" mode,
36645 **   * Creating a table (may require moving an overflow page).
36646 */
36647 static int accessPayload(
36648   BtCursor *pCur,      /* Cursor pointing to entry to read from */
36649   int offset,          /* Begin reading this far into payload */
36650   int amt,             /* Read this many bytes */
36651   unsigned char *pBuf, /* Write the bytes into this buffer */ 
36652   int skipKey,         /* offset begins at data if this is true */
36653   int eOp              /* zero to read. non-zero to write. */
36654 ){
36655   unsigned char *aPayload;
36656   int rc = SQLITE_OK;
36657   u32 nKey;
36658   int iIdx = 0;
36659   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
36660   BtShared *pBt;                              /* Btree this cursor belongs to */
36661
36662   assert( pPage );
36663   assert( pCur->eState==CURSOR_VALID );
36664   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
36665   assert( offset>=0 );
36666   assert( cursorHoldsMutex(pCur) );
36667
36668   getCellInfo(pCur);
36669   aPayload = pCur->info.pCell + pCur->info.nHeader;
36670   nKey = (pPage->intKey ? 0 : pCur->info.nKey);
36671
36672   if( skipKey ){
36673     offset += nKey;
36674   }
36675   if( offset+amt > nKey+pCur->info.nData ){
36676     /* Trying to read or write past the end of the data is an error */
36677     return SQLITE_CORRUPT_BKPT;
36678   }
36679
36680   /* Check if data must be read/written to/from the btree page itself. */
36681   if( offset<pCur->info.nLocal ){
36682     int a = amt;
36683     if( a+offset>pCur->info.nLocal ){
36684       a = pCur->info.nLocal - offset;
36685     }
36686     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
36687     offset = 0;
36688     pBuf += a;
36689     amt -= a;
36690   }else{
36691     offset -= pCur->info.nLocal;
36692   }
36693
36694   pBt = pCur->pBt;
36695   if( rc==SQLITE_OK && amt>0 ){
36696     const int ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
36697     Pgno nextPage;
36698
36699     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
36700
36701 #ifndef SQLITE_OMIT_INCRBLOB
36702     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
36703     ** has not been allocated, allocate it now. The array is sized at
36704     ** one entry for each overflow page in the overflow chain. The
36705     ** page number of the first overflow page is stored in aOverflow[0],
36706     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
36707     ** (the cache is lazily populated).
36708     */
36709     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
36710       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
36711       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
36712       if( nOvfl && !pCur->aOverflow ){
36713         rc = SQLITE_NOMEM;
36714       }
36715     }
36716
36717     /* If the overflow page-list cache has been allocated and the
36718     ** entry for the first required overflow page is valid, skip
36719     ** directly to it.
36720     */
36721     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
36722       iIdx = (offset/ovflSize);
36723       nextPage = pCur->aOverflow[iIdx];
36724       offset = (offset%ovflSize);
36725     }
36726 #endif
36727
36728     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
36729
36730 #ifndef SQLITE_OMIT_INCRBLOB
36731       /* If required, populate the overflow page-list cache. */
36732       if( pCur->aOverflow ){
36733         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
36734         pCur->aOverflow[iIdx] = nextPage;
36735       }
36736 #endif
36737
36738       if( offset>=ovflSize ){
36739         /* The only reason to read this page is to obtain the page
36740         ** number for the next page in the overflow chain. The page
36741         ** data is not required. So first try to lookup the overflow
36742         ** page-list cache, if any, then fall back to the getOverflowPage()
36743         ** function.
36744         */
36745 #ifndef SQLITE_OMIT_INCRBLOB
36746         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
36747           nextPage = pCur->aOverflow[iIdx+1];
36748         } else 
36749 #endif
36750           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
36751         offset -= ovflSize;
36752       }else{
36753         /* Need to read this page properly. It contains some of the
36754         ** range of data that is being read (eOp==0) or written (eOp!=0).
36755         */
36756         DbPage *pDbPage;
36757         int a = amt;
36758         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
36759         if( rc==SQLITE_OK ){
36760           aPayload = sqlite3PagerGetData(pDbPage);
36761           nextPage = get4byte(aPayload);
36762           if( a + offset > ovflSize ){
36763             a = ovflSize - offset;
36764           }
36765           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
36766           sqlite3PagerUnref(pDbPage);
36767           offset = 0;
36768           amt -= a;
36769           pBuf += a;
36770         }
36771       }
36772     }
36773   }
36774
36775   if( rc==SQLITE_OK && amt>0 ){
36776     return SQLITE_CORRUPT_BKPT;
36777   }
36778   return rc;
36779 }
36780
36781 /*
36782 ** Read part of the key associated with cursor pCur.  Exactly
36783 ** "amt" bytes will be transfered into pBuf[].  The transfer
36784 ** begins at "offset".
36785 **
36786 ** Return SQLITE_OK on success or an error code if anything goes
36787 ** wrong.  An error is returned if "offset+amt" is larger than
36788 ** the available payload.
36789 */
36790 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
36791   int rc;
36792
36793   assert( cursorHoldsMutex(pCur) );
36794   rc = restoreCursorPosition(pCur);
36795   if( rc==SQLITE_OK ){
36796     assert( pCur->eState==CURSOR_VALID );
36797     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
36798     if( pCur->apPage[0]->intKey ){
36799       return SQLITE_CORRUPT_BKPT;
36800     }
36801     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
36802     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
36803   }
36804   return rc;
36805 }
36806
36807 /*
36808 ** Read part of the data associated with cursor pCur.  Exactly
36809 ** "amt" bytes will be transfered into pBuf[].  The transfer
36810 ** begins at "offset".
36811 **
36812 ** Return SQLITE_OK on success or an error code if anything goes
36813 ** wrong.  An error is returned if "offset+amt" is larger than
36814 ** the available payload.
36815 */
36816 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
36817   int rc;
36818
36819 #ifndef SQLITE_OMIT_INCRBLOB
36820   if ( pCur->eState==CURSOR_INVALID ){
36821     return SQLITE_ABORT;
36822   }
36823 #endif
36824
36825   assert( cursorHoldsMutex(pCur) );
36826   rc = restoreCursorPosition(pCur);
36827   if( rc==SQLITE_OK ){
36828     assert( pCur->eState==CURSOR_VALID );
36829     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
36830     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
36831     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
36832   }
36833   return rc;
36834 }
36835
36836 /*
36837 ** Return a pointer to payload information from the entry that the 
36838 ** pCur cursor is pointing to.  The pointer is to the beginning of
36839 ** the key if skipKey==0 and it points to the beginning of data if
36840 ** skipKey==1.  The number of bytes of available key/data is written
36841 ** into *pAmt.  If *pAmt==0, then the value returned will not be
36842 ** a valid pointer.
36843 **
36844 ** This routine is an optimization.  It is common for the entire key
36845 ** and data to fit on the local page and for there to be no overflow
36846 ** pages.  When that is so, this routine can be used to access the
36847 ** key and data without making a copy.  If the key and/or data spills
36848 ** onto overflow pages, then accessPayload() must be used to reassembly
36849 ** the key/data and copy it into a preallocated buffer.
36850 **
36851 ** The pointer returned by this routine looks directly into the cached
36852 ** page of the database.  The data might change or move the next time
36853 ** any btree routine is called.
36854 */
36855 static const unsigned char *fetchPayload(
36856   BtCursor *pCur,      /* Cursor pointing to entry to read from */
36857   int *pAmt,           /* Write the number of available bytes here */
36858   int skipKey          /* read beginning at data if this is true */
36859 ){
36860   unsigned char *aPayload;
36861   MemPage *pPage;
36862   u32 nKey;
36863   int nLocal;
36864
36865   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
36866   assert( pCur->eState==CURSOR_VALID );
36867   assert( cursorHoldsMutex(pCur) );
36868   pPage = pCur->apPage[pCur->iPage];
36869   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
36870   getCellInfo(pCur);
36871   aPayload = pCur->info.pCell;
36872   aPayload += pCur->info.nHeader;
36873   if( pPage->intKey ){
36874     nKey = 0;
36875   }else{
36876     nKey = pCur->info.nKey;
36877   }
36878   if( skipKey ){
36879     aPayload += nKey;
36880     nLocal = pCur->info.nLocal - nKey;
36881   }else{
36882     nLocal = pCur->info.nLocal;
36883     if( nLocal>nKey ){
36884       nLocal = nKey;
36885     }
36886   }
36887   *pAmt = nLocal;
36888   return aPayload;
36889 }
36890
36891
36892 /*
36893 ** For the entry that cursor pCur is point to, return as
36894 ** many bytes of the key or data as are available on the local
36895 ** b-tree page.  Write the number of available bytes into *pAmt.
36896 **
36897 ** The pointer returned is ephemeral.  The key/data may move
36898 ** or be destroyed on the next call to any Btree routine,
36899 ** including calls from other threads against the same cache.
36900 ** Hence, a mutex on the BtShared should be held prior to calling
36901 ** this routine.
36902 **
36903 ** These routines is used to get quick access to key and data
36904 ** in the common case where no overflow pages are used.
36905 */
36906 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
36907   assert( cursorHoldsMutex(pCur) );
36908   if( pCur->eState==CURSOR_VALID ){
36909     return (const void*)fetchPayload(pCur, pAmt, 0);
36910   }
36911   return 0;
36912 }
36913 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
36914   assert( cursorHoldsMutex(pCur) );
36915   if( pCur->eState==CURSOR_VALID ){
36916     return (const void*)fetchPayload(pCur, pAmt, 1);
36917   }
36918   return 0;
36919 }
36920
36921
36922 /*
36923 ** Move the cursor down to a new child page.  The newPgno argument is the
36924 ** page number of the child page to move to.
36925 */
36926 static int moveToChild(BtCursor *pCur, u32 newPgno){
36927   int rc;
36928   int i = pCur->iPage;
36929   MemPage *pNewPage;
36930   BtShared *pBt = pCur->pBt;
36931
36932   assert( cursorHoldsMutex(pCur) );
36933   assert( pCur->eState==CURSOR_VALID );
36934   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
36935   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
36936     return SQLITE_CORRUPT_BKPT;
36937   }
36938   rc = getAndInitPage(pBt, newPgno, &pNewPage);
36939   if( rc ) return rc;
36940   pCur->apPage[i+1] = pNewPage;
36941   pCur->aiIdx[i+1] = 0;
36942   pCur->iPage++;
36943
36944   pCur->info.nSize = 0;
36945   pCur->validNKey = 0;
36946   if( pNewPage->nCell<1 ){
36947     return SQLITE_CORRUPT_BKPT;
36948   }
36949   return SQLITE_OK;
36950 }
36951
36952 #ifndef NDEBUG
36953 /*
36954 ** Page pParent is an internal (non-leaf) tree page. This function 
36955 ** asserts that page number iChild is the left-child if the iIdx'th
36956 ** cell in page pParent. Or, if iIdx is equal to the total number of
36957 ** cells in pParent, that page number iChild is the right-child of
36958 ** the page.
36959 */
36960 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
36961   assert( iIdx<=pParent->nCell );
36962   if( iIdx==pParent->nCell ){
36963     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
36964   }else{
36965     assert( get4byte(findCell(pParent, iIdx))==iChild );
36966   }
36967 }
36968 #else
36969 #  define assertParentIndex(x,y,z) 
36970 #endif
36971
36972 /*
36973 ** Move the cursor up to the parent page.
36974 **
36975 ** pCur->idx is set to the cell index that contains the pointer
36976 ** to the page we are coming from.  If we are coming from the
36977 ** right-most child page then pCur->idx is set to one more than
36978 ** the largest cell index.
36979 */
36980 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
36981   assert( cursorHoldsMutex(pCur) );
36982   assert( pCur->eState==CURSOR_VALID );
36983   assert( pCur->iPage>0 );
36984   assert( pCur->apPage[pCur->iPage] );
36985   assertParentIndex(
36986     pCur->apPage[pCur->iPage-1], 
36987     pCur->aiIdx[pCur->iPage-1], 
36988     pCur->apPage[pCur->iPage]->pgno
36989   );
36990   releasePage(pCur->apPage[pCur->iPage]);
36991   pCur->iPage--;
36992   pCur->info.nSize = 0;
36993   pCur->validNKey = 0;
36994 }
36995
36996 /*
36997 ** Move the cursor to the root page
36998 */
36999 static int moveToRoot(BtCursor *pCur){
37000   MemPage *pRoot;
37001   int rc = SQLITE_OK;
37002   Btree *p = pCur->pBtree;
37003   BtShared *pBt = p->pBt;
37004
37005   assert( cursorHoldsMutex(pCur) );
37006   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
37007   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
37008   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
37009   if( pCur->eState>=CURSOR_REQUIRESEEK ){
37010     if( pCur->eState==CURSOR_FAULT ){
37011       return pCur->skip;
37012     }
37013     sqlite3BtreeClearCursor(pCur);
37014   }
37015
37016   if( pCur->iPage>=0 ){
37017     int i;
37018     for(i=1; i<=pCur->iPage; i++){
37019       releasePage(pCur->apPage[i]);
37020     }
37021   }else{
37022     if( 
37023       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
37024     ){
37025       pCur->eState = CURSOR_INVALID;
37026       return rc;
37027     }
37028   }
37029
37030   pRoot = pCur->apPage[0];
37031   assert( pRoot->pgno==pCur->pgnoRoot );
37032   pCur->iPage = 0;
37033   pCur->aiIdx[0] = 0;
37034   pCur->info.nSize = 0;
37035   pCur->atLast = 0;
37036   pCur->validNKey = 0;
37037
37038   if( pRoot->nCell==0 && !pRoot->leaf ){
37039     Pgno subpage;
37040     assert( pRoot->pgno==1 );
37041     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
37042     assert( subpage>0 );
37043     pCur->eState = CURSOR_VALID;
37044     rc = moveToChild(pCur, subpage);
37045   }else{
37046     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
37047   }
37048   return rc;
37049 }
37050
37051 /*
37052 ** Move the cursor down to the left-most leaf entry beneath the
37053 ** entry to which it is currently pointing.
37054 **
37055 ** The left-most leaf is the one with the smallest key - the first
37056 ** in ascending order.
37057 */
37058 static int moveToLeftmost(BtCursor *pCur){
37059   Pgno pgno;
37060   int rc = SQLITE_OK;
37061   MemPage *pPage;
37062
37063   assert( cursorHoldsMutex(pCur) );
37064   assert( pCur->eState==CURSOR_VALID );
37065   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
37066     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
37067     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
37068     rc = moveToChild(pCur, pgno);
37069   }
37070   return rc;
37071 }
37072
37073 /*
37074 ** Move the cursor down to the right-most leaf entry beneath the
37075 ** page to which it is currently pointing.  Notice the difference
37076 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
37077 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
37078 ** finds the right-most entry beneath the *page*.
37079 **
37080 ** The right-most entry is the one with the largest key - the last
37081 ** key in ascending order.
37082 */
37083 static int moveToRightmost(BtCursor *pCur){
37084   Pgno pgno;
37085   int rc = SQLITE_OK;
37086   MemPage *pPage;
37087
37088   assert( cursorHoldsMutex(pCur) );
37089   assert( pCur->eState==CURSOR_VALID );
37090   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
37091     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37092     pCur->aiIdx[pCur->iPage] = pPage->nCell;
37093     rc = moveToChild(pCur, pgno);
37094   }
37095   if( rc==SQLITE_OK ){
37096     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
37097     pCur->info.nSize = 0;
37098     pCur->validNKey = 0;
37099   }
37100   return rc;
37101 }
37102
37103 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
37104 ** on success.  Set *pRes to 0 if the cursor actually points to something
37105 ** or set *pRes to 1 if the table is empty.
37106 */
37107 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
37108   int rc;
37109
37110   assert( cursorHoldsMutex(pCur) );
37111   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37112   rc = moveToRoot(pCur);
37113   if( rc==SQLITE_OK ){
37114     if( pCur->eState==CURSOR_INVALID ){
37115       assert( pCur->apPage[pCur->iPage]->nCell==0 );
37116       *pRes = 1;
37117       rc = SQLITE_OK;
37118     }else{
37119       assert( pCur->apPage[pCur->iPage]->nCell>0 );
37120       *pRes = 0;
37121       rc = moveToLeftmost(pCur);
37122     }
37123   }
37124   return rc;
37125 }
37126
37127 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
37128 ** on success.  Set *pRes to 0 if the cursor actually points to something
37129 ** or set *pRes to 1 if the table is empty.
37130 */
37131 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
37132   int rc;
37133  
37134   assert( cursorHoldsMutex(pCur) );
37135   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37136   rc = moveToRoot(pCur);
37137   if( rc==SQLITE_OK ){
37138     if( CURSOR_INVALID==pCur->eState ){
37139       assert( pCur->apPage[pCur->iPage]->nCell==0 );
37140       *pRes = 1;
37141     }else{
37142       assert( pCur->eState==CURSOR_VALID );
37143       *pRes = 0;
37144       rc = moveToRightmost(pCur);
37145       getCellInfo(pCur);
37146       pCur->atLast = rc==SQLITE_OK;
37147     }
37148   }
37149   return rc;
37150 }
37151
37152 /* Move the cursor so that it points to an entry near the key 
37153 ** specified by pIdxKey or intKey.   Return a success code.
37154 **
37155 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
37156 ** must be NULL.  For index tables, pIdxKey is used and intKey
37157 ** is ignored.
37158 **
37159 ** If an exact match is not found, then the cursor is always
37160 ** left pointing at a leaf page which would hold the entry if it
37161 ** were present.  The cursor might point to an entry that comes
37162 ** before or after the key.
37163 **
37164 ** The result of comparing the key with the entry to which the
37165 ** cursor is written to *pRes if pRes!=NULL.  The meaning of
37166 ** this value is as follows:
37167 **
37168 **     *pRes<0      The cursor is left pointing at an entry that
37169 **                  is smaller than pKey or if the table is empty
37170 **                  and the cursor is therefore left point to nothing.
37171 **
37172 **     *pRes==0     The cursor is left pointing at an entry that
37173 **                  exactly matches pKey.
37174 **
37175 **     *pRes>0      The cursor is left pointing at an entry that
37176 **                  is larger than pKey.
37177 **
37178 */
37179 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
37180   BtCursor *pCur,          /* The cursor to be moved */
37181   UnpackedRecord *pIdxKey, /* Unpacked index key */
37182   i64 intKey,              /* The table key */
37183   int biasRight,           /* If true, bias the search to the high end */
37184   int *pRes                /* Write search results here */
37185 ){
37186   int rc;
37187
37188   assert( cursorHoldsMutex(pCur) );
37189   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37190
37191   /* If the cursor is already positioned at the point we are trying
37192   ** to move to, then just return without doing any work */
37193   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
37194    && pCur->apPage[0]->intKey 
37195   ){
37196     if( pCur->info.nKey==intKey ){
37197       *pRes = 0;
37198       return SQLITE_OK;
37199     }
37200     if( pCur->atLast && pCur->info.nKey<intKey ){
37201       *pRes = -1;
37202       return SQLITE_OK;
37203     }
37204   }
37205
37206   rc = moveToRoot(pCur);
37207   if( rc ){
37208     return rc;
37209   }
37210   assert( pCur->apPage[pCur->iPage] );
37211   assert( pCur->apPage[pCur->iPage]->isInit );
37212   if( pCur->eState==CURSOR_INVALID ){
37213     *pRes = -1;
37214     assert( pCur->apPage[pCur->iPage]->nCell==0 );
37215     return SQLITE_OK;
37216   }
37217   assert( pCur->apPage[0]->intKey || pIdxKey );
37218   for(;;){
37219     int lwr, upr;
37220     Pgno chldPg;
37221     MemPage *pPage = pCur->apPage[pCur->iPage];
37222     int c = -1;  /* pRes return if table is empty must be -1 */
37223     lwr = 0;
37224     upr = pPage->nCell-1;
37225     if( !pPage->intKey && pIdxKey==0 ){
37226       rc = SQLITE_CORRUPT_BKPT;
37227       goto moveto_finish;
37228     }
37229     if( biasRight ){
37230       pCur->aiIdx[pCur->iPage] = upr;
37231     }else{
37232       pCur->aiIdx[pCur->iPage] = (upr+lwr)/2;
37233     }
37234     if( lwr<=upr ) for(;;){
37235       void *pCellKey;
37236       i64 nCellKey;
37237       int idx = pCur->aiIdx[pCur->iPage];
37238       pCur->info.nSize = 0;
37239       pCur->validNKey = 1;
37240       if( pPage->intKey ){
37241         u8 *pCell;
37242         pCell = findCell(pPage, idx) + pPage->childPtrSize;
37243         if( pPage->hasData ){
37244           u32 dummy;
37245           pCell += getVarint32(pCell, dummy);
37246         }
37247         getVarint(pCell, (u64*)&nCellKey);
37248         if( nCellKey==intKey ){
37249           c = 0;
37250         }else if( nCellKey<intKey ){
37251           c = -1;
37252         }else{
37253           assert( nCellKey>intKey );
37254           c = +1;
37255         }
37256       }else{
37257         int available;
37258         pCellKey = (void *)fetchPayload(pCur, &available, 0);
37259         nCellKey = pCur->info.nKey;
37260         if( available>=nCellKey ){
37261           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37262         }else{
37263           pCellKey = sqlite3Malloc( nCellKey );
37264           if( pCellKey==0 ){
37265             rc = SQLITE_NOMEM;
37266             goto moveto_finish;
37267           }
37268           rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
37269           c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
37270           sqlite3_free(pCellKey);
37271           if( rc ) goto moveto_finish;
37272         }
37273       }
37274       if( c==0 ){
37275         pCur->info.nKey = nCellKey;
37276         if( pPage->intKey && !pPage->leaf ){
37277           lwr = idx;
37278           upr = lwr - 1;
37279           break;
37280         }else{
37281           if( pRes ) *pRes = 0;
37282           rc = SQLITE_OK;
37283           goto moveto_finish;
37284         }
37285       }
37286       if( c<0 ){
37287         lwr = idx+1;
37288       }else{
37289         upr = idx-1;
37290       }
37291       if( lwr>upr ){
37292         pCur->info.nKey = nCellKey;
37293         break;
37294       }
37295       pCur->aiIdx[pCur->iPage] = (lwr+upr)/2;
37296     }
37297     assert( lwr==upr+1 );
37298     assert( pPage->isInit );
37299     if( pPage->leaf ){
37300       chldPg = 0;
37301     }else if( lwr>=pPage->nCell ){
37302       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
37303     }else{
37304       chldPg = get4byte(findCell(pPage, lwr));
37305     }
37306     if( chldPg==0 ){
37307       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
37308       if( pRes ) *pRes = c;
37309       rc = SQLITE_OK;
37310       goto moveto_finish;
37311     }
37312     pCur->aiIdx[pCur->iPage] = lwr;
37313     pCur->info.nSize = 0;
37314     pCur->validNKey = 0;
37315     rc = moveToChild(pCur, chldPg);
37316     if( rc ) goto moveto_finish;
37317   }
37318 moveto_finish:
37319   return rc;
37320 }
37321
37322 /*
37323 ** In this version of BtreeMoveto, pKey is a packed index record
37324 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
37325 ** record and then call BtreeMovetoUnpacked() to do the work.
37326 */
37327 SQLITE_PRIVATE int sqlite3BtreeMoveto(
37328   BtCursor *pCur,     /* Cursor open on the btree to be searched */
37329   const void *pKey,   /* Packed key if the btree is an index */
37330   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
37331   int bias,           /* Bias search to the high end */
37332   int *pRes           /* Write search results here */
37333 ){
37334   int rc;                    /* Status code */
37335   UnpackedRecord *pIdxKey;   /* Unpacked index key */
37336   UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
37337
37338   if( pKey ){
37339     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
37340                                       aSpace, sizeof(aSpace));
37341     if( pIdxKey==0 ) return SQLITE_NOMEM;
37342   }else{
37343     pIdxKey = 0;
37344   }
37345   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
37346   if( pKey ){
37347     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
37348   }
37349   return rc;
37350 }
37351
37352
37353 /*
37354 ** Return TRUE if the cursor is not pointing at an entry of the table.
37355 **
37356 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
37357 ** past the last entry in the table or sqlite3BtreePrev() moves past
37358 ** the first entry.  TRUE is also returned if the table is empty.
37359 */
37360 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
37361   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
37362   ** have been deleted? This API will need to change to return an error code
37363   ** as well as the boolean result value.
37364   */
37365   return (CURSOR_VALID!=pCur->eState);
37366 }
37367
37368 /*
37369 ** Return the database connection handle for a cursor.
37370 */
37371 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
37372   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
37373   return pCur->pBtree->db;
37374 }
37375
37376 /*
37377 ** Advance the cursor to the next entry in the database.  If
37378 ** successful then set *pRes=0.  If the cursor
37379 ** was already pointing to the last entry in the database before
37380 ** this routine was called, then set *pRes=1.
37381 */
37382 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
37383   int rc;
37384   int idx;
37385   MemPage *pPage;
37386
37387   assert( cursorHoldsMutex(pCur) );
37388   rc = restoreCursorPosition(pCur);
37389   if( rc!=SQLITE_OK ){
37390     return rc;
37391   }
37392   assert( pRes!=0 );
37393   if( CURSOR_INVALID==pCur->eState ){
37394     *pRes = 1;
37395     return SQLITE_OK;
37396   }
37397   if( pCur->skip>0 ){
37398     pCur->skip = 0;
37399     *pRes = 0;
37400     return SQLITE_OK;
37401   }
37402   pCur->skip = 0;
37403
37404   pPage = pCur->apPage[pCur->iPage];
37405   idx = ++pCur->aiIdx[pCur->iPage];
37406   assert( pPage->isInit );
37407   assert( idx<=pPage->nCell );
37408
37409   pCur->info.nSize = 0;
37410   pCur->validNKey = 0;
37411   if( idx>=pPage->nCell ){
37412     if( !pPage->leaf ){
37413       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
37414       if( rc ) return rc;
37415       rc = moveToLeftmost(pCur);
37416       *pRes = 0;
37417       return rc;
37418     }
37419     do{
37420       if( pCur->iPage==0 ){
37421         *pRes = 1;
37422         pCur->eState = CURSOR_INVALID;
37423         return SQLITE_OK;
37424       }
37425       sqlite3BtreeMoveToParent(pCur);
37426       pPage = pCur->apPage[pCur->iPage];
37427     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
37428     *pRes = 0;
37429     if( pPage->intKey ){
37430       rc = sqlite3BtreeNext(pCur, pRes);
37431     }else{
37432       rc = SQLITE_OK;
37433     }
37434     return rc;
37435   }
37436   *pRes = 0;
37437   if( pPage->leaf ){
37438     return SQLITE_OK;
37439   }
37440   rc = moveToLeftmost(pCur);
37441   return rc;
37442 }
37443
37444
37445 /*
37446 ** Step the cursor to the back to the previous entry in the database.  If
37447 ** successful then set *pRes=0.  If the cursor
37448 ** was already pointing to the first entry in the database before
37449 ** this routine was called, then set *pRes=1.
37450 */
37451 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
37452   int rc;
37453   MemPage *pPage;
37454
37455   assert( cursorHoldsMutex(pCur) );
37456   rc = restoreCursorPosition(pCur);
37457   if( rc!=SQLITE_OK ){
37458     return rc;
37459   }
37460   pCur->atLast = 0;
37461   if( CURSOR_INVALID==pCur->eState ){
37462     *pRes = 1;
37463     return SQLITE_OK;
37464   }
37465   if( pCur->skip<0 ){
37466     pCur->skip = 0;
37467     *pRes = 0;
37468     return SQLITE_OK;
37469   }
37470   pCur->skip = 0;
37471
37472   pPage = pCur->apPage[pCur->iPage];
37473   assert( pPage->isInit );
37474   if( !pPage->leaf ){
37475     int idx = pCur->aiIdx[pCur->iPage];
37476     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
37477     if( rc ){
37478       return rc;
37479     }
37480     rc = moveToRightmost(pCur);
37481   }else{
37482     while( pCur->aiIdx[pCur->iPage]==0 ){
37483       if( pCur->iPage==0 ){
37484         pCur->eState = CURSOR_INVALID;
37485         *pRes = 1;
37486         return SQLITE_OK;
37487       }
37488       sqlite3BtreeMoveToParent(pCur);
37489     }
37490     pCur->info.nSize = 0;
37491     pCur->validNKey = 0;
37492
37493     pCur->aiIdx[pCur->iPage]--;
37494     pPage = pCur->apPage[pCur->iPage];
37495     if( pPage->intKey && !pPage->leaf ){
37496       rc = sqlite3BtreePrevious(pCur, pRes);
37497     }else{
37498       rc = SQLITE_OK;
37499     }
37500   }
37501   *pRes = 0;
37502   return rc;
37503 }
37504
37505 /*
37506 ** Allocate a new page from the database file.
37507 **
37508 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
37509 ** has already been called on the new page.)  The new page has also
37510 ** been referenced and the calling routine is responsible for calling
37511 ** sqlite3PagerUnref() on the new page when it is done.
37512 **
37513 ** SQLITE_OK is returned on success.  Any other return value indicates
37514 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
37515 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
37516 **
37517 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
37518 ** locate a page close to the page number "nearby".  This can be used in an
37519 ** attempt to keep related pages close to each other in the database file,
37520 ** which in turn can make database access faster.
37521 **
37522 ** If the "exact" parameter is not 0, and the page-number nearby exists 
37523 ** anywhere on the free-list, then it is guarenteed to be returned. This
37524 ** is only used by auto-vacuum databases when allocating a new table.
37525 */
37526 static int allocateBtreePage(
37527   BtShared *pBt, 
37528   MemPage **ppPage, 
37529   Pgno *pPgno, 
37530   Pgno nearby,
37531   u8 exact
37532 ){
37533   MemPage *pPage1;
37534   int rc;
37535   int n;     /* Number of pages on the freelist */
37536   int k;     /* Number of leaves on the trunk of the freelist */
37537   MemPage *pTrunk = 0;
37538   MemPage *pPrevTrunk = 0;
37539
37540   assert( sqlite3_mutex_held(pBt->mutex) );
37541   pPage1 = pBt->pPage1;
37542   n = get4byte(&pPage1->aData[36]);
37543   if( n>0 ){
37544     /* There are pages on the freelist.  Reuse one of those pages. */
37545     Pgno iTrunk;
37546     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
37547     
37548     /* If the 'exact' parameter was true and a query of the pointer-map
37549     ** shows that the page 'nearby' is somewhere on the free-list, then
37550     ** the entire-list will be searched for that page.
37551     */
37552 #ifndef SQLITE_OMIT_AUTOVACUUM
37553     if( exact && nearby<=pagerPagecount(pBt->pPager) ){
37554       u8 eType;
37555       assert( nearby>0 );
37556       assert( pBt->autoVacuum );
37557       rc = ptrmapGet(pBt, nearby, &eType, 0);
37558       if( rc ) return rc;
37559       if( eType==PTRMAP_FREEPAGE ){
37560         searchList = 1;
37561       }
37562       *pPgno = nearby;
37563     }
37564 #endif
37565
37566     /* Decrement the free-list count by 1. Set iTrunk to the index of the
37567     ** first free-list trunk page. iPrevTrunk is initially 1.
37568     */
37569     rc = sqlite3PagerWrite(pPage1->pDbPage);
37570     if( rc ) return rc;
37571     put4byte(&pPage1->aData[36], n-1);
37572
37573     /* The code within this loop is run only once if the 'searchList' variable
37574     ** is not true. Otherwise, it runs once for each trunk-page on the
37575     ** free-list until the page 'nearby' is located.
37576     */
37577     do {
37578       pPrevTrunk = pTrunk;
37579       if( pPrevTrunk ){
37580         iTrunk = get4byte(&pPrevTrunk->aData[0]);
37581       }else{
37582         iTrunk = get4byte(&pPage1->aData[32]);
37583       }
37584       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
37585       if( rc ){
37586         pTrunk = 0;
37587         goto end_allocate_page;
37588       }
37589
37590       k = get4byte(&pTrunk->aData[4]);
37591       if( k==0 && !searchList ){
37592         /* The trunk has no leaves and the list is not being searched. 
37593         ** So extract the trunk page itself and use it as the newly 
37594         ** allocated page */
37595         assert( pPrevTrunk==0 );
37596         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37597         if( rc ){
37598           goto end_allocate_page;
37599         }
37600         *pPgno = iTrunk;
37601         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
37602         *ppPage = pTrunk;
37603         pTrunk = 0;
37604         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
37605       }else if( k>pBt->usableSize/4 - 2 ){
37606         /* Value of k is out of range.  Database corruption */
37607         rc = SQLITE_CORRUPT_BKPT;
37608         goto end_allocate_page;
37609 #ifndef SQLITE_OMIT_AUTOVACUUM
37610       }else if( searchList && nearby==iTrunk ){
37611         /* The list is being searched and this trunk page is the page
37612         ** to allocate, regardless of whether it has leaves.
37613         */
37614         assert( *pPgno==iTrunk );
37615         *ppPage = pTrunk;
37616         searchList = 0;
37617         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37618         if( rc ){
37619           goto end_allocate_page;
37620         }
37621         if( k==0 ){
37622           if( !pPrevTrunk ){
37623             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
37624           }else{
37625             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
37626           }
37627         }else{
37628           /* The trunk page is required by the caller but it contains 
37629           ** pointers to free-list leaves. The first leaf becomes a trunk
37630           ** page in this case.
37631           */
37632           MemPage *pNewTrunk;
37633           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
37634           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
37635           if( rc!=SQLITE_OK ){
37636             goto end_allocate_page;
37637           }
37638           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
37639           if( rc!=SQLITE_OK ){
37640             releasePage(pNewTrunk);
37641             goto end_allocate_page;
37642           }
37643           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
37644           put4byte(&pNewTrunk->aData[4], k-1);
37645           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
37646           releasePage(pNewTrunk);
37647           if( !pPrevTrunk ){
37648             put4byte(&pPage1->aData[32], iNewTrunk);
37649           }else{
37650             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
37651             if( rc ){
37652               goto end_allocate_page;
37653             }
37654             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
37655           }
37656         }
37657         pTrunk = 0;
37658         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
37659 #endif
37660       }else{
37661         /* Extract a leaf from the trunk */
37662         int closest;
37663         Pgno iPage;
37664         unsigned char *aData = pTrunk->aData;
37665         rc = sqlite3PagerWrite(pTrunk->pDbPage);
37666         if( rc ){
37667           goto end_allocate_page;
37668         }
37669         if( nearby>0 ){
37670           int i, dist;
37671           closest = 0;
37672           dist = get4byte(&aData[8]) - nearby;
37673           if( dist<0 ) dist = -dist;
37674           for(i=1; i<k; i++){
37675             int d2 = get4byte(&aData[8+i*4]) - nearby;
37676             if( d2<0 ) d2 = -d2;
37677             if( d2<dist ){
37678               closest = i;
37679               dist = d2;
37680             }
37681           }
37682         }else{
37683           closest = 0;
37684         }
37685
37686         iPage = get4byte(&aData[8+closest*4]);
37687         if( !searchList || iPage==nearby ){
37688           int nPage;
37689           *pPgno = iPage;
37690           nPage = pagerPagecount(pBt->pPager);
37691           if( *pPgno>nPage ){
37692             /* Free page off the end of the file */
37693             rc = SQLITE_CORRUPT_BKPT;
37694             goto end_allocate_page;
37695           }
37696           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
37697                  ": %d more free pages\n",
37698                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
37699           if( closest<k-1 ){
37700             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
37701           }
37702           put4byte(&aData[4], k-1);
37703           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
37704           if( rc==SQLITE_OK ){
37705             sqlite3PagerDontRollback((*ppPage)->pDbPage);
37706             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
37707             if( rc!=SQLITE_OK ){
37708               releasePage(*ppPage);
37709             }
37710           }
37711           searchList = 0;
37712         }
37713       }
37714       releasePage(pPrevTrunk);
37715       pPrevTrunk = 0;
37716     }while( searchList );
37717   }else{
37718     /* There are no pages on the freelist, so create a new page at the
37719     ** end of the file */
37720     int nPage = pagerPagecount(pBt->pPager);
37721     *pPgno = nPage + 1;
37722
37723 #ifndef SQLITE_OMIT_AUTOVACUUM
37724     if( pBt->nTrunc ){
37725       /* An incr-vacuum has already run within this transaction. So the
37726       ** page to allocate is not from the physical end of the file, but
37727       ** at pBt->nTrunc. 
37728       */
37729       *pPgno = pBt->nTrunc+1;
37730       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
37731         (*pPgno)++;
37732       }
37733     }
37734     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
37735       /* If *pPgno refers to a pointer-map page, allocate two new pages
37736       ** at the end of the file instead of one. The first allocated page
37737       ** becomes a new pointer-map page, the second is used by the caller.
37738       */
37739       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
37740       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37741       (*pPgno)++;
37742       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
37743     }
37744     if( pBt->nTrunc ){
37745       pBt->nTrunc = *pPgno;
37746     }
37747 #endif
37748
37749     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37750     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
37751     if( rc ) return rc;
37752     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
37753     if( rc!=SQLITE_OK ){
37754       releasePage(*ppPage);
37755     }
37756     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
37757   }
37758
37759   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
37760
37761 end_allocate_page:
37762   releasePage(pTrunk);
37763   releasePage(pPrevTrunk);
37764   if( rc==SQLITE_OK && sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
37765     releasePage(*ppPage);
37766     return SQLITE_CORRUPT_BKPT;
37767   }
37768   return rc;
37769 }
37770
37771 /*
37772 ** Add a page of the database file to the freelist.
37773 **
37774 ** sqlite3PagerUnref() is NOT called for pPage.
37775 */
37776 static int freePage(MemPage *pPage){
37777   BtShared *pBt = pPage->pBt;
37778   MemPage *pPage1 = pBt->pPage1;
37779   int rc, n, k;
37780
37781   /* Prepare the page for freeing */
37782   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37783   assert( pPage->pgno>1 );
37784   pPage->isInit = 0;
37785
37786   /* Increment the free page count on pPage1 */
37787   rc = sqlite3PagerWrite(pPage1->pDbPage);
37788   if( rc ) return rc;
37789   n = get4byte(&pPage1->aData[36]);
37790   put4byte(&pPage1->aData[36], n+1);
37791
37792 #ifdef SQLITE_SECURE_DELETE
37793   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
37794   ** always fully overwrite deleted information with zeros.
37795   */
37796   rc = sqlite3PagerWrite(pPage->pDbPage);
37797   if( rc ) return rc;
37798   memset(pPage->aData, 0, pPage->pBt->pageSize);
37799 #endif
37800
37801   /* If the database supports auto-vacuum, write an entry in the pointer-map
37802   ** to indicate that the page is free.
37803   */
37804   if( ISAUTOVACUUM ){
37805     rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
37806     if( rc ) return rc;
37807   }
37808
37809   if( n==0 ){
37810     /* This is the first free page */
37811     rc = sqlite3PagerWrite(pPage->pDbPage);
37812     if( rc ) return rc;
37813     memset(pPage->aData, 0, 8);
37814     put4byte(&pPage1->aData[32], pPage->pgno);
37815     TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
37816   }else{
37817     /* Other free pages already exist.  Retrive the first trunk page
37818     ** of the freelist and find out how many leaves it has. */
37819     MemPage *pTrunk;
37820     rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
37821     if( rc ) return rc;
37822     k = get4byte(&pTrunk->aData[4]);
37823     if( k>=pBt->usableSize/4 - 8 ){
37824       /* The trunk is full.  Turn the page being freed into a new
37825       ** trunk page with no leaves.
37826       **
37827       ** Note that the trunk page is not really full until it contains
37828       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
37829       ** coded.  But due to a coding error in versions of SQLite prior to
37830       ** 3.6.0, databases with freelist trunk pages holding more than
37831       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
37832       ** to maintain backwards compatibility with older versions of SQLite,
37833       ** we will contain to restrict the number of entries to usableSize/4 - 8
37834       ** for now.  At some point in the future (once everyone has upgraded
37835       ** to 3.6.0 or later) we should consider fixing the conditional above
37836       ** to read "usableSize/4-2" instead of "usableSize/4-8".
37837       */
37838       rc = sqlite3PagerWrite(pPage->pDbPage);
37839       if( rc==SQLITE_OK ){
37840         put4byte(pPage->aData, pTrunk->pgno);
37841         put4byte(&pPage->aData[4], 0);
37842         put4byte(&pPage1->aData[32], pPage->pgno);
37843         TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
37844                 pPage->pgno, pTrunk->pgno));
37845       }
37846     }else if( k<0 ){
37847       rc = SQLITE_CORRUPT;
37848     }else{
37849       /* Add the newly freed page as a leaf on the current trunk */
37850       rc = sqlite3PagerWrite(pTrunk->pDbPage);
37851       if( rc==SQLITE_OK ){
37852         put4byte(&pTrunk->aData[4], k+1);
37853         put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
37854 #ifndef SQLITE_SECURE_DELETE
37855         rc = sqlite3PagerDontWrite(pPage->pDbPage);
37856 #endif
37857       }
37858       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
37859     }
37860     releasePage(pTrunk);
37861   }
37862   return rc;
37863 }
37864
37865 /*
37866 ** Free any overflow pages associated with the given Cell.
37867 */
37868 static int clearCell(MemPage *pPage, unsigned char *pCell){
37869   BtShared *pBt = pPage->pBt;
37870   CellInfo info;
37871   Pgno ovflPgno;
37872   int rc;
37873   int nOvfl;
37874   int ovflPageSize;
37875
37876   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37877   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37878   if( info.iOverflow==0 ){
37879     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
37880   }
37881   ovflPgno = get4byte(&pCell[info.iOverflow]);
37882   ovflPageSize = pBt->usableSize - 4;
37883   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
37884   assert( ovflPgno==0 || nOvfl>0 );
37885   while( nOvfl-- ){
37886     MemPage *pOvfl;
37887     if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt->pPager) ){
37888       return SQLITE_CORRUPT_BKPT;
37889     }
37890
37891     rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
37892     if( rc ) return rc;
37893     rc = freePage(pOvfl);
37894     sqlite3PagerUnref(pOvfl->pDbPage);
37895     if( rc ) return rc;
37896   }
37897   return SQLITE_OK;
37898 }
37899
37900 /*
37901 ** Create the byte sequence used to represent a cell on page pPage
37902 ** and write that byte sequence into pCell[].  Overflow pages are
37903 ** allocated and filled in as necessary.  The calling procedure
37904 ** is responsible for making sure sufficient space has been allocated
37905 ** for pCell[].
37906 **
37907 ** Note that pCell does not necessary need to point to the pPage->aData
37908 ** area.  pCell might point to some temporary storage.  The cell will
37909 ** be constructed in this temporary area then copied into pPage->aData
37910 ** later.
37911 */
37912 static int fillInCell(
37913   MemPage *pPage,                /* The page that contains the cell */
37914   unsigned char *pCell,          /* Complete text of the cell */
37915   const void *pKey, i64 nKey,    /* The key */
37916   const void *pData,int nData,   /* The data */
37917   int nZero,                     /* Extra zero bytes to append to pData */
37918   int *pnSize                    /* Write cell size here */
37919 ){
37920   int nPayload;
37921   const u8 *pSrc;
37922   int nSrc, n, rc;
37923   int spaceLeft;
37924   MemPage *pOvfl = 0;
37925   MemPage *pToRelease = 0;
37926   unsigned char *pPrior;
37927   unsigned char *pPayload;
37928   BtShared *pBt = pPage->pBt;
37929   Pgno pgnoOvfl = 0;
37930   int nHeader;
37931   CellInfo info;
37932
37933   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37934
37935   /* Fill in the header. */
37936   nHeader = 0;
37937   if( !pPage->leaf ){
37938     nHeader += 4;
37939   }
37940   if( pPage->hasData ){
37941     nHeader += putVarint(&pCell[nHeader], nData+nZero);
37942   }else{
37943     nData = nZero = 0;
37944   }
37945   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
37946   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
37947   assert( info.nHeader==nHeader );
37948   assert( info.nKey==nKey );
37949   assert( info.nData==nData+nZero );
37950   
37951   /* Fill in the payload */
37952   nPayload = nData + nZero;
37953   if( pPage->intKey ){
37954     pSrc = pData;
37955     nSrc = nData;
37956     nData = 0;
37957   }else{
37958     nPayload += nKey;
37959     pSrc = pKey;
37960     nSrc = nKey;
37961   }
37962   *pnSize = info.nSize;
37963   spaceLeft = info.nLocal;
37964   pPayload = &pCell[nHeader];
37965   pPrior = &pCell[info.iOverflow];
37966
37967   while( nPayload>0 ){
37968     if( spaceLeft==0 ){
37969       int isExact = 0;
37970 #ifndef SQLITE_OMIT_AUTOVACUUM
37971       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
37972       if( pBt->autoVacuum ){
37973         do{
37974           pgnoOvfl++;
37975         } while( 
37976           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
37977         );
37978         if( pgnoOvfl>1 ){
37979           /* isExact = 1; */
37980         }
37981       }
37982 #endif
37983       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
37984 #ifndef SQLITE_OMIT_AUTOVACUUM
37985       /* If the database supports auto-vacuum, and the second or subsequent
37986       ** overflow page is being allocated, add an entry to the pointer-map
37987       ** for that page now. 
37988       **
37989       ** If this is the first overflow page, then write a partial entry 
37990       ** to the pointer-map. If we write nothing to this pointer-map slot,
37991       ** then the optimistic overflow chain processing in clearCell()
37992       ** may misinterpret the uninitialised values and delete the
37993       ** wrong pages from the database.
37994       */
37995       if( pBt->autoVacuum && rc==SQLITE_OK ){
37996         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
37997         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
37998         if( rc ){
37999           releasePage(pOvfl);
38000         }
38001       }
38002 #endif
38003       if( rc ){
38004         releasePage(pToRelease);
38005         return rc;
38006       }
38007       put4byte(pPrior, pgnoOvfl);
38008       releasePage(pToRelease);
38009       pToRelease = pOvfl;
38010       pPrior = pOvfl->aData;
38011       put4byte(pPrior, 0);
38012       pPayload = &pOvfl->aData[4];
38013       spaceLeft = pBt->usableSize - 4;
38014     }
38015     n = nPayload;
38016     if( n>spaceLeft ) n = spaceLeft;
38017     if( nSrc>0 ){
38018       if( n>nSrc ) n = nSrc;
38019       assert( pSrc );
38020       memcpy(pPayload, pSrc, n);
38021     }else{
38022       memset(pPayload, 0, n);
38023     }
38024     nPayload -= n;
38025     pPayload += n;
38026     pSrc += n;
38027     nSrc -= n;
38028     spaceLeft -= n;
38029     if( nSrc==0 ){
38030       nSrc = nData;
38031       pSrc = pData;
38032     }
38033   }
38034   releasePage(pToRelease);
38035   return SQLITE_OK;
38036 }
38037
38038 /*
38039 ** Remove the i-th cell from pPage.  This routine effects pPage only.
38040 ** The cell content is not freed or deallocated.  It is assumed that
38041 ** the cell content has been copied someplace else.  This routine just
38042 ** removes the reference to the cell from pPage.
38043 **
38044 ** "sz" must be the number of bytes in the cell.
38045 */
38046 static void dropCell(MemPage *pPage, int idx, int sz){
38047   int i;          /* Loop counter */
38048   int pc;         /* Offset to cell content of cell being deleted */
38049   u8 *data;       /* pPage->aData */
38050   u8 *ptr;        /* Used to move bytes around within data[] */
38051
38052   assert( idx>=0 && idx<pPage->nCell );
38053   assert( sz==cellSize(pPage, idx) );
38054   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38055   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38056   data = pPage->aData;
38057   ptr = &data[pPage->cellOffset + 2*idx];
38058   pc = get2byte(ptr);
38059   assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
38060   freeSpace(pPage, pc, sz);
38061   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
38062     ptr[0] = ptr[2];
38063     ptr[1] = ptr[3];
38064   }
38065   pPage->nCell--;
38066   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
38067   pPage->nFree += 2;
38068 }
38069
38070 /*
38071 ** Insert a new cell on pPage at cell index "i".  pCell points to the
38072 ** content of the cell.
38073 **
38074 ** If the cell content will fit on the page, then put it there.  If it
38075 ** will not fit, then make a copy of the cell content into pTemp if
38076 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
38077 ** in pPage->aOvfl[] and make it point to the cell content (either
38078 ** in pTemp or the original pCell) and also record its index. 
38079 ** Allocating a new entry in pPage->aCell[] implies that 
38080 ** pPage->nOverflow is incremented.
38081 **
38082 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
38083 ** cell. The caller will overwrite them after this function returns. If
38084 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
38085 ** (but pCell+nSkip is always valid).
38086 */
38087 static int insertCell(
38088   MemPage *pPage,   /* Page into which we are copying */
38089   int i,            /* New cell becomes the i-th cell of the page */
38090   u8 *pCell,        /* Content of the new cell */
38091   int sz,           /* Bytes of content in pCell */
38092   u8 *pTemp,        /* Temp storage space for pCell, if needed */
38093   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
38094 ){
38095   int idx;          /* Where to write new cell content in data[] */
38096   int j;            /* Loop counter */
38097   int top;          /* First byte of content for any cell in data[] */
38098   int end;          /* First byte past the last cell pointer in data[] */
38099   int ins;          /* Index in data[] where new cell pointer is inserted */
38100   int hdr;          /* Offset into data[] of the page header */
38101   int cellOffset;   /* Address of first cell pointer in data[] */
38102   u8 *data;         /* The content of the whole page */
38103   u8 *ptr;          /* Used for moving information around in data[] */
38104
38105   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
38106   assert( sz==cellSizePtr(pPage, pCell) );
38107   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38108   if( pPage->nOverflow || sz+2>pPage->nFree ){
38109     if( pTemp ){
38110       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
38111       pCell = pTemp;
38112     }
38113     j = pPage->nOverflow++;
38114     assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
38115     pPage->aOvfl[j].pCell = pCell;
38116     pPage->aOvfl[j].idx = i;
38117     pPage->nFree = 0;
38118   }else{
38119     int rc = sqlite3PagerWrite(pPage->pDbPage);
38120     if( rc!=SQLITE_OK ){
38121       return rc;
38122     }
38123     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38124     data = pPage->aData;
38125     hdr = pPage->hdrOffset;
38126     top = get2byte(&data[hdr+5]);
38127     cellOffset = pPage->cellOffset;
38128     end = cellOffset + 2*pPage->nCell + 2;
38129     ins = cellOffset + 2*i;
38130     if( end > top - sz ){
38131       defragmentPage(pPage);
38132       top = get2byte(&data[hdr+5]);
38133       assert( end + sz <= top );
38134     }
38135     idx = allocateSpace(pPage, sz);
38136     assert( idx>0 );
38137     assert( end <= get2byte(&data[hdr+5]) );
38138     pPage->nCell++;
38139     pPage->nFree -= 2;
38140     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
38141     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
38142       ptr[0] = ptr[-2];
38143       ptr[1] = ptr[-1];
38144     }
38145     put2byte(&data[ins], idx);
38146     put2byte(&data[hdr+3], pPage->nCell);
38147 #ifndef SQLITE_OMIT_AUTOVACUUM
38148     if( pPage->pBt->autoVacuum ){
38149       /* The cell may contain a pointer to an overflow page. If so, write
38150       ** the entry for the overflow page into the pointer map.
38151       */
38152       CellInfo info;
38153       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38154       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38155       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
38156         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
38157         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
38158         if( rc!=SQLITE_OK ) return rc;
38159       }
38160     }
38161 #endif
38162   }
38163
38164   return SQLITE_OK;
38165 }
38166
38167 /*
38168 ** Add a list of cells to a page.  The page should be initially empty.
38169 ** The cells are guaranteed to fit on the page.
38170 */
38171 static void assemblePage(
38172   MemPage *pPage,   /* The page to be assemblied */
38173   int nCell,        /* The number of cells to add to this page */
38174   u8 **apCell,      /* Pointers to cell bodies */
38175   u16 *aSize        /* Sizes of the cells */
38176 ){
38177   int i;            /* Loop counter */
38178   int totalSize;    /* Total size of all cells */
38179   int hdr;          /* Index of page header */
38180   int cellptr;      /* Address of next cell pointer */
38181   int cellbody;     /* Address of next cell body */
38182   u8 *data;         /* Data for the page */
38183
38184   assert( pPage->nOverflow==0 );
38185   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38186   totalSize = 0;
38187   for(i=0; i<nCell; i++){
38188     totalSize += aSize[i];
38189   }
38190   assert( totalSize+2*nCell<=pPage->nFree );
38191   assert( pPage->nCell==0 );
38192   cellptr = pPage->cellOffset;
38193   data = pPage->aData;
38194   hdr = pPage->hdrOffset;
38195   put2byte(&data[hdr+3], nCell);
38196   if( nCell ){
38197     cellbody = allocateSpace(pPage, totalSize);
38198     assert( cellbody>0 );
38199     assert( pPage->nFree >= 2*nCell );
38200     pPage->nFree -= 2*nCell;
38201     for(i=0; i<nCell; i++){
38202       put2byte(&data[cellptr], cellbody);
38203       memcpy(&data[cellbody], apCell[i], aSize[i]);
38204       cellptr += 2;
38205       cellbody += aSize[i];
38206     }
38207     assert( cellbody==pPage->pBt->usableSize );
38208   }
38209   pPage->nCell = nCell;
38210 }
38211
38212 /*
38213 ** The following parameters determine how many adjacent pages get involved
38214 ** in a balancing operation.  NN is the number of neighbors on either side
38215 ** of the page that participate in the balancing operation.  NB is the
38216 ** total number of pages that participate, including the target page and
38217 ** NN neighbors on either side.
38218 **
38219 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
38220 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
38221 ** in exchange for a larger degradation in INSERT and UPDATE performance.
38222 ** The value of NN appears to give the best results overall.
38223 */
38224 #define NN 1             /* Number of neighbors on either side of pPage */
38225 #define NB (NN*2+1)      /* Total pages involved in the balance */
38226
38227 /* Forward reference */
38228 static int balance(BtCursor*, int);
38229
38230 #ifndef SQLITE_OMIT_QUICKBALANCE
38231 /*
38232 ** This version of balance() handles the common special case where
38233 ** a new entry is being inserted on the extreme right-end of the
38234 ** tree, in other words, when the new entry will become the largest
38235 ** entry in the tree.
38236 **
38237 ** Instead of trying balance the 3 right-most leaf pages, just add
38238 ** a new page to the right-hand side and put the one new entry in
38239 ** that page.  This leaves the right side of the tree somewhat
38240 ** unbalanced.  But odds are that we will be inserting new entries
38241 ** at the end soon afterwards so the nearly empty page will quickly
38242 ** fill up.  On average.
38243 **
38244 ** pPage is the leaf page which is the right-most page in the tree.
38245 ** pParent is its parent.  pPage must have a single overflow entry
38246 ** which is also the right-most entry on the page.
38247 */
38248 static int balance_quick(BtCursor *pCur){
38249   int rc;
38250   MemPage *pNew = 0;
38251   Pgno pgnoNew;
38252   u8 *pCell;
38253   u16 szCell;
38254   CellInfo info;
38255   MemPage *pPage = pCur->apPage[pCur->iPage];
38256   MemPage *pParent = pCur->apPage[pCur->iPage-1];
38257   BtShared *pBt = pPage->pBt;
38258   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
38259   int parentSize;                   /* Size of new divider cell */
38260   u8 parentCell[64];                /* Space for the new divider cell */
38261
38262   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38263
38264   /* Allocate a new page. Insert the overflow cell from pPage
38265   ** into it. Then remove the overflow cell from pPage.
38266   */
38267   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
38268   if( rc==SQLITE_OK ){
38269     pCell = pPage->aOvfl[0].pCell;
38270     szCell = cellSizePtr(pPage, pCell);
38271     zeroPage(pNew, pPage->aData[0]);
38272     assemblePage(pNew, 1, &pCell, &szCell);
38273     pPage->nOverflow = 0;
38274   
38275     /* pPage is currently the right-child of pParent. Change this
38276     ** so that the right-child is the new page allocated above and
38277     ** pPage is the next-to-right child. 
38278     **
38279     ** Ignore the return value of the call to fillInCell(). fillInCell()
38280     ** may only return other than SQLITE_OK if it is required to allocate
38281     ** one or more overflow pages. Since an internal table B-Tree cell 
38282     ** may never spill over onto an overflow page (it is a maximum of 
38283     ** 13 bytes in size), it is not neccessary to check the return code.
38284     **
38285     ** Similarly, the insertCell() function cannot fail if the page
38286     ** being inserted into is already writable and the cell does not 
38287     ** contain an overflow pointer. So ignore this return code too.
38288     */
38289     assert( pPage->nCell>0 );
38290     pCell = findCell(pPage, pPage->nCell-1);
38291     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38292     fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
38293     assert( parentSize<64 );
38294     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
38295     insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
38296     put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
38297     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
38298   
38299     /* If this is an auto-vacuum database, update the pointer map
38300     ** with entries for the new page, and any pointer from the 
38301     ** cell on the page to an overflow page.
38302     */
38303     if( ISAUTOVACUUM ){
38304       rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
38305       if( rc==SQLITE_OK ){
38306         rc = ptrmapPutOvfl(pNew, 0);
38307       }
38308     }
38309
38310     /* Release the reference to the new page. */
38311     releasePage(pNew);
38312   }
38313
38314   /* At this point the pPage->nFree variable is not set correctly with
38315   ** respect to the content of the page (because it was set to 0 by 
38316   ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
38317   ** correct.
38318   **
38319   ** This has to be done even if an error will be returned. Normally, if
38320   ** an error occurs during tree balancing, the contents of MemPage are
38321   ** not important, as they will be recalculated when the page is rolled
38322   ** back. But here, in balance_quick(), it is possible that pPage has 
38323   ** not yet been marked dirty or written into the journal file. Therefore
38324   ** it will not be rolled back and so it is important to make sure that
38325   ** the page data and contents of MemPage are consistent.
38326   */
38327   pPage->isInit = 0;
38328   sqlite3BtreeInitPage(pPage);
38329
38330   /* If everything else succeeded, balance the parent page, in 
38331   ** case the divider cell inserted caused it to become overfull.
38332   */
38333   if( rc==SQLITE_OK ){
38334     releasePage(pPage);
38335     pCur->iPage--;
38336     rc = balance(pCur, 0);
38337   }
38338   return rc;
38339 }
38340 #endif /* SQLITE_OMIT_QUICKBALANCE */
38341
38342 /*
38343 ** This routine redistributes Cells on pPage and up to NN*2 siblings
38344 ** of pPage so that all pages have about the same amount of free space.
38345 ** Usually NN siblings on either side of pPage is used in the balancing,
38346 ** though more siblings might come from one side if pPage is the first
38347 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
38348 ** (something which can only happen if pPage is the root page or a 
38349 ** child of root) then all available siblings participate in the balancing.
38350 **
38351 ** The number of siblings of pPage might be increased or decreased by one or
38352 ** two in an effort to keep pages nearly full but not over full. The root page
38353 ** is special and is allowed to be nearly empty. If pPage is 
38354 ** the root page, then the depth of the tree might be increased
38355 ** or decreased by one, as necessary, to keep the root page from being
38356 ** overfull or completely empty.
38357 **
38358 ** Note that when this routine is called, some of the Cells on pPage
38359 ** might not actually be stored in pPage->aData[].  This can happen
38360 ** if the page is overfull.  Part of the job of this routine is to
38361 ** make sure all Cells for pPage once again fit in pPage->aData[].
38362 **
38363 ** In the course of balancing the siblings of pPage, the parent of pPage
38364 ** might become overfull or underfull.  If that happens, then this routine
38365 ** is called recursively on the parent.
38366 **
38367 ** If this routine fails for any reason, it might leave the database
38368 ** in a corrupted state.  So if this routine fails, the database should
38369 ** be rolled back.
38370 */
38371 static int balance_nonroot(BtCursor *pCur){
38372   MemPage *pPage;              /* The over or underfull page to balance */
38373   MemPage *pParent;            /* The parent of pPage */
38374   BtShared *pBt;               /* The whole database */
38375   int nCell = 0;               /* Number of cells in apCell[] */
38376   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
38377   int nOld;                    /* Number of pages in apOld[] */
38378   int nNew;                    /* Number of pages in apNew[] */
38379   int nDiv;                    /* Number of cells in apDiv[] */
38380   int i, j, k;                 /* Loop counters */
38381   int idx;                     /* Index of pPage in pParent->aCell[] */
38382   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
38383   int rc;                      /* The return code */
38384   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
38385   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
38386   int usableSpace;             /* Bytes in pPage beyond the header */
38387   int pageFlags;               /* Value of pPage->aData[0] */
38388   int subtotal;                /* Subtotal of bytes in cells on one page */
38389   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
38390   int iSpace2 = 0;             /* First unused byte of aSpace2[] */
38391   int szScratch;               /* Size of scratch memory requested */
38392   MemPage *apOld[NB];          /* pPage and up to two siblings */
38393   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
38394   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
38395   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
38396   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
38397   u8 *apDiv[NB];               /* Divider cells in pParent */
38398   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
38399   int szNew[NB+2];             /* Combined size of cells place on i-th page */
38400   u8 **apCell = 0;             /* All cells begin balanced */
38401   u16 *szCell;                 /* Local size of all cells in apCell[] */
38402   u8 *aCopy[NB];         /* Space for holding data of apCopy[] */
38403   u8 *aSpace1;           /* Space for copies of dividers cells before balance */
38404   u8 *aSpace2 = 0;       /* Space for overflow dividers cells after balance */
38405   u8 *aFrom = 0;
38406
38407   pPage = pCur->apPage[pCur->iPage];
38408   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38409   VVA_ONLY( pCur->pagesShuffled = 1 );
38410
38411   /* 
38412   ** Find the parent page.
38413   */
38414   assert( pCur->iPage>0 );
38415   assert( pPage->isInit );
38416   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
38417   pBt = pPage->pBt;
38418   pParent = pCur->apPage[pCur->iPage-1];
38419   assert( pParent );
38420   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
38421     return rc;
38422   }
38423
38424   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
38425
38426 #ifndef SQLITE_OMIT_QUICKBALANCE
38427   /*
38428   ** A special case:  If a new entry has just been inserted into a
38429   ** table (that is, a btree with integer keys and all data at the leaves)
38430   ** and the new entry is the right-most entry in the tree (it has the
38431   ** largest key) then use the special balance_quick() routine for
38432   ** balancing.  balance_quick() is much faster and results in a tighter
38433   ** packing of data in the common case.
38434   */
38435   if( pPage->leaf &&
38436       pPage->intKey &&
38437       pPage->nOverflow==1 &&
38438       pPage->aOvfl[0].idx==pPage->nCell &&
38439       pParent->pgno!=1 &&
38440       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
38441   ){
38442     assert( pPage->intKey );
38443     /*
38444     ** TODO: Check the siblings to the left of pPage. It may be that
38445     ** they are not full and no new page is required.
38446     */
38447     return balance_quick(pCur);
38448   }
38449 #endif
38450
38451   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
38452     return rc;
38453   }
38454
38455   /*
38456   ** Find the cell in the parent page whose left child points back
38457   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
38458   ** is the rightmost child of pParent then set idx to pParent->nCell 
38459   */
38460   idx = pCur->aiIdx[pCur->iPage-1];
38461   assertParentIndex(pParent, idx, pPage->pgno);
38462
38463   /*
38464   ** Initialize variables so that it will be safe to jump
38465   ** directly to balance_cleanup at any moment.
38466   */
38467   nOld = nNew = 0;
38468
38469   /*
38470   ** Find sibling pages to pPage and the cells in pParent that divide
38471   ** the siblings.  An attempt is made to find NN siblings on either
38472   ** side of pPage.  More siblings are taken from one side, however, if
38473   ** pPage there are fewer than NN siblings on the other side.  If pParent
38474   ** has NB or fewer children then all children of pParent are taken.
38475   */
38476   nxDiv = idx - NN;
38477   if( nxDiv + NB > pParent->nCell ){
38478     nxDiv = pParent->nCell - NB + 1;
38479   }
38480   if( nxDiv<0 ){
38481     nxDiv = 0;
38482   }
38483   nDiv = 0;
38484   for(i=0, k=nxDiv; i<NB; i++, k++){
38485     if( k<pParent->nCell ){
38486       apDiv[i] = findCell(pParent, k);
38487       nDiv++;
38488       assert( !pParent->leaf );
38489       pgnoOld[i] = get4byte(apDiv[i]);
38490     }else if( k==pParent->nCell ){
38491       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
38492     }else{
38493       break;
38494     }
38495     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
38496     if( rc ) goto balance_cleanup;
38497     /* apOld[i]->idxParent = k; */
38498     apCopy[i] = 0;
38499     assert( i==nOld );
38500     nOld++;
38501     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
38502   }
38503
38504   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
38505   ** alignment */
38506   nMaxCells = (nMaxCells + 3)&~3;
38507
38508   /*
38509   ** Allocate space for memory structures
38510   */
38511   szScratch =
38512        nMaxCells*sizeof(u8*)                       /* apCell */
38513      + nMaxCells*sizeof(u16)                       /* szCell */
38514      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
38515      + pBt->pageSize                               /* aSpace1 */
38516      + (ISAUTOVACUUM ? nMaxCells : 0);             /* aFrom */
38517   apCell = sqlite3ScratchMalloc( szScratch ); 
38518   if( apCell==0 ){
38519     rc = SQLITE_NOMEM;
38520     goto balance_cleanup;
38521   }
38522   szCell = (u16*)&apCell[nMaxCells];
38523   aCopy[0] = (u8*)&szCell[nMaxCells];
38524   assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38525   for(i=1; i<NB; i++){
38526     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38527     assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38528   }
38529   aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
38530   assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
38531   if( ISAUTOVACUUM ){
38532     aFrom = &aSpace1[pBt->pageSize];
38533   }
38534   aSpace2 = sqlite3PageMalloc(pBt->pageSize);
38535   if( aSpace2==0 ){
38536     rc = SQLITE_NOMEM;
38537     goto balance_cleanup;
38538   }
38539   
38540   /*
38541   ** Make copies of the content of pPage and its siblings into aOld[].
38542   ** The rest of this function will use data from the copies rather
38543   ** that the original pages since the original pages will be in the
38544   ** process of being overwritten.
38545   */
38546   for(i=0; i<nOld; i++){
38547     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
38548     memcpy(p, apOld[i], sizeof(MemPage));
38549     p->aData = (void*)&p[1];
38550     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
38551   }
38552
38553   /*
38554   ** Load pointers to all cells on sibling pages and the divider cells
38555   ** into the local apCell[] array.  Make copies of the divider cells
38556   ** into space obtained form aSpace1[] and remove the the divider Cells
38557   ** from pParent.
38558   **
38559   ** If the siblings are on leaf pages, then the child pointers of the
38560   ** divider cells are stripped from the cells before they are copied
38561   ** into aSpace1[].  In this way, all cells in apCell[] are without
38562   ** child pointers.  If siblings are not leaves, then all cell in
38563   ** apCell[] include child pointers.  Either way, all cells in apCell[]
38564   ** are alike.
38565   **
38566   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
38567   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
38568   */
38569   nCell = 0;
38570   leafCorrection = pPage->leaf*4;
38571   leafData = pPage->hasData;
38572   for(i=0; i<nOld; i++){
38573     MemPage *pOld = apCopy[i];
38574     int limit = pOld->nCell+pOld->nOverflow;
38575     for(j=0; j<limit; j++){
38576       assert( nCell<nMaxCells );
38577       apCell[nCell] = findOverflowCell(pOld, j);
38578       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
38579       if( ISAUTOVACUUM ){
38580         int a;
38581         aFrom[nCell] = i;
38582         for(a=0; a<pOld->nOverflow; a++){
38583           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
38584             aFrom[nCell] = 0xFF;
38585             break;
38586           }
38587         }
38588       }
38589       nCell++;
38590     }
38591     if( i<nOld-1 ){
38592       u16 sz = cellSizePtr(pParent, apDiv[i]);
38593       if( leafData ){
38594         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
38595         ** are duplicates of keys on the child pages.  We need to remove
38596         ** the divider cells from pParent, but the dividers cells are not
38597         ** added to apCell[] because they are duplicates of child cells.
38598         */
38599         dropCell(pParent, nxDiv, sz);
38600       }else{
38601         u8 *pTemp;
38602         assert( nCell<nMaxCells );
38603         szCell[nCell] = sz;
38604         pTemp = &aSpace1[iSpace1];
38605         iSpace1 += sz;
38606         assert( sz<=pBt->pageSize/4 );
38607         assert( iSpace1<=pBt->pageSize );
38608         memcpy(pTemp, apDiv[i], sz);
38609         apCell[nCell] = pTemp+leafCorrection;
38610         if( ISAUTOVACUUM ){
38611           aFrom[nCell] = 0xFF;
38612         }
38613         dropCell(pParent, nxDiv, sz);
38614         szCell[nCell] -= leafCorrection;
38615         assert( get4byte(pTemp)==pgnoOld[i] );
38616         if( !pOld->leaf ){
38617           assert( leafCorrection==0 );
38618           /* The right pointer of the child page pOld becomes the left
38619           ** pointer of the divider cell */
38620           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
38621         }else{
38622           assert( leafCorrection==4 );
38623           if( szCell[nCell]<4 ){
38624             /* Do not allow any cells smaller than 4 bytes. */
38625             szCell[nCell] = 4;
38626           }
38627         }
38628         nCell++;
38629       }
38630     }
38631   }
38632
38633   /*
38634   ** Figure out the number of pages needed to hold all nCell cells.
38635   ** Store this number in "k".  Also compute szNew[] which is the total
38636   ** size of all cells on the i-th page and cntNew[] which is the index
38637   ** in apCell[] of the cell that divides page i from page i+1.  
38638   ** cntNew[k] should equal nCell.
38639   **
38640   ** Values computed by this block:
38641   **
38642   **           k: The total number of sibling pages
38643   **    szNew[i]: Spaced used on the i-th sibling page.
38644   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
38645   **              the right of the i-th sibling page.
38646   ** usableSpace: Number of bytes of space available on each sibling.
38647   ** 
38648   */
38649   usableSpace = pBt->usableSize - 12 + leafCorrection;
38650   for(subtotal=k=i=0; i<nCell; i++){
38651     assert( i<nMaxCells );
38652     subtotal += szCell[i] + 2;
38653     if( subtotal > usableSpace ){
38654       szNew[k] = subtotal - szCell[i];
38655       cntNew[k] = i;
38656       if( leafData ){ i--; }
38657       subtotal = 0;
38658       k++;
38659     }
38660   }
38661   szNew[k] = subtotal;
38662   cntNew[k] = nCell;
38663   k++;
38664
38665   /*
38666   ** The packing computed by the previous block is biased toward the siblings
38667   ** on the left side.  The left siblings are always nearly full, while the
38668   ** right-most sibling might be nearly empty.  This block of code attempts
38669   ** to adjust the packing of siblings to get a better balance.
38670   **
38671   ** This adjustment is more than an optimization.  The packing above might
38672   ** be so out of balance as to be illegal.  For example, the right-most
38673   ** sibling might be completely empty.  This adjustment is not optional.
38674   */
38675   for(i=k-1; i>0; i--){
38676     int szRight = szNew[i];  /* Size of sibling on the right */
38677     int szLeft = szNew[i-1]; /* Size of sibling on the left */
38678     int r;              /* Index of right-most cell in left sibling */
38679     int d;              /* Index of first cell to the left of right sibling */
38680
38681     r = cntNew[i-1] - 1;
38682     d = r + 1 - leafData;
38683     assert( d<nMaxCells );
38684     assert( r<nMaxCells );
38685     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
38686       szRight += szCell[d] + 2;
38687       szLeft -= szCell[r] + 2;
38688       cntNew[i-1]--;
38689       r = cntNew[i-1] - 1;
38690       d = r + 1 - leafData;
38691     }
38692     szNew[i] = szRight;
38693     szNew[i-1] = szLeft;
38694   }
38695
38696   /* Either we found one or more cells (cntnew[0])>0) or we are the
38697   ** a virtual root page.  A virtual root page is when the real root
38698   ** page is page 1 and we are the only child of that page.
38699   */
38700   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
38701
38702   /*
38703   ** Allocate k new pages.  Reuse old pages where possible.
38704   */
38705   assert( pPage->pgno>1 );
38706   pageFlags = pPage->aData[0];
38707   for(i=0; i<k; i++){
38708     MemPage *pNew;
38709     if( i<nOld ){
38710       pNew = apNew[i] = apOld[i];
38711       pgnoNew[i] = pgnoOld[i];
38712       apOld[i] = 0;
38713       rc = sqlite3PagerWrite(pNew->pDbPage);
38714       nNew++;
38715       if( rc ) goto balance_cleanup;
38716     }else{
38717       assert( i>0 );
38718       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
38719       if( rc ) goto balance_cleanup;
38720       apNew[i] = pNew;
38721       nNew++;
38722     }
38723   }
38724
38725   /* Free any old pages that were not reused as new pages.
38726   */
38727   while( i<nOld ){
38728     rc = freePage(apOld[i]);
38729     if( rc ) goto balance_cleanup;
38730     releasePage(apOld[i]);
38731     apOld[i] = 0;
38732     i++;
38733   }
38734
38735   /*
38736   ** Put the new pages in accending order.  This helps to
38737   ** keep entries in the disk file in order so that a scan
38738   ** of the table is a linear scan through the file.  That
38739   ** in turn helps the operating system to deliver pages
38740   ** from the disk more rapidly.
38741   **
38742   ** An O(n^2) insertion sort algorithm is used, but since
38743   ** n is never more than NB (a small constant), that should
38744   ** not be a problem.
38745   **
38746   ** When NB==3, this one optimization makes the database
38747   ** about 25% faster for large insertions and deletions.
38748   */
38749   for(i=0; i<k-1; i++){
38750     int minV = pgnoNew[i];
38751     int minI = i;
38752     for(j=i+1; j<k; j++){
38753       if( pgnoNew[j]<(unsigned)minV ){
38754         minI = j;
38755         minV = pgnoNew[j];
38756       }
38757     }
38758     if( minI>i ){
38759       int t;
38760       MemPage *pT;
38761       t = pgnoNew[i];
38762       pT = apNew[i];
38763       pgnoNew[i] = pgnoNew[minI];
38764       apNew[i] = apNew[minI];
38765       pgnoNew[minI] = t;
38766       apNew[minI] = pT;
38767     }
38768   }
38769   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
38770     pgnoOld[0], 
38771     nOld>=2 ? pgnoOld[1] : 0,
38772     nOld>=3 ? pgnoOld[2] : 0,
38773     pgnoNew[0], szNew[0],
38774     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
38775     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
38776     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
38777     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
38778
38779   /*
38780   ** Evenly distribute the data in apCell[] across the new pages.
38781   ** Insert divider cells into pParent as necessary.
38782   */
38783   j = 0;
38784   for(i=0; i<nNew; i++){
38785     /* Assemble the new sibling page. */
38786     MemPage *pNew = apNew[i];
38787     assert( j<nMaxCells );
38788     assert( pNew->pgno==pgnoNew[i] );
38789     zeroPage(pNew, pageFlags);
38790     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
38791     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
38792     assert( pNew->nOverflow==0 );
38793
38794     /* If this is an auto-vacuum database, update the pointer map entries
38795     ** that point to the siblings that were rearranged. These can be: left
38796     ** children of cells, the right-child of the page, or overflow pages
38797     ** pointed to by cells.
38798     */
38799     if( ISAUTOVACUUM ){
38800       for(k=j; k<cntNew[i]; k++){
38801         assert( k<nMaxCells );
38802         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
38803           rc = ptrmapPutOvfl(pNew, k-j);
38804           if( rc==SQLITE_OK && leafCorrection==0 ){
38805             rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
38806           }
38807           if( rc!=SQLITE_OK ){
38808             goto balance_cleanup;
38809           }
38810         }
38811       }
38812     }
38813
38814     j = cntNew[i];
38815
38816     /* If the sibling page assembled above was not the right-most sibling,
38817     ** insert a divider cell into the parent page.
38818     */
38819     if( i<nNew-1 && j<nCell ){
38820       u8 *pCell;
38821       u8 *pTemp;
38822       int sz;
38823
38824       assert( j<nMaxCells );
38825       pCell = apCell[j];
38826       sz = szCell[j] + leafCorrection;
38827       pTemp = &aSpace2[iSpace2];
38828       if( !pNew->leaf ){
38829         memcpy(&pNew->aData[8], pCell, 4);
38830         if( ISAUTOVACUUM 
38831          && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
38832         ){
38833           rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
38834           if( rc!=SQLITE_OK ){
38835             goto balance_cleanup;
38836           }
38837         }
38838       }else if( leafData ){
38839         /* If the tree is a leaf-data tree, and the siblings are leaves, 
38840         ** then there is no divider cell in apCell[]. Instead, the divider 
38841         ** cell consists of the integer key for the right-most cell of 
38842         ** the sibling-page assembled above only.
38843         */
38844         CellInfo info;
38845         j--;
38846         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
38847         pCell = pTemp;
38848         fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
38849         pTemp = 0;
38850       }else{
38851         pCell -= 4;
38852         /* Obscure case for non-leaf-data trees: If the cell at pCell was
38853         ** previously stored on a leaf node, and its reported size was 4
38854         ** bytes, then it may actually be smaller than this 
38855         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
38856         ** any cell). But it is important to pass the correct size to 
38857         ** insertCell(), so reparse the cell now.
38858         **
38859         ** Note that this can never happen in an SQLite data file, as all
38860         ** cells are at least 4 bytes. It only happens in b-trees used
38861         ** to evaluate "IN (SELECT ...)" and similar clauses.
38862         */
38863         if( szCell[j]==4 ){
38864           assert(leafCorrection==4);
38865           sz = cellSizePtr(pParent, pCell);
38866         }
38867       }
38868       iSpace2 += sz;
38869       assert( sz<=pBt->pageSize/4 );
38870       assert( iSpace2<=pBt->pageSize );
38871       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
38872       if( rc!=SQLITE_OK ) goto balance_cleanup;
38873       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
38874
38875       /* If this is an auto-vacuum database, and not a leaf-data tree,
38876       ** then update the pointer map with an entry for the overflow page
38877       ** that the cell just inserted points to (if any).
38878       */
38879       if( ISAUTOVACUUM && !leafData ){
38880         rc = ptrmapPutOvfl(pParent, nxDiv);
38881         if( rc!=SQLITE_OK ){
38882           goto balance_cleanup;
38883         }
38884       }
38885       j++;
38886       nxDiv++;
38887     }
38888
38889     /* Set the pointer-map entry for the new sibling page. */
38890     if( ISAUTOVACUUM ){
38891       rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
38892       if( rc!=SQLITE_OK ){
38893         goto balance_cleanup;
38894       }
38895     }
38896   }
38897   assert( j==nCell );
38898   assert( nOld>0 );
38899   assert( nNew>0 );
38900   if( (pageFlags & PTF_LEAF)==0 ){
38901     u8 *zChild = &apCopy[nOld-1]->aData[8];
38902     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
38903     if( ISAUTOVACUUM ){
38904       rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
38905       if( rc!=SQLITE_OK ){
38906         goto balance_cleanup;
38907       }
38908     }
38909   }
38910   if( nxDiv==pParent->nCell+pParent->nOverflow ){
38911     /* Right-most sibling is the right-most child of pParent */
38912     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
38913   }else{
38914     /* Right-most sibling is the left child of the first entry in pParent
38915     ** past the right-most divider entry */
38916     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
38917   }
38918
38919   /*
38920   ** Balance the parent page.  Note that the current page (pPage) might
38921   ** have been added to the freelist so it might no longer be initialized.
38922   ** But the parent page will always be initialized.
38923   */
38924   assert( pParent->isInit );
38925   sqlite3ScratchFree(apCell);
38926   apCell = 0;
38927   releasePage(pPage);
38928   pCur->iPage--;
38929   rc = balance(pCur, 0);
38930   
38931   /*
38932   ** Cleanup before returning.
38933   */
38934 balance_cleanup:
38935   sqlite3PageFree(aSpace2);
38936   sqlite3ScratchFree(apCell);
38937   for(i=0; i<nOld; i++){
38938     releasePage(apOld[i]);
38939   }
38940   for(i=0; i<nNew; i++){
38941     releasePage(apNew[i]);
38942   }
38943
38944   /* releasePage(pParent); */
38945   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
38946           pPage->pgno, nOld, nNew, nCell));
38947
38948   return rc;
38949 }
38950
38951 /*
38952 ** This routine is called for the root page of a btree when the root
38953 ** page contains no cells.  This is an opportunity to make the tree
38954 ** shallower by one level.
38955 */
38956 static int balance_shallower(BtCursor *pCur){
38957   MemPage *pPage;              /* Root page of B-Tree */
38958   MemPage *pChild;             /* The only child page of pPage */
38959   Pgno pgnoChild;              /* Page number for pChild */
38960   int rc = SQLITE_OK;          /* Return code from subprocedures */
38961   BtShared *pBt;                  /* The main BTree structure */
38962   int mxCellPerPage;           /* Maximum number of cells per page */
38963   u8 **apCell;                 /* All cells from pages being balanced */
38964   u16 *szCell;                 /* Local size of all cells */
38965
38966   assert( pCur->iPage==0 );
38967   pPage = pCur->apPage[0];
38968
38969   assert( pPage->nCell==0 );
38970   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38971   pBt = pPage->pBt;
38972   mxCellPerPage = MX_CELL(pBt);
38973   apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
38974   if( apCell==0 ) return SQLITE_NOMEM;
38975   szCell = (u16*)&apCell[mxCellPerPage];
38976   if( pPage->leaf ){
38977     /* The table is completely empty */
38978     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
38979   }else{
38980     /* The root page is empty but has one child.  Transfer the
38981     ** information from that one child into the root page if it 
38982     ** will fit.  This reduces the depth of the tree by one.
38983     **
38984     ** If the root page is page 1, it has less space available than
38985     ** its child (due to the 100 byte header that occurs at the beginning
38986     ** of the database fle), so it might not be able to hold all of the 
38987     ** information currently contained in the child.  If this is the 
38988     ** case, then do not do the transfer.  Leave page 1 empty except
38989     ** for the right-pointer to the child page.  The child page becomes
38990     ** the virtual root of the tree.
38991     */
38992     VVA_ONLY( pCur->pagesShuffled = 1 );
38993     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
38994     assert( pgnoChild>0 );
38995     assert( pgnoChild<=pagerPagecount(pPage->pBt->pPager) );
38996     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
38997     if( rc ) goto end_shallow_balance;
38998     if( pPage->pgno==1 ){
38999       rc = sqlite3BtreeInitPage(pChild);
39000       if( rc ) goto end_shallow_balance;
39001       assert( pChild->nOverflow==0 );
39002       if( pChild->nFree>=100 ){
39003         /* The child information will fit on the root page, so do the
39004         ** copy */
39005         int i;
39006         zeroPage(pPage, pChild->aData[0]);
39007         for(i=0; i<pChild->nCell; i++){
39008           apCell[i] = findCell(pChild,i);
39009           szCell[i] = cellSizePtr(pChild, apCell[i]);
39010         }
39011         assemblePage(pPage, pChild->nCell, apCell, szCell);
39012         /* Copy the right-pointer of the child to the parent. */
39013         put4byte(&pPage->aData[pPage->hdrOffset+8], 
39014             get4byte(&pChild->aData[pChild->hdrOffset+8]));
39015         freePage(pChild);
39016         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
39017       }else{
39018         /* The child has more information that will fit on the root.
39019         ** The tree is already balanced.  Do nothing. */
39020         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
39021       }
39022     }else{
39023       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
39024       pPage->isInit = 0;
39025       rc = sqlite3BtreeInitPage(pPage);
39026       assert( rc==SQLITE_OK );
39027       freePage(pChild);
39028       TRACE(("BALANCE: transfer child %d into root %d\n",
39029               pChild->pgno, pPage->pgno));
39030     }
39031     assert( pPage->nOverflow==0 );
39032     if( ISAUTOVACUUM ){
39033       rc = setChildPtrmaps(pPage);
39034     }
39035     releasePage(pChild);
39036   }
39037 end_shallow_balance:
39038   sqlite3_free(apCell);
39039   return rc;
39040 }
39041
39042
39043 /*
39044 ** The root page is overfull
39045 **
39046 ** When this happens, Create a new child page and copy the
39047 ** contents of the root into the child.  Then make the root
39048 ** page an empty page with rightChild pointing to the new
39049 ** child.   Finally, call balance_internal() on the new child
39050 ** to cause it to split.
39051 */
39052 static int balance_deeper(BtCursor *pCur){
39053   int rc;             /* Return value from subprocedures */
39054   MemPage *pPage;     /* Pointer to the root page */
39055   MemPage *pChild;    /* Pointer to a new child page */
39056   Pgno pgnoChild;     /* Page number of the new child page */
39057   BtShared *pBt;         /* The BTree */
39058   int usableSize;     /* Total usable size of a page */
39059   u8 *data;           /* Content of the parent page */
39060   u8 *cdata;          /* Content of the child page */
39061   int hdr;            /* Offset to page header in parent */
39062   int cbrk;           /* Offset to content of first cell in parent */
39063
39064   assert( pCur->iPage==0 );
39065   assert( pCur->apPage[0]->nOverflow>0 );
39066
39067   VVA_ONLY( pCur->pagesShuffled = 1 );
39068   pPage = pCur->apPage[0];
39069   pBt = pPage->pBt;
39070   assert( sqlite3_mutex_held(pBt->mutex) );
39071   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
39072   if( rc ) return rc;
39073   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
39074   usableSize = pBt->usableSize;
39075   data = pPage->aData;
39076   hdr = pPage->hdrOffset;
39077   cbrk = get2byte(&data[hdr+5]);
39078   cdata = pChild->aData;
39079   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
39080   memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
39081   
39082   rc = sqlite3BtreeInitPage(pChild);
39083   if( rc==SQLITE_OK ){
39084     int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
39085     memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
39086     pChild->nOverflow = pPage->nOverflow;
39087     if( pChild->nOverflow ){
39088       pChild->nFree = 0;
39089     }
39090     assert( pChild->nCell==pPage->nCell );
39091     zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
39092     put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
39093     TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
39094     if( ISAUTOVACUUM ){
39095       rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
39096       if( rc==SQLITE_OK ){
39097         rc = setChildPtrmaps(pChild);
39098       }
39099     }
39100   }
39101
39102   if( rc==SQLITE_OK ){
39103     pCur->iPage++;
39104     pCur->apPage[1] = pChild;
39105     pCur->aiIdx[0] = 0;
39106     rc = balance_nonroot(pCur);
39107   }else{
39108     releasePage(pChild);
39109   }
39110
39111   return rc;
39112 }
39113
39114 /*
39115 ** The page that pCur currently points to has just been modified in
39116 ** some way. This function figures out if this modification means the
39117 ** tree needs to be balanced, and if so calls the appropriate balancing 
39118 ** routine.
39119 ** 
39120 ** Parameter isInsert is true if a new cell was just inserted into the
39121 ** page, or false otherwise.
39122 */
39123 static int balance(BtCursor *pCur, int isInsert){
39124   int rc = SQLITE_OK;
39125   MemPage *pPage = pCur->apPage[pCur->iPage];
39126
39127   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39128   if( pCur->iPage==0 ){
39129     rc = sqlite3PagerWrite(pPage->pDbPage);
39130     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
39131       rc = balance_deeper(pCur);
39132     }
39133     if( rc==SQLITE_OK && pPage->nCell==0 ){
39134       rc = balance_shallower(pCur);
39135     }
39136   }else{
39137     if( pPage->nOverflow>0 || 
39138         (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
39139       rc = balance_nonroot(pCur);
39140     }
39141   }
39142   return rc;
39143 }
39144
39145 /*
39146 ** This routine checks all cursors that point to table pgnoRoot.
39147 ** If any of those cursors were opened with wrFlag==0 in a different
39148 ** database connection (a database connection that shares the pager
39149 ** cache with the current connection) and that other connection 
39150 ** is not in the ReadUncommmitted state, then this routine returns 
39151 ** SQLITE_LOCKED.
39152 **
39153 ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and 
39154 ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental 
39155 ** blob cursors are used for both reading and writing.
39156 **
39157 ** When pgnoRoot is the root page of an intkey table, this function is also
39158 ** responsible for invalidating incremental blob cursors when the table row
39159 ** on which they are opened is deleted or modified. Cursors are invalidated
39160 ** according to the following rules:
39161 **
39162 **   1) When BtreeClearTable() is called to completely delete the contents
39163 **      of a B-Tree table, pExclude is set to zero and parameter iRow is 
39164 **      set to non-zero. In this case all incremental blob cursors open
39165 **      on the table rooted at pgnoRoot are invalidated.
39166 **
39167 **   2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to 
39168 **      modify a table row via an SQL statement, pExclude is set to the 
39169 **      write cursor used to do the modification and parameter iRow is set
39170 **      to the integer row id of the B-Tree entry being modified. Unless
39171 **      pExclude is itself an incremental blob cursor, then all incremental
39172 **      blob cursors open on row iRow of the B-Tree are invalidated.
39173 **
39174 **   3) If both pExclude and iRow are set to zero, no incremental blob 
39175 **      cursors are invalidated.
39176 */
39177 static int checkReadLocks(
39178   Btree *pBtree, 
39179   Pgno pgnoRoot, 
39180   BtCursor *pExclude,
39181   i64 iRow
39182 ){
39183   BtCursor *p;
39184   BtShared *pBt = pBtree->pBt;
39185   sqlite3 *db = pBtree->db;
39186   assert( sqlite3BtreeHoldsMutex(pBtree) );
39187   for(p=pBt->pCursor; p; p=p->pNext){
39188     if( p==pExclude ) continue;
39189     if( p->pgnoRoot!=pgnoRoot ) continue;
39190 #ifndef SQLITE_OMIT_INCRBLOB
39191     if( p->isIncrblobHandle && ( 
39192          (!pExclude && iRow)
39193       || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
39194     )){
39195       p->eState = CURSOR_INVALID;
39196     }
39197 #endif
39198     if( p->eState!=CURSOR_VALID ) continue;
39199     if( p->wrFlag==0 
39200 #ifndef SQLITE_OMIT_INCRBLOB
39201      || p->isIncrblobHandle
39202 #endif
39203     ){
39204       sqlite3 *dbOther = p->pBtree->db;
39205       if( dbOther==0 ||
39206          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
39207         return SQLITE_LOCKED;
39208       }
39209     }
39210   }
39211   return SQLITE_OK;
39212 }
39213
39214 /*
39215 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
39216 ** and the data is given by (pData,nData).  The cursor is used only to
39217 ** define what table the record should be inserted into.  The cursor
39218 ** is left pointing at a random location.
39219 **
39220 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
39221 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
39222 */
39223 SQLITE_PRIVATE int sqlite3BtreeInsert(
39224   BtCursor *pCur,                /* Insert data into the table of this cursor */
39225   const void *pKey, i64 nKey,    /* The key of the new record */
39226   const void *pData, int nData,  /* The data of the new record */
39227   int nZero,                     /* Number of extra 0 bytes to append to data */
39228   int appendBias                 /* True if this is likely an append */
39229 ){
39230   int rc;
39231   int loc;
39232   int szNew;
39233   int idx;
39234   MemPage *pPage;
39235   Btree *p = pCur->pBtree;
39236   BtShared *pBt = p->pBt;
39237   unsigned char *oldCell;
39238   unsigned char *newCell = 0;
39239
39240   assert( cursorHoldsMutex(pCur) );
39241   if( pBt->inTransaction!=TRANS_WRITE ){
39242     /* Must start a transaction before doing an insert */
39243     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39244     return rc;
39245   }
39246   assert( !pBt->readOnly );
39247   if( !pCur->wrFlag ){
39248     return SQLITE_PERM;   /* Cursor not open for writing */
39249   }
39250   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
39251     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39252   }
39253   if( pCur->eState==CURSOR_FAULT ){
39254     return pCur->skip;
39255   }
39256
39257   /* Save the positions of any other cursors open on this table */
39258   sqlite3BtreeClearCursor(pCur);
39259   if( 
39260     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
39261     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
39262   ){
39263     return rc;
39264   }
39265
39266   pPage = pCur->apPage[pCur->iPage];
39267   assert( pPage->intKey || nKey>=0 );
39268   assert( pPage->leaf || !pPage->intKey );
39269   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
39270           pCur->pgnoRoot, nKey, nData, pPage->pgno,
39271           loc==0 ? "overwrite" : "new entry"));
39272   assert( pPage->isInit );
39273   allocateTempSpace(pBt);
39274   newCell = pBt->pTmpSpace;
39275   if( newCell==0 ) return SQLITE_NOMEM;
39276   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
39277   if( rc ) goto end_insert;
39278   assert( szNew==cellSizePtr(pPage, newCell) );
39279   assert( szNew<=MX_CELL_SIZE(pBt) );
39280   idx = pCur->aiIdx[pCur->iPage];
39281   if( loc==0 && CURSOR_VALID==pCur->eState ){
39282     u16 szOld;
39283     assert( idx<pPage->nCell );
39284     rc = sqlite3PagerWrite(pPage->pDbPage);
39285     if( rc ){
39286       goto end_insert;
39287     }
39288     oldCell = findCell(pPage, idx);
39289     if( !pPage->leaf ){
39290       memcpy(newCell, oldCell, 4);
39291     }
39292     szOld = cellSizePtr(pPage, oldCell);
39293     rc = clearCell(pPage, oldCell);
39294     if( rc ) goto end_insert;
39295     dropCell(pPage, idx, szOld);
39296   }else if( loc<0 && pPage->nCell>0 ){
39297     assert( pPage->leaf );
39298     idx = ++pCur->aiIdx[pCur->iPage];
39299     pCur->info.nSize = 0;
39300     pCur->validNKey = 0;
39301   }else{
39302     assert( pPage->leaf );
39303   }
39304   rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
39305   if( rc!=SQLITE_OK ) goto end_insert;
39306   rc = balance(pCur, 1);
39307   if( rc==SQLITE_OK ){
39308     moveToRoot(pCur);
39309   }
39310 end_insert:
39311   return rc;
39312 }
39313
39314 /*
39315 ** Delete the entry that the cursor is pointing to.  The cursor
39316 ** is left pointing at a arbitrary location.
39317 */
39318 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
39319   MemPage *pPage = pCur->apPage[pCur->iPage];
39320   int idx;
39321   unsigned char *pCell;
39322   int rc;
39323   Pgno pgnoChild = 0;
39324   Btree *p = pCur->pBtree;
39325   BtShared *pBt = p->pBt;
39326
39327   assert( cursorHoldsMutex(pCur) );
39328   assert( pPage->isInit );
39329   if( pBt->inTransaction!=TRANS_WRITE ){
39330     /* Must start a transaction before doing a delete */
39331     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39332     return rc;
39333   }
39334   assert( !pBt->readOnly );
39335   if( pCur->eState==CURSOR_FAULT ){
39336     return pCur->skip;
39337   }
39338   if( pCur->aiIdx[pCur->iPage]>=pPage->nCell ){
39339     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
39340   }
39341   if( !pCur->wrFlag ){
39342     return SQLITE_PERM;   /* Did not open this cursor for writing */
39343   }
39344   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
39345     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
39346   }
39347
39348   /* Restore the current cursor position (a no-op if the cursor is not in 
39349   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
39350   ** open on the same table. Then call sqlite3PagerWrite() on the page
39351   ** that the entry will be deleted from.
39352   */
39353   if( 
39354     (rc = restoreCursorPosition(pCur))!=0 ||
39355     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
39356     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
39357   ){
39358     return rc;
39359   }
39360
39361   /* Locate the cell within its page and leave pCell pointing to the
39362   ** data. The clearCell() call frees any overflow pages associated with the
39363   ** cell. The cell itself is still intact.
39364   */
39365   idx = pCur->aiIdx[pCur->iPage];
39366   pCell = findCell(pPage, idx);
39367   if( !pPage->leaf ){
39368     pgnoChild = get4byte(pCell);
39369   }
39370   rc = clearCell(pPage, pCell);
39371   if( rc ){
39372     return rc;
39373   }
39374
39375   if( !pPage->leaf ){
39376     /*
39377     ** The entry we are about to delete is not a leaf so if we do not
39378     ** do something we will leave a hole on an internal page.
39379     ** We have to fill the hole by moving in a cell from a leaf.  The
39380     ** next Cell after the one to be deleted is guaranteed to exist and
39381     ** to be a leaf so we can use it.
39382     */
39383     BtCursor leafCur;
39384     MemPage *pLeafPage;
39385
39386     unsigned char *pNext;
39387     int notUsed;
39388     unsigned char *tempCell = 0;
39389     assert( !pPage->intKey );
39390     sqlite3BtreeGetTempCursor(pCur, &leafCur);
39391     rc = sqlite3BtreeNext(&leafCur, &notUsed);
39392     if( rc==SQLITE_OK ){
39393       assert( leafCur.aiIdx[leafCur.iPage]==0 );
39394       pLeafPage = leafCur.apPage[leafCur.iPage];
39395       rc = sqlite3PagerWrite(pLeafPage->pDbPage);
39396     }
39397     if( rc==SQLITE_OK ){
39398       int leafCursorInvalid = 0;
39399       u16 szNext;
39400       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
39401          pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
39402       dropCell(pPage, idx, cellSizePtr(pPage, pCell));
39403       pNext = findCell(pLeafPage, 0);
39404       szNext = cellSizePtr(pLeafPage, pNext);
39405       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
39406       allocateTempSpace(pBt);
39407       tempCell = pBt->pTmpSpace;
39408       if( tempCell==0 ){
39409         rc = SQLITE_NOMEM;
39410       }
39411       if( rc==SQLITE_OK ){
39412         rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
39413       }
39414
39415
39416       /* The "if" statement in the next code block is critical.  The
39417       ** slightest error in that statement would allow SQLite to operate
39418       ** correctly most of the time but produce very rare failures.  To
39419       ** guard against this, the following macros help to verify that
39420       ** the "if" statement is well tested.
39421       */
39422       testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3 
39423                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39424       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3 
39425                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39426       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1 
39427                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39428       testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
39429                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
39430       testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
39431                  && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
39432
39433
39434       if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
39435           (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
39436       ){
39437         /* This branch is taken if the internal node is now either overflowing
39438         ** or underfull and the leaf node will be underfull after the just cell 
39439         ** copied to the internal node is deleted from it. This is a special
39440         ** case because the call to balance() to correct the internal node
39441         ** may change the tree structure and invalidate the contents of
39442         ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
39443         ** used by the balance() required to correct the underfull leaf
39444         ** node.
39445         **
39446         ** The formula used in the expression above are based on facets of
39447         ** the SQLite file-format that do not change over time.
39448         */
39449         testcase( pPage->nFree==pBt->usableSize*2/3+1 );
39450         testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
39451         leafCursorInvalid = 1;
39452       }        
39453
39454       if( rc==SQLITE_OK ){
39455         put4byte(findOverflowCell(pPage, idx), pgnoChild);
39456         VVA_ONLY( pCur->pagesShuffled = 0 );
39457         rc = balance(pCur, 0);
39458       }
39459
39460       if( rc==SQLITE_OK && leafCursorInvalid ){
39461         /* The leaf-node is now underfull and so the tree needs to be 
39462         ** rebalanced. However, the balance() operation on the internal
39463         ** node above may have modified the structure of the B-Tree and
39464         ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
39465         ** may not be trusted.
39466         **
39467         ** It is not possible to copy the ancestry from pCur, as the same
39468         ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
39469         ** arrays. 
39470         **
39471         ** The call to saveCursorPosition() below internally saves the 
39472         ** key that leafCur is currently pointing to. Currently, there
39473         ** are two copies of that key in the tree - one here on the leaf
39474         ** page and one on some internal node in the tree. The copy on
39475         ** the leaf node is always the next key in tree-order after the 
39476         ** copy on the internal node. So, the call to sqlite3BtreeNext()
39477         ** calls restoreCursorPosition() to point the cursor to the copy
39478         ** stored on the internal node, then advances to the next entry,
39479         ** which happens to be the copy of the key on the internal node.
39480         ** Net effect: leafCur is pointing back to the duplicate cell
39481         ** that needs to be removed, and the leafCur.apPage[] and
39482         ** leafCur.aiIdx[] arrays are correct.
39483         */
39484         VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
39485         rc = saveCursorPosition(&leafCur);
39486         if( rc==SQLITE_OK ){
39487           rc = sqlite3BtreeNext(&leafCur, &notUsed);
39488         }
39489         pLeafPage = leafCur.apPage[leafCur.iPage];
39490         assert( pLeafPage->pgno==leafPgno );
39491         assert( leafCur.aiIdx[leafCur.iPage]==0 );
39492       }
39493
39494       if( rc==SQLITE_OK ){
39495         dropCell(pLeafPage, 0, szNext);
39496         VVA_ONLY( leafCur.pagesShuffled = 0 );
39497         rc = balance(&leafCur, 0);
39498         assert( leafCursorInvalid || !leafCur.pagesShuffled
39499                                    || !pCur->pagesShuffled );
39500       }
39501     }
39502     sqlite3BtreeReleaseTempCursor(&leafCur);
39503   }else{
39504     TRACE(("DELETE: table=%d delete from leaf %d\n",
39505        pCur->pgnoRoot, pPage->pgno));
39506     dropCell(pPage, idx, cellSizePtr(pPage, pCell));
39507     rc = balance(pCur, 0);
39508   }
39509   if( rc==SQLITE_OK ){
39510     moveToRoot(pCur);
39511   }
39512   return rc;
39513 }
39514
39515 /*
39516 ** Create a new BTree table.  Write into *piTable the page
39517 ** number for the root page of the new table.
39518 **
39519 ** The type of type is determined by the flags parameter.  Only the
39520 ** following values of flags are currently in use.  Other values for
39521 ** flags might not work:
39522 **
39523 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
39524 **     BTREE_ZERODATA                  Used for SQL indices
39525 */
39526 static int btreeCreateTable(Btree *p, int *piTable, int flags){
39527   BtShared *pBt = p->pBt;
39528   MemPage *pRoot;
39529   Pgno pgnoRoot;
39530   int rc;
39531
39532   assert( sqlite3BtreeHoldsMutex(p) );
39533   if( pBt->inTransaction!=TRANS_WRITE ){
39534     /* Must start a transaction first */
39535     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39536     return rc;
39537   }
39538   assert( !pBt->readOnly );
39539
39540 #ifdef SQLITE_OMIT_AUTOVACUUM
39541   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
39542   if( rc ){
39543     return rc;
39544   }
39545 #else
39546   if( pBt->autoVacuum ){
39547     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
39548     MemPage *pPageMove; /* The page to move to. */
39549
39550     /* Creating a new table may probably require moving an existing database
39551     ** to make room for the new tables root page. In case this page turns
39552     ** out to be an overflow page, delete all overflow page-map caches
39553     ** held by open cursors.
39554     */
39555     invalidateAllOverflowCache(pBt);
39556
39557     /* Read the value of meta[3] from the database to determine where the
39558     ** root page of the new table should go. meta[3] is the largest root-page
39559     ** created so far, so the new root-page is (meta[3]+1).
39560     */
39561     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
39562     if( rc!=SQLITE_OK ){
39563       return rc;
39564     }
39565     pgnoRoot++;
39566
39567     /* The new root-page may not be allocated on a pointer-map page, or the
39568     ** PENDING_BYTE page.
39569     */
39570     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
39571         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
39572       pgnoRoot++;
39573     }
39574     assert( pgnoRoot>=3 );
39575
39576     /* Allocate a page. The page that currently resides at pgnoRoot will
39577     ** be moved to the allocated page (unless the allocated page happens
39578     ** to reside at pgnoRoot).
39579     */
39580     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
39581     if( rc!=SQLITE_OK ){
39582       return rc;
39583     }
39584
39585     if( pgnoMove!=pgnoRoot ){
39586       /* pgnoRoot is the page that will be used for the root-page of
39587       ** the new table (assuming an error did not occur). But we were
39588       ** allocated pgnoMove. If required (i.e. if it was not allocated
39589       ** by extending the file), the current page at position pgnoMove
39590       ** is already journaled.
39591       */
39592       u8 eType;
39593       Pgno iPtrPage;
39594
39595       releasePage(pPageMove);
39596
39597       /* Move the page currently at pgnoRoot to pgnoMove. */
39598       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
39599       if( rc!=SQLITE_OK ){
39600         return rc;
39601       }
39602       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
39603       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
39604         releasePage(pRoot);
39605         return rc;
39606       }
39607       assert( eType!=PTRMAP_ROOTPAGE );
39608       assert( eType!=PTRMAP_FREEPAGE );
39609       rc = sqlite3PagerWrite(pRoot->pDbPage);
39610       if( rc!=SQLITE_OK ){
39611         releasePage(pRoot);
39612         return rc;
39613       }
39614       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
39615       releasePage(pRoot);
39616
39617       /* Obtain the page at pgnoRoot */
39618       if( rc!=SQLITE_OK ){
39619         return rc;
39620       }
39621       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
39622       if( rc!=SQLITE_OK ){
39623         return rc;
39624       }
39625       rc = sqlite3PagerWrite(pRoot->pDbPage);
39626       if( rc!=SQLITE_OK ){
39627         releasePage(pRoot);
39628         return rc;
39629       }
39630     }else{
39631       pRoot = pPageMove;
39632     } 
39633
39634     /* Update the pointer-map and meta-data with the new root-page number. */
39635     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
39636     if( rc ){
39637       releasePage(pRoot);
39638       return rc;
39639     }
39640     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
39641     if( rc ){
39642       releasePage(pRoot);
39643       return rc;
39644     }
39645
39646   }else{
39647     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
39648     if( rc ) return rc;
39649   }
39650 #endif
39651   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
39652   zeroPage(pRoot, flags | PTF_LEAF);
39653   sqlite3PagerUnref(pRoot->pDbPage);
39654   *piTable = (int)pgnoRoot;
39655   return SQLITE_OK;
39656 }
39657 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
39658   int rc;
39659   sqlite3BtreeEnter(p);
39660   p->pBt->db = p->db;
39661   rc = btreeCreateTable(p, piTable, flags);
39662   sqlite3BtreeLeave(p);
39663   return rc;
39664 }
39665
39666 /*
39667 ** Erase the given database page and all its children.  Return
39668 ** the page to the freelist.
39669 */
39670 static int clearDatabasePage(
39671   BtShared *pBt,           /* The BTree that contains the table */
39672   Pgno pgno,            /* Page number to clear */
39673   MemPage *pParent,     /* Parent page.  NULL for the root */
39674   int freePageFlag      /* Deallocate page if true */
39675 ){
39676   MemPage *pPage = 0;
39677   int rc;
39678   unsigned char *pCell;
39679   int i;
39680
39681   assert( sqlite3_mutex_held(pBt->mutex) );
39682   if( pgno>pagerPagecount(pBt->pPager) ){
39683     return SQLITE_CORRUPT_BKPT;
39684   }
39685
39686   rc = getAndInitPage(pBt, pgno, &pPage);
39687   if( rc ) goto cleardatabasepage_out;
39688   for(i=0; i<pPage->nCell; i++){
39689     pCell = findCell(pPage, i);
39690     if( !pPage->leaf ){
39691       rc = clearDatabasePage(pBt, get4byte(pCell), pPage, 1);
39692       if( rc ) goto cleardatabasepage_out;
39693     }
39694     rc = clearCell(pPage, pCell);
39695     if( rc ) goto cleardatabasepage_out;
39696   }
39697   if( !pPage->leaf ){
39698     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage, 1);
39699     if( rc ) goto cleardatabasepage_out;
39700   }
39701   if( freePageFlag ){
39702     rc = freePage(pPage);
39703   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
39704     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
39705   }
39706
39707 cleardatabasepage_out:
39708   releasePage(pPage);
39709   return rc;
39710 }
39711
39712 /*
39713 ** Delete all information from a single table in the database.  iTable is
39714 ** the page number of the root of the table.  After this routine returns,
39715 ** the root page is empty, but still exists.
39716 **
39717 ** This routine will fail with SQLITE_LOCKED if there are any open
39718 ** read cursors on the table.  Open write cursors are moved to the
39719 ** root of the table.
39720 */
39721 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
39722   int rc;
39723   BtShared *pBt = p->pBt;
39724   sqlite3BtreeEnter(p);
39725   pBt->db = p->db;
39726   if( p->inTrans!=TRANS_WRITE ){
39727     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39728   }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
39729     /* nothing to do */
39730   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
39731     /* nothing to do */
39732   }else{
39733     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
39734   }
39735   sqlite3BtreeLeave(p);
39736   return rc;
39737 }
39738
39739 /*
39740 ** Erase all information in a table and add the root of the table to
39741 ** the freelist.  Except, the root of the principle table (the one on
39742 ** page 1) is never added to the freelist.
39743 **
39744 ** This routine will fail with SQLITE_LOCKED if there are any open
39745 ** cursors on the table.
39746 **
39747 ** If AUTOVACUUM is enabled and the page at iTable is not the last
39748 ** root page in the database file, then the last root page 
39749 ** in the database file is moved into the slot formerly occupied by
39750 ** iTable and that last slot formerly occupied by the last root page
39751 ** is added to the freelist instead of iTable.  In this say, all
39752 ** root pages are kept at the beginning of the database file, which
39753 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
39754 ** page number that used to be the last root page in the file before
39755 ** the move.  If no page gets moved, *piMoved is set to 0.
39756 ** The last root page is recorded in meta[3] and the value of
39757 ** meta[3] is updated by this procedure.
39758 */
39759 static int btreeDropTable(Btree *p, int iTable, int *piMoved){
39760   int rc;
39761   MemPage *pPage = 0;
39762   BtShared *pBt = p->pBt;
39763
39764   assert( sqlite3BtreeHoldsMutex(p) );
39765   if( p->inTrans!=TRANS_WRITE ){
39766     return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39767   }
39768
39769   /* It is illegal to drop a table if any cursors are open on the
39770   ** database. This is because in auto-vacuum mode the backend may
39771   ** need to move another root-page to fill a gap left by the deleted
39772   ** root page. If an open cursor was using this page a problem would 
39773   ** occur.
39774   */
39775   if( pBt->pCursor ){
39776     return SQLITE_LOCKED;
39777   }
39778
39779   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
39780   if( rc ) return rc;
39781   rc = sqlite3BtreeClearTable(p, iTable);
39782   if( rc ){
39783     releasePage(pPage);
39784     return rc;
39785   }
39786
39787   *piMoved = 0;
39788
39789   if( iTable>1 ){
39790 #ifdef SQLITE_OMIT_AUTOVACUUM
39791     rc = freePage(pPage);
39792     releasePage(pPage);
39793 #else
39794     if( pBt->autoVacuum ){
39795       Pgno maxRootPgno;
39796       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
39797       if( rc!=SQLITE_OK ){
39798         releasePage(pPage);
39799         return rc;
39800       }
39801
39802       if( iTable==maxRootPgno ){
39803         /* If the table being dropped is the table with the largest root-page
39804         ** number in the database, put the root page on the free list. 
39805         */
39806         rc = freePage(pPage);
39807         releasePage(pPage);
39808         if( rc!=SQLITE_OK ){
39809           return rc;
39810         }
39811       }else{
39812         /* The table being dropped does not have the largest root-page
39813         ** number in the database. So move the page that does into the 
39814         ** gap left by the deleted root-page.
39815         */
39816         MemPage *pMove;
39817         releasePage(pPage);
39818         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
39819         if( rc!=SQLITE_OK ){
39820           return rc;
39821         }
39822         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
39823         releasePage(pMove);
39824         if( rc!=SQLITE_OK ){
39825           return rc;
39826         }
39827         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
39828         if( rc!=SQLITE_OK ){
39829           return rc;
39830         }
39831         rc = freePage(pMove);
39832         releasePage(pMove);
39833         if( rc!=SQLITE_OK ){
39834           return rc;
39835         }
39836         *piMoved = maxRootPgno;
39837       }
39838
39839       /* Set the new 'max-root-page' value in the database header. This
39840       ** is the old value less one, less one more if that happens to
39841       ** be a root-page number, less one again if that is the
39842       ** PENDING_BYTE_PAGE.
39843       */
39844       maxRootPgno--;
39845       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
39846         maxRootPgno--;
39847       }
39848       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
39849         maxRootPgno--;
39850       }
39851       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
39852
39853       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
39854     }else{
39855       rc = freePage(pPage);
39856       releasePage(pPage);
39857     }
39858 #endif
39859   }else{
39860     /* If sqlite3BtreeDropTable was called on page 1. */
39861     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
39862     releasePage(pPage);
39863   }
39864   return rc;  
39865 }
39866 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
39867   int rc;
39868   sqlite3BtreeEnter(p);
39869   p->pBt->db = p->db;
39870   rc = btreeDropTable(p, iTable, piMoved);
39871   sqlite3BtreeLeave(p);
39872   return rc;
39873 }
39874
39875
39876 /*
39877 ** Read the meta-information out of a database file.  Meta[0]
39878 ** is the number of free pages currently in the database.  Meta[1]
39879 ** through meta[15] are available for use by higher layers.  Meta[0]
39880 ** is read-only, the others are read/write.
39881 ** 
39882 ** The schema layer numbers meta values differently.  At the schema
39883 ** layer (and the SetCookie and ReadCookie opcodes) the number of
39884 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
39885 */
39886 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
39887   DbPage *pDbPage;
39888   int rc;
39889   unsigned char *pP1;
39890   BtShared *pBt = p->pBt;
39891
39892   sqlite3BtreeEnter(p);
39893   pBt->db = p->db;
39894
39895   /* Reading a meta-data value requires a read-lock on page 1 (and hence
39896   ** the sqlite_master table. We grab this lock regardless of whether or
39897   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
39898   ** 1 is treated as a special case by queryTableLock() and lockTable()).
39899   */
39900   rc = queryTableLock(p, 1, READ_LOCK);
39901   if( rc!=SQLITE_OK ){
39902     sqlite3BtreeLeave(p);
39903     return rc;
39904   }
39905
39906   assert( idx>=0 && idx<=15 );
39907   if( pBt->pPage1 ){
39908     /* The b-tree is already holding a reference to page 1 of the database
39909     ** file. In this case the required meta-data value can be read directly
39910     ** from the page data of this reference. This is slightly faster than
39911     ** requesting a new reference from the pager layer.
39912     */
39913     pP1 = (unsigned char *)pBt->pPage1->aData;
39914   }else{
39915     /* The b-tree does not have a reference to page 1 of the database file.
39916     ** Obtain one from the pager layer.
39917     */
39918     rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
39919     if( rc ){
39920       sqlite3BtreeLeave(p);
39921       return rc;
39922     }
39923     pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
39924   }
39925   *pMeta = get4byte(&pP1[36 + idx*4]);
39926
39927   /* If the b-tree is not holding a reference to page 1, then one was 
39928   ** requested from the pager layer in the above block. Release it now.
39929   */
39930   if( !pBt->pPage1 ){
39931     sqlite3PagerUnref(pDbPage);
39932   }
39933
39934   /* If autovacuumed is disabled in this build but we are trying to 
39935   ** access an autovacuumed database, then make the database readonly. 
39936   */
39937 #ifdef SQLITE_OMIT_AUTOVACUUM
39938   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
39939 #endif
39940
39941   /* Grab the read-lock on page 1. */
39942   rc = lockTable(p, 1, READ_LOCK);
39943   sqlite3BtreeLeave(p);
39944   return rc;
39945 }
39946
39947 /*
39948 ** Write meta-information back into the database.  Meta[0] is
39949 ** read-only and may not be written.
39950 */
39951 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
39952   BtShared *pBt = p->pBt;
39953   unsigned char *pP1;
39954   int rc;
39955   assert( idx>=1 && idx<=15 );
39956   sqlite3BtreeEnter(p);
39957   pBt->db = p->db;
39958   if( p->inTrans!=TRANS_WRITE ){
39959     rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
39960   }else{
39961     assert( pBt->pPage1!=0 );
39962     pP1 = pBt->pPage1->aData;
39963     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
39964     if( rc==SQLITE_OK ){
39965       put4byte(&pP1[36 + idx*4], iMeta);
39966 #ifndef SQLITE_OMIT_AUTOVACUUM
39967       if( idx==7 ){
39968         assert( pBt->autoVacuum || iMeta==0 );
39969         assert( iMeta==0 || iMeta==1 );
39970         pBt->incrVacuum = iMeta;
39971       }
39972 #endif
39973     }
39974   }
39975   sqlite3BtreeLeave(p);
39976   return rc;
39977 }
39978
39979 /*
39980 ** Return the flag byte at the beginning of the page that the cursor
39981 ** is currently pointing to.
39982 */
39983 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
39984   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
39985   ** restoreCursorPosition() here.
39986   */
39987   MemPage *pPage;
39988   restoreCursorPosition(pCur);
39989   pPage = pCur->apPage[pCur->iPage];
39990   assert( cursorHoldsMutex(pCur) );
39991   assert( pPage->pBt==pCur->pBt );
39992   return pPage ? pPage->aData[pPage->hdrOffset] : 0;
39993 }
39994
39995
39996 /*
39997 ** Return the pager associated with a BTree.  This routine is used for
39998 ** testing and debugging only.
39999 */
40000 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
40001   return p->pBt->pPager;
40002 }
40003
40004 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40005 /*
40006 ** Append a message to the error message string.
40007 */
40008 static void checkAppendMsg(
40009   IntegrityCk *pCheck,
40010   char *zMsg1,
40011   const char *zFormat,
40012   ...
40013 ){
40014   va_list ap;
40015   if( !pCheck->mxErr ) return;
40016   pCheck->mxErr--;
40017   pCheck->nErr++;
40018   va_start(ap, zFormat);
40019   if( pCheck->errMsg.nChar ){
40020     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
40021   }
40022   if( zMsg1 ){
40023     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
40024   }
40025   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
40026   va_end(ap);
40027   if( pCheck->errMsg.mallocFailed ){
40028     pCheck->mallocFailed = 1;
40029   }
40030 }
40031 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40032
40033 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40034 /*
40035 ** Add 1 to the reference count for page iPage.  If this is the second
40036 ** reference to the page, add an error message to pCheck->zErrMsg.
40037 ** Return 1 if there are 2 ore more references to the page and 0 if
40038 ** if this is the first reference to the page.
40039 **
40040 ** Also check that the page number is in bounds.
40041 */
40042 static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
40043   if( iPage==0 ) return 1;
40044   if( iPage>pCheck->nPage || iPage<0 ){
40045     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
40046     return 1;
40047   }
40048   if( pCheck->anRef[iPage]==1 ){
40049     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
40050     return 1;
40051   }
40052   return  (pCheck->anRef[iPage]++)>1;
40053 }
40054
40055 #ifndef SQLITE_OMIT_AUTOVACUUM
40056 /*
40057 ** Check that the entry in the pointer-map for page iChild maps to 
40058 ** page iParent, pointer type ptrType. If not, append an error message
40059 ** to pCheck.
40060 */
40061 static void checkPtrmap(
40062   IntegrityCk *pCheck,   /* Integrity check context */
40063   Pgno iChild,           /* Child page number */
40064   u8 eType,              /* Expected pointer map type */
40065   Pgno iParent,          /* Expected pointer map parent page number */
40066   char *zContext         /* Context description (used for error msg) */
40067 ){
40068   int rc;
40069   u8 ePtrmapType;
40070   Pgno iPtrmapParent;
40071
40072   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
40073   if( rc!=SQLITE_OK ){
40074     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
40075     return;
40076   }
40077
40078   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
40079     checkAppendMsg(pCheck, zContext, 
40080       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
40081       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
40082   }
40083 }
40084 #endif
40085
40086 /*
40087 ** Check the integrity of the freelist or of an overflow page list.
40088 ** Verify that the number of pages on the list is N.
40089 */
40090 static void checkList(
40091   IntegrityCk *pCheck,  /* Integrity checking context */
40092   int isFreeList,       /* True for a freelist.  False for overflow page list */
40093   int iPage,            /* Page number for first page in the list */
40094   int N,                /* Expected number of pages in the list */
40095   char *zContext        /* Context for error messages */
40096 ){
40097   int i;
40098   int expected = N;
40099   int iFirst = iPage;
40100   while( N-- > 0 && pCheck->mxErr ){
40101     DbPage *pOvflPage;
40102     unsigned char *pOvflData;
40103     if( iPage<1 ){
40104       checkAppendMsg(pCheck, zContext,
40105          "%d of %d pages missing from overflow list starting at %d",
40106           N+1, expected, iFirst);
40107       break;
40108     }
40109     if( checkRef(pCheck, iPage, zContext) ) break;
40110     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
40111       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
40112       break;
40113     }
40114     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
40115     if( isFreeList ){
40116       int n = get4byte(&pOvflData[4]);
40117 #ifndef SQLITE_OMIT_AUTOVACUUM
40118       if( pCheck->pBt->autoVacuum ){
40119         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
40120       }
40121 #endif
40122       if( n>pCheck->pBt->usableSize/4-2 ){
40123         checkAppendMsg(pCheck, zContext,
40124            "freelist leaf count too big on page %d", iPage);
40125         N--;
40126       }else{
40127         for(i=0; i<n; i++){
40128           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
40129 #ifndef SQLITE_OMIT_AUTOVACUUM
40130           if( pCheck->pBt->autoVacuum ){
40131             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
40132           }
40133 #endif
40134           checkRef(pCheck, iFreePage, zContext);
40135         }
40136         N -= n;
40137       }
40138     }
40139 #ifndef SQLITE_OMIT_AUTOVACUUM
40140     else{
40141       /* If this database supports auto-vacuum and iPage is not the last
40142       ** page in this overflow list, check that the pointer-map entry for
40143       ** the following page matches iPage.
40144       */
40145       if( pCheck->pBt->autoVacuum && N>0 ){
40146         i = get4byte(pOvflData);
40147         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
40148       }
40149     }
40150 #endif
40151     iPage = get4byte(pOvflData);
40152     sqlite3PagerUnref(pOvflPage);
40153   }
40154 }
40155 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40156
40157 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40158 /*
40159 ** Do various sanity checks on a single page of a tree.  Return
40160 ** the tree depth.  Root pages return 0.  Parents of root pages
40161 ** return 1, and so forth.
40162 ** 
40163 ** These checks are done:
40164 **
40165 **      1.  Make sure that cells and freeblocks do not overlap
40166 **          but combine to completely cover the page.
40167 **  NO  2.  Make sure cell keys are in order.
40168 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
40169 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
40170 **      5.  Check the integrity of overflow pages.
40171 **      6.  Recursively call checkTreePage on all children.
40172 **      7.  Verify that the depth of all children is the same.
40173 **      8.  Make sure this page is at least 33% full or else it is
40174 **          the root of the tree.
40175 */
40176 static int checkTreePage(
40177   IntegrityCk *pCheck,  /* Context for the sanity check */
40178   int iPage,            /* Page number of the page to check */
40179   MemPage *pParent,     /* Parent page */
40180   char *zParentContext  /* Parent context */
40181 ){
40182   MemPage *pPage;
40183   int i, rc, depth, d2, pgno, cnt;
40184   int hdr, cellStart;
40185   int nCell;
40186   u8 *data;
40187   BtShared *pBt;
40188   int usableSize;
40189   char zContext[100];
40190   char *hit;
40191
40192   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
40193
40194   /* Check that the page exists
40195   */
40196   pBt = pCheck->pBt;
40197   usableSize = pBt->usableSize;
40198   if( iPage==0 ) return 0;
40199   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
40200   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
40201     checkAppendMsg(pCheck, zContext,
40202        "unable to get the page. error code=%d", rc);
40203     return 0;
40204   }
40205   if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
40206     checkAppendMsg(pCheck, zContext, 
40207                    "sqlite3BtreeInitPage() returns error code %d", rc);
40208     releasePage(pPage);
40209     return 0;
40210   }
40211
40212   /* Check out all the cells.
40213   */
40214   depth = 0;
40215   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
40216     u8 *pCell;
40217     int sz;
40218     CellInfo info;
40219
40220     /* Check payload overflow pages
40221     */
40222     sqlite3_snprintf(sizeof(zContext), zContext,
40223              "On tree page %d cell %d: ", iPage, i);
40224     pCell = findCell(pPage,i);
40225     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
40226     sz = info.nData;
40227     if( !pPage->intKey ) sz += info.nKey;
40228     assert( sz==info.nPayload );
40229     if( sz>info.nLocal ){
40230       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
40231       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
40232 #ifndef SQLITE_OMIT_AUTOVACUUM
40233       if( pBt->autoVacuum ){
40234         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
40235       }
40236 #endif
40237       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
40238     }
40239
40240     /* Check sanity of left child page.
40241     */
40242     if( !pPage->leaf ){
40243       pgno = get4byte(pCell);
40244 #ifndef SQLITE_OMIT_AUTOVACUUM
40245       if( pBt->autoVacuum ){
40246         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
40247       }
40248 #endif
40249       d2 = checkTreePage(pCheck,pgno,pPage,zContext);
40250       if( i>0 && d2!=depth ){
40251         checkAppendMsg(pCheck, zContext, "Child page depth differs");
40252       }
40253       depth = d2;
40254     }
40255   }
40256   if( !pPage->leaf ){
40257     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40258     sqlite3_snprintf(sizeof(zContext), zContext, 
40259                      "On page %d at right child: ", iPage);
40260 #ifndef SQLITE_OMIT_AUTOVACUUM
40261     if( pBt->autoVacuum ){
40262       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
40263     }
40264 #endif
40265     checkTreePage(pCheck, pgno, pPage, zContext);
40266   }
40267  
40268   /* Check for complete coverage of the page
40269   */
40270   data = pPage->aData;
40271   hdr = pPage->hdrOffset;
40272   hit = sqlite3PageMalloc( pBt->pageSize );
40273   if( hit==0 ){
40274     pCheck->mallocFailed = 1;
40275   }else{
40276     memset(hit, 0, usableSize );
40277     memset(hit, 1, get2byte(&data[hdr+5]));
40278     nCell = get2byte(&data[hdr+3]);
40279     cellStart = hdr + 12 - 4*pPage->leaf;
40280     for(i=0; i<nCell; i++){
40281       int pc = get2byte(&data[cellStart+i*2]);
40282       u16 size = 1024;
40283       int j;
40284       if( pc<=usableSize ){
40285         size = cellSizePtr(pPage, &data[pc]);
40286       }
40287       if( (pc+size-1)>=usableSize || pc<0 ){
40288         checkAppendMsg(pCheck, 0, 
40289             "Corruption detected in cell %d on page %d",i,iPage,0);
40290       }else{
40291         for(j=pc+size-1; j>=pc; j--) hit[j]++;
40292       }
40293     }
40294     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
40295            cnt++){
40296       int size = get2byte(&data[i+2]);
40297       int j;
40298       if( (i+size-1)>=usableSize || i<0 ){
40299         checkAppendMsg(pCheck, 0,  
40300             "Corruption detected in cell %d on page %d",i,iPage,0);
40301       }else{
40302         for(j=i+size-1; j>=i; j--) hit[j]++;
40303       }
40304       i = get2byte(&data[i]);
40305     }
40306     for(i=cnt=0; i<usableSize; i++){
40307       if( hit[i]==0 ){
40308         cnt++;
40309       }else if( hit[i]>1 ){
40310         checkAppendMsg(pCheck, 0,
40311           "Multiple uses for byte %d of page %d", i, iPage);
40312         break;
40313       }
40314     }
40315     if( cnt!=data[hdr+7] ){
40316       checkAppendMsg(pCheck, 0, 
40317           "Fragmented space is %d byte reported as %d on page %d",
40318           cnt, data[hdr+7], iPage);
40319     }
40320   }
40321   sqlite3PageFree(hit);
40322
40323   releasePage(pPage);
40324   return depth+1;
40325 }
40326 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40327
40328 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
40329 /*
40330 ** This routine does a complete check of the given BTree file.  aRoot[] is
40331 ** an array of pages numbers were each page number is the root page of
40332 ** a table.  nRoot is the number of entries in aRoot.
40333 **
40334 ** Write the number of error seen in *pnErr.  Except for some memory
40335 ** allocation errors,  nn error message is held in memory obtained from
40336 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
40337 ** returned.
40338 */
40339 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
40340   Btree *p,     /* The btree to be checked */
40341   int *aRoot,   /* An array of root pages numbers for individual trees */
40342   int nRoot,    /* Number of entries in aRoot[] */
40343   int mxErr,    /* Stop reporting errors after this many */
40344   int *pnErr    /* Write number of errors seen to this variable */
40345 ){
40346   int i;
40347   int nRef;
40348   IntegrityCk sCheck;
40349   BtShared *pBt = p->pBt;
40350   char zErr[100];
40351
40352   sqlite3BtreeEnter(p);
40353   pBt->db = p->db;
40354   nRef = sqlite3PagerRefcount(pBt->pPager);
40355   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
40356     *pnErr = 1;
40357     sqlite3BtreeLeave(p);
40358     return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
40359   }
40360   sCheck.pBt = pBt;
40361   sCheck.pPager = pBt->pPager;
40362   sCheck.nPage = pagerPagecount(sCheck.pPager);
40363   sCheck.mxErr = mxErr;
40364   sCheck.nErr = 0;
40365   sCheck.mallocFailed = 0;
40366   *pnErr = 0;
40367 #ifndef SQLITE_OMIT_AUTOVACUUM
40368   if( pBt->nTrunc!=0 ){
40369     sCheck.nPage = pBt->nTrunc;
40370   }
40371 #endif
40372   if( sCheck.nPage==0 ){
40373     unlockBtreeIfUnused(pBt);
40374     sqlite3BtreeLeave(p);
40375     return 0;
40376   }
40377   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
40378   if( !sCheck.anRef ){
40379     unlockBtreeIfUnused(pBt);
40380     *pnErr = 1;
40381     sqlite3BtreeLeave(p);
40382     return 0;
40383   }
40384   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
40385   i = PENDING_BYTE_PAGE(pBt);
40386   if( i<=sCheck.nPage ){
40387     sCheck.anRef[i] = 1;
40388   }
40389   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
40390
40391   /* Check the integrity of the freelist
40392   */
40393   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
40394             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
40395
40396   /* Check all the tables.
40397   */
40398   for(i=0; i<nRoot && sCheck.mxErr; i++){
40399     if( aRoot[i]==0 ) continue;
40400 #ifndef SQLITE_OMIT_AUTOVACUUM
40401     if( pBt->autoVacuum && aRoot[i]>1 ){
40402       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
40403     }
40404 #endif
40405     checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
40406   }
40407
40408   /* Make sure every page in the file is referenced
40409   */
40410   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
40411 #ifdef SQLITE_OMIT_AUTOVACUUM
40412     if( sCheck.anRef[i]==0 ){
40413       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40414     }
40415 #else
40416     /* If the database supports auto-vacuum, make sure no tables contain
40417     ** references to pointer-map pages.
40418     */
40419     if( sCheck.anRef[i]==0 && 
40420        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
40421       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
40422     }
40423     if( sCheck.anRef[i]!=0 && 
40424        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
40425       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
40426     }
40427 #endif
40428   }
40429
40430   /* Make sure this analysis did not leave any unref() pages
40431   */
40432   unlockBtreeIfUnused(pBt);
40433   if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
40434     checkAppendMsg(&sCheck, 0, 
40435       "Outstanding page count goes from %d to %d during this analysis",
40436       nRef, sqlite3PagerRefcount(pBt->pPager)
40437     );
40438   }
40439
40440   /* Clean  up and report errors.
40441   */
40442   sqlite3BtreeLeave(p);
40443   sqlite3_free(sCheck.anRef);
40444   if( sCheck.mallocFailed ){
40445     sqlite3StrAccumReset(&sCheck.errMsg);
40446     *pnErr = sCheck.nErr+1;
40447     return 0;
40448   }
40449   *pnErr = sCheck.nErr;
40450   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
40451   return sqlite3StrAccumFinish(&sCheck.errMsg);
40452 }
40453 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
40454
40455 /*
40456 ** Return the full pathname of the underlying database file.
40457 **
40458 ** The pager filename is invariant as long as the pager is
40459 ** open so it is safe to access without the BtShared mutex.
40460 */
40461 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
40462   assert( p->pBt->pPager!=0 );
40463   return sqlite3PagerFilename(p->pBt->pPager);
40464 }
40465
40466 /*
40467 ** Return the pathname of the directory that contains the database file.
40468 **
40469 ** The pager directory name is invariant as long as the pager is
40470 ** open so it is safe to access without the BtShared mutex.
40471 */
40472 SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
40473   assert( p->pBt->pPager!=0 );
40474   return sqlite3PagerDirname(p->pBt->pPager);
40475 }
40476
40477 /*
40478 ** Return the pathname of the journal file for this database. The return
40479 ** value of this routine is the same regardless of whether the journal file
40480 ** has been created or not.
40481 **
40482 ** The pager journal filename is invariant as long as the pager is
40483 ** open so it is safe to access without the BtShared mutex.
40484 */
40485 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
40486   assert( p->pBt->pPager!=0 );
40487   return sqlite3PagerJournalname(p->pBt->pPager);
40488 }
40489
40490 #ifndef SQLITE_OMIT_VACUUM
40491 /*
40492 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
40493 ** must be active for both files.
40494 **
40495 ** The size of file pTo may be reduced by this operation.
40496 ** If anything goes wrong, the transaction on pTo is rolled back. 
40497 **
40498 ** If successful, CommitPhaseOne() may be called on pTo before returning. 
40499 ** The caller should finish committing the transaction on pTo by calling
40500 ** sqlite3BtreeCommit().
40501 */
40502 static int btreeCopyFile(Btree *pTo, Btree *pFrom){
40503   int rc = SQLITE_OK;
40504   Pgno i;
40505
40506   Pgno nFromPage;     /* Number of pages in pFrom */
40507   Pgno nToPage;       /* Number of pages in pTo */
40508   Pgno nNewPage;      /* Number of pages in pTo after the copy */
40509
40510   Pgno iSkip;         /* Pending byte page in pTo */
40511   int nToPageSize;    /* Page size of pTo in bytes */
40512   int nFromPageSize;  /* Page size of pFrom in bytes */
40513
40514   BtShared *pBtTo = pTo->pBt;
40515   BtShared *pBtFrom = pFrom->pBt;
40516   pBtTo->db = pTo->db;
40517   pBtFrom->db = pFrom->db;
40518
40519   nToPageSize = pBtTo->pageSize;
40520   nFromPageSize = pBtFrom->pageSize;
40521
40522   if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
40523     return SQLITE_ERROR;
40524   }
40525   if( pBtTo->pCursor ){
40526     return SQLITE_BUSY;
40527   }
40528
40529   nToPage = pagerPagecount(pBtTo->pPager);
40530   nFromPage = pagerPagecount(pBtFrom->pPager);
40531   iSkip = PENDING_BYTE_PAGE(pBtTo);
40532
40533   /* Variable nNewPage is the number of pages required to store the
40534   ** contents of pFrom using the current page-size of pTo.
40535   */
40536   nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) / 
40537       (i64)nToPageSize;
40538
40539   for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
40540
40541     /* Journal the original page.
40542     **
40543     ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
40544     ** in database *pTo (before the copy). This page is never written 
40545     ** into the journal file. Unless i==iSkip or the page was not
40546     ** present in pTo before the copy operation, journal page i from pTo.
40547     */
40548     if( i!=iSkip && i<=nToPage ){
40549       DbPage *pDbPage = 0;
40550       rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
40551       if( rc==SQLITE_OK ){
40552         rc = sqlite3PagerWrite(pDbPage);
40553         if( rc==SQLITE_OK && i>nFromPage ){
40554           /* Yeah.  It seems wierd to call DontWrite() right after Write(). But
40555           ** that is because the names of those procedures do not exactly 
40556           ** represent what they do.  Write() really means "put this page in the
40557           ** rollback journal and mark it as dirty so that it will be written
40558           ** to the database file later."  DontWrite() undoes the second part of
40559           ** that and prevents the page from being written to the database. The
40560           ** page is still on the rollback journal, though.  And that is the 
40561           ** whole point of this block: to put pages on the rollback journal. 
40562           */
40563           rc = sqlite3PagerDontWrite(pDbPage);
40564         }
40565         sqlite3PagerUnref(pDbPage);
40566       }
40567     }
40568
40569     /* Overwrite the data in page i of the target database */
40570     if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
40571
40572       DbPage *pToPage = 0;
40573       sqlite3_int64 iOff;
40574
40575       rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
40576       if( rc==SQLITE_OK ){
40577         rc = sqlite3PagerWrite(pToPage);
40578       }
40579
40580       for(
40581         iOff=(i-1)*nToPageSize; 
40582         rc==SQLITE_OK && iOff<i*nToPageSize; 
40583         iOff += nFromPageSize
40584       ){
40585         DbPage *pFromPage = 0;
40586         Pgno iFrom = (iOff/nFromPageSize)+1;
40587
40588         if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
40589           continue;
40590         }
40591
40592         rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
40593         if( rc==SQLITE_OK ){
40594           char *zTo = sqlite3PagerGetData(pToPage);
40595           char *zFrom = sqlite3PagerGetData(pFromPage);
40596           int nCopy;
40597
40598           if( nFromPageSize>=nToPageSize ){
40599             zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
40600             nCopy = nToPageSize;
40601           }else{
40602             zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
40603             nCopy = nFromPageSize;
40604           }
40605
40606           memcpy(zTo, zFrom, nCopy);
40607           sqlite3PagerUnref(pFromPage);
40608         }
40609       }
40610
40611       if( pToPage ){
40612         MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
40613         p->isInit = 0;
40614         sqlite3PagerUnref(pToPage);
40615       }
40616     }
40617   }
40618
40619   /* If things have worked so far, the database file may need to be 
40620   ** truncated. The complex part is that it may need to be truncated to
40621   ** a size that is not an integer multiple of nToPageSize - the current
40622   ** page size used by the pager associated with B-Tree pTo.
40623   **
40624   ** For example, say the page-size of pTo is 2048 bytes and the original 
40625   ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024 
40626   ** bytes and 9 pages, then the file needs to be truncated to 9KB.
40627   */
40628   if( rc==SQLITE_OK ){
40629     if( nFromPageSize!=nToPageSize ){
40630       sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
40631       i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
40632       i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize; 
40633       i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
40634   
40635       assert( iSize<=iNow );
40636   
40637       /* Commit phase one syncs the journal file associated with pTo 
40638       ** containing the original data. It does not sync the database file
40639       ** itself. After doing this it is safe to use OsTruncate() and other
40640       ** file APIs on the database file directly.
40641       */
40642       pBtTo->db = pTo->db;
40643       rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
40644       if( iSize<iNow && rc==SQLITE_OK ){
40645         rc = sqlite3OsTruncate(pFile, iSize);
40646       }
40647   
40648       /* The loop that copied data from database pFrom to pTo did not
40649       ** populate the locking page of database pTo. If the page-size of
40650       ** pFrom is smaller than that of pTo, this means some data will
40651       ** not have been copied. 
40652       **
40653       ** This block copies the missing data from database pFrom to pTo 
40654       ** using file APIs. This is safe because at this point we know that
40655       ** all of the original data from pTo has been synced into the 
40656       ** journal file. At this point it would be safe to do anything at
40657       ** all to the database file except truncate it to zero bytes.
40658       */
40659       if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
40660         i64 iOff;
40661         for(
40662           iOff=iPending; 
40663           rc==SQLITE_OK && iOff<(iPending+nToPageSize); 
40664           iOff += nFromPageSize
40665         ){
40666           DbPage *pFromPage = 0;
40667           Pgno iFrom = (iOff/nFromPageSize)+1;
40668   
40669           if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
40670             continue;
40671           }
40672   
40673           rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
40674           if( rc==SQLITE_OK ){
40675             char *zFrom = sqlite3PagerGetData(pFromPage);
40676             rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
40677             sqlite3PagerUnref(pFromPage);
40678           }
40679         }
40680       }
40681   
40682       /* Sync the database file */
40683       if( rc==SQLITE_OK ){
40684         rc = sqlite3PagerSync(pBtTo->pPager);
40685       }
40686     }else{
40687       rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
40688     }
40689     if( rc==SQLITE_OK ){
40690       pBtTo->pageSizeFixed = 0;
40691     }
40692   }
40693
40694   if( rc ){
40695     sqlite3BtreeRollback(pTo);
40696   }
40697
40698   return rc;  
40699 }
40700 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
40701   int rc;
40702   sqlite3BtreeEnter(pTo);
40703   sqlite3BtreeEnter(pFrom);
40704   rc = btreeCopyFile(pTo, pFrom);
40705   sqlite3BtreeLeave(pFrom);
40706   sqlite3BtreeLeave(pTo);
40707   return rc;
40708 }
40709
40710 #endif /* SQLITE_OMIT_VACUUM */
40711
40712 /*
40713 ** Return non-zero if a transaction is active.
40714 */
40715 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
40716   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
40717   return (p && (p->inTrans==TRANS_WRITE));
40718 }
40719
40720 /*
40721 ** Return non-zero if a statement transaction is active.
40722 */
40723 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
40724   assert( sqlite3BtreeHoldsMutex(p) );
40725   return (p->pBt && p->pBt->inStmt);
40726 }
40727
40728 /*
40729 ** Return non-zero if a read (or write) transaction is active.
40730 */
40731 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
40732   assert( sqlite3_mutex_held(p->db->mutex) );
40733   return (p && (p->inTrans!=TRANS_NONE));
40734 }
40735
40736 /*
40737 ** This function returns a pointer to a blob of memory associated with
40738 ** a single shared-btree. The memory is used by client code for its own
40739 ** purposes (for example, to store a high-level schema associated with 
40740 ** the shared-btree). The btree layer manages reference counting issues.
40741 **
40742 ** The first time this is called on a shared-btree, nBytes bytes of memory
40743 ** are allocated, zeroed, and returned to the caller. For each subsequent 
40744 ** call the nBytes parameter is ignored and a pointer to the same blob
40745 ** of memory returned. 
40746 **
40747 ** If the nBytes parameter is 0 and the blob of memory has not yet been
40748 ** allocated, a null pointer is returned. If the blob has already been
40749 ** allocated, it is returned as normal.
40750 **
40751 ** Just before the shared-btree is closed, the function passed as the 
40752 ** xFree argument when the memory allocation was made is invoked on the 
40753 ** blob of allocated memory. This function should not call sqlite3_free()
40754 ** on the memory, the btree layer does that.
40755 */
40756 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
40757   BtShared *pBt = p->pBt;
40758   sqlite3BtreeEnter(p);
40759   if( !pBt->pSchema && nBytes ){
40760     pBt->pSchema = sqlite3MallocZero(nBytes);
40761     pBt->xFreeSchema = xFree;
40762   }
40763   sqlite3BtreeLeave(p);
40764   return pBt->pSchema;
40765 }
40766
40767 /*
40768 ** Return true if another user of the same shared btree as the argument
40769 ** handle holds an exclusive lock on the sqlite_master table.
40770 */
40771 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
40772   int rc;
40773   assert( sqlite3_mutex_held(p->db->mutex) );
40774   sqlite3BtreeEnter(p);
40775   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
40776   sqlite3BtreeLeave(p);
40777   return rc;
40778 }
40779
40780
40781 #ifndef SQLITE_OMIT_SHARED_CACHE
40782 /*
40783 ** Obtain a lock on the table whose root page is iTab.  The
40784 ** lock is a write lock if isWritelock is true or a read lock
40785 ** if it is false.
40786 */
40787 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
40788   int rc = SQLITE_OK;
40789   if( p->sharable ){
40790     u8 lockType = READ_LOCK + isWriteLock;
40791     assert( READ_LOCK+1==WRITE_LOCK );
40792     assert( isWriteLock==0 || isWriteLock==1 );
40793     sqlite3BtreeEnter(p);
40794     rc = queryTableLock(p, iTab, lockType);
40795     if( rc==SQLITE_OK ){
40796       rc = lockTable(p, iTab, lockType);
40797     }
40798     sqlite3BtreeLeave(p);
40799   }
40800   return rc;
40801 }
40802 #endif
40803
40804 #ifndef SQLITE_OMIT_INCRBLOB
40805 /*
40806 ** Argument pCsr must be a cursor opened for writing on an 
40807 ** INTKEY table currently pointing at a valid table entry. 
40808 ** This function modifies the data stored as part of that entry.
40809 ** Only the data content may only be modified, it is not possible
40810 ** to change the length of the data stored.
40811 */
40812 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
40813   assert( cursorHoldsMutex(pCsr) );
40814   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
40815   assert(pCsr->isIncrblobHandle);
40816
40817   restoreCursorPosition(pCsr);
40818   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
40819   if( pCsr->eState!=CURSOR_VALID ){
40820     return SQLITE_ABORT;
40821   }
40822
40823   /* Check some preconditions: 
40824   **   (a) the cursor is open for writing,
40825   **   (b) there is no read-lock on the table being modified and
40826   **   (c) the cursor points at a valid row of an intKey table.
40827   */
40828   if( !pCsr->wrFlag ){
40829     return SQLITE_READONLY;
40830   }
40831   assert( !pCsr->pBt->readOnly 
40832           && pCsr->pBt->inTransaction==TRANS_WRITE );
40833   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
40834     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
40835   }
40836   if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
40837     return SQLITE_ERROR;
40838   }
40839
40840   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
40841 }
40842
40843 /* 
40844 ** Set a flag on this cursor to cache the locations of pages from the 
40845 ** overflow list for the current row. This is used by cursors opened
40846 ** for incremental blob IO only.
40847 **
40848 ** This function sets a flag only. The actual page location cache
40849 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
40850 ** accessPayload() (the worker function for sqlite3BtreeData() and
40851 ** sqlite3BtreePutData()).
40852 */
40853 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
40854   assert( cursorHoldsMutex(pCur) );
40855   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
40856   assert(!pCur->isIncrblobHandle);
40857   assert(!pCur->aOverflow);
40858   pCur->isIncrblobHandle = 1;
40859 }
40860 #endif
40861
40862 /************** End of btree.c ***********************************************/
40863 /************** Begin file vdbefifo.c ****************************************/
40864 /*
40865 ** 2005 June 16
40866 **
40867 ** The author disclaims copyright to this source code.  In place of
40868 ** a legal notice, here is a blessing:
40869 **
40870 **    May you do good and not evil.
40871 **    May you find forgiveness for yourself and forgive others.
40872 **    May you share freely, never taking more than you give.
40873 **
40874 *************************************************************************
40875 ** This file implements a FIFO queue of rowids used for processing
40876 ** UPDATE and DELETE statements.
40877 **
40878 ** $Id: vdbefifo.c,v 1.8 2008/07/28 19:34:54 drh Exp $
40879 */
40880
40881 /*
40882 ** Constants FIFOSIZE_FIRST and FIFOSIZE_MAX are the initial
40883 ** number of entries in a fifo page and the maximum number of
40884 ** entries in a fifo page.
40885 */
40886 #define FIFOSIZE_FIRST (((128-sizeof(FifoPage))/8)+1)
40887 #ifdef SQLITE_MALLOC_SOFT_LIMIT
40888 # define FIFOSIZE_MAX   (((SQLITE_MALLOC_SOFT_LIMIT-sizeof(FifoPage))/8)+1)
40889 #else
40890 # define FIFOSIZE_MAX   (((262144-sizeof(FifoPage))/8)+1)
40891 #endif
40892
40893 /*
40894 ** Allocate a new FifoPage and return a pointer to it.  Return NULL if
40895 ** we run out of memory.  Leave space on the page for nEntry entries.
40896 */
40897 static FifoPage *allocateFifoPage(sqlite3 *db, int nEntry){
40898   FifoPage *pPage;
40899   if( nEntry>FIFOSIZE_MAX ){
40900     nEntry = FIFOSIZE_MAX;
40901   }
40902   pPage = sqlite3DbMallocRaw(db, sizeof(FifoPage) + sizeof(i64)*(nEntry-1) );
40903   if( pPage ){
40904     pPage->nSlot = nEntry;
40905     pPage->iWrite = 0;
40906     pPage->iRead = 0;
40907     pPage->pNext = 0;
40908   }
40909   return pPage;
40910 }
40911
40912 /*
40913 ** Initialize a Fifo structure.
40914 */
40915 SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo, sqlite3 *db){
40916   memset(pFifo, 0, sizeof(*pFifo));
40917   pFifo->db = db;
40918 }
40919
40920 /*
40921 ** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
40922 ** normally.   SQLITE_NOMEM is returned if we are unable to allocate
40923 ** memory.
40924 */
40925 SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
40926   FifoPage *pPage;
40927   pPage = pFifo->pLast;
40928   if( pPage==0 ){
40929     pPage = pFifo->pLast = pFifo->pFirst =
40930          allocateFifoPage(pFifo->db, FIFOSIZE_FIRST);
40931     if( pPage==0 ){
40932       return SQLITE_NOMEM;
40933     }
40934   }else if( pPage->iWrite>=pPage->nSlot ){
40935     pPage->pNext = allocateFifoPage(pFifo->db, pFifo->nEntry);
40936     if( pPage->pNext==0 ){
40937       return SQLITE_NOMEM;
40938     }
40939     pPage = pFifo->pLast = pPage->pNext;
40940   }
40941   pPage->aSlot[pPage->iWrite++] = val;
40942   pFifo->nEntry++;
40943   return SQLITE_OK;
40944 }
40945
40946 /*
40947 ** Extract a single 64-bit integer value from the Fifo.  The integer
40948 ** extracted is the one least recently inserted.  If the Fifo is empty
40949 ** return SQLITE_DONE.
40950 */
40951 SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
40952   FifoPage *pPage;
40953   if( pFifo->nEntry==0 ){
40954     return SQLITE_DONE;
40955   }
40956   assert( pFifo->nEntry>0 );
40957   pPage = pFifo->pFirst;
40958   assert( pPage!=0 );
40959   assert( pPage->iWrite>pPage->iRead );
40960   assert( pPage->iWrite<=pPage->nSlot );
40961   assert( pPage->iRead<pPage->nSlot );
40962   assert( pPage->iRead>=0 );
40963   *pVal = pPage->aSlot[pPage->iRead++];
40964   pFifo->nEntry--;
40965   if( pPage->iRead>=pPage->iWrite ){
40966     pFifo->pFirst = pPage->pNext;
40967     sqlite3DbFree(pFifo->db, pPage);
40968     if( pFifo->nEntry==0 ){
40969       assert( pFifo->pLast==pPage );
40970       pFifo->pLast = 0;
40971     }else{
40972       assert( pFifo->pFirst!=0 );
40973     }
40974   }else{
40975     assert( pFifo->nEntry>0 );
40976   }
40977   return SQLITE_OK;
40978 }
40979
40980 /*
40981 ** Delete all information from a Fifo object.   Free all memory held
40982 ** by the Fifo.
40983 */
40984 SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
40985   FifoPage *pPage, *pNextPage;
40986   for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
40987     pNextPage = pPage->pNext;
40988     sqlite3DbFree(pFifo->db, pPage);
40989   }
40990   sqlite3VdbeFifoInit(pFifo, pFifo->db);
40991 }
40992
40993 /************** End of vdbefifo.c ********************************************/
40994 /************** Begin file vdbemem.c *****************************************/
40995 /*
40996 ** 2004 May 26
40997 **
40998 ** The author disclaims copyright to this source code.  In place of
40999 ** a legal notice, here is a blessing:
41000 **
41001 **    May you do good and not evil.
41002 **    May you find forgiveness for yourself and forgive others.
41003 **    May you share freely, never taking more than you give.
41004 **
41005 *************************************************************************
41006 **
41007 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
41008 ** stores a single value in the VDBE.  Mem is an opaque structure visible
41009 ** only within the VDBE.  Interface routines refer to a Mem using the
41010 ** name sqlite_value
41011 **
41012 ** $Id: vdbemem.c,v 1.123 2008/09/16 12:06:08 danielk1977 Exp $
41013 */
41014
41015 /*
41016 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
41017 ** P if required.
41018 */
41019 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
41020
41021 /*
41022 ** If pMem is an object with a valid string representation, this routine
41023 ** ensures the internal encoding for the string representation is
41024 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
41025 **
41026 ** If pMem is not a string object, or the encoding of the string
41027 ** representation is already stored using the requested encoding, then this
41028 ** routine is a no-op.
41029 **
41030 ** SQLITE_OK is returned if the conversion is successful (or not required).
41031 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
41032 ** between formats.
41033 */
41034 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
41035   int rc;
41036   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
41037     return SQLITE_OK;
41038   }
41039   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41040 #ifdef SQLITE_OMIT_UTF16
41041   return SQLITE_ERROR;
41042 #else
41043
41044   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
41045   ** then the encoding of the value may not have changed.
41046   */
41047   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
41048   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
41049   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
41050   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
41051   return rc;
41052 #endif
41053 }
41054
41055 /*
41056 ** Make sure pMem->z points to a writable allocation of at least 
41057 ** n bytes.
41058 **
41059 ** If the memory cell currently contains string or blob data
41060 ** and the third argument passed to this function is true, the 
41061 ** current content of the cell is preserved. Otherwise, it may
41062 ** be discarded.  
41063 **
41064 ** This function sets the MEM_Dyn flag and clears any xDel callback.
41065 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
41066 ** not set, Mem.n is zeroed.
41067 */
41068 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
41069   assert( 1 >=
41070     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
41071     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
41072     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
41073     ((pMem->flags&MEM_Static) ? 1 : 0)
41074   );
41075
41076   if( n<32 ) n = 32;
41077   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
41078     if( preserve && pMem->z==pMem->zMalloc ){
41079       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
41080       if( !pMem->z ){
41081         pMem->flags = MEM_Null;
41082       }
41083       preserve = 0;
41084     }else{
41085       sqlite3DbFree(pMem->db, pMem->zMalloc);
41086       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
41087     }
41088   }
41089
41090   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
41091     memcpy(pMem->zMalloc, pMem->z, pMem->n);
41092   }
41093   if( pMem->flags&MEM_Dyn && pMem->xDel ){
41094     pMem->xDel((void *)(pMem->z));
41095   }
41096
41097   pMem->z = pMem->zMalloc;
41098   pMem->flags &= ~(MEM_Ephem|MEM_Static);
41099   pMem->xDel = 0;
41100   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
41101 }
41102
41103 /*
41104 ** Make the given Mem object MEM_Dyn.  In other words, make it so
41105 ** that any TEXT or BLOB content is stored in memory obtained from
41106 ** malloc().  In this way, we know that the memory is safe to be
41107 ** overwritten or altered.
41108 **
41109 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
41110 */
41111 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
41112   int f;
41113   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41114   expandBlob(pMem);
41115   f = pMem->flags;
41116   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
41117     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
41118       return SQLITE_NOMEM;
41119     }
41120     pMem->z[pMem->n] = 0;
41121     pMem->z[pMem->n+1] = 0;
41122     pMem->flags |= MEM_Term;
41123   }
41124
41125   return SQLITE_OK;
41126 }
41127
41128 /*
41129 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
41130 ** blob stored in dynamically allocated space.
41131 */
41132 #ifndef SQLITE_OMIT_INCRBLOB
41133 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
41134   if( pMem->flags & MEM_Zero ){
41135     int nByte;
41136     assert( pMem->flags&MEM_Blob );
41137     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41138
41139     /* Set nByte to the number of bytes required to store the expanded blob. */
41140     nByte = pMem->n + pMem->u.i;
41141     if( nByte<=0 ){
41142       nByte = 1;
41143     }
41144     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
41145       return SQLITE_NOMEM;
41146     }
41147
41148     memset(&pMem->z[pMem->n], 0, pMem->u.i);
41149     pMem->n += pMem->u.i;
41150     pMem->flags &= ~(MEM_Zero|MEM_Term);
41151   }
41152   return SQLITE_OK;
41153 }
41154 #endif
41155
41156
41157 /*
41158 ** Make sure the given Mem is \u0000 terminated.
41159 */
41160 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
41161   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41162   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
41163     return SQLITE_OK;   /* Nothing to do */
41164   }
41165   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
41166     return SQLITE_NOMEM;
41167   }
41168   pMem->z[pMem->n] = 0;
41169   pMem->z[pMem->n+1] = 0;
41170   pMem->flags |= MEM_Term;
41171   return SQLITE_OK;
41172 }
41173
41174 /*
41175 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
41176 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
41177 ** is a no-op.
41178 **
41179 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
41180 **
41181 ** A MEM_Null value will never be passed to this function. This function is
41182 ** used for converting values to text for returning to the user (i.e. via
41183 ** sqlite3_value_text()), or for ensuring that values to be used as btree
41184 ** keys are strings. In the former case a NULL pointer is returned the
41185 ** user and the later is an internal programming error.
41186 */
41187 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
41188   int rc = SQLITE_OK;
41189   int fg = pMem->flags;
41190   const int nByte = 32;
41191
41192   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41193   assert( !(fg&MEM_Zero) );
41194   assert( !(fg&(MEM_Str|MEM_Blob)) );
41195   assert( fg&(MEM_Int|MEM_Real) );
41196
41197   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
41198     return SQLITE_NOMEM;
41199   }
41200
41201   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
41202   ** string representation of the value. Then, if the required encoding
41203   ** is UTF-16le or UTF-16be do a translation.
41204   ** 
41205   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
41206   */
41207   if( fg & MEM_Int ){
41208     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
41209   }else{
41210     assert( fg & MEM_Real );
41211     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
41212   }
41213   pMem->n = strlen(pMem->z);
41214   pMem->enc = SQLITE_UTF8;
41215   pMem->flags |= MEM_Str|MEM_Term;
41216   sqlite3VdbeChangeEncoding(pMem, enc);
41217   return rc;
41218 }
41219
41220 /*
41221 ** Memory cell pMem contains the context of an aggregate function.
41222 ** This routine calls the finalize method for that function.  The
41223 ** result of the aggregate is stored back into pMem.
41224 **
41225 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
41226 ** otherwise.
41227 */
41228 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
41229   int rc = SQLITE_OK;
41230   if( pFunc && pFunc->xFinalize ){
41231     sqlite3_context ctx;
41232     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
41233     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41234     memset(&ctx, 0, sizeof(ctx));
41235     ctx.s.flags = MEM_Null;
41236     ctx.s.db = pMem->db;
41237     ctx.pMem = pMem;
41238     ctx.pFunc = pFunc;
41239     pFunc->xFinalize(&ctx);
41240     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
41241     sqlite3DbFree(pMem->db, pMem->zMalloc);
41242     *pMem = ctx.s;
41243     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
41244   }
41245   return rc;
41246 }
41247
41248 /*
41249 ** If the memory cell contains a string value that must be freed by
41250 ** invoking an external callback, free it now. Calling this function
41251 ** does not free any Mem.zMalloc buffer.
41252 */
41253 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
41254   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
41255   if( p->flags&MEM_Agg ){
41256     sqlite3VdbeMemFinalize(p, p->u.pDef);
41257     assert( (p->flags & MEM_Agg)==0 );
41258     sqlite3VdbeMemRelease(p);
41259   }else if( p->flags&MEM_Dyn && p->xDel ){
41260     p->xDel((void *)p->z);
41261     p->xDel = 0;
41262   }
41263 }
41264
41265 /*
41266 ** Release any memory held by the Mem. This may leave the Mem in an
41267 ** inconsistent state, for example with (Mem.z==0) and
41268 ** (Mem.type==SQLITE_TEXT).
41269 */
41270 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
41271   sqlite3VdbeMemReleaseExternal(p);
41272   sqlite3DbFree(p->db, p->zMalloc);
41273   p->z = 0;
41274   p->zMalloc = 0;
41275   p->xDel = 0;
41276 }
41277
41278 /*
41279 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
41280 ** If the double is too large, return 0x8000000000000000.
41281 **
41282 ** Most systems appear to do this simply by assigning
41283 ** variables and without the extra range tests.  But
41284 ** there are reports that windows throws an expection
41285 ** if the floating point value is out of range. (See ticket #2880.)
41286 ** Because we do not completely understand the problem, we will
41287 ** take the conservative approach and always do range tests
41288 ** before attempting the conversion.
41289 */
41290 static i64 doubleToInt64(double r){
41291   /*
41292   ** Many compilers we encounter do not define constants for the
41293   ** minimum and maximum 64-bit integers, or they define them
41294   ** inconsistently.  And many do not understand the "LL" notation.
41295   ** So we define our own static constants here using nothing
41296   ** larger than a 32-bit integer constant.
41297   */
41298   static const i64 maxInt = LARGEST_INT64;
41299   static const i64 minInt = SMALLEST_INT64;
41300
41301   if( r<(double)minInt ){
41302     return minInt;
41303   }else if( r>(double)maxInt ){
41304     return minInt;
41305   }else{
41306     return (i64)r;
41307   }
41308 }
41309
41310 /*
41311 ** Return some kind of integer value which is the best we can do
41312 ** at representing the value that *pMem describes as an integer.
41313 ** If pMem is an integer, then the value is exact.  If pMem is
41314 ** a floating-point then the value returned is the integer part.
41315 ** If pMem is a string or blob, then we make an attempt to convert
41316 ** it into a integer and return that.  If pMem is NULL, return 0.
41317 **
41318 ** If pMem is a string, its encoding might be changed.
41319 */
41320 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
41321   int flags;
41322   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41323   flags = pMem->flags;
41324   if( flags & MEM_Int ){
41325     return pMem->u.i;
41326   }else if( flags & MEM_Real ){
41327     return doubleToInt64(pMem->r);
41328   }else if( flags & (MEM_Str|MEM_Blob) ){
41329     i64 value;
41330     pMem->flags |= MEM_Str;
41331     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41332        || sqlite3VdbeMemNulTerminate(pMem) ){
41333       return 0;
41334     }
41335     assert( pMem->z );
41336     sqlite3Atoi64(pMem->z, &value);
41337     return value;
41338   }else{
41339     return 0;
41340   }
41341 }
41342
41343 /*
41344 ** Return the best representation of pMem that we can get into a
41345 ** double.  If pMem is already a double or an integer, return its
41346 ** value.  If it is a string or blob, try to convert it to a double.
41347 ** If it is a NULL, return 0.0.
41348 */
41349 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
41350   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41351   if( pMem->flags & MEM_Real ){
41352     return pMem->r;
41353   }else if( pMem->flags & MEM_Int ){
41354     return (double)pMem->u.i;
41355   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
41356     double val = 0.0;
41357     pMem->flags |= MEM_Str;
41358     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
41359        || sqlite3VdbeMemNulTerminate(pMem) ){
41360       return 0.0;
41361     }
41362     assert( pMem->z );
41363     sqlite3AtoF(pMem->z, &val);
41364     return val;
41365   }else{
41366     return 0.0;
41367   }
41368 }
41369
41370 /*
41371 ** The MEM structure is already a MEM_Real.  Try to also make it a
41372 ** MEM_Int if we can.
41373 */
41374 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
41375   assert( pMem->flags & MEM_Real );
41376   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41377
41378   pMem->u.i = doubleToInt64(pMem->r);
41379   if( pMem->r==(double)pMem->u.i ){
41380     pMem->flags |= MEM_Int;
41381   }
41382 }
41383
41384 static void setTypeFlag(Mem *pMem, int f){
41385   MemSetTypeFlag(pMem, f);
41386 }
41387
41388 /*
41389 ** Convert pMem to type integer.  Invalidate any prior representations.
41390 */
41391 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
41392   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41393   pMem->u.i = sqlite3VdbeIntValue(pMem);
41394   setTypeFlag(pMem, MEM_Int);
41395   return SQLITE_OK;
41396 }
41397
41398 /*
41399 ** Convert pMem so that it is of type MEM_Real.
41400 ** Invalidate any prior representations.
41401 */
41402 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
41403   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41404   pMem->r = sqlite3VdbeRealValue(pMem);
41405   setTypeFlag(pMem, MEM_Real);
41406   return SQLITE_OK;
41407 }
41408
41409 /*
41410 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
41411 ** Invalidate any prior representations.
41412 */
41413 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
41414   double r1, r2;
41415   i64 i;
41416   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
41417   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
41418   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41419   r1 = sqlite3VdbeRealValue(pMem);
41420   i = doubleToInt64(r1);
41421   r2 = (double)i;
41422   if( r1==r2 ){
41423     sqlite3VdbeMemIntegerify(pMem);
41424   }else{
41425     pMem->r = r1;
41426     setTypeFlag(pMem, MEM_Real);
41427   }
41428   return SQLITE_OK;
41429 }
41430
41431 /*
41432 ** Delete any previous value and set the value stored in *pMem to NULL.
41433 */
41434 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
41435   setTypeFlag(pMem, MEM_Null);
41436   pMem->type = SQLITE_NULL;
41437 }
41438
41439 /*
41440 ** Delete any previous value and set the value to be a BLOB of length
41441 ** n containing all zeros.
41442 */
41443 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
41444   sqlite3VdbeMemRelease(pMem);
41445   setTypeFlag(pMem, MEM_Blob);
41446   pMem->flags = MEM_Blob|MEM_Zero;
41447   pMem->type = SQLITE_BLOB;
41448   pMem->n = 0;
41449   if( n<0 ) n = 0;
41450   pMem->u.i = n;
41451   pMem->enc = SQLITE_UTF8;
41452 }
41453
41454 /*
41455 ** Delete any previous value and set the value stored in *pMem to val,
41456 ** manifest type INTEGER.
41457 */
41458 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
41459   sqlite3VdbeMemRelease(pMem);
41460   pMem->u.i = val;
41461   pMem->flags = MEM_Int;
41462   pMem->type = SQLITE_INTEGER;
41463 }
41464
41465 /*
41466 ** Delete any previous value and set the value stored in *pMem to val,
41467 ** manifest type REAL.
41468 */
41469 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
41470   if( sqlite3IsNaN(val) ){
41471     sqlite3VdbeMemSetNull(pMem);
41472   }else{
41473     sqlite3VdbeMemRelease(pMem);
41474     pMem->r = val;
41475     pMem->flags = MEM_Real;
41476     pMem->type = SQLITE_FLOAT;
41477   }
41478 }
41479
41480 /*
41481 ** Return true if the Mem object contains a TEXT or BLOB that is
41482 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
41483 */
41484 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
41485   assert( p->db!=0 );
41486   if( p->flags & (MEM_Str|MEM_Blob) ){
41487     int n = p->n;
41488     if( p->flags & MEM_Zero ){
41489       n += p->u.i;
41490     }
41491     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
41492   }
41493   return 0; 
41494 }
41495
41496 /*
41497 ** Size of struct Mem not including the Mem.zMalloc member.
41498 */
41499 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
41500
41501 /*
41502 ** Make an shallow copy of pFrom into pTo.  Prior contents of
41503 ** pTo are freed.  The pFrom->z field is not duplicated.  If
41504 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
41505 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
41506 */
41507 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
41508   sqlite3VdbeMemReleaseExternal(pTo);
41509   memcpy(pTo, pFrom, MEMCELLSIZE);
41510   pTo->xDel = 0;
41511   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
41512     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
41513     assert( srcType==MEM_Ephem || srcType==MEM_Static );
41514     pTo->flags |= srcType;
41515   }
41516 }
41517
41518 /*
41519 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
41520 ** freed before the copy is made.
41521 */
41522 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
41523   int rc = SQLITE_OK;
41524
41525   sqlite3VdbeMemReleaseExternal(pTo);
41526   memcpy(pTo, pFrom, MEMCELLSIZE);
41527   pTo->flags &= ~MEM_Dyn;
41528
41529   if( pTo->flags&(MEM_Str|MEM_Blob) ){
41530     if( 0==(pFrom->flags&MEM_Static) ){
41531       pTo->flags |= MEM_Ephem;
41532       rc = sqlite3VdbeMemMakeWriteable(pTo);
41533     }
41534   }
41535
41536   return rc;
41537 }
41538
41539 /*
41540 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
41541 ** freed. If pFrom contains ephemeral data, a copy is made.
41542 **
41543 ** pFrom contains an SQL NULL when this routine returns.
41544 */
41545 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
41546   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
41547   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
41548   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
41549
41550   sqlite3VdbeMemRelease(pTo);
41551   memcpy(pTo, pFrom, sizeof(Mem));
41552   pFrom->flags = MEM_Null;
41553   pFrom->xDel = 0;
41554   pFrom->zMalloc = 0;
41555 }
41556
41557 /*
41558 ** Change the value of a Mem to be a string or a BLOB.
41559 **
41560 ** The memory management strategy depends on the value of the xDel
41561 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
41562 ** string is copied into a (possibly existing) buffer managed by the 
41563 ** Mem structure. Otherwise, any existing buffer is freed and the
41564 ** pointer copied.
41565 */
41566 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
41567   Mem *pMem,          /* Memory cell to set to string value */
41568   const char *z,      /* String pointer */
41569   int n,              /* Bytes in string, or negative */
41570   u8 enc,             /* Encoding of z.  0 for BLOBs */
41571   void (*xDel)(void*) /* Destructor function */
41572 ){
41573   int nByte = n;      /* New value for pMem->n */
41574   int iLimit;         /* Maximum allowed string or blob size */
41575   int flags = 0;      /* New value for pMem->flags */
41576
41577   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
41578
41579   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
41580   if( !z ){
41581     sqlite3VdbeMemSetNull(pMem);
41582     return SQLITE_OK;
41583   }
41584
41585   if( pMem->db ){
41586     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
41587   }else{
41588     iLimit = SQLITE_MAX_LENGTH;
41589   }
41590   flags = (enc==0?MEM_Blob:MEM_Str);
41591   if( nByte<0 ){
41592     assert( enc!=0 );
41593     if( enc==SQLITE_UTF8 ){
41594       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
41595     }else{
41596       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
41597     }
41598     flags |= MEM_Term;
41599   }
41600   if( nByte>iLimit ){
41601     return SQLITE_TOOBIG;
41602   }
41603
41604   /* The following block sets the new values of Mem.z and Mem.xDel. It
41605   ** also sets a flag in local variable "flags" to indicate the memory
41606   ** management (one of MEM_Dyn or MEM_Static).
41607   */
41608   if( xDel==SQLITE_TRANSIENT ){
41609     int nAlloc = nByte;
41610     if( flags&MEM_Term ){
41611       nAlloc += (enc==SQLITE_UTF8?1:2);
41612     }
41613     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
41614       return SQLITE_NOMEM;
41615     }
41616     memcpy(pMem->z, z, nAlloc);
41617   }else if( xDel==SQLITE_DYNAMIC ){
41618     sqlite3VdbeMemRelease(pMem);
41619     pMem->zMalloc = pMem->z = (char *)z;
41620     pMem->xDel = 0;
41621   }else{
41622     sqlite3VdbeMemRelease(pMem);
41623     pMem->z = (char *)z;
41624     pMem->xDel = xDel;
41625     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
41626   }
41627
41628   pMem->n = nByte;
41629   pMem->flags = flags;
41630   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
41631   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
41632
41633 #ifndef SQLITE_OMIT_UTF16
41634   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
41635     return SQLITE_NOMEM;
41636   }
41637 #endif
41638
41639   return SQLITE_OK;
41640 }
41641
41642 /*
41643 ** Compare the values contained by the two memory cells, returning
41644 ** negative, zero or positive if pMem1 is less than, equal to, or greater
41645 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
41646 ** and reals) sorted numerically, followed by text ordered by the collating
41647 ** sequence pColl and finally blob's ordered by memcmp().
41648 **
41649 ** Two NULL values are considered equal by this function.
41650 */
41651 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
41652   int rc;
41653   int f1, f2;
41654   int combined_flags;
41655
41656   /* Interchange pMem1 and pMem2 if the collating sequence specifies
41657   ** DESC order.
41658   */
41659   f1 = pMem1->flags;
41660   f2 = pMem2->flags;
41661   combined_flags = f1|f2;
41662  
41663   /* If one value is NULL, it is less than the other. If both values
41664   ** are NULL, return 0.
41665   */
41666   if( combined_flags&MEM_Null ){
41667     return (f2&MEM_Null) - (f1&MEM_Null);
41668   }
41669
41670   /* If one value is a number and the other is not, the number is less.
41671   ** If both are numbers, compare as reals if one is a real, or as integers
41672   ** if both values are integers.
41673   */
41674   if( combined_flags&(MEM_Int|MEM_Real) ){
41675     if( !(f1&(MEM_Int|MEM_Real)) ){
41676       return 1;
41677     }
41678     if( !(f2&(MEM_Int|MEM_Real)) ){
41679       return -1;
41680     }
41681     if( (f1 & f2 & MEM_Int)==0 ){
41682       double r1, r2;
41683       if( (f1&MEM_Real)==0 ){
41684         r1 = pMem1->u.i;
41685       }else{
41686         r1 = pMem1->r;
41687       }
41688       if( (f2&MEM_Real)==0 ){
41689         r2 = pMem2->u.i;
41690       }else{
41691         r2 = pMem2->r;
41692       }
41693       if( r1<r2 ) return -1;
41694       if( r1>r2 ) return 1;
41695       return 0;
41696     }else{
41697       assert( f1&MEM_Int );
41698       assert( f2&MEM_Int );
41699       if( pMem1->u.i < pMem2->u.i ) return -1;
41700       if( pMem1->u.i > pMem2->u.i ) return 1;
41701       return 0;
41702     }
41703   }
41704
41705   /* If one value is a string and the other is a blob, the string is less.
41706   ** If both are strings, compare using the collating functions.
41707   */
41708   if( combined_flags&MEM_Str ){
41709     if( (f1 & MEM_Str)==0 ){
41710       return 1;
41711     }
41712     if( (f2 & MEM_Str)==0 ){
41713       return -1;
41714     }
41715
41716     assert( pMem1->enc==pMem2->enc );
41717     assert( pMem1->enc==SQLITE_UTF8 || 
41718             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
41719
41720     /* The collation sequence must be defined at this point, even if
41721     ** the user deletes the collation sequence after the vdbe program is
41722     ** compiled (this was not always the case).
41723     */
41724     assert( !pColl || pColl->xCmp );
41725
41726     if( pColl ){
41727       if( pMem1->enc==pColl->enc ){
41728         /* The strings are already in the correct encoding.  Call the
41729         ** comparison function directly */
41730         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
41731       }else{
41732         const void *v1, *v2;
41733         int n1, n2;
41734         Mem c1;
41735         Mem c2;
41736         memset(&c1, 0, sizeof(c1));
41737         memset(&c2, 0, sizeof(c2));
41738         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
41739         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
41740         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
41741         n1 = v1==0 ? 0 : c1.n;
41742         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
41743         n2 = v2==0 ? 0 : c2.n;
41744         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
41745         sqlite3VdbeMemRelease(&c1);
41746         sqlite3VdbeMemRelease(&c2);
41747         return rc;
41748       }
41749     }
41750     /* If a NULL pointer was passed as the collate function, fall through
41751     ** to the blob case and use memcmp().  */
41752   }
41753  
41754   /* Both values must be blobs.  Compare using memcmp().  */
41755   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
41756   if( rc==0 ){
41757     rc = pMem1->n - pMem2->n;
41758   }
41759   return rc;
41760 }
41761
41762 /*
41763 ** Move data out of a btree key or data field and into a Mem structure.
41764 ** The data or key is taken from the entry that pCur is currently pointing
41765 ** to.  offset and amt determine what portion of the data or key to retrieve.
41766 ** key is true to get the key or false to get data.  The result is written
41767 ** into the pMem element.
41768 **
41769 ** The pMem structure is assumed to be uninitialized.  Any prior content
41770 ** is overwritten without being freed.
41771 **
41772 ** If this routine fails for any reason (malloc returns NULL or unable
41773 ** to read from the disk) then the pMem is left in an inconsistent state.
41774 */
41775 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
41776   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
41777   int offset,       /* Offset from the start of data to return bytes from. */
41778   int amt,          /* Number of bytes to return. */
41779   int key,          /* If true, retrieve from the btree key, not data. */
41780   Mem *pMem         /* OUT: Return data in this Mem structure. */
41781 ){
41782   char *zData;       /* Data from the btree layer */
41783   int available = 0; /* Number of bytes available on the local btree page */
41784   sqlite3 *db;       /* Database connection */
41785   int rc = SQLITE_OK;
41786
41787   db = sqlite3BtreeCursorDb(pCur);
41788   assert( sqlite3_mutex_held(db->mutex) );
41789   if( key ){
41790     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
41791   }else{
41792     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
41793   }
41794   assert( zData!=0 );
41795
41796   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
41797     sqlite3VdbeMemRelease(pMem);
41798     pMem->z = &zData[offset];
41799     pMem->flags = MEM_Blob|MEM_Ephem;
41800   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
41801     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
41802     pMem->enc = 0;
41803     pMem->type = SQLITE_BLOB;
41804     if( key ){
41805       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
41806     }else{
41807       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
41808     }
41809     pMem->z[amt] = 0;
41810     pMem->z[amt+1] = 0;
41811     if( rc!=SQLITE_OK ){
41812       sqlite3VdbeMemRelease(pMem);
41813     }
41814   }
41815   pMem->n = amt;
41816
41817   return rc;
41818 }
41819
41820 #if 0
41821 /*
41822 ** Perform various checks on the memory cell pMem. An assert() will
41823 ** fail if pMem is internally inconsistent.
41824 */
41825 SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
41826   int flags = pMem->flags;
41827   assert( flags!=0 );  /* Must define some type */
41828   if( flags & (MEM_Str|MEM_Blob) ){
41829     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
41830     assert( x!=0 );            /* Strings must define a string subtype */
41831     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
41832     assert( pMem->z!=0 );      /* Strings must have a value */
41833     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
41834     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
41835     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
41836     /* No destructor unless there is MEM_Dyn */
41837     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
41838
41839     if( (flags & MEM_Str) ){
41840       assert( pMem->enc==SQLITE_UTF8 || 
41841               pMem->enc==SQLITE_UTF16BE ||
41842               pMem->enc==SQLITE_UTF16LE 
41843       );
41844       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
41845       ** must be the length of the string.  (Later:)  If the database file
41846       ** has been corrupted, '\000' characters might have been inserted
41847       ** into the middle of the string.  In that case, the strlen() might
41848       ** be less.
41849       */
41850       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
41851         assert( strlen(pMem->z)<=pMem->n );
41852         assert( pMem->z[pMem->n]==0 );
41853       }
41854     }
41855   }else{
41856     /* Cannot define a string subtype for non-string objects */
41857     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
41858     assert( pMem->xDel==0 );
41859   }
41860   /* MEM_Null excludes all other types */
41861   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
41862           || (pMem->flags&MEM_Null)==0 );
41863   /* If the MEM is both real and integer, the values are equal */
41864   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
41865           || pMem->r==pMem->u.i );
41866 }
41867 #endif
41868
41869 /* This function is only available internally, it is not part of the
41870 ** external API. It works in a similar way to sqlite3_value_text(),
41871 ** except the data returned is in the encoding specified by the second
41872 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
41873 ** SQLITE_UTF8.
41874 **
41875 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
41876 ** If that is the case, then the result must be aligned on an even byte
41877 ** boundary.
41878 */
41879 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
41880   if( !pVal ) return 0;
41881
41882   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
41883   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
41884
41885   if( pVal->flags&MEM_Null ){
41886     return 0;
41887   }
41888   assert( (MEM_Blob>>3) == MEM_Str );
41889   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
41890   expandBlob(pVal);
41891   if( pVal->flags&MEM_Str ){
41892     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
41893     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
41894       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
41895       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
41896         return 0;
41897       }
41898     }
41899     sqlite3VdbeMemNulTerminate(pVal);
41900   }else{
41901     assert( (pVal->flags&MEM_Blob)==0 );
41902     sqlite3VdbeMemStringify(pVal, enc);
41903     assert( 0==(1&(int)pVal->z) );
41904   }
41905   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
41906               || pVal->db->mallocFailed );
41907   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
41908     return pVal->z;
41909   }else{
41910     return 0;
41911   }
41912 }
41913
41914 /*
41915 ** Create a new sqlite3_value object.
41916 */
41917 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
41918   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
41919   if( p ){
41920     p->flags = MEM_Null;
41921     p->type = SQLITE_NULL;
41922     p->db = db;
41923   }
41924   return p;
41925 }
41926
41927 /*
41928 ** Create a new sqlite3_value object, containing the value of pExpr.
41929 **
41930 ** This only works for very simple expressions that consist of one constant
41931 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
41932 ** be converted directly into a value, then the value is allocated and
41933 ** a pointer written to *ppVal. The caller is responsible for deallocating
41934 ** the value by passing it to sqlite3ValueFree() later on. If the expression
41935 ** cannot be converted to a value, then *ppVal is set to NULL.
41936 */
41937 SQLITE_PRIVATE int sqlite3ValueFromExpr(
41938   sqlite3 *db,              /* The database connection */
41939   Expr *pExpr,              /* The expression to evaluate */
41940   u8 enc,                   /* Encoding to use */
41941   u8 affinity,              /* Affinity to use */
41942   sqlite3_value **ppVal     /* Write the new value here */
41943 ){
41944   int op;
41945   char *zVal = 0;
41946   sqlite3_value *pVal = 0;
41947
41948   if( !pExpr ){
41949     *ppVal = 0;
41950     return SQLITE_OK;
41951   }
41952   op = pExpr->op;
41953
41954   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
41955     zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
41956     pVal = sqlite3ValueNew(db);
41957     if( !zVal || !pVal ) goto no_mem;
41958     sqlite3Dequote(zVal);
41959     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
41960     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
41961       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
41962     }else{
41963       sqlite3ValueApplyAffinity(pVal, affinity, enc);
41964     }
41965   }else if( op==TK_UMINUS ) {
41966     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
41967       pVal->u.i = -1 * pVal->u.i;
41968       pVal->r = -1.0 * pVal->r;
41969     }
41970   }
41971 #ifndef SQLITE_OMIT_BLOB_LITERAL
41972   else if( op==TK_BLOB ){
41973     int nVal;
41974     assert( pExpr->token.n>=3 );
41975     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
41976     assert( pExpr->token.z[1]=='\'' );
41977     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
41978     pVal = sqlite3ValueNew(db);
41979     nVal = pExpr->token.n - 3;
41980     zVal = (char*)pExpr->token.z + 2;
41981     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
41982                          0, SQLITE_DYNAMIC);
41983   }
41984 #endif
41985
41986   *ppVal = pVal;
41987   return SQLITE_OK;
41988
41989 no_mem:
41990   db->mallocFailed = 1;
41991   sqlite3DbFree(db, zVal);
41992   sqlite3ValueFree(pVal);
41993   *ppVal = 0;
41994   return SQLITE_NOMEM;
41995 }
41996
41997 /*
41998 ** Change the string value of an sqlite3_value object
41999 */
42000 SQLITE_PRIVATE void sqlite3ValueSetStr(
42001   sqlite3_value *v,     /* Value to be set */
42002   int n,                /* Length of string z */
42003   const void *z,        /* Text of the new string */
42004   u8 enc,               /* Encoding to use */
42005   void (*xDel)(void*)   /* Destructor for the string */
42006 ){
42007   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
42008 }
42009
42010 /*
42011 ** Free an sqlite3_value object
42012 */
42013 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
42014   if( !v ) return;
42015   sqlite3VdbeMemRelease((Mem *)v);
42016   sqlite3DbFree(((Mem*)v)->db, v);
42017 }
42018
42019 /*
42020 ** Return the number of bytes in the sqlite3_value object assuming
42021 ** that it uses the encoding "enc"
42022 */
42023 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
42024   Mem *p = (Mem*)pVal;
42025   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
42026     if( p->flags & MEM_Zero ){
42027       return p->n+p->u.i;
42028     }else{
42029       return p->n;
42030     }
42031   }
42032   return 0;
42033 }
42034
42035 /************** End of vdbemem.c *********************************************/
42036 /************** Begin file vdbeaux.c *****************************************/
42037 /*
42038 ** 2003 September 6
42039 **
42040 ** The author disclaims copyright to this source code.  In place of
42041 ** a legal notice, here is a blessing:
42042 **
42043 **    May you do good and not evil.
42044 **    May you find forgiveness for yourself and forgive others.
42045 **    May you share freely, never taking more than you give.
42046 **
42047 *************************************************************************
42048 ** This file contains code used for creating, destroying, and populating
42049 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
42050 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
42051 ** But that file was getting too big so this subroutines were split out.
42052 **
42053 ** $Id: vdbeaux.c,v 1.412 2008/10/11 17:51:39 danielk1977 Exp $
42054 */
42055
42056
42057
42058 /*
42059 ** When debugging the code generator in a symbolic debugger, one can
42060 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
42061 ** as they are added to the instruction stream.
42062 */
42063 #ifdef SQLITE_DEBUG
42064 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
42065 #endif
42066
42067
42068 /*
42069 ** Create a new virtual database engine.
42070 */
42071 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
42072   Vdbe *p;
42073   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
42074   if( p==0 ) return 0;
42075   p->db = db;
42076   if( db->pVdbe ){
42077     db->pVdbe->pPrev = p;
42078   }
42079   p->pNext = db->pVdbe;
42080   p->pPrev = 0;
42081   db->pVdbe = p;
42082   p->magic = VDBE_MAGIC_INIT;
42083   return p;
42084 }
42085
42086 /*
42087 ** Remember the SQL string for a prepared statement.
42088 */
42089 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
42090   if( p==0 ) return;
42091   assert( p->zSql==0 );
42092   p->zSql = sqlite3DbStrNDup(p->db, z, n);
42093 }
42094
42095 /*
42096 ** Return the SQL associated with a prepared statement
42097 */
42098 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
42099   return ((Vdbe *)pStmt)->zSql;
42100 }
42101
42102 /*
42103 ** Swap all content between two VDBE structures.
42104 */
42105 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
42106   Vdbe tmp, *pTmp;
42107   char *zTmp;
42108   int nTmp;
42109   tmp = *pA;
42110   *pA = *pB;
42111   *pB = tmp;
42112   pTmp = pA->pNext;
42113   pA->pNext = pB->pNext;
42114   pB->pNext = pTmp;
42115   pTmp = pA->pPrev;
42116   pA->pPrev = pB->pPrev;
42117   pB->pPrev = pTmp;
42118   zTmp = pA->zSql;
42119   pA->zSql = pB->zSql;
42120   pB->zSql = zTmp;
42121   nTmp = pA->nSql;
42122   pA->nSql = pB->nSql;
42123   pB->nSql = nTmp;
42124 }
42125
42126 #ifdef SQLITE_DEBUG
42127 /*
42128 ** Turn tracing on or off
42129 */
42130 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
42131   p->trace = trace;
42132 }
42133 #endif
42134
42135 /*
42136 ** Resize the Vdbe.aOp array so that it contains at least N
42137 ** elements.
42138 **
42139 ** If an out-of-memory error occurs while resizing the array,
42140 ** Vdbe.aOp and Vdbe.nOpAlloc remain unchanged (this is so that
42141 ** any opcodes already allocated can be correctly deallocated
42142 ** along with the rest of the Vdbe).
42143 */
42144 static void resizeOpArray(Vdbe *p, int N){
42145   VdbeOp *pNew;
42146   pNew = sqlite3DbRealloc(p->db, p->aOp, N*sizeof(Op));
42147   if( pNew ){
42148     p->nOpAlloc = N;
42149     p->aOp = pNew;
42150   }
42151 }
42152
42153 /*
42154 ** Add a new instruction to the list of instructions current in the
42155 ** VDBE.  Return the address of the new instruction.
42156 **
42157 ** Parameters:
42158 **
42159 **    p               Pointer to the VDBE
42160 **
42161 **    op              The opcode for this instruction
42162 **
42163 **    p1, p2, p3      Operands
42164 **
42165 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
42166 ** the sqlite3VdbeChangeP4() function to change the value of the P4
42167 ** operand.
42168 */
42169 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
42170   int i;
42171   VdbeOp *pOp;
42172
42173   i = p->nOp;
42174   assert( p->magic==VDBE_MAGIC_INIT );
42175   if( p->nOpAlloc<=i ){
42176     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
42177     if( p->db->mallocFailed ){
42178       return 0;
42179     }
42180   }
42181   p->nOp++;
42182   pOp = &p->aOp[i];
42183   pOp->opcode = op;
42184   pOp->p5 = 0;
42185   pOp->p1 = p1;
42186   pOp->p2 = p2;
42187   pOp->p3 = p3;
42188   pOp->p4.p = 0;
42189   pOp->p4type = P4_NOTUSED;
42190   p->expired = 0;
42191 #ifdef SQLITE_DEBUG
42192   pOp->zComment = 0;
42193   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
42194 #endif
42195 #ifdef VDBE_PROFILE
42196   pOp->cycles = 0;
42197   pOp->cnt = 0;
42198 #endif
42199   return i;
42200 }
42201 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
42202   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
42203 }
42204 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
42205   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
42206 }
42207 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
42208   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
42209 }
42210
42211
42212 /*
42213 ** Add an opcode that includes the p4 value as a pointer.
42214 */
42215 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
42216   Vdbe *p,            /* Add the opcode to this VM */
42217   int op,             /* The new opcode */
42218   int p1,             /* The P1 operand */
42219   int p2,             /* The P2 operand */
42220   int p3,             /* The P3 operand */
42221   const char *zP4,    /* The P4 operand */
42222   int p4type          /* P4 operand type */
42223 ){
42224   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
42225   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
42226   return addr;
42227 }
42228
42229 /*
42230 ** Create a new symbolic label for an instruction that has yet to be
42231 ** coded.  The symbolic label is really just a negative number.  The
42232 ** label can be used as the P2 value of an operation.  Later, when
42233 ** the label is resolved to a specific address, the VDBE will scan
42234 ** through its operation list and change all values of P2 which match
42235 ** the label into the resolved address.
42236 **
42237 ** The VDBE knows that a P2 value is a label because labels are
42238 ** always negative and P2 values are suppose to be non-negative.
42239 ** Hence, a negative P2 value is a label that has yet to be resolved.
42240 **
42241 ** Zero is returned if a malloc() fails.
42242 */
42243 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
42244   int i;
42245   i = p->nLabel++;
42246   assert( p->magic==VDBE_MAGIC_INIT );
42247   if( i>=p->nLabelAlloc ){
42248     p->nLabelAlloc = p->nLabelAlloc*2 + 10;
42249     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
42250                                     p->nLabelAlloc*sizeof(p->aLabel[0]));
42251   }
42252   if( p->aLabel ){
42253     p->aLabel[i] = -1;
42254   }
42255   return -1-i;
42256 }
42257
42258 /*
42259 ** Resolve label "x" to be the address of the next instruction to
42260 ** be inserted.  The parameter "x" must have been obtained from
42261 ** a prior call to sqlite3VdbeMakeLabel().
42262 */
42263 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
42264   int j = -1-x;
42265   assert( p->magic==VDBE_MAGIC_INIT );
42266   assert( j>=0 && j<p->nLabel );
42267   if( p->aLabel ){
42268     p->aLabel[j] = p->nOp;
42269   }
42270 }
42271
42272 /*
42273 ** Loop through the program looking for P2 values that are negative
42274 ** on jump instructions.  Each such value is a label.  Resolve the
42275 ** label by setting the P2 value to its correct non-zero value.
42276 **
42277 ** This routine is called once after all opcodes have been inserted.
42278 **
42279 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
42280 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
42281 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
42282 **
42283 ** This routine also does the following optimization:  It scans for
42284 ** instructions that might cause a statement rollback.  Such instructions
42285 ** are:
42286 **
42287 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
42288 **   *  OP_Destroy
42289 **   *  OP_VUpdate
42290 **   *  OP_VRename
42291 **
42292 ** If no such instruction is found, then every Statement instruction 
42293 ** is changed to a Noop.  In this way, we avoid creating the statement 
42294 ** journal file unnecessarily.
42295 */
42296 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
42297   int i;
42298   int nMaxArgs = 0;
42299   Op *pOp;
42300   int *aLabel = p->aLabel;
42301   int doesStatementRollback = 0;
42302   int hasStatementBegin = 0;
42303   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42304     u8 opcode = pOp->opcode;
42305
42306     if( opcode==OP_Function || opcode==OP_AggStep ){
42307       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
42308 #ifndef SQLITE_OMIT_VIRTUALTABLE
42309     }else if( opcode==OP_VUpdate ){
42310       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
42311 #endif
42312     }
42313     if( opcode==OP_Halt ){
42314       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
42315         doesStatementRollback = 1;
42316       }
42317     }else if( opcode==OP_Statement ){
42318       hasStatementBegin = 1;
42319     }else if( opcode==OP_Destroy ){
42320       doesStatementRollback = 1;
42321 #ifndef SQLITE_OMIT_VIRTUALTABLE
42322     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
42323       doesStatementRollback = 1;
42324     }else if( opcode==OP_VFilter ){
42325       int n;
42326       assert( p->nOp - i >= 3 );
42327       assert( pOp[-1].opcode==OP_Integer );
42328       n = pOp[-1].p1;
42329       if( n>nMaxArgs ) nMaxArgs = n;
42330 #endif
42331     }
42332
42333     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
42334       assert( -1-pOp->p2<p->nLabel );
42335       pOp->p2 = aLabel[-1-pOp->p2];
42336     }
42337   }
42338   sqlite3DbFree(p->db, p->aLabel);
42339   p->aLabel = 0;
42340
42341   *pMaxFuncArgs = nMaxArgs;
42342
42343   /* If we never rollback a statement transaction, then statement
42344   ** transactions are not needed.  So change every OP_Statement
42345   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
42346   ** which can be expensive on some platforms.
42347   */
42348   if( hasStatementBegin && !doesStatementRollback ){
42349     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
42350       if( pOp->opcode==OP_Statement ){
42351         pOp->opcode = OP_Noop;
42352       }
42353     }
42354   }
42355 }
42356
42357 /*
42358 ** Return the address of the next instruction to be inserted.
42359 */
42360 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
42361   assert( p->magic==VDBE_MAGIC_INIT );
42362   return p->nOp;
42363 }
42364
42365 /*
42366 ** Add a whole list of operations to the operation stack.  Return the
42367 ** address of the first operation added.
42368 */
42369 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
42370   int addr;
42371   assert( p->magic==VDBE_MAGIC_INIT );
42372   if( p->nOp + nOp > p->nOpAlloc ){
42373     resizeOpArray(p, p->nOpAlloc ? p->nOpAlloc*2 : 1024/sizeof(Op));
42374     assert( p->nOp+nOp<=p->nOpAlloc || p->db->mallocFailed );
42375   }
42376   if( p->db->mallocFailed ){
42377     return 0;
42378   }
42379   addr = p->nOp;
42380   if( nOp>0 ){
42381     int i;
42382     VdbeOpList const *pIn = aOp;
42383     for(i=0; i<nOp; i++, pIn++){
42384       int p2 = pIn->p2;
42385       VdbeOp *pOut = &p->aOp[i+addr];
42386       pOut->opcode = pIn->opcode;
42387       pOut->p1 = pIn->p1;
42388       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
42389         pOut->p2 = addr + ADDR(p2);
42390       }else{
42391         pOut->p2 = p2;
42392       }
42393       pOut->p3 = pIn->p3;
42394       pOut->p4type = P4_NOTUSED;
42395       pOut->p4.p = 0;
42396       pOut->p5 = 0;
42397 #ifdef SQLITE_DEBUG
42398       pOut->zComment = 0;
42399       if( sqlite3VdbeAddopTrace ){
42400         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
42401       }
42402 #endif
42403     }
42404     p->nOp += nOp;
42405   }
42406   return addr;
42407 }
42408
42409 /*
42410 ** Change the value of the P1 operand for a specific instruction.
42411 ** This routine is useful when a large program is loaded from a
42412 ** static array using sqlite3VdbeAddOpList but we want to make a
42413 ** few minor changes to the program.
42414 */
42415 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
42416   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42417   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42418     p->aOp[addr].p1 = val;
42419   }
42420 }
42421
42422 /*
42423 ** Change the value of the P2 operand for a specific instruction.
42424 ** This routine is useful for setting a jump destination.
42425 */
42426 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
42427   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42428   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42429     p->aOp[addr].p2 = val;
42430   }
42431 }
42432
42433 /*
42434 ** Change the value of the P3 operand for a specific instruction.
42435 */
42436 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
42437   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42438   if( p && addr>=0 && p->nOp>addr && p->aOp ){
42439     p->aOp[addr].p3 = val;
42440   }
42441 }
42442
42443 /*
42444 ** Change the value of the P5 operand for the most recently
42445 ** added operation.
42446 */
42447 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
42448   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
42449   if( p && p->aOp ){
42450     assert( p->nOp>0 );
42451     p->aOp[p->nOp-1].p5 = val;
42452   }
42453 }
42454
42455 /*
42456 ** Change the P2 operand of instruction addr so that it points to
42457 ** the address of the next instruction to be coded.
42458 */
42459 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
42460   sqlite3VdbeChangeP2(p, addr, p->nOp);
42461 }
42462
42463
42464 /*
42465 ** If the input FuncDef structure is ephemeral, then free it.  If
42466 ** the FuncDef is not ephermal, then do nothing.
42467 */
42468 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
42469   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
42470     sqlite3DbFree(db, pDef);
42471   }
42472 }
42473
42474 /*
42475 ** Delete a P4 value if necessary.
42476 */
42477 static void freeP4(sqlite3 *db, int p4type, void *p4){
42478   if( p4 ){
42479     switch( p4type ){
42480       case P4_REAL:
42481       case P4_INT64:
42482       case P4_MPRINTF:
42483       case P4_DYNAMIC:
42484       case P4_KEYINFO:
42485       case P4_INTARRAY:
42486       case P4_KEYINFO_HANDOFF: {
42487         sqlite3DbFree(db, p4);
42488         break;
42489       }
42490       case P4_VDBEFUNC: {
42491         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
42492         freeEphemeralFunction(db, pVdbeFunc->pFunc);
42493         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
42494         sqlite3DbFree(db, pVdbeFunc);
42495         break;
42496       }
42497       case P4_FUNCDEF: {
42498         freeEphemeralFunction(db, (FuncDef*)p4);
42499         break;
42500       }
42501       case P4_MEM: {
42502         sqlite3ValueFree((sqlite3_value*)p4);
42503         break;
42504       }
42505     }
42506   }
42507 }
42508
42509
42510 /*
42511 ** Change N opcodes starting at addr to No-ops.
42512 */
42513 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
42514   if( p && p->aOp ){
42515     VdbeOp *pOp = &p->aOp[addr];
42516     sqlite3 *db = p->db;
42517     while( N-- ){
42518       freeP4(db, pOp->p4type, pOp->p4.p);
42519       memset(pOp, 0, sizeof(pOp[0]));
42520       pOp->opcode = OP_Noop;
42521       pOp++;
42522     }
42523   }
42524 }
42525
42526 /*
42527 ** Change the value of the P4 operand for a specific instruction.
42528 ** This routine is useful when a large program is loaded from a
42529 ** static array using sqlite3VdbeAddOpList but we want to make a
42530 ** few minor changes to the program.
42531 **
42532 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
42533 ** the string is made into memory obtained from sqlite3_malloc().
42534 ** A value of n==0 means copy bytes of zP4 up to and including the
42535 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
42536 **
42537 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
42538 ** A copy is made of the KeyInfo structure into memory obtained from
42539 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
42540 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
42541 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
42542 ** caller should not free the allocation, it will be freed when the Vdbe is
42543 ** finalized.
42544 ** 
42545 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
42546 ** to a string or structure that is guaranteed to exist for the lifetime of
42547 ** the Vdbe. In these cases we can just copy the pointer.
42548 **
42549 ** If addr<0 then change P4 on the most recently inserted instruction.
42550 */
42551 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
42552   Op *pOp;
42553   sqlite3 *db;
42554   assert( p!=0 );
42555   db = p->db;
42556   assert( p->magic==VDBE_MAGIC_INIT );
42557   if( p->aOp==0 || db->mallocFailed ){
42558     if (n != P4_KEYINFO) {
42559       freeP4(db, n, (void*)*(char**)&zP4);
42560     }
42561     return;
42562   }
42563   assert( addr<p->nOp );
42564   if( addr<0 ){
42565     addr = p->nOp - 1;
42566     if( addr<0 ) return;
42567   }
42568   pOp = &p->aOp[addr];
42569   freeP4(db, pOp->p4type, pOp->p4.p);
42570   pOp->p4.p = 0;
42571   if( n==P4_INT32 ){
42572     /* Note: this cast is safe, because the origin data point was an int
42573     ** that was cast to a (const char *). */
42574     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
42575     pOp->p4type = n;
42576   }else if( zP4==0 ){
42577     pOp->p4.p = 0;
42578     pOp->p4type = P4_NOTUSED;
42579   }else if( n==P4_KEYINFO ){
42580     KeyInfo *pKeyInfo;
42581     int nField, nByte;
42582
42583     nField = ((KeyInfo*)zP4)->nField;
42584     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
42585     pKeyInfo = sqlite3Malloc( nByte );
42586     pOp->p4.pKeyInfo = pKeyInfo;
42587     if( pKeyInfo ){
42588       u8 *aSortOrder;
42589       memcpy(pKeyInfo, zP4, nByte);
42590       aSortOrder = pKeyInfo->aSortOrder;
42591       if( aSortOrder ){
42592         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
42593         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
42594       }
42595       pOp->p4type = P4_KEYINFO;
42596     }else{
42597       p->db->mallocFailed = 1;
42598       pOp->p4type = P4_NOTUSED;
42599     }
42600   }else if( n==P4_KEYINFO_HANDOFF ){
42601     pOp->p4.p = (void*)zP4;
42602     pOp->p4type = P4_KEYINFO;
42603   }else if( n<0 ){
42604     pOp->p4.p = (void*)zP4;
42605     pOp->p4type = n;
42606   }else{
42607     if( n==0 ) n = strlen(zP4);
42608     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
42609     pOp->p4type = P4_DYNAMIC;
42610   }
42611 }
42612
42613 #ifndef NDEBUG
42614 /*
42615 ** Change the comment on the the most recently coded instruction.  Or
42616 ** insert a No-op and add the comment to that new instruction.  This
42617 ** makes the code easier to read during debugging.  None of this happens
42618 ** in a production build.
42619 */
42620 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
42621   va_list ap;
42622   assert( p->nOp>0 || p->aOp==0 );
42623   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
42624   if( p->nOp ){
42625     char **pz = &p->aOp[p->nOp-1].zComment;
42626     va_start(ap, zFormat);
42627     sqlite3DbFree(p->db, *pz);
42628     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
42629     va_end(ap);
42630   }
42631 }
42632 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
42633   va_list ap;
42634   sqlite3VdbeAddOp0(p, OP_Noop);
42635   assert( p->nOp>0 || p->aOp==0 );
42636   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
42637   if( p->nOp ){
42638     char **pz = &p->aOp[p->nOp-1].zComment;
42639     va_start(ap, zFormat);
42640     sqlite3DbFree(p->db, *pz);
42641     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
42642     va_end(ap);
42643   }
42644 }
42645 #endif  /* NDEBUG */
42646
42647 /*
42648 ** Return the opcode for a given address.
42649 */
42650 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
42651   assert( p->magic==VDBE_MAGIC_INIT );
42652   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
42653   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
42654 }
42655
42656 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
42657      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
42658 /*
42659 ** Compute a string that describes the P4 parameter for an opcode.
42660 ** Use zTemp for any required temporary buffer space.
42661 */
42662 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
42663   char *zP4 = zTemp;
42664   assert( nTemp>=20 );
42665   switch( pOp->p4type ){
42666     case P4_KEYINFO_STATIC:
42667     case P4_KEYINFO: {
42668       int i, j;
42669       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
42670       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
42671       i = strlen(zTemp);
42672       for(j=0; j<pKeyInfo->nField; j++){
42673         CollSeq *pColl = pKeyInfo->aColl[j];
42674         if( pColl ){
42675           int n = strlen(pColl->zName);
42676           if( i+n>nTemp-6 ){
42677             memcpy(&zTemp[i],",...",4);
42678             break;
42679           }
42680           zTemp[i++] = ',';
42681           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
42682             zTemp[i++] = '-';
42683           }
42684           memcpy(&zTemp[i], pColl->zName,n+1);
42685           i += n;
42686         }else if( i+4<nTemp-6 ){
42687           memcpy(&zTemp[i],",nil",4);
42688           i += 4;
42689         }
42690       }
42691       zTemp[i++] = ')';
42692       zTemp[i] = 0;
42693       assert( i<nTemp );
42694       break;
42695     }
42696     case P4_COLLSEQ: {
42697       CollSeq *pColl = pOp->p4.pColl;
42698       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
42699       break;
42700     }
42701     case P4_FUNCDEF: {
42702       FuncDef *pDef = pOp->p4.pFunc;
42703       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
42704       break;
42705     }
42706     case P4_INT64: {
42707       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
42708       break;
42709     }
42710     case P4_INT32: {
42711       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
42712       break;
42713     }
42714     case P4_REAL: {
42715       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
42716       break;
42717     }
42718     case P4_MEM: {
42719       Mem *pMem = pOp->p4.pMem;
42720       assert( (pMem->flags & MEM_Null)==0 );
42721       if( pMem->flags & MEM_Str ){
42722         zP4 = pMem->z;
42723       }else if( pMem->flags & MEM_Int ){
42724         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
42725       }else if( pMem->flags & MEM_Real ){
42726         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
42727       }
42728       break;
42729     }
42730 #ifndef SQLITE_OMIT_VIRTUALTABLE
42731     case P4_VTAB: {
42732       sqlite3_vtab *pVtab = pOp->p4.pVtab;
42733       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
42734       break;
42735     }
42736 #endif
42737     case P4_INTARRAY: {
42738       sqlite3_snprintf(nTemp, zTemp, "intarray");
42739       break;
42740     }
42741     default: {
42742       zP4 = pOp->p4.z;
42743       if( zP4==0 ){
42744         zP4 = zTemp;
42745         zTemp[0] = 0;
42746       }
42747     }
42748   }
42749   assert( zP4!=0 );
42750   return zP4;
42751 }
42752 #endif
42753
42754 /*
42755 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
42756 **
42757 */
42758 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
42759   int mask;
42760   assert( i>=0 && i<p->db->nDb );
42761   assert( i<sizeof(p->btreeMask)*8 );
42762   mask = 1<<i;
42763   if( (p->btreeMask & mask)==0 ){
42764     p->btreeMask |= mask;
42765     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
42766   }
42767 }
42768
42769
42770 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
42771 /*
42772 ** Print a single opcode.  This routine is used for debugging only.
42773 */
42774 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
42775   char *zP4;
42776   char zPtr[50];
42777   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
42778   if( pOut==0 ) pOut = stdout;
42779   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
42780   fprintf(pOut, zFormat1, pc, 
42781       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
42782 #ifdef SQLITE_DEBUG
42783       pOp->zComment ? pOp->zComment : ""
42784 #else
42785       ""
42786 #endif
42787   );
42788   fflush(pOut);
42789 }
42790 #endif
42791
42792 /*
42793 ** Release an array of N Mem elements
42794 */
42795 static void releaseMemArray(Mem *p, int N){
42796   if( p && N ){
42797     Mem *pEnd;
42798     sqlite3 *db = p->db;
42799     int malloc_failed = db->mallocFailed;
42800     for(pEnd=&p[N]; p<pEnd; p++){
42801       assert( (&p[1])==pEnd || p[0].db==p[1].db );
42802
42803       /* This block is really an inlined version of sqlite3VdbeMemRelease()
42804       ** that takes advantage of the fact that the memory cell value is 
42805       ** being set to NULL after releasing any dynamic resources.
42806       **
42807       ** The justification for duplicating code is that according to 
42808       ** callgrind, this causes a certain test case to hit the CPU 4.7 
42809       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
42810       ** sqlite3MemRelease() were called from here. With -O2, this jumps
42811       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
42812       ** with no indexes using a single prepared INSERT statement, bind() 
42813       ** and reset(). Inserts are grouped into a transaction.
42814       */
42815       if( p->flags&(MEM_Agg|MEM_Dyn) ){
42816         sqlite3VdbeMemRelease(p);
42817       }else if( p->zMalloc ){
42818         sqlite3DbFree(db, p->zMalloc);
42819         p->zMalloc = 0;
42820       }
42821
42822       p->flags = MEM_Null;
42823     }
42824     db->mallocFailed = malloc_failed;
42825   }
42826 }
42827
42828 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
42829 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
42830   int ii;
42831   int nFree = 0;
42832   assert( sqlite3_mutex_held(p->db->mutex) );
42833   for(ii=1; ii<=p->nMem; ii++){
42834     Mem *pMem = &p->aMem[ii];
42835     if( pMem->z && pMem->flags&MEM_Dyn ){
42836       assert( !pMem->xDel );
42837       nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
42838       sqlite3VdbeMemRelease(pMem);
42839     }
42840   }
42841   return nFree;
42842 }
42843 #endif
42844
42845 #ifndef SQLITE_OMIT_EXPLAIN
42846 /*
42847 ** Give a listing of the program in the virtual machine.
42848 **
42849 ** The interface is the same as sqlite3VdbeExec().  But instead of
42850 ** running the code, it invokes the callback once for each instruction.
42851 ** This feature is used to implement "EXPLAIN".
42852 **
42853 ** When p->explain==1, each instruction is listed.  When
42854 ** p->explain==2, only OP_Explain instructions are listed and these
42855 ** are shown in a different format.  p->explain==2 is used to implement
42856 ** EXPLAIN QUERY PLAN.
42857 */
42858 SQLITE_PRIVATE int sqlite3VdbeList(
42859   Vdbe *p                   /* The VDBE */
42860 ){
42861   sqlite3 *db = p->db;
42862   int i;
42863   int rc = SQLITE_OK;
42864   Mem *pMem = p->pResultSet = &p->aMem[1];
42865
42866   assert( p->explain );
42867   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
42868   assert( db->magic==SQLITE_MAGIC_BUSY );
42869   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
42870
42871   /* Even though this opcode does not use dynamic strings for
42872   ** the result, result columns may become dynamic if the user calls
42873   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
42874   */
42875   releaseMemArray(pMem, p->nMem);
42876
42877   do{
42878     i = p->pc++;
42879   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
42880   if( i>=p->nOp ){
42881     p->rc = SQLITE_OK;
42882     rc = SQLITE_DONE;
42883   }else if( db->u1.isInterrupted ){
42884     p->rc = SQLITE_INTERRUPT;
42885     rc = SQLITE_ERROR;
42886     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
42887   }else{
42888     char *z;
42889     Op *pOp = &p->aOp[i];
42890     if( p->explain==1 ){
42891       pMem->flags = MEM_Int;
42892       pMem->type = SQLITE_INTEGER;
42893       pMem->u.i = i;                                /* Program counter */
42894       pMem++;
42895   
42896       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
42897       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
42898       assert( pMem->z!=0 );
42899       pMem->n = strlen(pMem->z);
42900       pMem->type = SQLITE_TEXT;
42901       pMem->enc = SQLITE_UTF8;
42902       pMem++;
42903     }
42904
42905     pMem->flags = MEM_Int;
42906     pMem->u.i = pOp->p1;                          /* P1 */
42907     pMem->type = SQLITE_INTEGER;
42908     pMem++;
42909
42910     pMem->flags = MEM_Int;
42911     pMem->u.i = pOp->p2;                          /* P2 */
42912     pMem->type = SQLITE_INTEGER;
42913     pMem++;
42914
42915     if( p->explain==1 ){
42916       pMem->flags = MEM_Int;
42917       pMem->u.i = pOp->p3;                          /* P3 */
42918       pMem->type = SQLITE_INTEGER;
42919       pMem++;
42920     }
42921
42922     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
42923       p->db->mallocFailed = 1;
42924       return SQLITE_NOMEM;
42925     }
42926     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
42927     z = displayP4(pOp, pMem->z, 32);
42928     if( z!=pMem->z ){
42929       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
42930     }else{
42931       assert( pMem->z!=0 );
42932       pMem->n = strlen(pMem->z);
42933       pMem->enc = SQLITE_UTF8;
42934     }
42935     pMem->type = SQLITE_TEXT;
42936     pMem++;
42937
42938     if( p->explain==1 ){
42939       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
42940         p->db->mallocFailed = 1;
42941         return SQLITE_NOMEM;
42942       }
42943       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
42944       pMem->n = 2;
42945       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
42946       pMem->type = SQLITE_TEXT;
42947       pMem->enc = SQLITE_UTF8;
42948       pMem++;
42949   
42950 #ifdef SQLITE_DEBUG
42951       if( pOp->zComment ){
42952         pMem->flags = MEM_Str|MEM_Term;
42953         pMem->z = pOp->zComment;
42954         pMem->n = strlen(pMem->z);
42955         pMem->enc = SQLITE_UTF8;
42956         pMem->type = SQLITE_TEXT;
42957       }else
42958 #endif
42959       {
42960         pMem->flags = MEM_Null;                       /* Comment */
42961         pMem->type = SQLITE_NULL;
42962       }
42963     }
42964
42965     p->nResColumn = 8 - 5*(p->explain-1);
42966     p->rc = SQLITE_OK;
42967     rc = SQLITE_ROW;
42968   }
42969   return rc;
42970 }
42971 #endif /* SQLITE_OMIT_EXPLAIN */
42972
42973 #ifdef SQLITE_DEBUG
42974 /*
42975 ** Print the SQL that was used to generate a VDBE program.
42976 */
42977 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
42978   int nOp = p->nOp;
42979   VdbeOp *pOp;
42980   if( nOp<1 ) return;
42981   pOp = &p->aOp[0];
42982   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
42983     const char *z = pOp->p4.z;
42984     while( isspace(*(u8*)z) ) z++;
42985     printf("SQL: [%s]\n", z);
42986   }
42987 }
42988 #endif
42989
42990 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
42991 /*
42992 ** Print an IOTRACE message showing SQL content.
42993 */
42994 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
42995   int nOp = p->nOp;
42996   VdbeOp *pOp;
42997   if( sqlite3IoTrace==0 ) return;
42998   if( nOp<1 ) return;
42999   pOp = &p->aOp[0];
43000   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
43001     int i, j;
43002     char z[1000];
43003     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
43004     for(i=0; isspace((unsigned char)z[i]); i++){}
43005     for(j=0; z[i]; i++){
43006       if( isspace((unsigned char)z[i]) ){
43007         if( z[i-1]!=' ' ){
43008           z[j++] = ' ';
43009         }
43010       }else{
43011         z[j++] = z[i];
43012       }
43013     }
43014     z[j] = 0;
43015     sqlite3IoTrace("SQL %s\n", z);
43016   }
43017 }
43018 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
43019
43020
43021 /*
43022 ** Prepare a virtual machine for execution.  This involves things such
43023 ** as allocating stack space and initializing the program counter.
43024 ** After the VDBE has be prepped, it can be executed by one or more
43025 ** calls to sqlite3VdbeExec().  
43026 **
43027 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
43028 ** VDBE_MAGIC_RUN.
43029 */
43030 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
43031   Vdbe *p,                       /* The VDBE */
43032   int nVar,                      /* Number of '?' see in the SQL statement */
43033   int nMem,                      /* Number of memory cells to allocate */
43034   int nCursor,                   /* Number of cursors to allocate */
43035   int isExplain                  /* True if the EXPLAIN keywords is present */
43036 ){
43037   int n;
43038   sqlite3 *db = p->db;
43039
43040   assert( p!=0 );
43041   assert( p->magic==VDBE_MAGIC_INIT );
43042
43043   /* There should be at least one opcode.
43044   */
43045   assert( p->nOp>0 );
43046
43047   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. This
43048    * is because the call to resizeOpArray() below may shrink the
43049    * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN 
43050    * state.
43051    */
43052   p->magic = VDBE_MAGIC_RUN;
43053
43054   /* For each cursor required, also allocate a memory cell. Memory
43055   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
43056   ** the vdbe program. Instead they are used to allocate space for
43057   ** Cursor/BtCursor structures. The blob of memory associated with 
43058   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
43059   ** stores the blob of memory associated with cursor 1, etc.
43060   **
43061   ** See also: allocateCursor().
43062   */
43063   nMem += nCursor;
43064
43065   /*
43066   ** Allocation space for registers.
43067   */
43068   if( p->aMem==0 ){
43069     int nArg;       /* Maximum number of args passed to a user function. */
43070     resolveP2Values(p, &nArg);
43071     /*resizeOpArray(p, p->nOp);*/
43072     assert( nVar>=0 );
43073     if( isExplain && nMem<10 ){
43074       p->nMem = nMem = 10;
43075     }
43076     p->aMem = sqlite3DbMallocZero(db,
43077         nMem*sizeof(Mem)               /* aMem */
43078       + nVar*sizeof(Mem)               /* aVar */
43079       + nArg*sizeof(Mem*)              /* apArg */
43080       + nVar*sizeof(char*)             /* azVar */
43081       + nCursor*sizeof(Cursor*) + 1    /* apCsr */
43082     );
43083     if( !db->mallocFailed ){
43084       p->aMem--;             /* aMem[] goes from 1..nMem */
43085       p->nMem = nMem;        /*       not from 0..nMem-1 */
43086       p->aVar = &p->aMem[nMem+1];
43087       p->nVar = nVar;
43088       p->okVar = 0;
43089       p->apArg = (Mem**)&p->aVar[nVar];
43090       p->azVar = (char**)&p->apArg[nArg];
43091       p->apCsr = (Cursor**)&p->azVar[nVar];
43092       p->nCursor = nCursor;
43093       for(n=0; n<nVar; n++){
43094         p->aVar[n].flags = MEM_Null;
43095         p->aVar[n].db = db;
43096       }
43097       for(n=1; n<=nMem; n++){
43098         p->aMem[n].flags = MEM_Null;
43099         p->aMem[n].db = db;
43100       }
43101     }
43102   }
43103 #ifdef SQLITE_DEBUG
43104   for(n=1; n<p->nMem; n++){
43105     assert( p->aMem[n].db==db );
43106   }
43107 #endif
43108
43109   p->pc = -1;
43110   p->rc = SQLITE_OK;
43111   p->uniqueCnt = 0;
43112   p->errorAction = OE_Abort;
43113   p->explain |= isExplain;
43114   p->magic = VDBE_MAGIC_RUN;
43115   p->nChange = 0;
43116   p->cacheCtr = 1;
43117   p->minWriteFileFormat = 255;
43118   p->openedStatement = 0;
43119 #ifdef VDBE_PROFILE
43120   {
43121     int i;
43122     for(i=0; i<p->nOp; i++){
43123       p->aOp[i].cnt = 0;
43124       p->aOp[i].cycles = 0;
43125     }
43126   }
43127 #endif
43128 }
43129
43130 /*
43131 ** Close a VDBE cursor and release all the resources that cursor 
43132 ** happens to hold.
43133 */
43134 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
43135   if( pCx==0 ){
43136     return;
43137   }
43138   if( pCx->pBt ){
43139     sqlite3BtreeClose(pCx->pBt);
43140     /* The pCx->pCursor will be close automatically, if it exists, by
43141     ** the call above. */
43142   }else if( pCx->pCursor ){
43143     sqlite3BtreeCloseCursor(pCx->pCursor);
43144   }
43145 #ifndef SQLITE_OMIT_VIRTUALTABLE
43146   if( pCx->pVtabCursor ){
43147     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
43148     const sqlite3_module *pModule = pCx->pModule;
43149     p->inVtabMethod = 1;
43150     (void)sqlite3SafetyOff(p->db);
43151     pModule->xClose(pVtabCursor);
43152     (void)sqlite3SafetyOn(p->db);
43153     p->inVtabMethod = 0;
43154   }
43155 #endif
43156   if( !pCx->ephemPseudoTable ){
43157     sqlite3DbFree(p->db, pCx->pData);
43158   }
43159 }
43160
43161 /*
43162 ** Close all cursors except for VTab cursors that are currently
43163 ** in use.
43164 */
43165 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
43166   int i;
43167   if( p->apCsr==0 ) return;
43168   for(i=0; i<p->nCursor; i++){
43169     Cursor *pC = p->apCsr[i];
43170     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
43171       sqlite3VdbeFreeCursor(p, pC);
43172       p->apCsr[i] = 0;
43173     }
43174   }
43175 }
43176
43177 /*
43178 ** Clean up the VM after execution.
43179 **
43180 ** This routine will automatically close any cursors, lists, and/or
43181 ** sorters that were left open.  It also deletes the values of
43182 ** variables in the aVar[] array.
43183 */
43184 static void Cleanup(Vdbe *p){
43185   int i;
43186   sqlite3 *db = p->db;
43187   closeAllCursorsExceptActiveVtabs(p);
43188   for(i=1; i<=p->nMem; i++){
43189     MemSetTypeFlag(&p->aMem[i], MEM_Null);
43190   }
43191   releaseMemArray(&p->aMem[1], p->nMem);
43192   sqlite3VdbeFifoClear(&p->sFifo);
43193   if( p->contextStack ){
43194     for(i=0; i<p->contextStackTop; i++){
43195       sqlite3VdbeFifoClear(&p->contextStack[i].sFifo);
43196     }
43197     sqlite3DbFree(db, p->contextStack);
43198   }
43199   p->contextStack = 0;
43200   p->contextStackDepth = 0;
43201   p->contextStackTop = 0;
43202   sqlite3DbFree(db, p->zErrMsg);
43203   p->zErrMsg = 0;
43204   p->pResultSet = 0;
43205 }
43206
43207 /*
43208 ** Set the number of result columns that will be returned by this SQL
43209 ** statement. This is now set at compile time, rather than during
43210 ** execution of the vdbe program so that sqlite3_column_count() can
43211 ** be called on an SQL statement before sqlite3_step().
43212 */
43213 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
43214   Mem *pColName;
43215   int n;
43216   sqlite3 *db = p->db;
43217
43218   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
43219   sqlite3DbFree(db, p->aColName);
43220   n = nResColumn*COLNAME_N;
43221   p->nResColumn = nResColumn;
43222   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
43223   if( p->aColName==0 ) return;
43224   while( n-- > 0 ){
43225     pColName->flags = MEM_Null;
43226     pColName->db = p->db;
43227     pColName++;
43228   }
43229 }
43230
43231 /*
43232 ** Set the name of the idx'th column to be returned by the SQL statement.
43233 ** zName must be a pointer to a nul terminated string.
43234 **
43235 ** This call must be made after a call to sqlite3VdbeSetNumCols().
43236 **
43237 ** If N==P4_STATIC  it means that zName is a pointer to a constant static
43238 ** string and we can just copy the pointer. If it is P4_DYNAMIC, then 
43239 ** the string is freed using sqlite3DbFree(db, ) when the vdbe is finished with
43240 ** it. Otherwise, N bytes of zName are copied.
43241 */
43242 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
43243   int rc;
43244   Mem *pColName;
43245   assert( idx<p->nResColumn );
43246   assert( var<COLNAME_N );
43247   if( p->db->mallocFailed ) return SQLITE_NOMEM;
43248   assert( p->aColName!=0 );
43249   pColName = &(p->aColName[idx+var*p->nResColumn]);
43250   if( N==P4_DYNAMIC || N==P4_STATIC ){
43251     rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC);
43252   }else{
43253     rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT);
43254   }
43255   if( rc==SQLITE_OK && N==P4_DYNAMIC ){
43256     pColName->flags &= (~MEM_Static);
43257     pColName->zMalloc = pColName->z;
43258   }
43259   return rc;
43260 }
43261
43262 /*
43263 ** A read or write transaction may or may not be active on database handle
43264 ** db. If a transaction is active, commit it. If there is a
43265 ** write-transaction spanning more than one database file, this routine
43266 ** takes care of the master journal trickery.
43267 */
43268 static int vdbeCommit(sqlite3 *db, Vdbe *p){
43269   int i;
43270   int nTrans = 0;  /* Number of databases with an active write-transaction */
43271   int rc = SQLITE_OK;
43272   int needXcommit = 0;
43273
43274   /* Before doing anything else, call the xSync() callback for any
43275   ** virtual module tables written in this transaction. This has to
43276   ** be done before determining whether a master journal file is 
43277   ** required, as an xSync() callback may add an attached database
43278   ** to the transaction.
43279   */
43280   rc = sqlite3VtabSync(db, &p->zErrMsg);
43281   if( rc!=SQLITE_OK ){
43282     return rc;
43283   }
43284
43285   /* This loop determines (a) if the commit hook should be invoked and
43286   ** (b) how many database files have open write transactions, not 
43287   ** including the temp database. (b) is important because if more than 
43288   ** one database file has an open write transaction, a master journal
43289   ** file is required for an atomic commit.
43290   */ 
43291   for(i=0; i<db->nDb; i++){ 
43292     Btree *pBt = db->aDb[i].pBt;
43293     if( sqlite3BtreeIsInTrans(pBt) ){
43294       needXcommit = 1;
43295       if( i!=1 ) nTrans++;
43296     }
43297   }
43298
43299   /* If there are any write-transactions at all, invoke the commit hook */
43300   if( needXcommit && db->xCommitCallback ){
43301     (void)sqlite3SafetyOff(db);
43302     rc = db->xCommitCallback(db->pCommitArg);
43303     (void)sqlite3SafetyOn(db);
43304     if( rc ){
43305       return SQLITE_CONSTRAINT;
43306     }
43307   }
43308
43309   /* The simple case - no more than one database file (not counting the
43310   ** TEMP database) has a transaction active.   There is no need for the
43311   ** master-journal.
43312   **
43313   ** If the return value of sqlite3BtreeGetFilename() is a zero length
43314   ** string, it means the main database is :memory: or a temp file.  In 
43315   ** that case we do not support atomic multi-file commits, so use the 
43316   ** simple case then too.
43317   */
43318   if( 0==strlen(sqlite3BtreeGetFilename(db->aDb[0].pBt)) || nTrans<=1 ){
43319     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43320       Btree *pBt = db->aDb[i].pBt;
43321       if( pBt ){
43322         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
43323       }
43324     }
43325
43326     /* Do the commit only if all databases successfully complete phase 1. 
43327     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
43328     ** IO error while deleting or truncating a journal file. It is unlikely,
43329     ** but could happen. In this case abandon processing and return the error.
43330     */
43331     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
43332       Btree *pBt = db->aDb[i].pBt;
43333       if( pBt ){
43334         rc = sqlite3BtreeCommitPhaseTwo(pBt);
43335       }
43336     }
43337     if( rc==SQLITE_OK ){
43338       sqlite3VtabCommit(db);
43339     }
43340   }
43341
43342   /* The complex case - There is a multi-file write-transaction active.
43343   ** This requires a master journal file to ensure the transaction is
43344   ** committed atomicly.
43345   */
43346 #ifndef SQLITE_OMIT_DISKIO
43347   else{
43348     sqlite3_vfs *pVfs = db->pVfs;
43349     int needSync = 0;
43350     char *zMaster = 0;   /* File-name for the master journal */
43351     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
43352     sqlite3_file *pMaster = 0;
43353     i64 offset = 0;
43354     int res;
43355
43356     /* Select a master journal file name */
43357     do {
43358       u32 random;
43359       sqlite3DbFree(db, zMaster);
43360       sqlite3_randomness(sizeof(random), &random);
43361       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, random&0x7fffffff);
43362       if( !zMaster ){
43363         return SQLITE_NOMEM;
43364       }
43365       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
43366     }while( rc==SQLITE_OK && res );
43367     if( rc==SQLITE_OK ){
43368       /* Open the master journal. */
43369       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
43370           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43371           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
43372       );
43373     }
43374     if( rc!=SQLITE_OK ){
43375       sqlite3DbFree(db, zMaster);
43376       return rc;
43377     }
43378  
43379     /* Write the name of each database file in the transaction into the new
43380     ** master journal file. If an error occurs at this point close
43381     ** and delete the master journal file. All the individual journal files
43382     ** still have 'null' as the master journal pointer, so they will roll
43383     ** back independently if a failure occurs.
43384     */
43385     for(i=0; i<db->nDb; i++){
43386       Btree *pBt = db->aDb[i].pBt;
43387       if( i==1 ) continue;   /* Ignore the TEMP database */
43388       if( sqlite3BtreeIsInTrans(pBt) ){
43389         char const *zFile = sqlite3BtreeGetJournalname(pBt);
43390         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
43391         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
43392           needSync = 1;
43393         }
43394         rc = sqlite3OsWrite(pMaster, zFile, strlen(zFile)+1, offset);
43395         offset += strlen(zFile)+1;
43396         if( rc!=SQLITE_OK ){
43397           sqlite3OsCloseFree(pMaster);
43398           sqlite3OsDelete(pVfs, zMaster, 0);
43399           sqlite3DbFree(db, zMaster);
43400           return rc;
43401         }
43402       }
43403     }
43404
43405     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
43406     ** flag is set this is not required.
43407     */
43408     zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
43409     if( (needSync 
43410      && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
43411      && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){
43412       sqlite3OsCloseFree(pMaster);
43413       sqlite3OsDelete(pVfs, zMaster, 0);
43414       sqlite3DbFree(db, zMaster);
43415       return rc;
43416     }
43417
43418     /* Sync all the db files involved in the transaction. The same call
43419     ** sets the master journal pointer in each individual journal. If
43420     ** an error occurs here, do not delete the master journal file.
43421     **
43422     ** If the error occurs during the first call to
43423     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
43424     ** master journal file will be orphaned. But we cannot delete it,
43425     ** in case the master journal file name was written into the journal
43426     ** file before the failure occured.
43427     */
43428     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
43429       Btree *pBt = db->aDb[i].pBt;
43430       if( pBt ){
43431         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
43432       }
43433     }
43434     sqlite3OsCloseFree(pMaster);
43435     if( rc!=SQLITE_OK ){
43436       sqlite3DbFree(db, zMaster);
43437       return rc;
43438     }
43439
43440     /* Delete the master journal file. This commits the transaction. After
43441     ** doing this the directory is synced again before any individual
43442     ** transaction files are deleted.
43443     */
43444     rc = sqlite3OsDelete(pVfs, zMaster, 1);
43445     sqlite3DbFree(db, zMaster);
43446     zMaster = 0;
43447     if( rc ){
43448       return rc;
43449     }
43450
43451     /* All files and directories have already been synced, so the following
43452     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
43453     ** deleting or truncating journals. If something goes wrong while
43454     ** this is happening we don't really care. The integrity of the
43455     ** transaction is already guaranteed, but some stray 'cold' journals
43456     ** may be lying around. Returning an error code won't help matters.
43457     */
43458     disable_simulated_io_errors();
43459     sqlite3BeginBenignMalloc();
43460     for(i=0; i<db->nDb; i++){ 
43461       Btree *pBt = db->aDb[i].pBt;
43462       if( pBt ){
43463         sqlite3BtreeCommitPhaseTwo(pBt);
43464       }
43465     }
43466     sqlite3EndBenignMalloc();
43467     enable_simulated_io_errors();
43468
43469     sqlite3VtabCommit(db);
43470   }
43471 #endif
43472
43473   return rc;
43474 }
43475
43476 /* 
43477 ** This routine checks that the sqlite3.activeVdbeCnt count variable
43478 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
43479 ** currently active. An assertion fails if the two counts do not match.
43480 ** This is an internal self-check only - it is not an essential processing
43481 ** step.
43482 **
43483 ** This is a no-op if NDEBUG is defined.
43484 */
43485 #ifndef NDEBUG
43486 static void checkActiveVdbeCnt(sqlite3 *db){
43487   Vdbe *p;
43488   int cnt = 0;
43489   p = db->pVdbe;
43490   while( p ){
43491     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
43492       cnt++;
43493     }
43494     p = p->pNext;
43495   }
43496   assert( cnt==db->activeVdbeCnt );
43497 }
43498 #else
43499 #define checkActiveVdbeCnt(x)
43500 #endif
43501
43502 /*
43503 ** For every Btree that in database connection db which 
43504 ** has been modified, "trip" or invalidate each cursor in
43505 ** that Btree might have been modified so that the cursor
43506 ** can never be used again.  This happens when a rollback
43507 *** occurs.  We have to trip all the other cursors, even
43508 ** cursor from other VMs in different database connections,
43509 ** so that none of them try to use the data at which they
43510 ** were pointing and which now may have been changed due
43511 ** to the rollback.
43512 **
43513 ** Remember that a rollback can delete tables complete and
43514 ** reorder rootpages.  So it is not sufficient just to save
43515 ** the state of the cursor.  We have to invalidate the cursor
43516 ** so that it is never used again.
43517 */
43518 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
43519   int i;
43520   for(i=0; i<db->nDb; i++){
43521     Btree *p = db->aDb[i].pBt;
43522     if( p && sqlite3BtreeIsInTrans(p) ){
43523       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
43524     }
43525   }
43526 }
43527
43528 /*
43529 ** This routine is called the when a VDBE tries to halt.  If the VDBE
43530 ** has made changes and is in autocommit mode, then commit those
43531 ** changes.  If a rollback is needed, then do the rollback.
43532 **
43533 ** This routine is the only way to move the state of a VM from
43534 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
43535 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
43536 **
43537 ** Return an error code.  If the commit could not complete because of
43538 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
43539 ** means the close did not happen and needs to be repeated.
43540 */
43541 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
43542   sqlite3 *db = p->db;
43543   int i;
43544   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
43545   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
43546
43547   /* This function contains the logic that determines if a statement or
43548   ** transaction will be committed or rolled back as a result of the
43549   ** execution of this virtual machine. 
43550   **
43551   ** If any of the following errors occur:
43552   **
43553   **     SQLITE_NOMEM
43554   **     SQLITE_IOERR
43555   **     SQLITE_FULL
43556   **     SQLITE_INTERRUPT
43557   **
43558   ** Then the internal cache might have been left in an inconsistent
43559   ** state.  We need to rollback the statement transaction, if there is
43560   ** one, or the complete transaction if there is no statement transaction.
43561   */
43562
43563   if( p->db->mallocFailed ){
43564     p->rc = SQLITE_NOMEM;
43565   }
43566   closeAllCursorsExceptActiveVtabs(p);
43567   if( p->magic!=VDBE_MAGIC_RUN ){
43568     return SQLITE_OK;
43569   }
43570   checkActiveVdbeCnt(db);
43571
43572   /* No commit or rollback needed if the program never started */
43573   if( p->pc>=0 ){
43574     int mrc;   /* Primary error code from p->rc */
43575
43576     /* Lock all btrees used by the statement */
43577     sqlite3BtreeMutexArrayEnter(&p->aMutex);
43578
43579     /* Check for one of the special errors */
43580     mrc = p->rc & 0xff;
43581     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
43582                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
43583     if( isSpecialError ){
43584       /* This loop does static analysis of the query to see which of the
43585       ** following three categories it falls into:
43586       **
43587       **     Read-only
43588       **     Query with statement journal
43589       **     Query without statement journal
43590       **
43591       ** We could do something more elegant than this static analysis (i.e.
43592       ** store the type of query as part of the compliation phase), but 
43593       ** handling malloc() or IO failure is a fairly obscure edge case so 
43594       ** this is probably easier. Todo: Might be an opportunity to reduce 
43595       ** code size a very small amount though...
43596       */
43597       int notReadOnly = 0;
43598       int isStatement = 0;
43599       assert(p->aOp || p->nOp==0);
43600       for(i=0; i<p->nOp; i++){ 
43601         switch( p->aOp[i].opcode ){
43602           case OP_Transaction:
43603             notReadOnly |= p->aOp[i].p2;
43604             break;
43605           case OP_Statement:
43606             isStatement = 1;
43607             break;
43608         }
43609       }
43610
43611    
43612       /* If the query was read-only, we need do no rollback at all. Otherwise,
43613       ** proceed with the special handling.
43614       */
43615       if( notReadOnly || mrc!=SQLITE_INTERRUPT ){
43616         if( p->rc==SQLITE_IOERR_BLOCKED && isStatement ){
43617           xFunc = sqlite3BtreeRollbackStmt;
43618           p->rc = SQLITE_BUSY;
43619         } else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && isStatement ){
43620           xFunc = sqlite3BtreeRollbackStmt;
43621         }else{
43622           /* We are forced to roll back the active transaction. Before doing
43623           ** so, abort any other statements this handle currently has active.
43624           */
43625           invalidateCursorsOnModifiedBtrees(db);
43626           sqlite3RollbackAll(db);
43627           db->autoCommit = 1;
43628         }
43629       }
43630     }
43631   
43632     /* If the auto-commit flag is set and this is the only active vdbe, then
43633     ** we do either a commit or rollback of the current transaction. 
43634     **
43635     ** Note: This block also runs if one of the special errors handled 
43636     ** above has occured. 
43637     */
43638     if( db->autoCommit && db->activeVdbeCnt==1 ){
43639       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
43640         /* The auto-commit flag is true, and the vdbe program was 
43641         ** successful or hit an 'OR FAIL' constraint. This means a commit 
43642         ** is required.
43643         */
43644         int rc = vdbeCommit(db, p);
43645         if( rc==SQLITE_BUSY ){
43646           sqlite3BtreeMutexArrayLeave(&p->aMutex);
43647           return SQLITE_BUSY;
43648         }else if( rc!=SQLITE_OK ){
43649           p->rc = rc;
43650           sqlite3RollbackAll(db);
43651         }else{
43652           sqlite3CommitInternalChanges(db);
43653         }
43654       }else{
43655         sqlite3RollbackAll(db);
43656       }
43657     }else if( !xFunc ){
43658       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
43659         if( p->openedStatement ){
43660           xFunc = sqlite3BtreeCommitStmt;
43661         } 
43662       }else if( p->errorAction==OE_Abort ){
43663         xFunc = sqlite3BtreeRollbackStmt;
43664       }else{
43665         invalidateCursorsOnModifiedBtrees(db);
43666         sqlite3RollbackAll(db);
43667         db->autoCommit = 1;
43668       }
43669     }
43670   
43671     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
43672     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
43673     ** and the return code is still SQLITE_OK, set the return code to the new
43674     ** error value.
43675     */
43676     assert(!xFunc ||
43677       xFunc==sqlite3BtreeCommitStmt ||
43678       xFunc==sqlite3BtreeRollbackStmt
43679     );
43680     for(i=0; xFunc && i<db->nDb; i++){ 
43681       int rc;
43682       Btree *pBt = db->aDb[i].pBt;
43683       if( pBt ){
43684         rc = xFunc(pBt);
43685         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
43686           p->rc = rc;
43687           sqlite3DbFree(db, p->zErrMsg);
43688           p->zErrMsg = 0;
43689         }
43690       }
43691     }
43692   
43693     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
43694     ** set the change counter. 
43695     */
43696     if( p->changeCntOn && p->pc>=0 ){
43697       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
43698         sqlite3VdbeSetChanges(db, p->nChange);
43699       }else{
43700         sqlite3VdbeSetChanges(db, 0);
43701       }
43702       p->nChange = 0;
43703     }
43704   
43705     /* Rollback or commit any schema changes that occurred. */
43706     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
43707       sqlite3ResetInternalSchema(db, 0);
43708       db->flags = (db->flags | SQLITE_InternChanges);
43709     }
43710
43711     /* Release the locks */
43712     sqlite3BtreeMutexArrayLeave(&p->aMutex);
43713   }
43714
43715   /* We have successfully halted and closed the VM.  Record this fact. */
43716   if( p->pc>=0 ){
43717     db->activeVdbeCnt--;
43718   }
43719   p->magic = VDBE_MAGIC_HALT;
43720   checkActiveVdbeCnt(db);
43721   if( p->db->mallocFailed ){
43722     p->rc = SQLITE_NOMEM;
43723   }
43724
43725   return SQLITE_OK;
43726 }
43727
43728
43729 /*
43730 ** Each VDBE holds the result of the most recent sqlite3_step() call
43731 ** in p->rc.  This routine sets that result back to SQLITE_OK.
43732 */
43733 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
43734   p->rc = SQLITE_OK;
43735 }
43736
43737 /*
43738 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
43739 ** Write any error messages into *pzErrMsg.  Return the result code.
43740 **
43741 ** After this routine is run, the VDBE should be ready to be executed
43742 ** again.
43743 **
43744 ** To look at it another way, this routine resets the state of the
43745 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
43746 ** VDBE_MAGIC_INIT.
43747 */
43748 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
43749   sqlite3 *db;
43750   db = p->db;
43751
43752   /* If the VM did not run to completion or if it encountered an
43753   ** error, then it might not have been halted properly.  So halt
43754   ** it now.
43755   */
43756   (void)sqlite3SafetyOn(db);
43757   sqlite3VdbeHalt(p);
43758   (void)sqlite3SafetyOff(db);
43759
43760   /* If the VDBE has be run even partially, then transfer the error code
43761   ** and error message from the VDBE into the main database structure.  But
43762   ** if the VDBE has just been set to run but has not actually executed any
43763   ** instructions yet, leave the main database error information unchanged.
43764   */
43765   if( p->pc>=0 ){
43766     if( p->zErrMsg ){
43767       sqlite3BeginBenignMalloc();
43768       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
43769       sqlite3EndBenignMalloc();
43770       db->errCode = p->rc;
43771       sqlite3DbFree(db, p->zErrMsg);
43772       p->zErrMsg = 0;
43773     }else if( p->rc ){
43774       sqlite3Error(db, p->rc, 0);
43775     }else{
43776       sqlite3Error(db, SQLITE_OK, 0);
43777     }
43778   }else if( p->rc && p->expired ){
43779     /* The expired flag was set on the VDBE before the first call
43780     ** to sqlite3_step(). For consistency (since sqlite3_step() was
43781     ** called), set the database error in this case as well.
43782     */
43783     sqlite3Error(db, p->rc, 0);
43784     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
43785     sqlite3DbFree(db, p->zErrMsg);
43786     p->zErrMsg = 0;
43787   }
43788
43789   /* Reclaim all memory used by the VDBE
43790   */
43791   Cleanup(p);
43792
43793   /* Save profiling information from this VDBE run.
43794   */
43795 #ifdef VDBE_PROFILE
43796   {
43797     FILE *out = fopen("vdbe_profile.out", "a");
43798     if( out ){
43799       int i;
43800       fprintf(out, "---- ");
43801       for(i=0; i<p->nOp; i++){
43802         fprintf(out, "%02x", p->aOp[i].opcode);
43803       }
43804       fprintf(out, "\n");
43805       for(i=0; i<p->nOp; i++){
43806         fprintf(out, "%6d %10lld %8lld ",
43807            p->aOp[i].cnt,
43808            p->aOp[i].cycles,
43809            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
43810         );
43811         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
43812       }
43813       fclose(out);
43814     }
43815   }
43816 #endif
43817   p->magic = VDBE_MAGIC_INIT;
43818   return p->rc & db->errMask;
43819 }
43820  
43821 /*
43822 ** Clean up and delete a VDBE after execution.  Return an integer which is
43823 ** the result code.  Write any error message text into *pzErrMsg.
43824 */
43825 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
43826   int rc = SQLITE_OK;
43827   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
43828     rc = sqlite3VdbeReset(p);
43829     assert( (rc & p->db->errMask)==rc );
43830   }else if( p->magic!=VDBE_MAGIC_INIT ){
43831     return SQLITE_MISUSE;
43832   }
43833   sqlite3VdbeDelete(p);
43834   return rc;
43835 }
43836
43837 /*
43838 ** Call the destructor for each auxdata entry in pVdbeFunc for which
43839 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
43840 ** are always destroyed.  To destroy all auxdata entries, call this
43841 ** routine with mask==0.
43842 */
43843 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
43844   int i;
43845   for(i=0; i<pVdbeFunc->nAux; i++){
43846     struct AuxData *pAux = &pVdbeFunc->apAux[i];
43847     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
43848       if( pAux->xDelete ){
43849         pAux->xDelete(pAux->pAux);
43850       }
43851       pAux->pAux = 0;
43852     }
43853   }
43854 }
43855
43856 /*
43857 ** Delete an entire VDBE.
43858 */
43859 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
43860   int i;
43861   sqlite3 *db;
43862
43863   if( p==0 ) return;
43864   db = p->db;
43865   if( p->pPrev ){
43866     p->pPrev->pNext = p->pNext;
43867   }else{
43868     assert( db->pVdbe==p );
43869     db->pVdbe = p->pNext;
43870   }
43871   if( p->pNext ){
43872     p->pNext->pPrev = p->pPrev;
43873   }
43874   if( p->aOp ){
43875     Op *pOp = p->aOp;
43876     for(i=0; i<p->nOp; i++, pOp++){
43877       freeP4(db, pOp->p4type, pOp->p4.p);
43878 #ifdef SQLITE_DEBUG
43879       sqlite3DbFree(db, pOp->zComment);
43880 #endif     
43881     }
43882     sqlite3DbFree(db, p->aOp);
43883   }
43884   releaseMemArray(p->aVar, p->nVar);
43885   sqlite3DbFree(db, p->aLabel);
43886   if( p->aMem ){
43887     sqlite3DbFree(db, &p->aMem[1]);
43888   }
43889   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
43890   sqlite3DbFree(db, p->aColName);
43891   sqlite3DbFree(db, p->zSql);
43892   p->magic = VDBE_MAGIC_DEAD;
43893   sqlite3DbFree(db, p);
43894 }
43895
43896 /*
43897 ** If a MoveTo operation is pending on the given cursor, then do that
43898 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
43899 ** routine does nothing and returns SQLITE_OK.
43900 */
43901 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
43902   if( p->deferredMoveto ){
43903     int res, rc;
43904 #ifdef SQLITE_TEST
43905     extern int sqlite3_search_count;
43906 #endif
43907     assert( p->isTable );
43908     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
43909     if( rc ) return rc;
43910     p->lastRowid = keyToInt(p->movetoTarget);
43911     p->rowidIsValid = res==0;
43912     if( res<0 ){
43913       rc = sqlite3BtreeNext(p->pCursor, &res);
43914       if( rc ) return rc;
43915     }
43916 #ifdef SQLITE_TEST
43917     sqlite3_search_count++;
43918 #endif
43919     p->deferredMoveto = 0;
43920     p->cacheStatus = CACHE_STALE;
43921   }else if( p->pCursor ){
43922     int hasMoved;
43923     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
43924     if( rc ) return rc;
43925     if( hasMoved ){
43926       p->cacheStatus = CACHE_STALE;
43927       p->nullRow = 1;
43928     }
43929   }
43930   return SQLITE_OK;
43931 }
43932
43933 /*
43934 ** The following functions:
43935 **
43936 ** sqlite3VdbeSerialType()
43937 ** sqlite3VdbeSerialTypeLen()
43938 ** sqlite3VdbeSerialLen()
43939 ** sqlite3VdbeSerialPut()
43940 ** sqlite3VdbeSerialGet()
43941 **
43942 ** encapsulate the code that serializes values for storage in SQLite
43943 ** data and index records. Each serialized value consists of a
43944 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
43945 ** integer, stored as a varint.
43946 **
43947 ** In an SQLite index record, the serial type is stored directly before
43948 ** the blob of data that it corresponds to. In a table record, all serial
43949 ** types are stored at the start of the record, and the blobs of data at
43950 ** the end. Hence these functions allow the caller to handle the
43951 ** serial-type and data blob seperately.
43952 **
43953 ** The following table describes the various storage classes for data:
43954 **
43955 **   serial type        bytes of data      type
43956 **   --------------     ---------------    ---------------
43957 **      0                     0            NULL
43958 **      1                     1            signed integer
43959 **      2                     2            signed integer
43960 **      3                     3            signed integer
43961 **      4                     4            signed integer
43962 **      5                     6            signed integer
43963 **      6                     8            signed integer
43964 **      7                     8            IEEE float
43965 **      8                     0            Integer constant 0
43966 **      9                     0            Integer constant 1
43967 **     10,11                               reserved for expansion
43968 **    N>=12 and even       (N-12)/2        BLOB
43969 **    N>=13 and odd        (N-13)/2        text
43970 **
43971 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
43972 ** of SQLite will not understand those serial types.
43973 */
43974
43975 /*
43976 ** Return the serial-type for the value stored in pMem.
43977 */
43978 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
43979   int flags = pMem->flags;
43980   int n;
43981
43982   if( flags&MEM_Null ){
43983     return 0;
43984   }
43985   if( flags&MEM_Int ){
43986     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
43987 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
43988     i64 i = pMem->u.i;
43989     u64 u;
43990     if( file_format>=4 && (i&1)==i ){
43991       return 8+i;
43992     }
43993     u = i<0 ? -i : i;
43994     if( u<=127 ) return 1;
43995     if( u<=32767 ) return 2;
43996     if( u<=8388607 ) return 3;
43997     if( u<=2147483647 ) return 4;
43998     if( u<=MAX_6BYTE ) return 5;
43999     return 6;
44000   }
44001   if( flags&MEM_Real ){
44002     return 7;
44003   }
44004   assert( flags&(MEM_Str|MEM_Blob) );
44005   n = pMem->n;
44006   if( flags & MEM_Zero ){
44007     n += pMem->u.i;
44008   }
44009   assert( n>=0 );
44010   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
44011 }
44012
44013 /*
44014 ** Return the length of the data corresponding to the supplied serial-type.
44015 */
44016 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
44017   if( serial_type>=12 ){
44018     return (serial_type-12)/2;
44019   }else{
44020     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
44021     return aSize[serial_type];
44022   }
44023 }
44024
44025 /*
44026 ** If we are on an architecture with mixed-endian floating 
44027 ** points (ex: ARM7) then swap the lower 4 bytes with the 
44028 ** upper 4 bytes.  Return the result.
44029 **
44030 ** For most architectures, this is a no-op.
44031 **
44032 ** (later):  It is reported to me that the mixed-endian problem
44033 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
44034 ** that early versions of GCC stored the two words of a 64-bit
44035 ** float in the wrong order.  And that error has been propagated
44036 ** ever since.  The blame is not necessarily with GCC, though.
44037 ** GCC might have just copying the problem from a prior compiler.
44038 ** I am also told that newer versions of GCC that follow a different
44039 ** ABI get the byte order right.
44040 **
44041 ** Developers using SQLite on an ARM7 should compile and run their
44042 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
44043 ** enabled, some asserts below will ensure that the byte order of
44044 ** floating point values is correct.
44045 **
44046 ** (2007-08-30)  Frank van Vugt has studied this problem closely
44047 ** and has send his findings to the SQLite developers.  Frank
44048 ** writes that some Linux kernels offer floating point hardware
44049 ** emulation that uses only 32-bit mantissas instead of a full 
44050 ** 48-bits as required by the IEEE standard.  (This is the
44051 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
44052 ** byte swapping becomes very complicated.  To avoid problems,
44053 ** the necessary byte swapping is carried out using a 64-bit integer
44054 ** rather than a 64-bit float.  Frank assures us that the code here
44055 ** works for him.  We, the developers, have no way to independently
44056 ** verify this, but Frank seems to know what he is talking about
44057 ** so we trust him.
44058 */
44059 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
44060 static u64 floatSwap(u64 in){
44061   union {
44062     u64 r;
44063     u32 i[2];
44064   } u;
44065   u32 t;
44066
44067   u.r = in;
44068   t = u.i[0];
44069   u.i[0] = u.i[1];
44070   u.i[1] = t;
44071   return u.r;
44072 }
44073 # define swapMixedEndianFloat(X)  X = floatSwap(X)
44074 #else
44075 # define swapMixedEndianFloat(X)
44076 #endif
44077
44078 /*
44079 ** Write the serialized data blob for the value stored in pMem into 
44080 ** buf. It is assumed that the caller has allocated sufficient space.
44081 ** Return the number of bytes written.
44082 **
44083 ** nBuf is the amount of space left in buf[].  nBuf must always be
44084 ** large enough to hold the entire field.  Except, if the field is
44085 ** a blob with a zero-filled tail, then buf[] might be just the right
44086 ** size to hold everything except for the zero-filled tail.  If buf[]
44087 ** is only big enough to hold the non-zero prefix, then only write that
44088 ** prefix into buf[].  But if buf[] is large enough to hold both the
44089 ** prefix and the tail then write the prefix and set the tail to all
44090 ** zeros.
44091 **
44092 ** Return the number of bytes actually written into buf[].  The number
44093 ** of bytes in the zero-filled tail is included in the return value only
44094 ** if those bytes were zeroed in buf[].
44095 */ 
44096 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
44097   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
44098   int len;
44099
44100   /* Integer and Real */
44101   if( serial_type<=7 && serial_type>0 ){
44102     u64 v;
44103     int i;
44104     if( serial_type==7 ){
44105       assert( sizeof(v)==sizeof(pMem->r) );
44106       memcpy(&v, &pMem->r, sizeof(v));
44107       swapMixedEndianFloat(v);
44108     }else{
44109       v = pMem->u.i;
44110     }
44111     len = i = sqlite3VdbeSerialTypeLen(serial_type);
44112     assert( len<=nBuf );
44113     while( i-- ){
44114       buf[i] = (v&0xFF);
44115       v >>= 8;
44116     }
44117     return len;
44118   }
44119
44120   /* String or blob */
44121   if( serial_type>=12 ){
44122     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.i:0)
44123              == sqlite3VdbeSerialTypeLen(serial_type) );
44124     assert( pMem->n<=nBuf );
44125     len = pMem->n;
44126     memcpy(buf, pMem->z, len);
44127     if( pMem->flags & MEM_Zero ){
44128       len += pMem->u.i;
44129       if( len>nBuf ){
44130         len = nBuf;
44131       }
44132       memset(&buf[pMem->n], 0, len-pMem->n);
44133     }
44134     return len;
44135   }
44136
44137   /* NULL or constants 0 or 1 */
44138   return 0;
44139 }
44140
44141 /*
44142 ** Deserialize the data blob pointed to by buf as serial type serial_type
44143 ** and store the result in pMem.  Return the number of bytes read.
44144 */ 
44145 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
44146   const unsigned char *buf,     /* Buffer to deserialize from */
44147   u32 serial_type,              /* Serial type to deserialize */
44148   Mem *pMem                     /* Memory cell to write value into */
44149 ){
44150   switch( serial_type ){
44151     case 10:   /* Reserved for future use */
44152     case 11:   /* Reserved for future use */
44153     case 0: {  /* NULL */
44154       pMem->flags = MEM_Null;
44155       break;
44156     }
44157     case 1: { /* 1-byte signed integer */
44158       pMem->u.i = (signed char)buf[0];
44159       pMem->flags = MEM_Int;
44160       return 1;
44161     }
44162     case 2: { /* 2-byte signed integer */
44163       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
44164       pMem->flags = MEM_Int;
44165       return 2;
44166     }
44167     case 3: { /* 3-byte signed integer */
44168       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
44169       pMem->flags = MEM_Int;
44170       return 3;
44171     }
44172     case 4: { /* 4-byte signed integer */
44173       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44174       pMem->flags = MEM_Int;
44175       return 4;
44176     }
44177     case 5: { /* 6-byte signed integer */
44178       u64 x = (((signed char)buf[0])<<8) | buf[1];
44179       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
44180       x = (x<<32) | y;
44181       pMem->u.i = *(i64*)&x;
44182       pMem->flags = MEM_Int;
44183       return 6;
44184     }
44185     case 6:   /* 8-byte signed integer */
44186     case 7: { /* IEEE floating point */
44187       u64 x;
44188       u32 y;
44189 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
44190       /* Verify that integers and floating point values use the same
44191       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
44192       ** defined that 64-bit floating point values really are mixed
44193       ** endian.
44194       */
44195       static const u64 t1 = ((u64)0x3ff00000)<<32;
44196       static const double r1 = 1.0;
44197       u64 t2 = t1;
44198       swapMixedEndianFloat(t2);
44199       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
44200 #endif
44201
44202       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
44203       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
44204       x = (x<<32) | y;
44205       if( serial_type==6 ){
44206         pMem->u.i = *(i64*)&x;
44207         pMem->flags = MEM_Int;
44208       }else{
44209         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
44210         swapMixedEndianFloat(x);
44211         memcpy(&pMem->r, &x, sizeof(x));
44212         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
44213       }
44214       return 8;
44215     }
44216     case 8:    /* Integer 0 */
44217     case 9: {  /* Integer 1 */
44218       pMem->u.i = serial_type-8;
44219       pMem->flags = MEM_Int;
44220       return 0;
44221     }
44222     default: {
44223       int len = (serial_type-12)/2;
44224       pMem->z = (char *)buf;
44225       pMem->n = len;
44226       pMem->xDel = 0;
44227       if( serial_type&0x01 ){
44228         pMem->flags = MEM_Str | MEM_Ephem;
44229       }else{
44230         pMem->flags = MEM_Blob | MEM_Ephem;
44231       }
44232       return len;
44233     }
44234   }
44235   return 0;
44236 }
44237
44238
44239 /*
44240 ** Given the nKey-byte encoding of a record in pKey[], parse the
44241 ** record into a UnpackedRecord structure.  Return a pointer to
44242 ** that structure.
44243 **
44244 ** The calling function might provide szSpace bytes of memory
44245 ** space at pSpace.  This space can be used to hold the returned
44246 ** VDbeParsedRecord structure if it is large enough.  If it is
44247 ** not big enough, space is obtained from sqlite3_malloc().
44248 **
44249 ** The returned structure should be closed by a call to
44250 ** sqlite3VdbeDeleteUnpackedRecord().
44251 */ 
44252 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
44253   KeyInfo *pKeyInfo,     /* Information about the record format */
44254   int nKey,              /* Size of the binary record */
44255   const void *pKey,      /* The binary record */
44256   UnpackedRecord *pSpace,/* Space available to hold resulting object */
44257   int szSpace            /* Size of pSpace[] in bytes */
44258 ){
44259   const unsigned char *aKey = (const unsigned char *)pKey;
44260   UnpackedRecord *p;
44261   int nByte;
44262   int idx, d;
44263   u16 u;                 /* Unsigned loop counter */
44264   u32 szHdr;
44265   Mem *pMem;
44266   
44267   assert( sizeof(Mem)>sizeof(*p) );
44268   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
44269   if( nByte>szSpace ){
44270     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
44271     if( p==0 ) return 0;
44272     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
44273   }else{
44274     p = pSpace;
44275     p->flags = UNPACKED_NEED_DESTROY;
44276   }
44277   p->pKeyInfo = pKeyInfo;
44278   p->nField = pKeyInfo->nField + 1;
44279   p->aMem = pMem = &((Mem*)p)[1];
44280   idx = getVarint32(aKey, szHdr);
44281   d = szHdr;
44282   u = 0;
44283   while( idx<szHdr && u<p->nField ){
44284     u32 serial_type;
44285
44286     idx += getVarint32( aKey+idx, serial_type);
44287     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
44288     pMem->enc = pKeyInfo->enc;
44289     pMem->db = pKeyInfo->db;
44290     pMem->flags = 0;
44291     pMem->zMalloc = 0;
44292     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
44293     pMem++;
44294     u++;
44295   }
44296   assert( u<=pKeyInfo->nField + 1 );
44297   p->nField = u;
44298   return (void*)p;
44299 }
44300
44301 /*
44302 ** This routine destroys a UnpackedRecord object
44303 */
44304 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
44305   if( p ){
44306     if( p->flags & UNPACKED_NEED_DESTROY ){
44307       int i;
44308       Mem *pMem;
44309       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
44310         if( pMem->zMalloc ){
44311           sqlite3VdbeMemRelease(pMem);
44312         }
44313       }
44314     }
44315     if( p->flags & UNPACKED_NEED_FREE ){
44316       sqlite3DbFree(p->pKeyInfo->db, p);
44317     }
44318   }
44319 }
44320
44321 /*
44322 ** This function compares the two table rows or index records
44323 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
44324 ** or positive integer if key1 is less than, equal to or 
44325 ** greater than key2.  The {nKey1, pKey1} key must be a blob
44326 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
44327 ** key must be a parsed key such as obtained from
44328 ** sqlite3VdbeParseRecord.
44329 **
44330 ** Key1 and Key2 do not have to contain the same number of fields.
44331 ** The key with fewer fields is usually compares less than the 
44332 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
44333 ** and the common prefixes are equal, then key1 is less than key2.
44334 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
44335 ** equal, then the keys are considered to be equal and
44336 ** the parts beyond the common prefix are ignored.
44337 **
44338 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
44339 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
44340 ** an index key, and thus ends with a rowid value.  The last byte
44341 ** of the header will therefore be the serial type of the rowid:
44342 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
44343 ** The serial type of the final rowid will always be a single byte.
44344 ** By ignoring this last byte of the header, we force the comparison
44345 ** to ignore the rowid at the end of key1.
44346 */
44347 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
44348   int nKey1, const void *pKey1, /* Left key */
44349   UnpackedRecord *pPKey2        /* Right key */
44350 ){
44351   u32 d1;            /* Offset into aKey[] of next data element */
44352   u32 idx1;          /* Offset into aKey[] of next header element */
44353   u32 szHdr1;        /* Number of bytes in header */
44354   int i = 0;
44355   int nField;
44356   int rc = 0;
44357   const unsigned char *aKey1 = (const unsigned char *)pKey1;
44358   KeyInfo *pKeyInfo;
44359   Mem mem1;
44360
44361   pKeyInfo = pPKey2->pKeyInfo;
44362   mem1.enc = pKeyInfo->enc;
44363   mem1.db = pKeyInfo->db;
44364   mem1.flags = 0;
44365   mem1.zMalloc = 0;
44366   
44367   idx1 = getVarint32(aKey1, szHdr1);
44368   d1 = szHdr1;
44369   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
44370     szHdr1--;
44371   }
44372   nField = pKeyInfo->nField;
44373   while( idx1<szHdr1 && i<pPKey2->nField ){
44374     u32 serial_type1;
44375
44376     /* Read the serial types for the next element in each key. */
44377     idx1 += getVarint32( aKey1+idx1, serial_type1 );
44378     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
44379
44380     /* Extract the values to be compared.
44381     */
44382     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
44383
44384     /* Do the comparison
44385     */
44386     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
44387                            i<nField ? pKeyInfo->aColl[i] : 0);
44388     if( rc!=0 ){
44389       break;
44390     }
44391     i++;
44392   }
44393   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
44394
44395   if( rc==0 ){
44396     /* rc==0 here means that one of the keys ran out of fields and
44397     ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
44398     ** flag is set, then break the tie by treating key2 as larger.
44399     ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
44400     ** are considered to be equal.  Otherwise, the longer key is the 
44401     ** larger.  As it happens, the pPKey2 will always be the longer
44402     ** if there is a difference.
44403     */
44404     if( pPKey2->flags & UNPACKED_INCRKEY ){
44405       rc = -1;
44406     }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
44407       /* Leave rc==0 */
44408     }else if( idx1<szHdr1 ){
44409       rc = 1;
44410     }
44411   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
44412                && pKeyInfo->aSortOrder[i] ){
44413     rc = -rc;
44414   }
44415
44416   return rc;
44417 }
44418  
44419
44420 /*
44421 ** pCur points at an index entry created using the OP_MakeRecord opcode.
44422 ** Read the rowid (the last field in the record) and store it in *rowid.
44423 ** Return SQLITE_OK if everything works, or an error code otherwise.
44424 */
44425 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
44426   i64 nCellKey = 0;
44427   int rc;
44428   u32 szHdr;        /* Size of the header */
44429   u32 typeRowid;    /* Serial type of the rowid */
44430   u32 lenRowid;     /* Size of the rowid */
44431   Mem m, v;
44432
44433   sqlite3BtreeKeySize(pCur, &nCellKey);
44434   if( nCellKey<=0 ){
44435     return SQLITE_CORRUPT_BKPT;
44436   }
44437   m.flags = 0;
44438   m.db = 0;
44439   m.zMalloc = 0;
44440   rc = sqlite3VdbeMemFromBtree(pCur, 0, nCellKey, 1, &m);
44441   if( rc ){
44442     return rc;
44443   }
44444   (void)getVarint32((u8*)m.z, szHdr);
44445   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
44446   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
44447   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
44448   *rowid = v.u.i;
44449   sqlite3VdbeMemRelease(&m);
44450   return SQLITE_OK;
44451 }
44452
44453 /*
44454 ** Compare the key of the index entry that cursor pC is point to against
44455 ** the key string in pKey (of length nKey).  Write into *pRes a number
44456 ** that is negative, zero, or positive if pC is less than, equal to,
44457 ** or greater than pKey.  Return SQLITE_OK on success.
44458 **
44459 ** pKey is either created without a rowid or is truncated so that it
44460 ** omits the rowid at the end.  The rowid at the end of the index entry
44461 ** is ignored as well.  Hence, this routine only compares the prefixes 
44462 ** of the keys prior to the final rowid, not the entire key.
44463 **
44464 ** pUnpacked may be an unpacked version of pKey,nKey.  If pUnpacked is
44465 ** supplied it is used in place of pKey,nKey.
44466 */
44467 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
44468   Cursor *pC,                 /* The cursor to compare against */
44469   UnpackedRecord *pUnpacked,  /* Unpacked version of pKey and nKey */
44470   int *res                    /* Write the comparison result here */
44471 ){
44472   i64 nCellKey = 0;
44473   int rc;
44474   BtCursor *pCur = pC->pCursor;
44475   Mem m;
44476
44477   sqlite3BtreeKeySize(pCur, &nCellKey);
44478   if( nCellKey<=0 ){
44479     *res = 0;
44480     return SQLITE_OK;
44481   }
44482   m.db = 0;
44483   m.flags = 0;
44484   m.zMalloc = 0;
44485   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, nCellKey, 1, &m);
44486   if( rc ){
44487     return rc;
44488   }
44489   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
44490   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
44491   sqlite3VdbeMemRelease(&m);
44492   return SQLITE_OK;
44493 }
44494
44495 /*
44496 ** This routine sets the value to be returned by subsequent calls to
44497 ** sqlite3_changes() on the database handle 'db'. 
44498 */
44499 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
44500   assert( sqlite3_mutex_held(db->mutex) );
44501   db->nChange = nChange;
44502   db->nTotalChange += nChange;
44503 }
44504
44505 /*
44506 ** Set a flag in the vdbe to update the change counter when it is finalised
44507 ** or reset.
44508 */
44509 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
44510   v->changeCntOn = 1;
44511 }
44512
44513 /*
44514 ** Mark every prepared statement associated with a database connection
44515 ** as expired.
44516 **
44517 ** An expired statement means that recompilation of the statement is
44518 ** recommend.  Statements expire when things happen that make their
44519 ** programs obsolete.  Removing user-defined functions or collating
44520 ** sequences, or changing an authorization function are the types of
44521 ** things that make prepared statements obsolete.
44522 */
44523 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
44524   Vdbe *p;
44525   for(p = db->pVdbe; p; p=p->pNext){
44526     p->expired = 1;
44527   }
44528 }
44529
44530 /*
44531 ** Return the database associated with the Vdbe.
44532 */
44533 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
44534   return v->db;
44535 }
44536
44537 /************** End of vdbeaux.c *********************************************/
44538 /************** Begin file vdbeapi.c *****************************************/
44539 /*
44540 ** 2004 May 26
44541 **
44542 ** The author disclaims copyright to this source code.  In place of
44543 ** a legal notice, here is a blessing:
44544 **
44545 **    May you do good and not evil.
44546 **    May you find forgiveness for yourself and forgive others.
44547 **    May you share freely, never taking more than you give.
44548 **
44549 *************************************************************************
44550 **
44551 ** This file contains code use to implement APIs that are part of the
44552 ** VDBE.
44553 **
44554 ** $Id: vdbeapi.c,v 1.147 2008/10/13 10:37:50 danielk1977 Exp $
44555 */
44556
44557 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
44558 /*
44559 ** The following structure contains pointers to the end points of a
44560 ** doubly-linked list of all compiled SQL statements that may be holding
44561 ** buffers eligible for release when the sqlite3_release_memory() interface is
44562 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
44563 ** mutex.
44564 **
44565 ** Statements are added to the end of this list when sqlite3_reset() is
44566 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
44567 ** is called. When statements are added to this list, the associated 
44568 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
44569 ** can be freed using sqlite3VdbeReleaseMemory().
44570 **
44571 ** When statements are added or removed from this list, the mutex
44572 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
44573 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
44574 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
44575 */
44576 struct StatementLruList {
44577   Vdbe *pFirst;
44578   Vdbe *pLast;
44579 };
44580 static struct StatementLruList sqlite3LruStatements;
44581
44582 /*
44583 ** Check that the list looks to be internally consistent. This is used
44584 ** as part of an assert() statement as follows:
44585 **
44586 **   assert( stmtLruCheck() );
44587 */
44588 #ifndef NDEBUG
44589 static int stmtLruCheck(){
44590   Vdbe *p;
44591   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
44592     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
44593     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
44594     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
44595     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
44596   }
44597   return 1;
44598 }
44599 #endif
44600
44601 /*
44602 ** Add vdbe p to the end of the statement lru list. It is assumed that
44603 ** p is not already part of the list when this is called. The lru list
44604 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
44605 */
44606 static void stmtLruAdd(Vdbe *p){
44607   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44608
44609   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
44610     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44611     return;
44612   }
44613
44614   assert( stmtLruCheck() );
44615
44616   if( !sqlite3LruStatements.pFirst ){
44617     assert( !sqlite3LruStatements.pLast );
44618     sqlite3LruStatements.pFirst = p;
44619     sqlite3LruStatements.pLast = p;
44620   }else{
44621     assert( !sqlite3LruStatements.pLast->pLruNext );
44622     p->pLruPrev = sqlite3LruStatements.pLast;
44623     sqlite3LruStatements.pLast->pLruNext = p;
44624     sqlite3LruStatements.pLast = p;
44625   }
44626
44627   assert( stmtLruCheck() );
44628
44629   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44630 }
44631
44632 /*
44633 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
44634 ** statement p from the least-recently-used statement list. If the 
44635 ** statement is not currently part of the list, this call is a no-op.
44636 */
44637 static void stmtLruRemoveNomutex(Vdbe *p){
44638   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
44639     assert( stmtLruCheck() );
44640     if( p->pLruNext ){
44641       p->pLruNext->pLruPrev = p->pLruPrev;
44642     }else{
44643       sqlite3LruStatements.pLast = p->pLruPrev;
44644     }
44645     if( p->pLruPrev ){
44646       p->pLruPrev->pLruNext = p->pLruNext;
44647     }else{
44648       sqlite3LruStatements.pFirst = p->pLruNext;
44649     }
44650     p->pLruNext = 0;
44651     p->pLruPrev = 0;
44652     assert( stmtLruCheck() );
44653   }
44654 }
44655
44656 /*
44657 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
44658 ** statement p from the least-recently-used statement list. If the 
44659 ** statement is not currently part of the list, this call is a no-op.
44660 */
44661 static void stmtLruRemove(Vdbe *p){
44662   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44663   stmtLruRemoveNomutex(p);
44664   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44665 }
44666
44667 /*
44668 ** Try to release n bytes of memory by freeing buffers associated 
44669 ** with the memory registers of currently unused vdbes.
44670 */
44671 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
44672   Vdbe *p;
44673   Vdbe *pNext;
44674   int nFree = 0;
44675
44676   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44677   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
44678     pNext = p->pLruNext;
44679
44680     /* For each statement handle in the lru list, attempt to obtain the
44681     ** associated database mutex. If it cannot be obtained, continue
44682     ** to the next statement handle. It is not possible to block on
44683     ** the database mutex - that could cause deadlock.
44684     */
44685     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
44686       nFree += sqlite3VdbeReleaseBuffers(p);
44687       stmtLruRemoveNomutex(p);
44688       sqlite3_mutex_leave(p->db->mutex);
44689     }
44690   }
44691   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
44692
44693   return nFree;
44694 }
44695
44696 /*
44697 ** Call sqlite3Reprepare() on the statement. Remove it from the
44698 ** lru list before doing so, as Reprepare() will free all the
44699 ** memory register buffers anyway.
44700 */
44701 int vdbeReprepare(Vdbe *p){
44702   stmtLruRemove(p);
44703   return sqlite3Reprepare(p);
44704 }
44705
44706 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
44707   #define stmtLruRemove(x)
44708   #define stmtLruAdd(x)
44709   #define vdbeReprepare(x) sqlite3Reprepare(x)
44710 #endif
44711
44712
44713 #ifndef SQLITE_OMIT_DEPRECATED
44714 /*
44715 ** Return TRUE (non-zero) of the statement supplied as an argument needs
44716 ** to be recompiled.  A statement needs to be recompiled whenever the
44717 ** execution environment changes in a way that would alter the program
44718 ** that sqlite3_prepare() generates.  For example, if new functions or
44719 ** collating sequences are registered or if an authorizer function is
44720 ** added or changed.
44721 */
44722 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
44723   Vdbe *p = (Vdbe*)pStmt;
44724   return p==0 || p->expired;
44725 }
44726 #endif
44727
44728 /*
44729 ** The following routine destroys a virtual machine that is created by
44730 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
44731 ** success/failure code that describes the result of executing the virtual
44732 ** machine.
44733 **
44734 ** This routine sets the error code and string returned by
44735 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
44736 */
44737 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
44738   int rc;
44739   if( pStmt==0 ){
44740     rc = SQLITE_OK;
44741   }else{
44742     Vdbe *v = (Vdbe*)pStmt;
44743 #if SQLITE_THREADSAFE
44744     sqlite3_mutex *mutex = v->db->mutex;
44745 #endif
44746     sqlite3_mutex_enter(mutex);
44747     stmtLruRemove(v);
44748     rc = sqlite3VdbeFinalize(v);
44749     sqlite3_mutex_leave(mutex);
44750   }
44751   return rc;
44752 }
44753
44754 /*
44755 ** Terminate the current execution of an SQL statement and reset it
44756 ** back to its starting state so that it can be reused. A success code from
44757 ** the prior execution is returned.
44758 **
44759 ** This routine sets the error code and string returned by
44760 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
44761 */
44762 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
44763   int rc;
44764   if( pStmt==0 ){
44765     rc = SQLITE_OK;
44766   }else{
44767     Vdbe *v = (Vdbe*)pStmt;
44768     sqlite3_mutex_enter(v->db->mutex);
44769     rc = sqlite3VdbeReset(v);
44770     stmtLruAdd(v);
44771     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
44772     assert( (rc & (v->db->errMask))==rc );
44773     sqlite3_mutex_leave(v->db->mutex);
44774   }
44775   return rc;
44776 }
44777
44778 /*
44779 ** Set all the parameters in the compiled SQL statement to NULL.
44780 */
44781 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
44782   int i;
44783   int rc = SQLITE_OK;
44784   Vdbe *p = (Vdbe*)pStmt;
44785 #if SQLITE_THREADSAFE
44786   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
44787 #endif
44788   sqlite3_mutex_enter(mutex);
44789   for(i=0; i<p->nVar; i++){
44790     sqlite3VdbeMemRelease(&p->aVar[i]);
44791     p->aVar[i].flags = MEM_Null;
44792   }
44793   sqlite3_mutex_leave(mutex);
44794   return rc;
44795 }
44796
44797
44798 /**************************** sqlite3_value_  *******************************
44799 ** The following routines extract information from a Mem or sqlite3_value
44800 ** structure.
44801 */
44802 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
44803   Mem *p = (Mem*)pVal;
44804   if( p->flags & (MEM_Blob|MEM_Str) ){
44805     sqlite3VdbeMemExpandBlob(p);
44806     p->flags &= ~MEM_Str;
44807     p->flags |= MEM_Blob;
44808     return p->z;
44809   }else{
44810     return sqlite3_value_text(pVal);
44811   }
44812 }
44813 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
44814   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
44815 }
44816 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
44817   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
44818 }
44819 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
44820   return sqlite3VdbeRealValue((Mem*)pVal);
44821 }
44822 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
44823   return sqlite3VdbeIntValue((Mem*)pVal);
44824 }
44825 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
44826   return sqlite3VdbeIntValue((Mem*)pVal);
44827 }
44828 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
44829   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
44830 }
44831 #ifndef SQLITE_OMIT_UTF16
44832 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
44833   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
44834 }
44835 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
44836   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
44837 }
44838 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
44839   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
44840 }
44841 #endif /* SQLITE_OMIT_UTF16 */
44842 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
44843   return pVal->type;
44844 }
44845
44846 /**************************** sqlite3_result_  *******************************
44847 ** The following routines are used by user-defined functions to specify
44848 ** the function result.
44849 */
44850 SQLITE_API void sqlite3_result_blob(
44851   sqlite3_context *pCtx, 
44852   const void *z, 
44853   int n, 
44854   void (*xDel)(void *)
44855 ){
44856   assert( n>=0 );
44857   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44858   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
44859 }
44860 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
44861   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44862   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
44863 }
44864 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
44865   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44866   pCtx->isError = SQLITE_ERROR;
44867   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
44868 }
44869 #ifndef SQLITE_OMIT_UTF16
44870 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
44871   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44872   pCtx->isError = SQLITE_ERROR;
44873   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
44874 }
44875 #endif
44876 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
44877   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44878   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
44879 }
44880 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
44881   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44882   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
44883 }
44884 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
44885   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44886   sqlite3VdbeMemSetNull(&pCtx->s);
44887 }
44888 SQLITE_API void sqlite3_result_text(
44889   sqlite3_context *pCtx, 
44890   const char *z, 
44891   int n,
44892   void (*xDel)(void *)
44893 ){
44894   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44895   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
44896 }
44897 #ifndef SQLITE_OMIT_UTF16
44898 SQLITE_API void sqlite3_result_text16(
44899   sqlite3_context *pCtx, 
44900   const void *z, 
44901   int n, 
44902   void (*xDel)(void *)
44903 ){
44904   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44905   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
44906 }
44907 SQLITE_API void sqlite3_result_text16be(
44908   sqlite3_context *pCtx, 
44909   const void *z, 
44910   int n, 
44911   void (*xDel)(void *)
44912 ){
44913   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44914   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
44915 }
44916 SQLITE_API void sqlite3_result_text16le(
44917   sqlite3_context *pCtx, 
44918   const void *z, 
44919   int n, 
44920   void (*xDel)(void *)
44921 ){
44922   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44923   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
44924 }
44925 #endif /* SQLITE_OMIT_UTF16 */
44926 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
44927   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44928   sqlite3VdbeMemCopy(&pCtx->s, pValue);
44929 }
44930 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
44931   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44932   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
44933 }
44934 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
44935   pCtx->isError = errCode;
44936 }
44937
44938 /* Force an SQLITE_TOOBIG error. */
44939 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
44940   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44941   pCtx->isError = SQLITE_TOOBIG;
44942   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
44943                        SQLITE_UTF8, SQLITE_STATIC);
44944 }
44945
44946 /* An SQLITE_NOMEM error. */
44947 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
44948   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
44949   sqlite3VdbeMemSetNull(&pCtx->s);
44950   pCtx->isError = SQLITE_NOMEM;
44951   pCtx->s.db->mallocFailed = 1;
44952 }
44953
44954 /*
44955 ** Execute the statement pStmt, either until a row of data is ready, the
44956 ** statement is completely executed or an error occurs.
44957 **
44958 ** This routine implements the bulk of the logic behind the sqlite_step()
44959 ** API.  The only thing omitted is the automatic recompile if a 
44960 ** schema change has occurred.  That detail is handled by the
44961 ** outer sqlite3_step() wrapper procedure.
44962 */
44963 static int sqlite3Step(Vdbe *p){
44964   sqlite3 *db;
44965   int rc;
44966
44967   assert(p);
44968   if( p->magic!=VDBE_MAGIC_RUN ){
44969     return SQLITE_MISUSE;
44970   }
44971
44972   /* Assert that malloc() has not failed */
44973   db = p->db;
44974   if( db->mallocFailed ){
44975     return SQLITE_NOMEM;
44976   }
44977
44978   if( p->pc<=0 && p->expired ){
44979     if( p->rc==SQLITE_OK ){
44980       p->rc = SQLITE_SCHEMA;
44981     }
44982     rc = SQLITE_ERROR;
44983     goto end_of_step;
44984   }
44985   if( sqlite3SafetyOn(db) ){
44986     p->rc = SQLITE_MISUSE;
44987     return SQLITE_MISUSE;
44988   }
44989   if( p->pc<0 ){
44990     /* If there are no other statements currently running, then
44991     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
44992     ** from interrupting a statement that has not yet started.
44993     */
44994     if( db->activeVdbeCnt==0 ){
44995       db->u1.isInterrupted = 0;
44996     }
44997
44998 #ifndef SQLITE_OMIT_TRACE
44999     if( db->xProfile && !db->init.busy ){
45000       double rNow;
45001       sqlite3OsCurrentTime(db->pVfs, &rNow);
45002       p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0;
45003     }
45004 #endif
45005
45006     db->activeVdbeCnt++;
45007     p->pc = 0;
45008     stmtLruRemove(p);
45009   }
45010 #ifndef SQLITE_OMIT_EXPLAIN
45011   if( p->explain ){
45012     rc = sqlite3VdbeList(p);
45013   }else
45014 #endif /* SQLITE_OMIT_EXPLAIN */
45015   {
45016     rc = sqlite3VdbeExec(p);
45017   }
45018
45019   if( sqlite3SafetyOff(db) ){
45020     rc = SQLITE_MISUSE;
45021   }
45022
45023 #ifndef SQLITE_OMIT_TRACE
45024   /* Invoke the profile callback if there is one
45025   */
45026   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
45027            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
45028     double rNow;
45029     u64 elapseTime;
45030
45031     sqlite3OsCurrentTime(db->pVfs, &rNow);
45032     elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime;
45033     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
45034   }
45035 #endif
45036
45037   db->errCode = rc;
45038   /*sqlite3Error(p->db, rc, 0);*/
45039   p->rc = sqlite3ApiExit(p->db, p->rc);
45040 end_of_step:
45041   assert( (rc&0xff)==rc );
45042   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
45043     /* This behavior occurs if sqlite3_prepare_v2() was used to build
45044     ** the prepared statement.  Return error codes directly */
45045     p->db->errCode = p->rc;
45046     /* sqlite3Error(p->db, p->rc, 0); */
45047     return p->rc;
45048   }else{
45049     /* This is for legacy sqlite3_prepare() builds and when the code
45050     ** is SQLITE_ROW or SQLITE_DONE */
45051     return rc;
45052   }
45053 }
45054
45055 /*
45056 ** This is the top-level implementation of sqlite3_step().  Call
45057 ** sqlite3Step() to do most of the work.  If a schema error occurs,
45058 ** call sqlite3Reprepare() and try again.
45059 */
45060 #ifdef SQLITE_OMIT_PARSER
45061 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
45062   int rc = SQLITE_MISUSE;
45063   if( pStmt ){
45064     Vdbe *v;
45065     v = (Vdbe*)pStmt;
45066     sqlite3_mutex_enter(v->db->mutex);
45067     rc = sqlite3Step(v);
45068     sqlite3_mutex_leave(v->db->mutex);
45069   }
45070   return rc;
45071 }
45072 #else
45073 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
45074   int rc = SQLITE_MISUSE;
45075   if( pStmt ){
45076     int cnt = 0;
45077     Vdbe *v = (Vdbe*)pStmt;
45078     sqlite3 *db = v->db;
45079     sqlite3_mutex_enter(db->mutex);
45080     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
45081            && cnt++ < 5
45082            && vdbeReprepare(v) ){
45083       sqlite3_reset(pStmt);
45084       v->expired = 0;
45085     }
45086     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
45087       /* This case occurs after failing to recompile an sql statement. 
45088       ** The error message from the SQL compiler has already been loaded 
45089       ** into the database handle. This block copies the error message 
45090       ** from the database handle into the statement and sets the statement
45091       ** program counter to 0 to ensure that when the statement is 
45092       ** finalized or reset the parser error message is available via
45093       ** sqlite3_errmsg() and sqlite3_errcode().
45094       */
45095       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
45096       sqlite3DbFree(db, v->zErrMsg);
45097       if( !db->mallocFailed ){
45098         v->zErrMsg = sqlite3DbStrDup(db, zErr);
45099       } else {
45100         v->zErrMsg = 0;
45101         v->rc = SQLITE_NOMEM;
45102       }
45103     }
45104     rc = sqlite3ApiExit(db, rc);
45105     sqlite3_mutex_leave(db->mutex);
45106   }
45107   return rc;
45108 }
45109 #endif
45110
45111 /*
45112 ** Extract the user data from a sqlite3_context structure and return a
45113 ** pointer to it.
45114 */
45115 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
45116   assert( p && p->pFunc );
45117   return p->pFunc->pUserData;
45118 }
45119
45120 /*
45121 ** Extract the user data from a sqlite3_context structure and return a
45122 ** pointer to it.
45123 */
45124 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
45125   assert( p && p->pFunc );
45126   return p->s.db;
45127 }
45128
45129 /*
45130 ** The following is the implementation of an SQL function that always
45131 ** fails with an error message stating that the function is used in the
45132 ** wrong context.  The sqlite3_overload_function() API might construct
45133 ** SQL function that use this routine so that the functions will exist
45134 ** for name resolution but are actually overloaded by the xFindFunction
45135 ** method of virtual tables.
45136 */
45137 SQLITE_PRIVATE void sqlite3InvalidFunction(
45138   sqlite3_context *context,  /* The function calling context */
45139   int argc,                  /* Number of arguments to the function */
45140   sqlite3_value **argv       /* Value of each argument */
45141 ){
45142   const char *zName = context->pFunc->zName;
45143   char *zErr;
45144   zErr = sqlite3MPrintf(0,
45145       "unable to use function %s in the requested context", zName);
45146   sqlite3_result_error(context, zErr, -1);
45147   sqlite3_free(zErr);
45148 }
45149
45150 /*
45151 ** Allocate or return the aggregate context for a user function.  A new
45152 ** context is allocated on the first call.  Subsequent calls return the
45153 ** same context that was returned on prior calls.
45154 */
45155 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
45156   Mem *pMem;
45157   assert( p && p->pFunc && p->pFunc->xStep );
45158   assert( sqlite3_mutex_held(p->s.db->mutex) );
45159   pMem = p->pMem;
45160   if( (pMem->flags & MEM_Agg)==0 ){
45161     if( nByte==0 ){
45162       sqlite3VdbeMemReleaseExternal(pMem);
45163       pMem->flags = MEM_Null;
45164       pMem->z = 0;
45165     }else{
45166       sqlite3VdbeMemGrow(pMem, nByte, 0);
45167       pMem->flags = MEM_Agg;
45168       pMem->u.pDef = p->pFunc;
45169       if( pMem->z ){
45170         memset(pMem->z, 0, nByte);
45171       }
45172     }
45173   }
45174   return (void*)pMem->z;
45175 }
45176
45177 /*
45178 ** Return the auxilary data pointer, if any, for the iArg'th argument to
45179 ** the user-function defined by pCtx.
45180 */
45181 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
45182   VdbeFunc *pVdbeFunc;
45183
45184   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45185   pVdbeFunc = pCtx->pVdbeFunc;
45186   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
45187     return 0;
45188   }
45189   return pVdbeFunc->apAux[iArg].pAux;
45190 }
45191
45192 /*
45193 ** Set the auxilary data pointer and delete function, for the iArg'th
45194 ** argument to the user-function defined by pCtx. Any previous value is
45195 ** deleted by calling the delete function specified when it was set.
45196 */
45197 SQLITE_API void sqlite3_set_auxdata(
45198   sqlite3_context *pCtx, 
45199   int iArg, 
45200   void *pAux, 
45201   void (*xDelete)(void*)
45202 ){
45203   struct AuxData *pAuxData;
45204   VdbeFunc *pVdbeFunc;
45205   if( iArg<0 ) goto failed;
45206
45207   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
45208   pVdbeFunc = pCtx->pVdbeFunc;
45209   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
45210     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
45211     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
45212     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
45213     if( !pVdbeFunc ){
45214       goto failed;
45215     }
45216     pCtx->pVdbeFunc = pVdbeFunc;
45217     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
45218     pVdbeFunc->nAux = iArg+1;
45219     pVdbeFunc->pFunc = pCtx->pFunc;
45220   }
45221
45222   pAuxData = &pVdbeFunc->apAux[iArg];
45223   if( pAuxData->pAux && pAuxData->xDelete ){
45224     pAuxData->xDelete(pAuxData->pAux);
45225   }
45226   pAuxData->pAux = pAux;
45227   pAuxData->xDelete = xDelete;
45228   return;
45229
45230 failed:
45231   if( xDelete ){
45232     xDelete(pAux);
45233   }
45234 }
45235
45236 #ifndef SQLITE_OMIT_DEPRECATED
45237 /*
45238 ** Return the number of times the Step function of a aggregate has been 
45239 ** called.
45240 **
45241 ** This function is deprecated.  Do not use it for new code.  It is
45242 ** provide only to avoid breaking legacy code.  New aggregate function
45243 ** implementations should keep their own counts within their aggregate
45244 ** context.
45245 */
45246 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
45247   assert( p && p->pFunc && p->pFunc->xStep );
45248   return p->pMem->n;
45249 }
45250 #endif
45251
45252 /*
45253 ** Return the number of columns in the result set for the statement pStmt.
45254 */
45255 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
45256   Vdbe *pVm = (Vdbe *)pStmt;
45257   return pVm ? pVm->nResColumn : 0;
45258 }
45259
45260 /*
45261 ** Return the number of values available from the current row of the
45262 ** currently executing statement pStmt.
45263 */
45264 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
45265   Vdbe *pVm = (Vdbe *)pStmt;
45266   if( pVm==0 || pVm->pResultSet==0 ) return 0;
45267   return pVm->nResColumn;
45268 }
45269
45270
45271 /*
45272 ** Check to see if column iCol of the given statement is valid.  If
45273 ** it is, return a pointer to the Mem for the value of that column.
45274 ** If iCol is not valid, return a pointer to a Mem which has a value
45275 ** of NULL.
45276 */
45277 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
45278   Vdbe *pVm;
45279   int vals;
45280   Mem *pOut;
45281
45282   pVm = (Vdbe *)pStmt;
45283   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
45284     sqlite3_mutex_enter(pVm->db->mutex);
45285     vals = sqlite3_data_count(pStmt);
45286     pOut = &pVm->pResultSet[i];
45287   }else{
45288     static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
45289     if( pVm->db ){
45290       sqlite3_mutex_enter(pVm->db->mutex);
45291       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
45292     }
45293     pOut = (Mem*)&nullMem;
45294   }
45295   return pOut;
45296 }
45297
45298 /*
45299 ** This function is called after invoking an sqlite3_value_XXX function on a 
45300 ** column value (i.e. a value returned by evaluating an SQL expression in the
45301 ** select list of a SELECT statement) that may cause a malloc() failure. If 
45302 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
45303 ** code of statement pStmt set to SQLITE_NOMEM.
45304 **
45305 ** Specifically, this is called from within:
45306 **
45307 **     sqlite3_column_int()
45308 **     sqlite3_column_int64()
45309 **     sqlite3_column_text()
45310 **     sqlite3_column_text16()
45311 **     sqlite3_column_real()
45312 **     sqlite3_column_bytes()
45313 **     sqlite3_column_bytes16()
45314 **
45315 ** But not for sqlite3_column_blob(), which never calls malloc().
45316 */
45317 static void columnMallocFailure(sqlite3_stmt *pStmt)
45318 {
45319   /* If malloc() failed during an encoding conversion within an
45320   ** sqlite3_column_XXX API, then set the return code of the statement to
45321   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
45322   ** and _finalize() will return NOMEM.
45323   */
45324   Vdbe *p = (Vdbe *)pStmt;
45325   if( p ){
45326     p->rc = sqlite3ApiExit(p->db, p->rc);
45327     sqlite3_mutex_leave(p->db->mutex);
45328   }
45329 }
45330
45331 /**************************** sqlite3_column_  *******************************
45332 ** The following routines are used to access elements of the current row
45333 ** in the result set.
45334 */
45335 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
45336   const void *val;
45337   val = sqlite3_value_blob( columnMem(pStmt,i) );
45338   /* Even though there is no encoding conversion, value_blob() might
45339   ** need to call malloc() to expand the result of a zeroblob() 
45340   ** expression. 
45341   */
45342   columnMallocFailure(pStmt);
45343   return val;
45344 }
45345 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
45346   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
45347   columnMallocFailure(pStmt);
45348   return val;
45349 }
45350 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
45351   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
45352   columnMallocFailure(pStmt);
45353   return val;
45354 }
45355 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
45356   double val = sqlite3_value_double( columnMem(pStmt,i) );
45357   columnMallocFailure(pStmt);
45358   return val;
45359 }
45360 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
45361   int val = sqlite3_value_int( columnMem(pStmt,i) );
45362   columnMallocFailure(pStmt);
45363   return val;
45364 }
45365 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
45366   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
45367   columnMallocFailure(pStmt);
45368   return val;
45369 }
45370 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
45371   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
45372   columnMallocFailure(pStmt);
45373   return val;
45374 }
45375 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
45376   Mem *pOut = columnMem(pStmt, i);
45377   if( pOut->flags&MEM_Static ){
45378     pOut->flags &= ~MEM_Static;
45379     pOut->flags |= MEM_Ephem;
45380   }
45381   columnMallocFailure(pStmt);
45382   return (sqlite3_value *)pOut;
45383 }
45384 #ifndef SQLITE_OMIT_UTF16
45385 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
45386   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
45387   columnMallocFailure(pStmt);
45388   return val;
45389 }
45390 #endif /* SQLITE_OMIT_UTF16 */
45391 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
45392   int iType = sqlite3_value_type( columnMem(pStmt,i) );
45393   columnMallocFailure(pStmt);
45394   return iType;
45395 }
45396
45397 /* The following function is experimental and subject to change or
45398 ** removal */
45399 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
45400 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
45401 **}
45402 */
45403
45404 /*
45405 ** Convert the N-th element of pStmt->pColName[] into a string using
45406 ** xFunc() then return that string.  If N is out of range, return 0.
45407 **
45408 ** There are up to 5 names for each column.  useType determines which
45409 ** name is returned.  Here are the names:
45410 **
45411 **    0      The column name as it should be displayed for output
45412 **    1      The datatype name for the column
45413 **    2      The name of the database that the column derives from
45414 **    3      The name of the table that the column derives from
45415 **    4      The name of the table column that the result column derives from
45416 **
45417 ** If the result is not a simple column reference (if it is an expression
45418 ** or a constant) then useTypes 2, 3, and 4 return NULL.
45419 */
45420 static const void *columnName(
45421   sqlite3_stmt *pStmt,
45422   int N,
45423   const void *(*xFunc)(Mem*),
45424   int useType
45425 ){
45426   const void *ret = 0;
45427   Vdbe *p = (Vdbe *)pStmt;
45428   int n;
45429   
45430
45431   if( p!=0 ){
45432     n = sqlite3_column_count(pStmt);
45433     if( N<n && N>=0 ){
45434       N += useType*n;
45435       sqlite3_mutex_enter(p->db->mutex);
45436       ret = xFunc(&p->aColName[N]);
45437
45438       /* A malloc may have failed inside of the xFunc() call. If this
45439       ** is the case, clear the mallocFailed flag and return NULL.
45440       */
45441       if( p->db && p->db->mallocFailed ){
45442         p->db->mallocFailed = 0;
45443         ret = 0;
45444       }
45445       sqlite3_mutex_leave(p->db->mutex);
45446     }
45447   }
45448   return ret;
45449 }
45450
45451 /*
45452 ** Return the name of the Nth column of the result set returned by SQL
45453 ** statement pStmt.
45454 */
45455 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
45456   return columnName(
45457       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
45458 }
45459 #ifndef SQLITE_OMIT_UTF16
45460 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
45461   return columnName(
45462       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
45463 }
45464 #endif
45465
45466 /*
45467 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
45468 ** not define OMIT_DECLTYPE.
45469 */
45470 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
45471 # error "Must not define both SQLITE_OMIT_DECLTYPE \
45472          and SQLITE_ENABLE_COLUMN_METADATA"
45473 #endif
45474
45475 #ifndef SQLITE_OMIT_DECLTYPE
45476 /*
45477 ** Return the column declaration type (if applicable) of the 'i'th column
45478 ** of the result set of SQL statement pStmt.
45479 */
45480 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
45481   return columnName(
45482       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
45483 }
45484 #ifndef SQLITE_OMIT_UTF16
45485 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
45486   return columnName(
45487       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
45488 }
45489 #endif /* SQLITE_OMIT_UTF16 */
45490 #endif /* SQLITE_OMIT_DECLTYPE */
45491
45492 #ifdef SQLITE_ENABLE_COLUMN_METADATA
45493 /*
45494 ** Return the name of the database from which a result column derives.
45495 ** NULL is returned if the result column is an expression or constant or
45496 ** anything else which is not an unabiguous reference to a database column.
45497 */
45498 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
45499   return columnName(
45500       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
45501 }
45502 #ifndef SQLITE_OMIT_UTF16
45503 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
45504   return columnName(
45505       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
45506 }
45507 #endif /* SQLITE_OMIT_UTF16 */
45508
45509 /*
45510 ** Return the name of the table from which a result column derives.
45511 ** NULL is returned if the result column is an expression or constant or
45512 ** anything else which is not an unabiguous reference to a database column.
45513 */
45514 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
45515   return columnName(
45516       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
45517 }
45518 #ifndef SQLITE_OMIT_UTF16
45519 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
45520   return columnName(
45521       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
45522 }
45523 #endif /* SQLITE_OMIT_UTF16 */
45524
45525 /*
45526 ** Return the name of the table column from which a result column derives.
45527 ** NULL is returned if the result column is an expression or constant or
45528 ** anything else which is not an unabiguous reference to a database column.
45529 */
45530 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
45531   return columnName(
45532       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
45533 }
45534 #ifndef SQLITE_OMIT_UTF16
45535 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
45536   return columnName(
45537       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
45538 }
45539 #endif /* SQLITE_OMIT_UTF16 */
45540 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
45541
45542
45543 /******************************* sqlite3_bind_  ***************************
45544 ** 
45545 ** Routines used to attach values to wildcards in a compiled SQL statement.
45546 */
45547 /*
45548 ** Unbind the value bound to variable i in virtual machine p. This is the 
45549 ** the same as binding a NULL value to the column. If the "i" parameter is
45550 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
45551 **
45552 ** A successful evaluation of this routine acquires the mutex on p.
45553 ** the mutex is released if any kind of error occurs.
45554 **
45555 ** The error code stored in database p->db is overwritten with the return
45556 ** value in any case.
45557 */
45558 static int vdbeUnbind(Vdbe *p, int i){
45559   Mem *pVar;
45560   if( p==0 ) return SQLITE_MISUSE;
45561   sqlite3_mutex_enter(p->db->mutex);
45562   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
45563     sqlite3Error(p->db, SQLITE_MISUSE, 0);
45564     sqlite3_mutex_leave(p->db->mutex);
45565     return SQLITE_MISUSE;
45566   }
45567   if( i<1 || i>p->nVar ){
45568     sqlite3Error(p->db, SQLITE_RANGE, 0);
45569     sqlite3_mutex_leave(p->db->mutex);
45570     return SQLITE_RANGE;
45571   }
45572   i--;
45573   pVar = &p->aVar[i];
45574   sqlite3VdbeMemRelease(pVar);
45575   pVar->flags = MEM_Null;
45576   sqlite3Error(p->db, SQLITE_OK, 0);
45577   return SQLITE_OK;
45578 }
45579
45580 /*
45581 ** Bind a text or BLOB value.
45582 */
45583 static int bindText(
45584   sqlite3_stmt *pStmt,   /* The statement to bind against */
45585   int i,                 /* Index of the parameter to bind */
45586   const void *zData,     /* Pointer to the data to be bound */
45587   int nData,             /* Number of bytes of data to be bound */
45588   void (*xDel)(void*),   /* Destructor for the data */
45589   int encoding           /* Encoding for the data */
45590 ){
45591   Vdbe *p = (Vdbe *)pStmt;
45592   Mem *pVar;
45593   int rc;
45594
45595   rc = vdbeUnbind(p, i);
45596   if( rc==SQLITE_OK ){
45597     if( zData!=0 ){
45598       pVar = &p->aVar[i-1];
45599       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
45600       if( rc==SQLITE_OK && encoding!=0 ){
45601         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
45602       }
45603       sqlite3Error(p->db, rc, 0);
45604       rc = sqlite3ApiExit(p->db, rc);
45605     }
45606     sqlite3_mutex_leave(p->db->mutex);
45607   }
45608   return rc;
45609 }
45610
45611
45612 /*
45613 ** Bind a blob value to an SQL statement variable.
45614 */
45615 SQLITE_API int sqlite3_bind_blob(
45616   sqlite3_stmt *pStmt, 
45617   int i, 
45618   const void *zData, 
45619   int nData, 
45620   void (*xDel)(void*)
45621 ){
45622   return bindText(pStmt, i, zData, nData, xDel, 0);
45623 }
45624 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
45625   int rc;
45626   Vdbe *p = (Vdbe *)pStmt;
45627   rc = vdbeUnbind(p, i);
45628   if( rc==SQLITE_OK ){
45629     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
45630     sqlite3_mutex_leave(p->db->mutex);
45631   }
45632   return rc;
45633 }
45634 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
45635   return sqlite3_bind_int64(p, i, (i64)iValue);
45636 }
45637 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
45638   int rc;
45639   Vdbe *p = (Vdbe *)pStmt;
45640   rc = vdbeUnbind(p, i);
45641   if( rc==SQLITE_OK ){
45642     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
45643     sqlite3_mutex_leave(p->db->mutex);
45644   }
45645   return rc;
45646 }
45647 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
45648   int rc;
45649   Vdbe *p = (Vdbe*)pStmt;
45650   rc = vdbeUnbind(p, i);
45651   if( rc==SQLITE_OK ){
45652     sqlite3_mutex_leave(p->db->mutex);
45653   }
45654   return rc;
45655 }
45656 SQLITE_API int sqlite3_bind_text( 
45657   sqlite3_stmt *pStmt, 
45658   int i, 
45659   const char *zData, 
45660   int nData, 
45661   void (*xDel)(void*)
45662 ){
45663   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
45664 }
45665 #ifndef SQLITE_OMIT_UTF16
45666 SQLITE_API int sqlite3_bind_text16(
45667   sqlite3_stmt *pStmt, 
45668   int i, 
45669   const void *zData, 
45670   int nData, 
45671   void (*xDel)(void*)
45672 ){
45673   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
45674 }
45675 #endif /* SQLITE_OMIT_UTF16 */
45676 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
45677   int rc;
45678   Vdbe *p = (Vdbe *)pStmt;
45679   rc = vdbeUnbind(p, i);
45680   if( rc==SQLITE_OK ){
45681     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
45682     if( rc==SQLITE_OK ){
45683       rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
45684     }
45685     sqlite3_mutex_leave(p->db->mutex);
45686   }
45687   rc = sqlite3ApiExit(p->db, rc);
45688   return rc;
45689 }
45690 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
45691   int rc;
45692   Vdbe *p = (Vdbe *)pStmt;
45693   rc = vdbeUnbind(p, i);
45694   if( rc==SQLITE_OK ){
45695     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
45696     sqlite3_mutex_leave(p->db->mutex);
45697   }
45698   return rc;
45699 }
45700
45701 /*
45702 ** Return the number of wildcards that can be potentially bound to.
45703 ** This routine is added to support DBD::SQLite.  
45704 */
45705 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
45706   Vdbe *p = (Vdbe*)pStmt;
45707   return p ? p->nVar : 0;
45708 }
45709
45710 /*
45711 ** Create a mapping from variable numbers to variable names
45712 ** in the Vdbe.azVar[] array, if such a mapping does not already
45713 ** exist.
45714 */
45715 static void createVarMap(Vdbe *p){
45716   if( !p->okVar ){
45717     sqlite3_mutex_enter(p->db->mutex);
45718     if( !p->okVar ){
45719       int j;
45720       Op *pOp;
45721       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
45722         if( pOp->opcode==OP_Variable ){
45723           assert( pOp->p1>0 && pOp->p1<=p->nVar );
45724           p->azVar[pOp->p1-1] = pOp->p4.z;
45725         }
45726       }
45727       p->okVar = 1;
45728     }
45729     sqlite3_mutex_leave(p->db->mutex);
45730   }
45731 }
45732
45733 /*
45734 ** Return the name of a wildcard parameter.  Return NULL if the index
45735 ** is out of range or if the wildcard is unnamed.
45736 **
45737 ** The result is always UTF-8.
45738 */
45739 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
45740   Vdbe *p = (Vdbe*)pStmt;
45741   if( p==0 || i<1 || i>p->nVar ){
45742     return 0;
45743   }
45744   createVarMap(p);
45745   return p->azVar[i-1];
45746 }
45747
45748 /*
45749 ** Given a wildcard parameter name, return the index of the variable
45750 ** with that name.  If there is no variable with the given name,
45751 ** return 0.
45752 */
45753 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
45754   Vdbe *p = (Vdbe*)pStmt;
45755   int i;
45756   if( p==0 ){
45757     return 0;
45758   }
45759   createVarMap(p); 
45760   if( zName ){
45761     for(i=0; i<p->nVar; i++){
45762       const char *z = p->azVar[i];
45763       if( z && strcmp(z,zName)==0 ){
45764         return i+1;
45765       }
45766     }
45767   }
45768   return 0;
45769 }
45770
45771 /*
45772 ** Transfer all bindings from the first statement over to the second.
45773 ** If the two statements contain a different number of bindings, then
45774 ** an SQLITE_ERROR is returned.
45775 */
45776 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
45777   Vdbe *pFrom = (Vdbe*)pFromStmt;
45778   Vdbe *pTo = (Vdbe*)pToStmt;
45779   int i, rc = SQLITE_OK;
45780   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
45781     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
45782     || pTo->db!=pFrom->db ){
45783     return SQLITE_MISUSE;
45784   }
45785   if( pFrom->nVar!=pTo->nVar ){
45786     return SQLITE_ERROR;
45787   }
45788   sqlite3_mutex_enter(pTo->db->mutex);
45789   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
45790     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
45791   }
45792   sqlite3_mutex_leave(pTo->db->mutex);
45793   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
45794   return rc;
45795 }
45796
45797 #ifndef SQLITE_OMIT_DEPRECATED
45798 /*
45799 ** Deprecated external interface.  Internal/core SQLite code
45800 ** should call sqlite3TransferBindings.
45801 */
45802 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
45803   return sqlite3TransferBindings(pFromStmt, pToStmt);
45804 }
45805 #endif
45806
45807 /*
45808 ** Return the sqlite3* database handle to which the prepared statement given
45809 ** in the argument belongs.  This is the same database handle that was
45810 ** the first argument to the sqlite3_prepare() that was used to create
45811 ** the statement in the first place.
45812 */
45813 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
45814   return pStmt ? ((Vdbe*)pStmt)->db : 0;
45815 }
45816
45817 /*
45818 ** Return a pointer to the next prepared statement after pStmt associated
45819 ** with database connection pDb.  If pStmt is NULL, return the first
45820 ** prepared statement for the database connection.  Return NULL if there
45821 ** are no more.
45822 */
45823 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
45824   sqlite3_stmt *pNext;
45825   sqlite3_mutex_enter(pDb->mutex);
45826   if( pStmt==0 ){
45827     pNext = (sqlite3_stmt*)pDb->pVdbe;
45828   }else{
45829     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
45830   }
45831   sqlite3_mutex_leave(pDb->mutex);
45832   return pNext;
45833 }
45834
45835 /*
45836 ** Return the value of a status counter for a prepared statement
45837 */
45838 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
45839   Vdbe *pVdbe = (Vdbe*)pStmt;
45840   int v = pVdbe->aCounter[op-1];
45841   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
45842   return v;
45843 }
45844
45845 /************** End of vdbeapi.c *********************************************/
45846 /************** Begin file vdbe.c ********************************************/
45847 /*
45848 ** 2001 September 15
45849 **
45850 ** The author disclaims copyright to this source code.  In place of
45851 ** a legal notice, here is a blessing:
45852 **
45853 **    May you do good and not evil.
45854 **    May you find forgiveness for yourself and forgive others.
45855 **    May you share freely, never taking more than you give.
45856 **
45857 *************************************************************************
45858 ** The code in this file implements execution method of the 
45859 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
45860 ** handles housekeeping details such as creating and deleting
45861 ** VDBE instances.  This file is solely interested in executing
45862 ** the VDBE program.
45863 **
45864 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
45865 ** to a VDBE.
45866 **
45867 ** The SQL parser generates a program which is then executed by
45868 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
45869 ** similar in form to assembly language.  The program consists of
45870 ** a linear sequence of operations.  Each operation has an opcode 
45871 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
45872 ** is a null-terminated string.  Operand P5 is an unsigned character.
45873 ** Few opcodes use all 5 operands.
45874 **
45875 ** Computation results are stored on a set of registers numbered beginning
45876 ** with 1 and going up to Vdbe.nMem.  Each register can store
45877 ** either an integer, a null-terminated string, a floating point
45878 ** number, or the SQL "NULL" value.  An implicit conversion from one
45879 ** type to the other occurs as necessary.
45880 ** 
45881 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
45882 ** function which does the work of interpreting a VDBE program.
45883 ** But other routines are also provided to help in building up
45884 ** a program instruction by instruction.
45885 **
45886 ** Various scripts scan this source file in order to generate HTML
45887 ** documentation, headers files, or other derived files.  The formatting
45888 ** of the code in this file is, therefore, important.  See other comments
45889 ** in this file for details.  If in doubt, do not deviate from existing
45890 ** commenting and indentation practices when changing or adding code.
45891 **
45892 ** $Id: vdbe.c,v 1.782 2008/10/08 17:58:49 danielk1977 Exp $
45893 */
45894
45895 /*
45896 ** The following global variable is incremented every time a cursor
45897 ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
45898 ** procedures use this information to make sure that indices are
45899 ** working correctly.  This variable has no function other than to
45900 ** help verify the correct operation of the library.
45901 */
45902 #ifdef SQLITE_TEST
45903 SQLITE_API int sqlite3_search_count = 0;
45904 #endif
45905
45906 /*
45907 ** When this global variable is positive, it gets decremented once before
45908 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
45909 ** field of the sqlite3 structure is set in order to simulate and interrupt.
45910 **
45911 ** This facility is used for testing purposes only.  It does not function
45912 ** in an ordinary build.
45913 */
45914 #ifdef SQLITE_TEST
45915 SQLITE_API int sqlite3_interrupt_count = 0;
45916 #endif
45917
45918 /*
45919 ** The next global variable is incremented each type the OP_Sort opcode
45920 ** is executed.  The test procedures use this information to make sure that
45921 ** sorting is occurring or not occurring at appropriate times.   This variable
45922 ** has no function other than to help verify the correct operation of the
45923 ** library.
45924 */
45925 #ifdef SQLITE_TEST
45926 SQLITE_API int sqlite3_sort_count = 0;
45927 #endif
45928
45929 /*
45930 ** The next global variable records the size of the largest MEM_Blob
45931 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
45932 ** use this information to make sure that the zero-blob functionality
45933 ** is working correctly.   This variable has no function other than to
45934 ** help verify the correct operation of the library.
45935 */
45936 #ifdef SQLITE_TEST
45937 SQLITE_API int sqlite3_max_blobsize = 0;
45938 static void updateMaxBlobsize(Mem *p){
45939   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
45940     sqlite3_max_blobsize = p->n;
45941   }
45942 }
45943 #endif
45944
45945 /*
45946 ** Test a register to see if it exceeds the current maximum blob size.
45947 ** If it does, record the new maximum blob size.
45948 */
45949 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
45950 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
45951 #else
45952 # define UPDATE_MAX_BLOBSIZE(P)
45953 #endif
45954
45955 /*
45956 ** Convert the given register into a string if it isn't one
45957 ** already. Return non-zero if a malloc() fails.
45958 */
45959 #define Stringify(P, enc) \
45960    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
45961      { goto no_mem; }
45962
45963 /*
45964 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
45965 ** a pointer to a dynamically allocated string where some other entity
45966 ** is responsible for deallocating that string.  Because the register
45967 ** does not control the string, it might be deleted without the register
45968 ** knowing it.
45969 **
45970 ** This routine converts an ephemeral string into a dynamically allocated
45971 ** string that the register itself controls.  In other words, it
45972 ** converts an MEM_Ephem string into an MEM_Dyn string.
45973 */
45974 #define Deephemeralize(P) \
45975    if( ((P)->flags&MEM_Ephem)!=0 \
45976        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
45977
45978 /*
45979 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
45980 ** P if required.
45981 */
45982 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
45983
45984 /*
45985 ** Argument pMem points at a register that will be passed to a
45986 ** user-defined function or returned to the user as the result of a query.
45987 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
45988 ** register variables.  This routine sets the pMem->enc and pMem->type
45989 ** variables used by the sqlite3_value_*() routines.
45990 */
45991 #define storeTypeInfo(A,B) _storeTypeInfo(A)
45992 static void _storeTypeInfo(Mem *pMem){
45993   int flags = pMem->flags;
45994   if( flags & MEM_Null ){
45995     pMem->type = SQLITE_NULL;
45996   }
45997   else if( flags & MEM_Int ){
45998     pMem->type = SQLITE_INTEGER;
45999   }
46000   else if( flags & MEM_Real ){
46001     pMem->type = SQLITE_FLOAT;
46002   }
46003   else if( flags & MEM_Str ){
46004     pMem->type = SQLITE_TEXT;
46005   }else{
46006     pMem->type = SQLITE_BLOB;
46007   }
46008 }
46009
46010 /*
46011 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
46012 ** created by mkopcodeh.awk during compilation.  Data is obtained
46013 ** from the comments following the "case OP_xxxx:" statements in
46014 ** this file.  
46015 */
46016 static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
46017
46018 /*
46019 ** Return true if an opcode has any of the OPFLG_xxx properties
46020 ** specified by mask.
46021 */
46022 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
46023   assert( opcode>0 && opcode<sizeof(opcodeProperty) );
46024   return (opcodeProperty[opcode]&mask)!=0;
46025 }
46026
46027 /*
46028 ** Allocate cursor number iCur.  Return a pointer to it.  Return NULL
46029 ** if we run out of memory.
46030 */
46031 static Cursor *allocateCursor(
46032   Vdbe *p, 
46033   int iCur, 
46034   Op *pOp,
46035   int iDb, 
46036   int isBtreeCursor
46037 ){
46038   /* Find the memory cell that will be used to store the blob of memory
46039   ** required for this Cursor structure. It is convenient to use a 
46040   ** vdbe memory cell to manage the memory allocation required for a
46041   ** Cursor structure for the following reasons:
46042   **
46043   **   * Sometimes cursor numbers are used for a couple of different
46044   **     purposes in a vdbe program. The different uses might require
46045   **     different sized allocations. Memory cells provide growable
46046   **     allocations.
46047   **
46048   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
46049   **     be freed lazily via the sqlite3_release_memory() API. This
46050   **     minimizes the number of malloc calls made by the system.
46051   **
46052   ** Memory cells for cursors are allocated at the top of the address
46053   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
46054   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
46055   */
46056   Mem *pMem = &p->aMem[p->nMem-iCur];
46057
46058   int nByte;
46059   Cursor *pCx = 0;
46060   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
46061   ** the number of fields in the records contained in the table or
46062   ** index being opened. Use this to reserve space for the 
46063   ** Cursor.aType[] array.
46064   */
46065   int nField = 0;
46066   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
46067     nField = pOp->p2;
46068   }
46069   nByte = 
46070       sizeof(Cursor) + 
46071       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
46072       2*nField*sizeof(u32);
46073
46074   assert( iCur<p->nCursor );
46075   if( p->apCsr[iCur] ){
46076     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
46077     p->apCsr[iCur] = 0;
46078   }
46079   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46080     p->apCsr[iCur] = pCx = (Cursor *)pMem->z;
46081     memset(pMem->z, 0, nByte);
46082     pCx->iDb = iDb;
46083     pCx->nField = nField;
46084     if( nField ){
46085       pCx->aType = (u32 *)&pMem->z[sizeof(Cursor)];
46086     }
46087     if( isBtreeCursor ){
46088       pCx->pCursor = (BtCursor *)&pMem->z[sizeof(Cursor)+2*nField*sizeof(u32)];
46089     }
46090   }
46091   return pCx;
46092 }
46093
46094 /*
46095 ** Try to convert a value into a numeric representation if we can
46096 ** do so without loss of information.  In other words, if the string
46097 ** looks like a number, convert it into a number.  If it does not
46098 ** look like a number, leave it alone.
46099 */
46100 static void applyNumericAffinity(Mem *pRec){
46101   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
46102     int realnum;
46103     sqlite3VdbeMemNulTerminate(pRec);
46104     if( (pRec->flags&MEM_Str)
46105          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
46106       i64 value;
46107       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
46108       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
46109         pRec->u.i = value;
46110         MemSetTypeFlag(pRec, MEM_Int);
46111       }else{
46112         sqlite3VdbeMemRealify(pRec);
46113       }
46114     }
46115   }
46116 }
46117
46118 /*
46119 ** Processing is determine by the affinity parameter:
46120 **
46121 ** SQLITE_AFF_INTEGER:
46122 ** SQLITE_AFF_REAL:
46123 ** SQLITE_AFF_NUMERIC:
46124 **    Try to convert pRec to an integer representation or a 
46125 **    floating-point representation if an integer representation
46126 **    is not possible.  Note that the integer representation is
46127 **    always preferred, even if the affinity is REAL, because
46128 **    an integer representation is more space efficient on disk.
46129 **
46130 ** SQLITE_AFF_TEXT:
46131 **    Convert pRec to a text representation.
46132 **
46133 ** SQLITE_AFF_NONE:
46134 **    No-op.  pRec is unchanged.
46135 */
46136 static void applyAffinity(
46137   Mem *pRec,          /* The value to apply affinity to */
46138   char affinity,      /* The affinity to be applied */
46139   u8 enc              /* Use this text encoding */
46140 ){
46141   if( affinity==SQLITE_AFF_TEXT ){
46142     /* Only attempt the conversion to TEXT if there is an integer or real
46143     ** representation (blob and NULL do not get converted) but no string
46144     ** representation.
46145     */
46146     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
46147       sqlite3VdbeMemStringify(pRec, enc);
46148     }
46149     pRec->flags &= ~(MEM_Real|MEM_Int);
46150   }else if( affinity!=SQLITE_AFF_NONE ){
46151     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
46152              || affinity==SQLITE_AFF_NUMERIC );
46153     applyNumericAffinity(pRec);
46154     if( pRec->flags & MEM_Real ){
46155       sqlite3VdbeIntegerAffinity(pRec);
46156     }
46157   }
46158 }
46159
46160 /*
46161 ** Try to convert the type of a function argument or a result column
46162 ** into a numeric representation.  Use either INTEGER or REAL whichever
46163 ** is appropriate.  But only do the conversion if it is possible without
46164 ** loss of information and return the revised type of the argument.
46165 **
46166 ** This is an EXPERIMENTAL api and is subject to change or removal.
46167 */
46168 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
46169   Mem *pMem = (Mem*)pVal;
46170   applyNumericAffinity(pMem);
46171   storeTypeInfo(pMem, 0);
46172   return pMem->type;
46173 }
46174
46175 /*
46176 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
46177 ** not the internal Mem* type.
46178 */
46179 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
46180   sqlite3_value *pVal, 
46181   u8 affinity, 
46182   u8 enc
46183 ){
46184   applyAffinity((Mem *)pVal, affinity, enc);
46185 }
46186
46187 #ifdef SQLITE_DEBUG
46188 /*
46189 ** Write a nice string representation of the contents of cell pMem
46190 ** into buffer zBuf, length nBuf.
46191 */
46192 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
46193   char *zCsr = zBuf;
46194   int f = pMem->flags;
46195
46196   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
46197
46198   if( f&MEM_Blob ){
46199     int i;
46200     char c;
46201     if( f & MEM_Dyn ){
46202       c = 'z';
46203       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46204     }else if( f & MEM_Static ){
46205       c = 't';
46206       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46207     }else if( f & MEM_Ephem ){
46208       c = 'e';
46209       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46210     }else{
46211       c = 's';
46212     }
46213
46214     sqlite3_snprintf(100, zCsr, "%c", c);
46215     zCsr += strlen(zCsr);
46216     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
46217     zCsr += strlen(zCsr);
46218     for(i=0; i<16 && i<pMem->n; i++){
46219       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
46220       zCsr += strlen(zCsr);
46221     }
46222     for(i=0; i<16 && i<pMem->n; i++){
46223       char z = pMem->z[i];
46224       if( z<32 || z>126 ) *zCsr++ = '.';
46225       else *zCsr++ = z;
46226     }
46227
46228     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
46229     zCsr += strlen(zCsr);
46230     if( f & MEM_Zero ){
46231       sqlite3_snprintf(100, zCsr,"+%lldz",pMem->u.i);
46232       zCsr += strlen(zCsr);
46233     }
46234     *zCsr = '\0';
46235   }else if( f & MEM_Str ){
46236     int j, k;
46237     zBuf[0] = ' ';
46238     if( f & MEM_Dyn ){
46239       zBuf[1] = 'z';
46240       assert( (f & (MEM_Static|MEM_Ephem))==0 );
46241     }else if( f & MEM_Static ){
46242       zBuf[1] = 't';
46243       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
46244     }else if( f & MEM_Ephem ){
46245       zBuf[1] = 'e';
46246       assert( (f & (MEM_Static|MEM_Dyn))==0 );
46247     }else{
46248       zBuf[1] = 's';
46249     }
46250     k = 2;
46251     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
46252     k += strlen(&zBuf[k]);
46253     zBuf[k++] = '[';
46254     for(j=0; j<15 && j<pMem->n; j++){
46255       u8 c = pMem->z[j];
46256       if( c>=0x20 && c<0x7f ){
46257         zBuf[k++] = c;
46258       }else{
46259         zBuf[k++] = '.';
46260       }
46261     }
46262     zBuf[k++] = ']';
46263     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
46264     k += strlen(&zBuf[k]);
46265     zBuf[k++] = 0;
46266   }
46267 }
46268 #endif
46269
46270 #ifdef SQLITE_DEBUG
46271 /*
46272 ** Print the value of a register for tracing purposes:
46273 */
46274 static void memTracePrint(FILE *out, Mem *p){
46275   if( p->flags & MEM_Null ){
46276     fprintf(out, " NULL");
46277   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
46278     fprintf(out, " si:%lld", p->u.i);
46279   }else if( p->flags & MEM_Int ){
46280     fprintf(out, " i:%lld", p->u.i);
46281   }else if( p->flags & MEM_Real ){
46282     fprintf(out, " r:%g", p->r);
46283   }else{
46284     char zBuf[200];
46285     sqlite3VdbeMemPrettyPrint(p, zBuf);
46286     fprintf(out, " ");
46287     fprintf(out, "%s", zBuf);
46288   }
46289 }
46290 static void registerTrace(FILE *out, int iReg, Mem *p){
46291   fprintf(out, "REG[%d] = ", iReg);
46292   memTracePrint(out, p);
46293   fprintf(out, "\n");
46294 }
46295 #endif
46296
46297 #ifdef SQLITE_DEBUG
46298 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
46299 #else
46300 #  define REGISTER_TRACE(R,M)
46301 #endif
46302
46303
46304 #ifdef VDBE_PROFILE
46305
46306 /* 
46307 ** hwtime.h contains inline assembler code for implementing 
46308 ** high-performance timing routines.
46309 */
46310 /************** Include hwtime.h in the middle of vdbe.c *********************/
46311 /************** Begin file hwtime.h ******************************************/
46312 /*
46313 ** 2008 May 27
46314 **
46315 ** The author disclaims copyright to this source code.  In place of
46316 ** a legal notice, here is a blessing:
46317 **
46318 **    May you do good and not evil.
46319 **    May you find forgiveness for yourself and forgive others.
46320 **    May you share freely, never taking more than you give.
46321 **
46322 ******************************************************************************
46323 **
46324 ** This file contains inline asm code for retrieving "high-performance"
46325 ** counters for x86 class CPUs.
46326 **
46327 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
46328 */
46329 #ifndef _HWTIME_H_
46330 #define _HWTIME_H_
46331
46332 /*
46333 ** The following routine only works on pentium-class (or newer) processors.
46334 ** It uses the RDTSC opcode to read the cycle count value out of the
46335 ** processor and returns that value.  This can be used for high-res
46336 ** profiling.
46337 */
46338 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
46339       (defined(i386) || defined(__i386__) || defined(_M_IX86))
46340
46341   #if defined(__GNUC__)
46342
46343   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46344      unsigned int lo, hi;
46345      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
46346      return (sqlite_uint64)hi << 32 | lo;
46347   }
46348
46349   #elif defined(_MSC_VER)
46350
46351   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
46352      __asm {
46353         rdtsc
46354         ret       ; return value at EDX:EAX
46355      }
46356   }
46357
46358   #endif
46359
46360 #elif (defined(__GNUC__) && defined(__x86_64__))
46361
46362   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46363       unsigned long val;
46364       __asm__ __volatile__ ("rdtsc" : "=A" (val));
46365       return val;
46366   }
46367  
46368 #elif (defined(__GNUC__) && defined(__ppc__))
46369
46370   __inline__ sqlite_uint64 sqlite3Hwtime(void){
46371       unsigned long long retval;
46372       unsigned long junk;
46373       __asm__ __volatile__ ("\n\
46374           1:      mftbu   %1\n\
46375                   mftb    %L0\n\
46376                   mftbu   %0\n\
46377                   cmpw    %0,%1\n\
46378                   bne     1b"
46379                   : "=r" (retval), "=r" (junk));
46380       return retval;
46381   }
46382
46383 #else
46384
46385   #error Need implementation of sqlite3Hwtime() for your platform.
46386
46387   /*
46388   ** To compile without implementing sqlite3Hwtime() for your platform,
46389   ** you can remove the above #error and use the following
46390   ** stub function.  You will lose timing support for many
46391   ** of the debugging and testing utilities, but it should at
46392   ** least compile and run.
46393   */
46394 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
46395
46396 #endif
46397
46398 #endif /* !defined(_HWTIME_H_) */
46399
46400 /************** End of hwtime.h **********************************************/
46401 /************** Continuing where we left off in vdbe.c ***********************/
46402
46403 #endif
46404
46405 /*
46406 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
46407 ** sqlite3_interrupt() routine has been called.  If it has been, then
46408 ** processing of the VDBE program is interrupted.
46409 **
46410 ** This macro added to every instruction that does a jump in order to
46411 ** implement a loop.  This test used to be on every single instruction,
46412 ** but that meant we more testing that we needed.  By only testing the
46413 ** flag on jump instructions, we get a (small) speed improvement.
46414 */
46415 #define CHECK_FOR_INTERRUPT \
46416    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
46417
46418 #ifdef SQLITE_DEBUG
46419 static int fileExists(sqlite3 *db, const char *zFile){
46420   int res = 0;
46421   int rc = SQLITE_OK;
46422 #ifdef SQLITE_TEST
46423   /* If we are currently testing IO errors, then do not call OsAccess() to
46424   ** test for the presence of zFile. This is because any IO error that
46425   ** occurs here will not be reported, causing the test to fail.
46426   */
46427   extern int sqlite3_io_error_pending;
46428   if( sqlite3_io_error_pending<=0 )
46429 #endif
46430     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
46431   return (res && rc==SQLITE_OK);
46432 }
46433 #endif
46434
46435 /*
46436 ** Execute as much of a VDBE program as we can then return.
46437 **
46438 ** sqlite3VdbeMakeReady() must be called before this routine in order to
46439 ** close the program with a final OP_Halt and to set up the callbacks
46440 ** and the error message pointer.
46441 **
46442 ** Whenever a row or result data is available, this routine will either
46443 ** invoke the result callback (if there is one) or return with
46444 ** SQLITE_ROW.
46445 **
46446 ** If an attempt is made to open a locked database, then this routine
46447 ** will either invoke the busy callback (if there is one) or it will
46448 ** return SQLITE_BUSY.
46449 **
46450 ** If an error occurs, an error message is written to memory obtained
46451 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
46452 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
46453 **
46454 ** If the callback ever returns non-zero, then the program exits
46455 ** immediately.  There will be no error message but the p->rc field is
46456 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
46457 **
46458 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
46459 ** routine to return SQLITE_ERROR.
46460 **
46461 ** Other fatal errors return SQLITE_ERROR.
46462 **
46463 ** After this routine has finished, sqlite3VdbeFinalize() should be
46464 ** used to clean up the mess that was left behind.
46465 */
46466 SQLITE_PRIVATE int sqlite3VdbeExec(
46467   Vdbe *p                    /* The VDBE */
46468 ){
46469   int pc;                    /* The program counter */
46470   Op *pOp;                   /* Current operation */
46471   int rc = SQLITE_OK;        /* Value to return */
46472   sqlite3 *db = p->db;       /* The database */
46473   u8 encoding = ENC(db);     /* The database encoding */
46474   Mem *pIn1, *pIn2, *pIn3;   /* Input operands */
46475   Mem *pOut;                 /* Output operand */
46476   u8 opProperty;
46477   int iCompare = 0;          /* Result of last OP_Compare operation */
46478   int *aPermute = 0;         /* Permuation of columns for OP_Compare */
46479 #ifdef VDBE_PROFILE
46480   u64 start;                 /* CPU clock count at start of opcode */
46481   int origPc;                /* Program counter at start of opcode */
46482 #endif
46483 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
46484   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
46485 #endif
46486   UnpackedRecord aTempRec[16]; /* Space to hold a transient UnpackedRecord */
46487
46488
46489   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
46490   assert( db->magic==SQLITE_MAGIC_BUSY );
46491   sqlite3BtreeMutexArrayEnter(&p->aMutex);
46492   if( p->rc==SQLITE_NOMEM ){
46493     /* This happens if a malloc() inside a call to sqlite3_column_text() or
46494     ** sqlite3_column_text16() failed.  */
46495     goto no_mem;
46496   }
46497   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
46498   p->rc = SQLITE_OK;
46499   assert( p->explain==0 );
46500   p->pResultSet = 0;
46501   db->busyHandler.nBusy = 0;
46502   CHECK_FOR_INTERRUPT;
46503   sqlite3VdbeIOTraceSql(p);
46504 #ifdef SQLITE_DEBUG
46505   sqlite3BeginBenignMalloc();
46506   if( p->pc==0 
46507    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
46508   ){
46509     int i;
46510     printf("VDBE Program Listing:\n");
46511     sqlite3VdbePrintSql(p);
46512     for(i=0; i<p->nOp; i++){
46513       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
46514     }
46515   }
46516   if( fileExists(db, "vdbe_trace") ){
46517     p->trace = stdout;
46518   }
46519   sqlite3EndBenignMalloc();
46520 #endif
46521   for(pc=p->pc; rc==SQLITE_OK; pc++){
46522     assert( pc>=0 && pc<p->nOp );
46523     if( db->mallocFailed ) goto no_mem;
46524 #ifdef VDBE_PROFILE
46525     origPc = pc;
46526     start = sqlite3Hwtime();
46527 #endif
46528     pOp = &p->aOp[pc];
46529
46530     /* Only allow tracing if SQLITE_DEBUG is defined.
46531     */
46532 #ifdef SQLITE_DEBUG
46533     if( p->trace ){
46534       if( pc==0 ){
46535         printf("VDBE Execution Trace:\n");
46536         sqlite3VdbePrintSql(p);
46537       }
46538       sqlite3VdbePrintOp(p->trace, pc, pOp);
46539     }
46540     if( p->trace==0 && pc==0 ){
46541       sqlite3BeginBenignMalloc();
46542       if( fileExists(db, "vdbe_sqltrace") ){
46543         sqlite3VdbePrintSql(p);
46544       }
46545       sqlite3EndBenignMalloc();
46546     }
46547 #endif
46548       
46549
46550     /* Check to see if we need to simulate an interrupt.  This only happens
46551     ** if we have a special test build.
46552     */
46553 #ifdef SQLITE_TEST
46554     if( sqlite3_interrupt_count>0 ){
46555       sqlite3_interrupt_count--;
46556       if( sqlite3_interrupt_count==0 ){
46557         sqlite3_interrupt(db);
46558       }
46559     }
46560 #endif
46561
46562 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
46563     /* Call the progress callback if it is configured and the required number
46564     ** of VDBE ops have been executed (either since this invocation of
46565     ** sqlite3VdbeExec() or since last time the progress callback was called).
46566     ** If the progress callback returns non-zero, exit the virtual machine with
46567     ** a return code SQLITE_ABORT.
46568     */
46569     if( db->xProgress ){
46570       if( db->nProgressOps==nProgressOps ){
46571         int prc;
46572         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
46573         prc =db->xProgress(db->pProgressArg);
46574         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
46575         if( prc!=0 ){
46576           rc = SQLITE_INTERRUPT;
46577           goto vdbe_error_halt;
46578         }
46579         nProgressOps = 0;
46580       }
46581       nProgressOps++;
46582     }
46583 #endif
46584
46585     /* Do common setup processing for any opcode that is marked
46586     ** with the "out2-prerelease" tag.  Such opcodes have a single
46587     ** output which is specified by the P2 parameter.  The P2 register
46588     ** is initialized to a NULL.
46589     */
46590     opProperty = opcodeProperty[pOp->opcode];
46591     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
46592       assert( pOp->p2>0 );
46593       assert( pOp->p2<=p->nMem );
46594       pOut = &p->aMem[pOp->p2];
46595       sqlite3VdbeMemReleaseExternal(pOut);
46596       pOut->flags = MEM_Null;
46597     }else
46598  
46599     /* Do common setup for opcodes marked with one of the following
46600     ** combinations of properties.
46601     **
46602     **           in1
46603     **           in1 in2
46604     **           in1 in2 out3
46605     **           in1 in3
46606     **
46607     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
46608     ** registers for inputs.  Variable pOut points to the output register.
46609     */
46610     if( (opProperty & OPFLG_IN1)!=0 ){
46611       assert( pOp->p1>0 );
46612       assert( pOp->p1<=p->nMem );
46613       pIn1 = &p->aMem[pOp->p1];
46614       REGISTER_TRACE(pOp->p1, pIn1);
46615       if( (opProperty & OPFLG_IN2)!=0 ){
46616         assert( pOp->p2>0 );
46617         assert( pOp->p2<=p->nMem );
46618         pIn2 = &p->aMem[pOp->p2];
46619         REGISTER_TRACE(pOp->p2, pIn2);
46620         if( (opProperty & OPFLG_OUT3)!=0 ){
46621           assert( pOp->p3>0 );
46622           assert( pOp->p3<=p->nMem );
46623           pOut = &p->aMem[pOp->p3];
46624         }
46625       }else if( (opProperty & OPFLG_IN3)!=0 ){
46626         assert( pOp->p3>0 );
46627         assert( pOp->p3<=p->nMem );
46628         pIn3 = &p->aMem[pOp->p3];
46629         REGISTER_TRACE(pOp->p3, pIn3);
46630       }
46631     }else if( (opProperty & OPFLG_IN2)!=0 ){
46632       assert( pOp->p2>0 );
46633       assert( pOp->p2<=p->nMem );
46634       pIn2 = &p->aMem[pOp->p2];
46635       REGISTER_TRACE(pOp->p2, pIn2);
46636     }else if( (opProperty & OPFLG_IN3)!=0 ){
46637       assert( pOp->p3>0 );
46638       assert( pOp->p3<=p->nMem );
46639       pIn3 = &p->aMem[pOp->p3];
46640       REGISTER_TRACE(pOp->p3, pIn3);
46641     }
46642
46643     switch( pOp->opcode ){
46644
46645 /*****************************************************************************
46646 ** What follows is a massive switch statement where each case implements a
46647 ** separate instruction in the virtual machine.  If we follow the usual
46648 ** indentation conventions, each case should be indented by 6 spaces.  But
46649 ** that is a lot of wasted space on the left margin.  So the code within
46650 ** the switch statement will break with convention and be flush-left. Another
46651 ** big comment (similar to this one) will mark the point in the code where
46652 ** we transition back to normal indentation.
46653 **
46654 ** The formatting of each case is important.  The makefile for SQLite
46655 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
46656 ** file looking for lines that begin with "case OP_".  The opcodes.h files
46657 ** will be filled with #defines that give unique integer values to each
46658 ** opcode and the opcodes.c file is filled with an array of strings where
46659 ** each string is the symbolic name for the corresponding opcode.  If the
46660 ** case statement is followed by a comment of the form "/# same as ... #/"
46661 ** that comment is used to determine the particular value of the opcode.
46662 **
46663 ** Other keywords in the comment that follows each case are used to
46664 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
46665 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
46666 ** the mkopcodeh.awk script for additional information.
46667 **
46668 ** Documentation about VDBE opcodes is generated by scanning this file
46669 ** for lines of that contain "Opcode:".  That line and all subsequent
46670 ** comment lines are used in the generation of the opcode.html documentation
46671 ** file.
46672 **
46673 ** SUMMARY:
46674 **
46675 **     Formatting is important to scripts that scan this file.
46676 **     Do not deviate from the formatting style currently in use.
46677 **
46678 *****************************************************************************/
46679
46680 /* Opcode:  Goto * P2 * * *
46681 **
46682 ** An unconditional jump to address P2.
46683 ** The next instruction executed will be 
46684 ** the one at index P2 from the beginning of
46685 ** the program.
46686 */
46687 case OP_Goto: {             /* jump */
46688   CHECK_FOR_INTERRUPT;
46689   pc = pOp->p2 - 1;
46690   break;
46691 }
46692
46693 /* Opcode:  Gosub P1 P2 * * *
46694 **
46695 ** Write the current address onto register P1
46696 ** and then jump to address P2.
46697 */
46698 case OP_Gosub: {            /* jump */
46699   assert( pOp->p1>0 );
46700   assert( pOp->p1<=p->nMem );
46701   pIn1 = &p->aMem[pOp->p1];
46702   assert( (pIn1->flags & MEM_Dyn)==0 );
46703   pIn1->flags = MEM_Int;
46704   pIn1->u.i = pc;
46705   REGISTER_TRACE(pOp->p1, pIn1);
46706   pc = pOp->p2 - 1;
46707   break;
46708 }
46709
46710 /* Opcode:  Return P1 * * * *
46711 **
46712 ** Jump to the next instruction after the address in register P1.
46713 */
46714 case OP_Return: {           /* in1 */
46715   assert( pIn1->flags & MEM_Int );
46716   pc = pIn1->u.i;
46717   break;
46718 }
46719
46720 /* Opcode:  Yield P1 * * * *
46721 **
46722 ** Swap the program counter with the value in register P1.
46723 */
46724 case OP_Yield: {
46725   int pcDest;
46726   assert( pOp->p1>0 );
46727   assert( pOp->p1<=p->nMem );
46728   pIn1 = &p->aMem[pOp->p1];
46729   assert( (pIn1->flags & MEM_Dyn)==0 );
46730   pIn1->flags = MEM_Int;
46731   pcDest = pIn1->u.i;
46732   pIn1->u.i = pc;
46733   REGISTER_TRACE(pOp->p1, pIn1);
46734   pc = pcDest;
46735   break;
46736 }
46737
46738
46739 /* Opcode:  Halt P1 P2 * P4 *
46740 **
46741 ** Exit immediately.  All open cursors, Fifos, etc are closed
46742 ** automatically.
46743 **
46744 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
46745 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
46746 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
46747 ** whether or not to rollback the current transaction.  Do not rollback
46748 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
46749 ** then back out all changes that have occurred during this execution of the
46750 ** VDBE, but do not rollback the transaction. 
46751 **
46752 ** If P4 is not null then it is an error message string.
46753 **
46754 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
46755 ** every program.  So a jump past the last instruction of the program
46756 ** is the same as executing Halt.
46757 */
46758 case OP_Halt: {
46759   p->rc = pOp->p1;
46760   p->pc = pc;
46761   p->errorAction = pOp->p2;
46762   if( pOp->p4.z ){
46763     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
46764   }
46765   rc = sqlite3VdbeHalt(p);
46766   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
46767   if( rc==SQLITE_BUSY ){
46768     p->rc = rc = SQLITE_BUSY;
46769   }else{
46770     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
46771   }
46772   goto vdbe_return;
46773 }
46774
46775 /* Opcode: Integer P1 P2 * * *
46776 **
46777 ** The 32-bit integer value P1 is written into register P2.
46778 */
46779 case OP_Integer: {         /* out2-prerelease */
46780   pOut->flags = MEM_Int;
46781   pOut->u.i = pOp->p1;
46782   break;
46783 }
46784
46785 /* Opcode: Int64 * P2 * P4 *
46786 **
46787 ** P4 is a pointer to a 64-bit integer value.
46788 ** Write that value into register P2.
46789 */
46790 case OP_Int64: {           /* out2-prerelease */
46791   assert( pOp->p4.pI64!=0 );
46792   pOut->flags = MEM_Int;
46793   pOut->u.i = *pOp->p4.pI64;
46794   break;
46795 }
46796
46797 /* Opcode: Real * P2 * P4 *
46798 **
46799 ** P4 is a pointer to a 64-bit floating point value.
46800 ** Write that value into register P2.
46801 */
46802 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
46803   pOut->flags = MEM_Real;
46804   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
46805   pOut->r = *pOp->p4.pReal;
46806   break;
46807 }
46808
46809 /* Opcode: String8 * P2 * P4 *
46810 **
46811 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
46812 ** into an OP_String before it is executed for the first time.
46813 */
46814 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
46815   assert( pOp->p4.z!=0 );
46816   pOp->opcode = OP_String;
46817   pOp->p1 = strlen(pOp->p4.z);
46818
46819 #ifndef SQLITE_OMIT_UTF16
46820   if( encoding!=SQLITE_UTF8 ){
46821     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
46822     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
46823     if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
46824     pOut->zMalloc = 0;
46825     pOut->flags |= MEM_Static;
46826     pOut->flags &= ~MEM_Dyn;
46827     if( pOp->p4type==P4_DYNAMIC ){
46828       sqlite3DbFree(db, pOp->p4.z);
46829     }
46830     pOp->p4type = P4_DYNAMIC;
46831     pOp->p4.z = pOut->z;
46832     pOp->p1 = pOut->n;
46833     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46834       goto too_big;
46835     }
46836     UPDATE_MAX_BLOBSIZE(pOut);
46837     break;
46838   }
46839 #endif
46840   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
46841     goto too_big;
46842   }
46843   /* Fall through to the next case, OP_String */
46844 }
46845   
46846 /* Opcode: String P1 P2 * P4 *
46847 **
46848 ** The string value P4 of length P1 (bytes) is stored in register P2.
46849 */
46850 case OP_String: {          /* out2-prerelease */
46851   assert( pOp->p4.z!=0 );
46852   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
46853   pOut->z = pOp->p4.z;
46854   pOut->n = pOp->p1;
46855   pOut->enc = encoding;
46856   UPDATE_MAX_BLOBSIZE(pOut);
46857   break;
46858 }
46859
46860 /* Opcode: Null * P2 * * *
46861 **
46862 ** Write a NULL into register P2.
46863 */
46864 case OP_Null: {           /* out2-prerelease */
46865   break;
46866 }
46867
46868
46869 #ifndef SQLITE_OMIT_BLOB_LITERAL
46870 /* Opcode: Blob P1 P2 * P4
46871 **
46872 ** P4 points to a blob of data P1 bytes long.  Store this
46873 ** blob in register P2. This instruction is not coded directly
46874 ** by the compiler. Instead, the compiler layer specifies
46875 ** an OP_HexBlob opcode, with the hex string representation of
46876 ** the blob as P4. This opcode is transformed to an OP_Blob
46877 ** the first time it is executed.
46878 */
46879 case OP_Blob: {                /* out2-prerelease */
46880   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
46881   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
46882   pOut->enc = encoding;
46883   UPDATE_MAX_BLOBSIZE(pOut);
46884   break;
46885 }
46886 #endif /* SQLITE_OMIT_BLOB_LITERAL */
46887
46888 /* Opcode: Variable P1 P2 * * *
46889 **
46890 ** The value of variable P1 is written into register P2. A variable is
46891 ** an unknown in the original SQL string as handed to sqlite3_compile().
46892 ** Any occurrence of the '?' character in the original SQL is considered
46893 ** a variable.  Variables in the SQL string are number from left to
46894 ** right beginning with 1.  The values of variables are set using the
46895 ** sqlite3_bind() API.
46896 */
46897 case OP_Variable: {           /* out2-prerelease */
46898   int j = pOp->p1 - 1;
46899   Mem *pVar;
46900   assert( j>=0 && j<p->nVar );
46901
46902   pVar = &p->aVar[j];
46903   if( sqlite3VdbeMemTooBig(pVar) ){
46904     goto too_big;
46905   }
46906   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
46907   UPDATE_MAX_BLOBSIZE(pOut);
46908   break;
46909 }
46910
46911 /* Opcode: Move P1 P2 P3 * *
46912 **
46913 ** Move the values in register P1..P1+P3-1 over into
46914 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
46915 ** left holding a NULL.  It is an error for register ranges
46916 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
46917 */
46918 case OP_Move: {
46919   char *zMalloc;
46920   int n = pOp->p3;
46921   int p1 = pOp->p1;
46922   int p2 = pOp->p2;
46923   assert( n>0 );
46924   assert( p1>0 );
46925   assert( p1+n<p->nMem );
46926   pIn1 = &p->aMem[p1];
46927   assert( p2>0 );
46928   assert( p2+n<p->nMem );
46929   pOut = &p->aMem[p2];
46930   assert( p1+n<=p2 || p2+n<=p1 );
46931   while( n-- ){
46932     zMalloc = pOut->zMalloc;
46933     pOut->zMalloc = 0;
46934     sqlite3VdbeMemMove(pOut, pIn1);
46935     pIn1->zMalloc = zMalloc;
46936     REGISTER_TRACE(p2++, pOut);
46937     pIn1++;
46938     pOut++;
46939   }
46940   break;
46941 }
46942
46943 /* Opcode: Copy P1 P2 * * *
46944 **
46945 ** Make a copy of register P1 into register P2.
46946 **
46947 ** This instruction makes a deep copy of the value.  A duplicate
46948 ** is made of any string or blob constant.  See also OP_SCopy.
46949 */
46950 case OP_Copy: {
46951   assert( pOp->p1>0 );
46952   assert( pOp->p1<=p->nMem );
46953   pIn1 = &p->aMem[pOp->p1];
46954   assert( pOp->p2>0 );
46955   assert( pOp->p2<=p->nMem );
46956   pOut = &p->aMem[pOp->p2];
46957   assert( pOut!=pIn1 );
46958   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
46959   Deephemeralize(pOut);
46960   REGISTER_TRACE(pOp->p2, pOut);
46961   break;
46962 }
46963
46964 /* Opcode: SCopy P1 P2 * * *
46965 **
46966 ** Make a shallow copy of register P1 into register P2.
46967 **
46968 ** This instruction makes a shallow copy of the value.  If the value
46969 ** is a string or blob, then the copy is only a pointer to the
46970 ** original and hence if the original changes so will the copy.
46971 ** Worse, if the original is deallocated, the copy becomes invalid.
46972 ** Thus the program must guarantee that the original will not change
46973 ** during the lifetime of the copy.  Use OP_Copy to make a complete
46974 ** copy.
46975 */
46976 case OP_SCopy: {
46977   assert( pOp->p1>0 );
46978   assert( pOp->p1<=p->nMem );
46979   pIn1 = &p->aMem[pOp->p1];
46980   REGISTER_TRACE(pOp->p1, pIn1);
46981   assert( pOp->p2>0 );
46982   assert( pOp->p2<=p->nMem );
46983   pOut = &p->aMem[pOp->p2];
46984   assert( pOut!=pIn1 );
46985   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
46986   REGISTER_TRACE(pOp->p2, pOut);
46987   break;
46988 }
46989
46990 /* Opcode: ResultRow P1 P2 * * *
46991 **
46992 ** The registers P1 through P1+P2-1 contain a single row of
46993 ** results. This opcode causes the sqlite3_step() call to terminate
46994 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
46995 ** structure to provide access to the top P1 values as the result
46996 ** row.
46997 */
46998 case OP_ResultRow: {
46999   Mem *pMem;
47000   int i;
47001   assert( p->nResColumn==pOp->p2 );
47002   assert( pOp->p1>0 );
47003   assert( pOp->p1+pOp->p2<=p->nMem );
47004
47005   /* Invalidate all ephemeral cursor row caches */
47006   p->cacheCtr = (p->cacheCtr + 2)|1;
47007
47008   /* Make sure the results of the current row are \000 terminated
47009   ** and have an assigned type.  The results are de-ephemeralized as
47010   ** as side effect.
47011   */
47012   pMem = p->pResultSet = &p->aMem[pOp->p1];
47013   for(i=0; i<pOp->p2; i++){
47014     sqlite3VdbeMemNulTerminate(&pMem[i]);
47015     storeTypeInfo(&pMem[i], encoding);
47016     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
47017   }
47018   if( db->mallocFailed ) goto no_mem;
47019
47020   /* Return SQLITE_ROW
47021   */
47022   p->nCallback++;
47023   p->pc = pc + 1;
47024   rc = SQLITE_ROW;
47025   goto vdbe_return;
47026 }
47027
47028 /* Opcode: Concat P1 P2 P3 * *
47029 **
47030 ** Add the text in register P1 onto the end of the text in
47031 ** register P2 and store the result in register P3.
47032 ** If either the P1 or P2 text are NULL then store NULL in P3.
47033 **
47034 **   P3 = P2 || P1
47035 **
47036 ** It is illegal for P1 and P3 to be the same register. Sometimes,
47037 ** if P3 is the same register as P2, the implementation is able
47038 ** to avoid a memcpy().
47039 */
47040 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
47041   i64 nByte;
47042
47043   assert( pIn1!=pOut );
47044   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
47045     sqlite3VdbeMemSetNull(pOut);
47046     break;
47047   }
47048   ExpandBlob(pIn1);
47049   Stringify(pIn1, encoding);
47050   ExpandBlob(pIn2);
47051   Stringify(pIn2, encoding);
47052   nByte = pIn1->n + pIn2->n;
47053   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47054     goto too_big;
47055   }
47056   MemSetTypeFlag(pOut, MEM_Str);
47057   if( sqlite3VdbeMemGrow(pOut, nByte+2, pOut==pIn2) ){
47058     goto no_mem;
47059   }
47060   if( pOut!=pIn2 ){
47061     memcpy(pOut->z, pIn2->z, pIn2->n);
47062   }
47063   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
47064   pOut->z[nByte] = 0;
47065   pOut->z[nByte+1] = 0;
47066   pOut->flags |= MEM_Term;
47067   pOut->n = nByte;
47068   pOut->enc = encoding;
47069   UPDATE_MAX_BLOBSIZE(pOut);
47070   break;
47071 }
47072
47073 /* Opcode: Add P1 P2 P3 * *
47074 **
47075 ** Add the value in register P1 to the value in register P2
47076 ** and store the result in register P3.
47077 ** If either input is NULL, the result is NULL.
47078 */
47079 /* Opcode: Multiply P1 P2 P3 * *
47080 **
47081 **
47082 ** Multiply the value in register P1 by the value in register P2
47083 ** and store the result in register P3.
47084 ** If either input is NULL, the result is NULL.
47085 */
47086 /* Opcode: Subtract P1 P2 P3 * *
47087 **
47088 ** Subtract the value in register P1 from the value in register P2
47089 ** and store the result in register P3.
47090 ** If either input is NULL, the result is NULL.
47091 */
47092 /* Opcode: Divide P1 P2 P3 * *
47093 **
47094 ** Divide the value in register P1 by the value in register P2
47095 ** and store the result in register P3.  If the value in register P2
47096 ** is zero, then the result is NULL.
47097 ** If either input is NULL, the result is NULL.
47098 */
47099 /* Opcode: Remainder P1 P2 P3 * *
47100 **
47101 ** Compute the remainder after integer division of the value in
47102 ** register P1 by the value in register P2 and store the result in P3. 
47103 ** If the value in register P2 is zero the result is NULL.
47104 ** If either operand is NULL, the result is NULL.
47105 */
47106 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
47107 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
47108 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
47109 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
47110 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
47111   int flags;
47112   applyNumericAffinity(pIn1);
47113   applyNumericAffinity(pIn2);
47114   flags = pIn1->flags | pIn2->flags;
47115   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
47116   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
47117     i64 a, b;
47118     a = pIn1->u.i;
47119     b = pIn2->u.i;
47120     switch( pOp->opcode ){
47121       case OP_Add:         b += a;       break;
47122       case OP_Subtract:    b -= a;       break;
47123       case OP_Multiply:    b *= a;       break;
47124       case OP_Divide: {
47125         if( a==0 ) goto arithmetic_result_is_null;
47126         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
47127         ** -1 returns an integer too large to store in a 64-bit data-type. On
47128         ** some architectures, the value overflows to (1<<63). On others,
47129         ** a SIGFPE is issued. The following statement normalizes this
47130         ** behavior so that all architectures behave as if integer 
47131         ** overflow occurred.
47132         */
47133         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
47134         b /= a;
47135         break;
47136       }
47137       default: {
47138         if( a==0 ) goto arithmetic_result_is_null;
47139         if( a==-1 ) a = 1;
47140         b %= a;
47141         break;
47142       }
47143     }
47144     pOut->u.i = b;
47145     MemSetTypeFlag(pOut, MEM_Int);
47146   }else{
47147     double a, b;
47148     a = sqlite3VdbeRealValue(pIn1);
47149     b = sqlite3VdbeRealValue(pIn2);
47150     switch( pOp->opcode ){
47151       case OP_Add:         b += a;       break;
47152       case OP_Subtract:    b -= a;       break;
47153       case OP_Multiply:    b *= a;       break;
47154       case OP_Divide: {
47155         if( a==0.0 ) goto arithmetic_result_is_null;
47156         b /= a;
47157         break;
47158       }
47159       default: {
47160         i64 ia = (i64)a;
47161         i64 ib = (i64)b;
47162         if( ia==0 ) goto arithmetic_result_is_null;
47163         if( ia==-1 ) ia = 1;
47164         b = ib % ia;
47165         break;
47166       }
47167     }
47168     if( sqlite3IsNaN(b) ){
47169       goto arithmetic_result_is_null;
47170     }
47171     pOut->r = b;
47172     MemSetTypeFlag(pOut, MEM_Real);
47173     if( (flags & MEM_Real)==0 ){
47174       sqlite3VdbeIntegerAffinity(pOut);
47175     }
47176   }
47177   break;
47178
47179 arithmetic_result_is_null:
47180   sqlite3VdbeMemSetNull(pOut);
47181   break;
47182 }
47183
47184 /* Opcode: CollSeq * * P4
47185 **
47186 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
47187 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
47188 ** be returned. This is used by the built-in min(), max() and nullif()
47189 ** functions.
47190 **
47191 ** The interface used by the implementation of the aforementioned functions
47192 ** to retrieve the collation sequence set by this opcode is not available
47193 ** publicly, only to user functions defined in func.c.
47194 */
47195 case OP_CollSeq: {
47196   assert( pOp->p4type==P4_COLLSEQ );
47197   break;
47198 }
47199
47200 /* Opcode: Function P1 P2 P3 P4 P5
47201 **
47202 ** Invoke a user function (P4 is a pointer to a Function structure that
47203 ** defines the function) with P5 arguments taken from register P2 and
47204 ** successors.  The result of the function is stored in register P3.
47205 ** Register P3 must not be one of the function inputs.
47206 **
47207 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
47208 ** function was determined to be constant at compile time. If the first
47209 ** argument was constant then bit 0 of P1 is set. This is used to determine
47210 ** whether meta data associated with a user function argument using the
47211 ** sqlite3_set_auxdata() API may be safely retained until the next
47212 ** invocation of this opcode.
47213 **
47214 ** See also: AggStep and AggFinal
47215 */
47216 case OP_Function: {
47217   int i;
47218   Mem *pArg;
47219   sqlite3_context ctx;
47220   sqlite3_value **apVal;
47221   int n = pOp->p5;
47222
47223   apVal = p->apArg;
47224   assert( apVal || n==0 );
47225
47226   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
47227   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
47228   pArg = &p->aMem[pOp->p2];
47229   for(i=0; i<n; i++, pArg++){
47230     apVal[i] = pArg;
47231     storeTypeInfo(pArg, encoding);
47232     REGISTER_TRACE(pOp->p2, pArg);
47233   }
47234
47235   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
47236   if( pOp->p4type==P4_FUNCDEF ){
47237     ctx.pFunc = pOp->p4.pFunc;
47238     ctx.pVdbeFunc = 0;
47239   }else{
47240     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
47241     ctx.pFunc = ctx.pVdbeFunc->pFunc;
47242   }
47243
47244   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47245   pOut = &p->aMem[pOp->p3];
47246   ctx.s.flags = MEM_Null;
47247   ctx.s.db = db;
47248   ctx.s.xDel = 0;
47249   ctx.s.zMalloc = 0;
47250
47251   /* The output cell may already have a buffer allocated. Move
47252   ** the pointer to ctx.s so in case the user-function can use
47253   ** the already allocated buffer instead of allocating a new one.
47254   */
47255   sqlite3VdbeMemMove(&ctx.s, pOut);
47256   MemSetTypeFlag(&ctx.s, MEM_Null);
47257
47258   ctx.isError = 0;
47259   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
47260     assert( pOp>p->aOp );
47261     assert( pOp[-1].p4type==P4_COLLSEQ );
47262     assert( pOp[-1].opcode==OP_CollSeq );
47263     ctx.pColl = pOp[-1].p4.pColl;
47264   }
47265   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
47266   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
47267   if( sqlite3SafetyOn(db) ){
47268     sqlite3VdbeMemRelease(&ctx.s);
47269     goto abort_due_to_misuse;
47270   }
47271   if( db->mallocFailed ){
47272     /* Even though a malloc() has failed, the implementation of the
47273     ** user function may have called an sqlite3_result_XXX() function
47274     ** to return a value. The following call releases any resources
47275     ** associated with such a value.
47276     **
47277     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
47278     ** fails also (the if(...) statement above). But if people are
47279     ** misusing sqlite, they have bigger problems than a leaked value.
47280     */
47281     sqlite3VdbeMemRelease(&ctx.s);
47282     goto no_mem;
47283   }
47284
47285   /* If any auxiliary data functions have been called by this user function,
47286   ** immediately call the destructor for any non-static values.
47287   */
47288   if( ctx.pVdbeFunc ){
47289     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
47290     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
47291     pOp->p4type = P4_VDBEFUNC;
47292   }
47293
47294   /* If the function returned an error, throw an exception */
47295   if( ctx.isError ){
47296     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
47297     rc = ctx.isError;
47298   }
47299
47300   /* Copy the result of the function into register P3 */
47301   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
47302   sqlite3VdbeMemMove(pOut, &ctx.s);
47303   if( sqlite3VdbeMemTooBig(pOut) ){
47304     goto too_big;
47305   }
47306   REGISTER_TRACE(pOp->p3, pOut);
47307   UPDATE_MAX_BLOBSIZE(pOut);
47308   break;
47309 }
47310
47311 /* Opcode: BitAnd P1 P2 P3 * *
47312 **
47313 ** Take the bit-wise AND of the values in register P1 and P2 and
47314 ** store the result in register P3.
47315 ** If either input is NULL, the result is NULL.
47316 */
47317 /* Opcode: BitOr P1 P2 P3 * *
47318 **
47319 ** Take the bit-wise OR of the values in register P1 and P2 and
47320 ** store the result in register P3.
47321 ** If either input is NULL, the result is NULL.
47322 */
47323 /* Opcode: ShiftLeft P1 P2 P3 * *
47324 **
47325 ** Shift the integer value in register P2 to the left by the
47326 ** number of bits specified by the integer in regiser P1.
47327 ** Store the result in register P3.
47328 ** If either input is NULL, the result is NULL.
47329 */
47330 /* Opcode: ShiftRight P1 P2 P3 * *
47331 **
47332 ** Shift the integer value in register P2 to the right by the
47333 ** number of bits specified by the integer in register P1.
47334 ** Store the result in register P3.
47335 ** If either input is NULL, the result is NULL.
47336 */
47337 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
47338 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
47339 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
47340 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
47341   i64 a, b;
47342
47343   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
47344     sqlite3VdbeMemSetNull(pOut);
47345     break;
47346   }
47347   a = sqlite3VdbeIntValue(pIn2);
47348   b = sqlite3VdbeIntValue(pIn1);
47349   switch( pOp->opcode ){
47350     case OP_BitAnd:      a &= b;     break;
47351     case OP_BitOr:       a |= b;     break;
47352     case OP_ShiftLeft:   a <<= b;    break;
47353     default:  assert( pOp->opcode==OP_ShiftRight );
47354                          a >>= b;    break;
47355   }
47356   pOut->u.i = a;
47357   MemSetTypeFlag(pOut, MEM_Int);
47358   break;
47359 }
47360
47361 /* Opcode: AddImm  P1 P2 * * *
47362 ** 
47363 ** Add the constant P2 to the value in register P1.
47364 ** The result is always an integer.
47365 **
47366 ** To force any register to be an integer, just add 0.
47367 */
47368 case OP_AddImm: {            /* in1 */
47369   sqlite3VdbeMemIntegerify(pIn1);
47370   pIn1->u.i += pOp->p2;
47371   break;
47372 }
47373
47374 /* Opcode: ForceInt P1 P2 P3 * *
47375 **
47376 ** Convert value in register P1 into an integer.  If the value 
47377 ** in P1 is not numeric (meaning that is is a NULL or a string that
47378 ** does not look like an integer or floating point number) then
47379 ** jump to P2.  If the value in P1 is numeric then
47380 ** convert it into the least integer that is greater than or equal to its
47381 ** current value if P3==0, or to the least integer that is strictly
47382 ** greater than its current value if P3==1.
47383 */
47384 case OP_ForceInt: {            /* jump, in1 */
47385   i64 v;
47386   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47387   if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){
47388     pc = pOp->p2 - 1;
47389     break;
47390   }
47391   if( pIn1->flags & MEM_Int ){
47392     v = pIn1->u.i + (pOp->p3!=0);
47393   }else{
47394     assert( pIn1->flags & MEM_Real );
47395     v = (sqlite3_int64)pIn1->r;
47396     if( pIn1->r>(double)v ) v++;
47397     if( pOp->p3 && pIn1->r==(double)v ) v++;
47398   }
47399   pIn1->u.i = v;
47400   MemSetTypeFlag(pIn1, MEM_Int);
47401   break;
47402 }
47403
47404 /* Opcode: MustBeInt P1 P2 * * *
47405 ** 
47406 ** Force the value in register P1 to be an integer.  If the value
47407 ** in P1 is not an integer and cannot be converted into an integer
47408 ** without data loss, then jump immediately to P2, or if P2==0
47409 ** raise an SQLITE_MISMATCH exception.
47410 */
47411 case OP_MustBeInt: {            /* jump, in1 */
47412   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
47413   if( (pIn1->flags & MEM_Int)==0 ){
47414     if( pOp->p2==0 ){
47415       rc = SQLITE_MISMATCH;
47416       goto abort_due_to_error;
47417     }else{
47418       pc = pOp->p2 - 1;
47419     }
47420   }else{
47421     MemSetTypeFlag(pIn1, MEM_Int);
47422   }
47423   break;
47424 }
47425
47426 /* Opcode: RealAffinity P1 * * * *
47427 **
47428 ** If register P1 holds an integer convert it to a real value.
47429 **
47430 ** This opcode is used when extracting information from a column that
47431 ** has REAL affinity.  Such column values may still be stored as
47432 ** integers, for space efficiency, but after extraction we want them
47433 ** to have only a real value.
47434 */
47435 case OP_RealAffinity: {                  /* in1 */
47436   if( pIn1->flags & MEM_Int ){
47437     sqlite3VdbeMemRealify(pIn1);
47438   }
47439   break;
47440 }
47441
47442 #ifndef SQLITE_OMIT_CAST
47443 /* Opcode: ToText P1 * * * *
47444 **
47445 ** Force the value in register P1 to be text.
47446 ** If the value is numeric, convert it to a string using the
47447 ** equivalent of printf().  Blob values are unchanged and
47448 ** are afterwards simply interpreted as text.
47449 **
47450 ** A NULL value is not changed by this routine.  It remains NULL.
47451 */
47452 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
47453   if( pIn1->flags & MEM_Null ) break;
47454   assert( MEM_Str==(MEM_Blob>>3) );
47455   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
47456   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47457   rc = ExpandBlob(pIn1);
47458   assert( pIn1->flags & MEM_Str || db->mallocFailed );
47459   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob);
47460   UPDATE_MAX_BLOBSIZE(pIn1);
47461   break;
47462 }
47463
47464 /* Opcode: ToBlob P1 * * * *
47465 **
47466 ** Force the value in register P1 to be a BLOB.
47467 ** If the value is numeric, convert it to a string first.
47468 ** Strings are simply reinterpreted as blobs with no change
47469 ** to the underlying data.
47470 **
47471 ** A NULL value is not changed by this routine.  It remains NULL.
47472 */
47473 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
47474   if( pIn1->flags & MEM_Null ) break;
47475   if( (pIn1->flags & MEM_Blob)==0 ){
47476     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
47477     assert( pIn1->flags & MEM_Str || db->mallocFailed );
47478   }
47479   MemSetTypeFlag(pIn1, MEM_Blob);
47480   UPDATE_MAX_BLOBSIZE(pIn1);
47481   break;
47482 }
47483
47484 /* Opcode: ToNumeric P1 * * * *
47485 **
47486 ** Force the value in register P1 to be numeric (either an
47487 ** integer or a floating-point number.)
47488 ** If the value is text or blob, try to convert it to an using the
47489 ** equivalent of atoi() or atof() and store 0 if no such conversion 
47490 ** is possible.
47491 **
47492 ** A NULL value is not changed by this routine.  It remains NULL.
47493 */
47494 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
47495   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
47496     sqlite3VdbeMemNumerify(pIn1);
47497   }
47498   break;
47499 }
47500 #endif /* SQLITE_OMIT_CAST */
47501
47502 /* Opcode: ToInt P1 * * * *
47503 **
47504 ** Force the value in register P1 be an integer.  If
47505 ** The value is currently a real number, drop its fractional part.
47506 ** If the value is text or blob, try to convert it to an integer using the
47507 ** equivalent of atoi() and store 0 if no such conversion is possible.
47508 **
47509 ** A NULL value is not changed by this routine.  It remains NULL.
47510 */
47511 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
47512   if( (pIn1->flags & MEM_Null)==0 ){
47513     sqlite3VdbeMemIntegerify(pIn1);
47514   }
47515   break;
47516 }
47517
47518 #ifndef SQLITE_OMIT_CAST
47519 /* Opcode: ToReal P1 * * * *
47520 **
47521 ** Force the value in register P1 to be a floating point number.
47522 ** If The value is currently an integer, convert it.
47523 ** If the value is text or blob, try to convert it to an integer using the
47524 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
47525 **
47526 ** A NULL value is not changed by this routine.  It remains NULL.
47527 */
47528 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
47529   if( (pIn1->flags & MEM_Null)==0 ){
47530     sqlite3VdbeMemRealify(pIn1);
47531   }
47532   break;
47533 }
47534 #endif /* SQLITE_OMIT_CAST */
47535
47536 /* Opcode: Lt P1 P2 P3 P4 P5
47537 **
47538 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
47539 ** jump to address P2.  
47540 **
47541 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
47542 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
47543 ** bit is clear then fall thru if either operand is NULL.
47544 **
47545 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
47546 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
47547 ** to coerce both inputs according to this affinity before the
47548 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
47549 ** affinity is used. Note that the affinity conversions are stored
47550 ** back into the input registers P1 and P3.  So this opcode can cause
47551 ** persistent changes to registers P1 and P3.
47552 **
47553 ** Once any conversions have taken place, and neither value is NULL, 
47554 ** the values are compared. If both values are blobs then memcmp() is
47555 ** used to determine the results of the comparison.  If both values
47556 ** are text, then the appropriate collating function specified in
47557 ** P4 is  used to do the comparison.  If P4 is not specified then
47558 ** memcmp() is used to compare text string.  If both values are
47559 ** numeric, then a numeric comparison is used. If the two values
47560 ** are of different types, then numbers are considered less than
47561 ** strings and strings are considered less than blobs.
47562 **
47563 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
47564 ** store a boolean result (either 0, or 1, or NULL) in register P2.
47565 */
47566 /* Opcode: Ne P1 P2 P3 P4 P5
47567 **
47568 ** This works just like the Lt opcode except that the jump is taken if
47569 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
47570 ** additional information.
47571 */
47572 /* Opcode: Eq P1 P2 P3 P4 P5
47573 **
47574 ** This works just like the Lt opcode except that the jump is taken if
47575 ** the operands in registers P1 and P3 are equal.
47576 ** See the Lt opcode for additional information.
47577 */
47578 /* Opcode: Le P1 P2 P3 P4 P5
47579 **
47580 ** This works just like the Lt opcode except that the jump is taken if
47581 ** the content of register P3 is less than or equal to the content of
47582 ** register P1.  See the Lt opcode for additional information.
47583 */
47584 /* Opcode: Gt P1 P2 P3 P4 P5
47585 **
47586 ** This works just like the Lt opcode except that the jump is taken if
47587 ** the content of register P3 is greater than the content of
47588 ** register P1.  See the Lt opcode for additional information.
47589 */
47590 /* Opcode: Ge P1 P2 P3 P4 P5
47591 **
47592 ** This works just like the Lt opcode except that the jump is taken if
47593 ** the content of register P3 is greater than or equal to the content of
47594 ** register P1.  See the Lt opcode for additional information.
47595 */
47596 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
47597 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
47598 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
47599 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
47600 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
47601 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
47602   int flags;
47603   int res;
47604   char affinity;
47605
47606   flags = pIn1->flags|pIn3->flags;
47607
47608   if( flags&MEM_Null ){
47609     /* If either operand is NULL then the result is always NULL.
47610     ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
47611     */
47612     if( pOp->p5 & SQLITE_STOREP2 ){
47613       pOut = &p->aMem[pOp->p2];
47614       MemSetTypeFlag(pOut, MEM_Null);
47615       REGISTER_TRACE(pOp->p2, pOut);
47616     }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
47617       pc = pOp->p2-1;
47618     }
47619     break;
47620   }
47621
47622   affinity = pOp->p5 & SQLITE_AFF_MASK;
47623   if( affinity ){
47624     applyAffinity(pIn1, affinity, encoding);
47625     applyAffinity(pIn3, affinity, encoding);
47626   }
47627
47628   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
47629   ExpandBlob(pIn1);
47630   ExpandBlob(pIn3);
47631   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
47632   switch( pOp->opcode ){
47633     case OP_Eq:    res = res==0;     break;
47634     case OP_Ne:    res = res!=0;     break;
47635     case OP_Lt:    res = res<0;      break;
47636     case OP_Le:    res = res<=0;     break;
47637     case OP_Gt:    res = res>0;      break;
47638     default:       res = res>=0;     break;
47639   }
47640
47641   if( pOp->p5 & SQLITE_STOREP2 ){
47642     pOut = &p->aMem[pOp->p2];
47643     MemSetTypeFlag(pOut, MEM_Int);
47644     pOut->u.i = res;
47645     REGISTER_TRACE(pOp->p2, pOut);
47646   }else if( res ){
47647     pc = pOp->p2-1;
47648   }
47649   break;
47650 }
47651
47652 /* Opcode: Permutation * * * P4 *
47653 **
47654 ** Set the permuation used by the OP_Compare operator to be the array
47655 ** of integers in P4.
47656 **
47657 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
47658 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
47659 ** immediately prior to the OP_Compare.
47660 */
47661 case OP_Permutation: {
47662   assert( pOp->p4type==P4_INTARRAY );
47663   assert( pOp->p4.ai );
47664   aPermute = pOp->p4.ai;
47665   break;
47666 }
47667
47668 /* Opcode: Compare P1 P2 P3 P4 *
47669 **
47670 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
47671 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
47672 ** the comparison for use by the next OP_Jump instruct.
47673 **
47674 ** P4 is a KeyInfo structure that defines collating sequences and sort
47675 ** orders for the comparison.  The permutation applies to registers
47676 ** only.  The KeyInfo elements are used sequentially.
47677 **
47678 ** The comparison is a sort comparison, so NULLs compare equal,
47679 ** NULLs are less than numbers, numbers are less than strings,
47680 ** and strings are less than blobs.
47681 */
47682 case OP_Compare: {
47683   int n = pOp->p3;
47684   int i, p1, p2;
47685   const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
47686   assert( n>0 );
47687   assert( pKeyInfo!=0 );
47688   p1 = pOp->p1;
47689   assert( p1>0 && p1+n-1<p->nMem );
47690   p2 = pOp->p2;
47691   assert( p2>0 && p2+n-1<p->nMem );
47692   for(i=0; i<n; i++){
47693     int idx = aPermute ? aPermute[i] : i;
47694     CollSeq *pColl;    /* Collating sequence to use on this term */
47695     int bRev;          /* True for DESCENDING sort order */
47696     REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
47697     REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
47698     assert( i<pKeyInfo->nField );
47699     pColl = pKeyInfo->aColl[i];
47700     bRev = pKeyInfo->aSortOrder[i];
47701     iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
47702     if( iCompare ){
47703       if( bRev ) iCompare = -iCompare;
47704       break;
47705     }
47706   }
47707   aPermute = 0;
47708   break;
47709 }
47710
47711 /* Opcode: Jump P1 P2 P3 * *
47712 **
47713 ** Jump to the instruction at address P1, P2, or P3 depending on whether
47714 ** in the most recent OP_Compare instruction the P1 vector was less than
47715 ** equal to, or greater than the P2 vector, respectively.
47716 */
47717 case OP_Jump: {             /* jump */
47718   if( iCompare<0 ){
47719     pc = pOp->p1 - 1;
47720   }else if( iCompare==0 ){
47721     pc = pOp->p2 - 1;
47722   }else{
47723     pc = pOp->p3 - 1;
47724   }
47725   break;
47726 }
47727
47728 /* Opcode: And P1 P2 P3 * *
47729 **
47730 ** Take the logical AND of the values in registers P1 and P2 and
47731 ** write the result into register P3.
47732 **
47733 ** If either P1 or P2 is 0 (false) then the result is 0 even if
47734 ** the other input is NULL.  A NULL and true or two NULLs give
47735 ** a NULL output.
47736 */
47737 /* Opcode: Or P1 P2 P3 * *
47738 **
47739 ** Take the logical OR of the values in register P1 and P2 and
47740 ** store the answer in register P3.
47741 **
47742 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
47743 ** even if the other input is NULL.  A NULL and false or two NULLs
47744 ** give a NULL output.
47745 */
47746 case OP_And:              /* same as TK_AND, in1, in2, out3 */
47747 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
47748   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
47749
47750   if( pIn1->flags & MEM_Null ){
47751     v1 = 2;
47752   }else{
47753     v1 = sqlite3VdbeIntValue(pIn1)!=0;
47754   }
47755   if( pIn2->flags & MEM_Null ){
47756     v2 = 2;
47757   }else{
47758     v2 = sqlite3VdbeIntValue(pIn2)!=0;
47759   }
47760   if( pOp->opcode==OP_And ){
47761     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
47762     v1 = and_logic[v1*3+v2];
47763   }else{
47764     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
47765     v1 = or_logic[v1*3+v2];
47766   }
47767   if( v1==2 ){
47768     MemSetTypeFlag(pOut, MEM_Null);
47769   }else{
47770     pOut->u.i = v1;
47771     MemSetTypeFlag(pOut, MEM_Int);
47772   }
47773   break;
47774 }
47775
47776 /* Opcode: Not P1 * * * *
47777 **
47778 ** Interpret the value in register P1 as a boolean value.  Replace it
47779 ** with its complement.  If the value in register P1 is NULL its value
47780 ** is unchanged.
47781 */
47782 case OP_Not: {                /* same as TK_NOT, in1 */
47783   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
47784   sqlite3VdbeMemIntegerify(pIn1);
47785   pIn1->u.i = !pIn1->u.i;
47786   assert( pIn1->flags&MEM_Int );
47787   break;
47788 }
47789
47790 /* Opcode: BitNot P1 * * * *
47791 **
47792 ** Interpret the content of register P1 as an integer.  Replace it
47793 ** with its ones-complement.  If the value is originally NULL, leave
47794 ** it unchanged.
47795 */
47796 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
47797   if( pIn1->flags & MEM_Null ) break;  /* Do nothing to NULLs */
47798   sqlite3VdbeMemIntegerify(pIn1);
47799   pIn1->u.i = ~pIn1->u.i;
47800   assert( pIn1->flags&MEM_Int );
47801   break;
47802 }
47803
47804 /* Opcode: If P1 P2 P3 * *
47805 **
47806 ** Jump to P2 if the value in register P1 is true.  The value is
47807 ** is considered true if it is numeric and non-zero.  If the value
47808 ** in P1 is NULL then take the jump if P3 is true.
47809 */
47810 /* Opcode: IfNot P1 P2 P3 * *
47811 **
47812 ** Jump to P2 if the value in register P1 is False.  The value is
47813 ** is considered true if it has a numeric value of zero.  If the value
47814 ** in P1 is NULL then take the jump if P3 is true.
47815 */
47816 case OP_If:                 /* jump, in1 */
47817 case OP_IfNot: {            /* jump, in1 */
47818   int c;
47819   if( pIn1->flags & MEM_Null ){
47820     c = pOp->p3;
47821   }else{
47822 #ifdef SQLITE_OMIT_FLOATING_POINT
47823     c = sqlite3VdbeIntValue(pIn1);
47824 #else
47825     c = sqlite3VdbeRealValue(pIn1)!=0.0;
47826 #endif
47827     if( pOp->opcode==OP_IfNot ) c = !c;
47828   }
47829   if( c ){
47830     pc = pOp->p2-1;
47831   }
47832   break;
47833 }
47834
47835 /* Opcode: IsNull P1 P2 P3 * *
47836 **
47837 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
47838 ** than zero, then check all values reg(P1), reg(P1+1), 
47839 ** reg(P1+2), ..., reg(P1+P3-1).
47840 */
47841 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
47842   int n = pOp->p3;
47843   assert( pOp->p3==0 || pOp->p1>0 );
47844   do{
47845     if( (pIn1->flags & MEM_Null)!=0 ){
47846       pc = pOp->p2 - 1;
47847       break;
47848     }
47849     pIn1++;
47850   }while( --n > 0 );
47851   break;
47852 }
47853
47854 /* Opcode: NotNull P1 P2 * * *
47855 **
47856 ** Jump to P2 if the value in register P1 is not NULL.  
47857 */
47858 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
47859   if( (pIn1->flags & MEM_Null)==0 ){
47860     pc = pOp->p2 - 1;
47861   }
47862   break;
47863 }
47864
47865 /* Opcode: SetNumColumns * P2 * * *
47866 **
47867 ** This opcode sets the number of columns for the cursor opened by the
47868 ** following instruction to P2.
47869 **
47870 ** An OP_SetNumColumns is only useful if it occurs immediately before 
47871 ** one of the following opcodes:
47872 **
47873 **     OpenRead
47874 **     OpenWrite
47875 **     OpenPseudo
47876 **
47877 ** If the OP_Column opcode is to be executed on a cursor, then
47878 ** this opcode must be present immediately before the opcode that
47879 ** opens the cursor.
47880 */
47881 case OP_SetNumColumns: {
47882   break;
47883 }
47884
47885 /* Opcode: Column P1 P2 P3 P4 *
47886 **
47887 ** Interpret the data that cursor P1 points to as a structure built using
47888 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
47889 ** information about the format of the data.)  Extract the P2-th column
47890 ** from this record.  If there are less that (P2+1) 
47891 ** values in the record, extract a NULL.
47892 **
47893 ** The value extracted is stored in register P3.
47894 **
47895 ** If the KeyAsData opcode has previously executed on this cursor, then the
47896 ** field might be extracted from the key rather than the data.
47897 **
47898 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
47899 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
47900 ** the result.
47901 */
47902 case OP_Column: {
47903   u32 payloadSize;   /* Number of bytes in the record */
47904   int p1 = pOp->p1;  /* P1 value of the opcode */
47905   int p2 = pOp->p2;  /* column number to retrieve */
47906   Cursor *pC = 0;    /* The VDBE cursor */
47907   char *zRec;        /* Pointer to complete record-data */
47908   BtCursor *pCrsr;   /* The BTree cursor */
47909   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
47910   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
47911   u32 nField;        /* number of fields in the record */
47912   int len;           /* The length of the serialized data for the column */
47913   int i;             /* Loop counter */
47914   char *zData;       /* Part of the record being decoded */
47915   Mem *pDest;        /* Where to write the extracted value */
47916   Mem sMem;          /* For storing the record being decoded */
47917
47918   sMem.flags = 0;
47919   sMem.db = 0;
47920   sMem.zMalloc = 0;
47921   assert( p1<p->nCursor );
47922   assert( pOp->p3>0 && pOp->p3<=p->nMem );
47923   pDest = &p->aMem[pOp->p3];
47924   MemSetTypeFlag(pDest, MEM_Null);
47925
47926   /* This block sets the variable payloadSize to be the total number of
47927   ** bytes in the record.
47928   **
47929   ** zRec is set to be the complete text of the record if it is available.
47930   ** The complete record text is always available for pseudo-tables
47931   ** If the record is stored in a cursor, the complete record text
47932   ** might be available in the  pC->aRow cache.  Or it might not be.
47933   ** If the data is unavailable,  zRec is set to NULL.
47934   **
47935   ** We also compute the number of columns in the record.  For cursors,
47936   ** the number of columns is stored in the Cursor.nField element.
47937   */
47938   pC = p->apCsr[p1];
47939   assert( pC!=0 );
47940 #ifndef SQLITE_OMIT_VIRTUALTABLE
47941   assert( pC->pVtabCursor==0 );
47942 #endif
47943   if( pC->pCursor!=0 ){
47944     /* The record is stored in a B-Tree */
47945     rc = sqlite3VdbeCursorMoveto(pC);
47946     if( rc ) goto abort_due_to_error;
47947     zRec = 0;
47948     pCrsr = pC->pCursor;
47949     if( pC->nullRow ){
47950       payloadSize = 0;
47951     }else if( pC->cacheStatus==p->cacheCtr ){
47952       payloadSize = pC->payloadSize;
47953       zRec = (char*)pC->aRow;
47954     }else if( pC->isIndex ){
47955       i64 payloadSize64;
47956       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
47957       payloadSize = payloadSize64;
47958     }else{
47959       sqlite3BtreeDataSize(pCrsr, &payloadSize);
47960     }
47961     nField = pC->nField;
47962   }else{
47963     assert( pC->pseudoTable );
47964     /* The record is the sole entry of a pseudo-table */
47965     payloadSize = pC->nData;
47966     zRec = pC->pData;
47967     pC->cacheStatus = CACHE_STALE;
47968     assert( payloadSize==0 || zRec!=0 );
47969     nField = pC->nField;
47970     pCrsr = 0;
47971   }
47972
47973   /* If payloadSize is 0, then just store a NULL */
47974   if( payloadSize==0 ){
47975     assert( pDest->flags&MEM_Null );
47976     goto op_column_out;
47977   }
47978   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
47979     goto too_big;
47980   }
47981
47982   assert( p2<nField );
47983
47984   /* Read and parse the table header.  Store the results of the parse
47985   ** into the record header cache fields of the cursor.
47986   */
47987   aType = pC->aType;
47988   if( pC->cacheStatus==p->cacheCtr ){
47989     aOffset = pC->aOffset;
47990   }else{
47991     u8 *zIdx;        /* Index into header */
47992     u8 *zEndHdr;     /* Pointer to first byte after the header */
47993     u32 offset;      /* Offset into the data */
47994     int szHdrSz;     /* Size of the header size field at start of record */
47995     int avail;       /* Number of bytes of available data */
47996
47997     assert(aType);
47998     pC->aOffset = aOffset = &aType[nField];
47999     pC->payloadSize = payloadSize;
48000     pC->cacheStatus = p->cacheCtr;
48001
48002     /* Figure out how many bytes are in the header */
48003     if( zRec ){
48004       zData = zRec;
48005     }else{
48006       if( pC->isIndex ){
48007         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
48008       }else{
48009         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
48010       }
48011       /* If KeyFetch()/DataFetch() managed to get the entire payload,
48012       ** save the payload in the pC->aRow cache.  That will save us from
48013       ** having to make additional calls to fetch the content portion of
48014       ** the record.
48015       */
48016       if( avail>=payloadSize ){
48017         zRec = zData;
48018         pC->aRow = (u8*)zData;
48019       }else{
48020         pC->aRow = 0;
48021       }
48022     }
48023     /* The following assert is true in all cases accept when
48024     ** the database file has been corrupted externally.
48025     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
48026     szHdrSz = getVarint32((u8*)zData, offset);
48027
48028     /* The KeyFetch() or DataFetch() above are fast and will get the entire
48029     ** record header in most cases.  But they will fail to get the complete
48030     ** record header if the record header does not fit on a single page
48031     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
48032     ** acquire the complete header text.
48033     */
48034     if( !zRec && avail<offset ){
48035       sMem.flags = 0;
48036       sMem.db = 0;
48037       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
48038       if( rc!=SQLITE_OK ){
48039         goto op_column_out;
48040       }
48041       zData = sMem.z;
48042     }
48043     zEndHdr = (u8 *)&zData[offset];
48044     zIdx = (u8 *)&zData[szHdrSz];
48045
48046     /* Scan the header and use it to fill in the aType[] and aOffset[]
48047     ** arrays.  aType[i] will contain the type integer for the i-th
48048     ** column and aOffset[i] will contain the offset from the beginning
48049     ** of the record to the start of the data for the i-th column
48050     */
48051     for(i=0; i<nField; i++){
48052       if( zIdx<zEndHdr ){
48053         aOffset[i] = offset;
48054         zIdx += getVarint32(zIdx, aType[i]);
48055         offset += sqlite3VdbeSerialTypeLen(aType[i]);
48056       }else{
48057         /* If i is less that nField, then there are less fields in this
48058         ** record than SetNumColumns indicated there are columns in the
48059         ** table. Set the offset for any extra columns not present in
48060         ** the record to 0. This tells code below to store a NULL
48061         ** instead of deserializing a value from the record.
48062         */
48063         aOffset[i] = 0;
48064       }
48065     }
48066     sqlite3VdbeMemRelease(&sMem);
48067     sMem.flags = MEM_Null;
48068
48069     /* If we have read more header data than was contained in the header,
48070     ** or if the end of the last field appears to be past the end of the
48071     ** record, or if the end of the last field appears to be before the end
48072     ** of the record (when all fields present), then we must be dealing 
48073     ** with a corrupt database.
48074     */
48075     if( zIdx>zEndHdr || offset>payloadSize 
48076      || (zIdx==zEndHdr && offset!=payloadSize) ){
48077       rc = SQLITE_CORRUPT_BKPT;
48078       goto op_column_out;
48079     }
48080   }
48081
48082   /* Get the column information. If aOffset[p2] is non-zero, then 
48083   ** deserialize the value from the record. If aOffset[p2] is zero,
48084   ** then there are not enough fields in the record to satisfy the
48085   ** request.  In this case, set the value NULL or to P4 if P4 is
48086   ** a pointer to a Mem object.
48087   */
48088   if( aOffset[p2] ){
48089     assert( rc==SQLITE_OK );
48090     if( zRec ){
48091       sqlite3VdbeMemReleaseExternal(pDest);
48092       sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
48093     }else{
48094       len = sqlite3VdbeSerialTypeLen(aType[p2]);
48095       sqlite3VdbeMemMove(&sMem, pDest);
48096       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
48097       if( rc!=SQLITE_OK ){
48098         goto op_column_out;
48099       }
48100       zData = sMem.z;
48101       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
48102     }
48103     pDest->enc = encoding;
48104   }else{
48105     if( pOp->p4type==P4_MEM ){
48106       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
48107     }else{
48108       assert( pDest->flags&MEM_Null );
48109     }
48110   }
48111
48112   /* If we dynamically allocated space to hold the data (in the
48113   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
48114   ** dynamically allocated space over to the pDest structure.
48115   ** This prevents a memory copy.
48116   */
48117   if( sMem.zMalloc ){
48118     assert( sMem.z==sMem.zMalloc );
48119     assert( !(pDest->flags & MEM_Dyn) );
48120     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
48121     pDest->flags &= ~(MEM_Ephem|MEM_Static);
48122     pDest->flags |= MEM_Term;
48123     pDest->z = sMem.z;
48124     pDest->zMalloc = sMem.zMalloc;
48125   }
48126
48127   rc = sqlite3VdbeMemMakeWriteable(pDest);
48128
48129 op_column_out:
48130   UPDATE_MAX_BLOBSIZE(pDest);
48131   REGISTER_TRACE(pOp->p3, pDest);
48132   break;
48133 }
48134
48135 /* Opcode: Affinity P1 P2 * P4 *
48136 **
48137 ** Apply affinities to a range of P2 registers starting with P1.
48138 **
48139 ** P4 is a string that is P2 characters long. The nth character of the
48140 ** string indicates the column affinity that should be used for the nth
48141 ** memory cell in the range.
48142 */
48143 case OP_Affinity: {
48144   char *zAffinity = pOp->p4.z;
48145   Mem *pData0 = &p->aMem[pOp->p1];
48146   Mem *pLast = &pData0[pOp->p2-1];
48147   Mem *pRec;
48148
48149   for(pRec=pData0; pRec<=pLast; pRec++){
48150     ExpandBlob(pRec);
48151     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48152   }
48153   break;
48154 }
48155
48156 /* Opcode: MakeRecord P1 P2 P3 P4 *
48157 **
48158 ** Convert P2 registers beginning with P1 into a single entry
48159 ** suitable for use as a data record in a database table or as a key
48160 ** in an index.  The details of the format are irrelevant as long as
48161 ** the OP_Column opcode can decode the record later.
48162 ** Refer to source code comments for the details of the record
48163 ** format.
48164 **
48165 ** P4 may be a string that is P2 characters long.  The nth character of the
48166 ** string indicates the column affinity that should be used for the nth
48167 ** field of the index key.
48168 **
48169 ** The mapping from character to affinity is given by the SQLITE_AFF_
48170 ** macros defined in sqliteInt.h.
48171 **
48172 ** If P4 is NULL then all index fields have the affinity NONE.
48173 */
48174 case OP_MakeRecord: {
48175   /* Assuming the record contains N fields, the record format looks
48176   ** like this:
48177   **
48178   ** ------------------------------------------------------------------------
48179   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
48180   ** ------------------------------------------------------------------------
48181   **
48182   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
48183   ** and so froth.
48184   **
48185   ** Each type field is a varint representing the serial type of the 
48186   ** corresponding data element (see sqlite3VdbeSerialType()). The
48187   ** hdr-size field is also a varint which is the offset from the beginning
48188   ** of the record to data0.
48189   */
48190   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
48191   Mem *pRec;             /* The new record */
48192   u64 nData = 0;         /* Number of bytes of data space */
48193   int nHdr = 0;          /* Number of bytes of header space */
48194   u64 nByte = 0;         /* Data space required for this record */
48195   int nZero = 0;         /* Number of zero bytes at the end of the record */
48196   int nVarint;           /* Number of bytes in a varint */
48197   u32 serial_type;       /* Type field */
48198   Mem *pData0;           /* First field to be combined into the record */
48199   Mem *pLast;            /* Last field of the record */
48200   int nField;            /* Number of fields in the record */
48201   char *zAffinity;       /* The affinity string for the record */
48202   int file_format;       /* File format to use for encoding */
48203   int i;                 /* Space used in zNewRecord[] */
48204
48205   nField = pOp->p1;
48206   zAffinity = pOp->p4.z;
48207   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
48208   pData0 = &p->aMem[nField];
48209   nField = pOp->p2;
48210   pLast = &pData0[nField-1];
48211   file_format = p->minWriteFileFormat;
48212
48213   /* Loop through the elements that will make up the record to figure
48214   ** out how much space is required for the new record.
48215   */
48216   for(pRec=pData0; pRec<=pLast; pRec++){
48217     int len;
48218     if( zAffinity ){
48219       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
48220     }
48221     if( pRec->flags&MEM_Zero && pRec->n>0 ){
48222       sqlite3VdbeMemExpandBlob(pRec);
48223     }
48224     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48225     len = sqlite3VdbeSerialTypeLen(serial_type);
48226     nData += len;
48227     nHdr += sqlite3VarintLen(serial_type);
48228     if( pRec->flags & MEM_Zero ){
48229       /* Only pure zero-filled BLOBs can be input to this Opcode.
48230       ** We do not allow blobs with a prefix and a zero-filled tail. */
48231       nZero += pRec->u.i;
48232     }else if( len ){
48233       nZero = 0;
48234     }
48235   }
48236
48237   /* Add the initial header varint and total the size */
48238   nHdr += nVarint = sqlite3VarintLen(nHdr);
48239   if( nVarint<sqlite3VarintLen(nHdr) ){
48240     nHdr++;
48241   }
48242   nByte = nHdr+nData-nZero;
48243   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
48244     goto too_big;
48245   }
48246
48247   /* Make sure the output register has a buffer large enough to store 
48248   ** the new record. The output register (pOp->p3) is not allowed to
48249   ** be one of the input registers (because the following call to
48250   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
48251   */
48252   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
48253   pOut = &p->aMem[pOp->p3];
48254   if( sqlite3VdbeMemGrow(pOut, nByte, 0) ){
48255     goto no_mem;
48256   }
48257   zNewRecord = (u8 *)pOut->z;
48258
48259   /* Write the record */
48260   i = putVarint32(zNewRecord, nHdr);
48261   for(pRec=pData0; pRec<=pLast; pRec++){
48262     serial_type = sqlite3VdbeSerialType(pRec, file_format);
48263     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
48264   }
48265   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
48266     i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format);
48267   }
48268   assert( i==nByte );
48269
48270   assert( pOp->p3>0 && pOp->p3<=p->nMem );
48271   pOut->n = nByte;
48272   pOut->flags = MEM_Blob | MEM_Dyn;
48273   pOut->xDel = 0;
48274   if( nZero ){
48275     pOut->u.i = nZero;
48276     pOut->flags |= MEM_Zero;
48277   }
48278   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
48279   REGISTER_TRACE(pOp->p3, pOut);
48280   UPDATE_MAX_BLOBSIZE(pOut);
48281   break;
48282 }
48283
48284 /* Opcode: Statement P1 * * * *
48285 **
48286 ** Begin an individual statement transaction which is part of a larger
48287 ** transaction.  This is needed so that the statement
48288 ** can be rolled back after an error without having to roll back the
48289 ** entire transaction.  The statement transaction will automatically
48290 ** commit when the VDBE halts.
48291 **
48292 ** If the database connection is currently in autocommit mode (that 
48293 ** is to say, if it is in between BEGIN and COMMIT)
48294 ** and if there are no other active statements on the same database
48295 ** connection, then this operation is a no-op.  No statement transaction
48296 ** is needed since any error can use the normal ROLLBACK process to
48297 ** undo changes.
48298 **
48299 ** If a statement transaction is started, then a statement journal file
48300 ** will be allocated and initialized.
48301 **
48302 ** The statement is begun on the database file with index P1.  The main
48303 ** database file has an index of 0 and the file used for temporary tables
48304 ** has an index of 1.
48305 */
48306 case OP_Statement: {
48307   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
48308     int i = pOp->p1;
48309     Btree *pBt;
48310     assert( i>=0 && i<db->nDb );
48311     assert( db->aDb[i].pBt!=0 );
48312     pBt = db->aDb[i].pBt;
48313     assert( sqlite3BtreeIsInTrans(pBt) );
48314     assert( (p->btreeMask & (1<<i))!=0 );
48315     if( !sqlite3BtreeIsInStmt(pBt) ){
48316       rc = sqlite3BtreeBeginStmt(pBt);
48317       p->openedStatement = 1;
48318     }
48319   }
48320   break;
48321 }
48322
48323 /* Opcode: AutoCommit P1 P2 * * *
48324 **
48325 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
48326 ** back any currently active btree transactions. If there are any active
48327 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
48328 **
48329 ** This instruction causes the VM to halt.
48330 */
48331 case OP_AutoCommit: {
48332   u8 i = pOp->p1;
48333   u8 rollback = pOp->p2;
48334
48335   assert( i==1 || i==0 );
48336   assert( i==1 || rollback==0 );
48337
48338   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
48339
48340   if( db->activeVdbeCnt>1 && i && !db->autoCommit ){
48341     /* If this instruction implements a COMMIT or ROLLBACK, other VMs are
48342     ** still running, and a transaction is active, return an error indicating
48343     ** that the other VMs must complete first. 
48344     */
48345     sqlite3SetString(&p->zErrMsg, db, "cannot %s transaction - "
48346         "SQL statements in progress",
48347         rollback ? "rollback" : "commit");
48348     rc = SQLITE_ERROR;
48349   }else if( i!=db->autoCommit ){
48350     if( pOp->p2 ){
48351       assert( i==1 );
48352       sqlite3RollbackAll(db);
48353       db->autoCommit = 1;
48354     }else{
48355       db->autoCommit = i;
48356       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
48357         p->pc = pc;
48358         db->autoCommit = 1-i;
48359         p->rc = rc = SQLITE_BUSY;
48360         goto vdbe_return;
48361       }
48362     }
48363     if( p->rc==SQLITE_OK ){
48364       rc = SQLITE_DONE;
48365     }else{
48366       rc = SQLITE_ERROR;
48367     }
48368     goto vdbe_return;
48369   }else{
48370     sqlite3SetString(&p->zErrMsg, db,
48371         (!i)?"cannot start a transaction within a transaction":(
48372         (rollback)?"cannot rollback - no transaction is active":
48373                    "cannot commit - no transaction is active"));
48374          
48375     rc = SQLITE_ERROR;
48376   }
48377   break;
48378 }
48379
48380 /* Opcode: Transaction P1 P2 * * *
48381 **
48382 ** Begin a transaction.  The transaction ends when a Commit or Rollback
48383 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
48384 ** transaction might also be rolled back if an error is encountered.
48385 **
48386 ** P1 is the index of the database file on which the transaction is
48387 ** started.  Index 0 is the main database file and index 1 is the
48388 ** file used for temporary tables.  Indices of 2 or more are used for
48389 ** attached databases.
48390 **
48391 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
48392 ** obtained on the database file when a write-transaction is started.  No
48393 ** other process can start another write transaction while this transaction is
48394 ** underway.  Starting a write transaction also creates a rollback journal. A
48395 ** write transaction must be started before any changes can be made to the
48396 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
48397 ** on the file.
48398 **
48399 ** If P2 is zero, then a read-lock is obtained on the database file.
48400 */
48401 case OP_Transaction: {
48402   int i = pOp->p1;
48403   Btree *pBt;
48404
48405   assert( i>=0 && i<db->nDb );
48406   assert( (p->btreeMask & (1<<i))!=0 );
48407   pBt = db->aDb[i].pBt;
48408
48409   if( pBt ){
48410     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
48411     if( rc==SQLITE_BUSY ){
48412       p->pc = pc;
48413       p->rc = rc = SQLITE_BUSY;
48414       goto vdbe_return;
48415     }
48416     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
48417       goto abort_due_to_error;
48418     }
48419   }
48420   break;
48421 }
48422
48423 /* Opcode: ReadCookie P1 P2 P3 * *
48424 **
48425 ** Read cookie number P3 from database P1 and write it into register P2.
48426 ** P3==0 is the schema version.  P3==1 is the database format.
48427 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
48428 ** the main database file and P1==1 is the database file used to store
48429 ** temporary tables.
48430 **
48431 ** If P1 is negative, then this is a request to read the size of a
48432 ** databases free-list. P3 must be set to 1 in this case. The actual
48433 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
48434 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
48435 **
48436 ** There must be a read-lock on the database (either a transaction
48437 ** must be started or there must be an open cursor) before
48438 ** executing this instruction.
48439 */
48440 case OP_ReadCookie: {               /* out2-prerelease */
48441   int iMeta;
48442   int iDb = pOp->p1;
48443   int iCookie = pOp->p3;
48444
48445   assert( pOp->p3<SQLITE_N_BTREE_META );
48446   if( iDb<0 ){
48447     iDb = (-1*(iDb+1));
48448     iCookie *= -1;
48449   }
48450   assert( iDb>=0 && iDb<db->nDb );
48451   assert( db->aDb[iDb].pBt!=0 );
48452   assert( (p->btreeMask & (1<<iDb))!=0 );
48453   /* The indexing of meta values at the schema layer is off by one from
48454   ** the indexing in the btree layer.  The btree considers meta[0] to
48455   ** be the number of free pages in the database (a read-only value)
48456   ** and meta[1] to be the schema cookie.  The schema layer considers
48457   ** meta[1] to be the schema cookie.  So we have to shift the index
48458   ** by one in the following statement.
48459   */
48460   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
48461   pOut->u.i = iMeta;
48462   MemSetTypeFlag(pOut, MEM_Int);
48463   break;
48464 }
48465
48466 /* Opcode: SetCookie P1 P2 P3 * *
48467 **
48468 ** Write the content of register P3 (interpreted as an integer)
48469 ** into cookie number P2 of database P1.
48470 ** P2==0 is the schema version.  P2==1 is the database format.
48471 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
48472 ** the main database file and P1==1 is the database file used to store
48473 ** temporary tables.
48474 **
48475 ** A transaction must be started before executing this opcode.
48476 */
48477 case OP_SetCookie: {       /* in3 */
48478   Db *pDb;
48479   assert( pOp->p2<SQLITE_N_BTREE_META );
48480   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48481   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48482   pDb = &db->aDb[pOp->p1];
48483   assert( pDb->pBt!=0 );
48484   sqlite3VdbeMemIntegerify(pIn3);
48485   /* See note about index shifting on OP_ReadCookie */
48486   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
48487   if( pOp->p2==0 ){
48488     /* When the schema cookie changes, record the new cookie internally */
48489     pDb->pSchema->schema_cookie = pIn3->u.i;
48490     db->flags |= SQLITE_InternChanges;
48491   }else if( pOp->p2==1 ){
48492     /* Record changes in the file format */
48493     pDb->pSchema->file_format = pIn3->u.i;
48494   }
48495   if( pOp->p1==1 ){
48496     /* Invalidate all prepared statements whenever the TEMP database
48497     ** schema is changed.  Ticket #1644 */
48498     sqlite3ExpirePreparedStatements(db);
48499   }
48500   break;
48501 }
48502
48503 /* Opcode: VerifyCookie P1 P2 *
48504 **
48505 ** Check the value of global database parameter number 0 (the
48506 ** schema version) and make sure it is equal to P2.  
48507 ** P1 is the database number which is 0 for the main database file
48508 ** and 1 for the file holding temporary tables and some higher number
48509 ** for auxiliary databases.
48510 **
48511 ** The cookie changes its value whenever the database schema changes.
48512 ** This operation is used to detect when that the cookie has changed
48513 ** and that the current process needs to reread the schema.
48514 **
48515 ** Either a transaction needs to have been started or an OP_Open needs
48516 ** to be executed (to establish a read lock) before this opcode is
48517 ** invoked.
48518 */
48519 case OP_VerifyCookie: {
48520   int iMeta;
48521   Btree *pBt;
48522   assert( pOp->p1>=0 && pOp->p1<db->nDb );
48523   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
48524   pBt = db->aDb[pOp->p1].pBt;
48525   if( pBt ){
48526     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
48527   }else{
48528     rc = SQLITE_OK;
48529     iMeta = 0;
48530   }
48531   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
48532     sqlite3DbFree(db, p->zErrMsg);
48533     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
48534     /* If the schema-cookie from the database file matches the cookie 
48535     ** stored with the in-memory representation of the schema, do
48536     ** not reload the schema from the database file.
48537     **
48538     ** If virtual-tables are in use, this is not just an optimization.
48539     ** Often, v-tables store their data in other SQLite tables, which
48540     ** are queried from within xNext() and other v-table methods using
48541     ** prepared queries. If such a query is out-of-date, we do not want to
48542     ** discard the database schema, as the user code implementing the
48543     ** v-table would have to be ready for the sqlite3_vtab structure itself
48544     ** to be invalidated whenever sqlite3_step() is called from within 
48545     ** a v-table method.
48546     */
48547     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
48548       sqlite3ResetInternalSchema(db, pOp->p1);
48549     }
48550
48551     sqlite3ExpirePreparedStatements(db);
48552     rc = SQLITE_SCHEMA;
48553   }
48554   break;
48555 }
48556
48557 /* Opcode: OpenRead P1 P2 P3 P4 P5
48558 **
48559 ** Open a read-only cursor for the database table whose root page is
48560 ** P2 in a database file.  The database file is determined by P3. 
48561 ** P3==0 means the main database, P3==1 means the database used for 
48562 ** temporary tables, and P3>1 means used the corresponding attached
48563 ** database.  Give the new cursor an identifier of P1.  The P1
48564 ** values need not be contiguous but all P1 values should be small integers.
48565 ** It is an error for P1 to be negative.
48566 **
48567 ** If P5!=0 then use the content of register P2 as the root page, not
48568 ** the value of P2 itself.
48569 **
48570 ** There will be a read lock on the database whenever there is an
48571 ** open cursor.  If the database was unlocked prior to this instruction
48572 ** then a read lock is acquired as part of this instruction.  A read
48573 ** lock allows other processes to read the database but prohibits
48574 ** any other process from modifying the database.  The read lock is
48575 ** released when all cursors are closed.  If this instruction attempts
48576 ** to get a read lock but fails, the script terminates with an
48577 ** SQLITE_BUSY error code.
48578 **
48579 ** The P4 value is a pointer to a KeyInfo structure that defines the
48580 ** content and collating sequence of indices.  P4 is NULL for cursors
48581 ** that are not pointing to indices.
48582 **
48583 ** See also OpenWrite.
48584 */
48585 /* Opcode: OpenWrite P1 P2 P3 P4 P5
48586 **
48587 ** Open a read/write cursor named P1 on the table or index whose root
48588 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
48589 ** root page.
48590 **
48591 ** The P4 value is a pointer to a KeyInfo structure that defines the
48592 ** content and collating sequence of indices.  P4 is NULL for cursors
48593 ** that are not pointing to indices.
48594 **
48595 ** This instruction works just like OpenRead except that it opens the cursor
48596 ** in read/write mode.  For a given table, there can be one or more read-only
48597 ** cursors or a single read/write cursor but not both.
48598 **
48599 ** See also OpenRead.
48600 */
48601 case OP_OpenRead:
48602 case OP_OpenWrite: {
48603   int i = pOp->p1;
48604   int p2 = pOp->p2;
48605   int iDb = pOp->p3;
48606   int wrFlag;
48607   Btree *pX;
48608   Cursor *pCur;
48609   Db *pDb;
48610   
48611   assert( iDb>=0 && iDb<db->nDb );
48612   assert( (p->btreeMask & (1<<iDb))!=0 );
48613   pDb = &db->aDb[iDb];
48614   pX = pDb->pBt;
48615   assert( pX!=0 );
48616   if( pOp->opcode==OP_OpenWrite ){
48617     wrFlag = 1;
48618     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
48619       p->minWriteFileFormat = pDb->pSchema->file_format;
48620     }
48621   }else{
48622     wrFlag = 0;
48623   }
48624   if( pOp->p5 ){
48625     assert( p2>0 );
48626     assert( p2<=p->nMem );
48627     pIn2 = &p->aMem[p2];
48628     sqlite3VdbeMemIntegerify(pIn2);
48629     p2 = pIn2->u.i;
48630     assert( p2>=2 );
48631   }
48632   assert( i>=0 );
48633   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
48634   if( pCur==0 ) goto no_mem;
48635   pCur->nullRow = 1;
48636   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
48637   if( pOp->p4type==P4_KEYINFO ){
48638     pCur->pKeyInfo = pOp->p4.pKeyInfo;
48639     pCur->pKeyInfo->enc = ENC(p->db);
48640   }else{
48641     pCur->pKeyInfo = 0;
48642   }
48643   switch( rc ){
48644     case SQLITE_BUSY: {
48645       p->pc = pc;
48646       p->rc = rc = SQLITE_BUSY;
48647       goto vdbe_return;
48648     }
48649     case SQLITE_OK: {
48650       int flags = sqlite3BtreeFlags(pCur->pCursor);
48651       /* Sanity checking.  Only the lower four bits of the flags byte should
48652       ** be used.  Bit 3 (mask 0x08) is unpredictable.  The lower 3 bits
48653       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
48654       ** 2 (zerodata for indices).  If these conditions are not met it can
48655       ** only mean that we are dealing with a corrupt database file
48656       */
48657       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
48658         rc = SQLITE_CORRUPT_BKPT;
48659         goto abort_due_to_error;
48660       }
48661       pCur->isTable = (flags & BTREE_INTKEY)!=0;
48662       pCur->isIndex = (flags & BTREE_ZERODATA)!=0;
48663       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
48664       ** we expect to be opening an index.  If this is not what happened,
48665       ** then the database is corrupt
48666       */
48667       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
48668        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
48669         rc = SQLITE_CORRUPT_BKPT;
48670         goto abort_due_to_error;
48671       }
48672       break;
48673     }
48674     case SQLITE_EMPTY: {
48675       pCur->isTable = pOp->p4type!=P4_KEYINFO;
48676       pCur->isIndex = !pCur->isTable;
48677       pCur->pCursor = 0;
48678       rc = SQLITE_OK;
48679       break;
48680     }
48681     default: {
48682       goto abort_due_to_error;
48683     }
48684   }
48685   break;
48686 }
48687
48688 /* Opcode: OpenEphemeral P1 P2 * P4 *
48689 **
48690 ** Open a new cursor P1 to a transient table.
48691 ** The cursor is always opened read/write even if 
48692 ** the main database is read-only.  The transient or virtual
48693 ** table is deleted automatically when the cursor is closed.
48694 **
48695 ** P2 is the number of columns in the virtual table.
48696 ** The cursor points to a BTree table if P4==0 and to a BTree index
48697 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
48698 ** that defines the format of keys in the index.
48699 **
48700 ** This opcode was once called OpenTemp.  But that created
48701 ** confusion because the term "temp table", might refer either
48702 ** to a TEMP table at the SQL level, or to a table opened by
48703 ** this opcode.  Then this opcode was call OpenVirtual.  But
48704 ** that created confusion with the whole virtual-table idea.
48705 */
48706 case OP_OpenEphemeral: {
48707   int i = pOp->p1;
48708   Cursor *pCx;
48709   static const int openFlags = 
48710       SQLITE_OPEN_READWRITE |
48711       SQLITE_OPEN_CREATE |
48712       SQLITE_OPEN_EXCLUSIVE |
48713       SQLITE_OPEN_DELETEONCLOSE |
48714       SQLITE_OPEN_TRANSIENT_DB;
48715
48716   assert( i>=0 );
48717   pCx = allocateCursor(p, i, pOp, -1, 1);
48718   if( pCx==0 ) goto no_mem;
48719   pCx->nullRow = 1;
48720   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
48721                            &pCx->pBt);
48722   if( rc==SQLITE_OK ){
48723     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
48724   }
48725   if( rc==SQLITE_OK ){
48726     /* If a transient index is required, create it by calling
48727     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
48728     ** opening it. If a transient table is required, just use the
48729     ** automatically created table with root-page 1 (an INTKEY table).
48730     */
48731     if( pOp->p4.pKeyInfo ){
48732       int pgno;
48733       assert( pOp->p4type==P4_KEYINFO );
48734       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
48735       if( rc==SQLITE_OK ){
48736         assert( pgno==MASTER_ROOT+1 );
48737         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
48738                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
48739         pCx->pKeyInfo = pOp->p4.pKeyInfo;
48740         pCx->pKeyInfo->enc = ENC(p->db);
48741       }
48742       pCx->isTable = 0;
48743     }else{
48744       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
48745       pCx->isTable = 1;
48746     }
48747   }
48748   pCx->isIndex = !pCx->isTable;
48749   break;
48750 }
48751
48752 /* Opcode: OpenPseudo P1 P2 * * *
48753 **
48754 ** Open a new cursor that points to a fake table that contains a single
48755 ** row of data.  Any attempt to write a second row of data causes the
48756 ** first row to be deleted.  All data is deleted when the cursor is
48757 ** closed.
48758 **
48759 ** A pseudo-table created by this opcode is useful for holding the
48760 ** NEW or OLD tables in a trigger.  Also used to hold the a single
48761 ** row output from the sorter so that the row can be decomposed into
48762 ** individual columns using the OP_Column opcode.
48763 **
48764 ** When OP_Insert is executed to insert a row in to the pseudo table,
48765 ** the pseudo-table cursor may or may not make it's own copy of the
48766 ** original row data. If P2 is 0, then the pseudo-table will copy the
48767 ** original row data. Otherwise, a pointer to the original memory cell
48768 ** is stored. In this case, the vdbe program must ensure that the 
48769 ** memory cell containing the row data is not overwritten until the
48770 ** pseudo table is closed (or a new row is inserted into it).
48771 */
48772 case OP_OpenPseudo: {
48773   int i = pOp->p1;
48774   Cursor *pCx;
48775   assert( i>=0 );
48776   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
48777   if( pCx==0 ) goto no_mem;
48778   pCx->nullRow = 1;
48779   pCx->pseudoTable = 1;
48780   pCx->ephemPseudoTable = pOp->p2;
48781   pCx->isTable = 1;
48782   pCx->isIndex = 0;
48783   break;
48784 }
48785
48786 /* Opcode: Close P1 * * * *
48787 **
48788 ** Close a cursor previously opened as P1.  If P1 is not
48789 ** currently open, this instruction is a no-op.
48790 */
48791 case OP_Close: {
48792   int i = pOp->p1;
48793   assert( i>=0 && i<p->nCursor );
48794   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
48795   p->apCsr[i] = 0;
48796   break;
48797 }
48798
48799 /* Opcode: MoveGe P1 P2 P3 P4 *
48800 **
48801 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48802 ** use the integer value in register P3 as a key. If cursor P1 refers 
48803 ** to an SQL index, then P3 is the first in an array of P4 registers 
48804 ** that are used as an unpacked index key. 
48805 **
48806 ** Reposition cursor P1 so that  it points to the smallest entry that 
48807 ** is greater than or equal to the key value. If there are no records 
48808 ** greater than or equal to the key and P2 is not zero, then jump to P2.
48809 **
48810 ** A special feature of this opcode (and different from the
48811 ** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is
48812 ** zero and P1 is an SQL table (a b-tree with integer keys) then
48813 ** the seek is deferred until it is actually needed.  It might be
48814 ** the case that the cursor is never accessed.  By deferring the
48815 ** seek, we avoid unnecessary seeks.
48816 **
48817 ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe
48818 */
48819 /* Opcode: MoveGt P1 P2 P3 P4 *
48820 **
48821 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48822 ** use the integer value in register P3 as a key. If cursor P1 refers 
48823 ** to an SQL index, then P3 is the first in an array of P4 registers 
48824 ** that are used as an unpacked index key. 
48825 **
48826 ** Reposition cursor P1 so that  it points to the smallest entry that 
48827 ** is greater than the key value. If there are no records greater than 
48828 ** the key and P2 is not zero, then jump to P2.
48829 **
48830 ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe
48831 */
48832 /* Opcode: MoveLt P1 P2 P3 P4 * 
48833 **
48834 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48835 ** use the integer value in register P3 as a key. If cursor P1 refers 
48836 ** to an SQL index, then P3 is the first in an array of P4 registers 
48837 ** that are used as an unpacked index key. 
48838 **
48839 ** Reposition cursor P1 so that  it points to the largest entry that 
48840 ** is less than the key value. If there are no records less than 
48841 ** the key and P2 is not zero, then jump to P2.
48842 **
48843 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe
48844 */
48845 /* Opcode: MoveLe P1 P2 P3 P4 *
48846 **
48847 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
48848 ** use the integer value in register P3 as a key. If cursor P1 refers 
48849 ** to an SQL index, then P3 is the first in an array of P4 registers 
48850 ** that are used as an unpacked index key. 
48851 **
48852 ** Reposition cursor P1 so that it points to the largest entry that 
48853 ** is less than or equal to the key value. If there are no records 
48854 ** less than or equal to the key and P2 is not zero, then jump to P2.
48855 **
48856 ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt
48857 */
48858 case OP_MoveLt:         /* jump, in3 */
48859 case OP_MoveLe:         /* jump, in3 */
48860 case OP_MoveGe:         /* jump, in3 */
48861 case OP_MoveGt: {       /* jump, in3 */
48862   int i = pOp->p1;
48863   Cursor *pC;
48864
48865   assert( i>=0 && i<p->nCursor );
48866   pC = p->apCsr[i];
48867   assert( pC!=0 );
48868   if( pC->pCursor!=0 ){
48869     int res, oc;
48870     oc = pOp->opcode;
48871     pC->nullRow = 0;
48872     if( pC->isTable ){
48873       i64 iKey = sqlite3VdbeIntValue(pIn3);
48874       if( pOp->p2==0 ){
48875         assert( pOp->opcode==OP_MoveGe );
48876         pC->movetoTarget = iKey;
48877         pC->rowidIsValid = 0;
48878         pC->deferredMoveto = 1;
48879         break;
48880       }
48881       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
48882       if( rc!=SQLITE_OK ){
48883         goto abort_due_to_error;
48884       }
48885       pC->lastRowid = iKey;
48886       pC->rowidIsValid = res==0;
48887     }else{
48888       UnpackedRecord r;
48889       int nField = pOp->p4.i;
48890       assert( pOp->p4type==P4_INT32 );
48891       assert( nField>0 );
48892       r.pKeyInfo = pC->pKeyInfo;
48893       r.nField = nField;
48894       if( oc==OP_MoveGt || oc==OP_MoveLe ){
48895         r.flags = UNPACKED_INCRKEY;
48896       }else{
48897         r.flags = 0;
48898       }
48899       r.aMem = &p->aMem[pOp->p3];
48900       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
48901       if( rc!=SQLITE_OK ){
48902         goto abort_due_to_error;
48903       }
48904       pC->rowidIsValid = 0;
48905     }
48906     pC->deferredMoveto = 0;
48907     pC->cacheStatus = CACHE_STALE;
48908 #ifdef SQLITE_TEST
48909     sqlite3_search_count++;
48910 #endif
48911     if( oc==OP_MoveGe || oc==OP_MoveGt ){
48912       if( res<0 ){
48913         rc = sqlite3BtreeNext(pC->pCursor, &res);
48914         if( rc!=SQLITE_OK ) goto abort_due_to_error;
48915         pC->rowidIsValid = 0;
48916       }else{
48917         res = 0;
48918       }
48919     }else{
48920       assert( oc==OP_MoveLt || oc==OP_MoveLe );
48921       if( res>=0 ){
48922         rc = sqlite3BtreePrevious(pC->pCursor, &res);
48923         if( rc!=SQLITE_OK ) goto abort_due_to_error;
48924         pC->rowidIsValid = 0;
48925       }else{
48926         /* res might be negative because the table is empty.  Check to
48927         ** see if this is the case.
48928         */
48929         res = sqlite3BtreeEof(pC->pCursor);
48930       }
48931     }
48932     assert( pOp->p2>0 );
48933     if( res ){
48934       pc = pOp->p2 - 1;
48935     }
48936   }else if( !pC->pseudoTable ){
48937     /* This happens when attempting to open the sqlite3_master table
48938     ** for read access returns SQLITE_EMPTY. In this case always
48939     ** take the jump (since there are no records in the table).
48940     */
48941     pc = pOp->p2 - 1;
48942   }
48943   break;
48944 }
48945
48946 /* Opcode: Found P1 P2 P3 * *
48947 **
48948 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
48949 ** If an entry that matches the value in register p3 exists in P1 then
48950 ** jump to P2.  If the P3 value does not match any entry in P1
48951 ** then fall thru.  The P1 cursor is left pointing at the matching entry
48952 ** if it exists.
48953 **
48954 ** This instruction is used to implement the IN operator where the
48955 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
48956 ** may be a temporary index that holds the results of the SELECT
48957 ** statement.   This instruction is also used to implement the
48958 ** DISTINCT keyword in SELECT statements.
48959 **
48960 ** This instruction checks if index P1 contains a record for which 
48961 ** the first N serialized values exactly match the N serialized values
48962 ** in the record in register P3, where N is the total number of values in
48963 ** the P3 record (the P3 record is a prefix of the P1 record). 
48964 **
48965 ** See also: NotFound, IsUnique, NotExists
48966 */
48967 /* Opcode: NotFound P1 P2 P3 * *
48968 **
48969 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
48970 ** an index.  If no entry exists in P1 that matches the blob then jump
48971 ** to P2.  If an entry does existing, fall through.  The cursor is left
48972 ** pointing to the entry that matches.
48973 **
48974 ** See also: Found, NotExists, IsUnique
48975 */
48976 case OP_NotFound:       /* jump, in3 */
48977 case OP_Found: {        /* jump, in3 */
48978   int i = pOp->p1;
48979   int alreadyExists = 0;
48980   Cursor *pC;
48981   assert( i>=0 && i<p->nCursor );
48982   assert( p->apCsr[i]!=0 );
48983   if( (pC = p->apCsr[i])->pCursor!=0 ){
48984     int res;
48985     UnpackedRecord *pIdxKey;
48986
48987     assert( pC->isTable==0 );
48988     assert( pIn3->flags & MEM_Blob );
48989     pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
48990                                       aTempRec, sizeof(aTempRec));
48991     if( pIdxKey==0 ){
48992       goto no_mem;
48993     }
48994     if( pOp->opcode==OP_Found ){
48995       pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
48996     }
48997     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
48998     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48999     if( rc!=SQLITE_OK ){
49000       break;
49001     }
49002     alreadyExists = (res==0);
49003     pC->deferredMoveto = 0;
49004     pC->cacheStatus = CACHE_STALE;
49005   }
49006   if( pOp->opcode==OP_Found ){
49007     if( alreadyExists ) pc = pOp->p2 - 1;
49008   }else{
49009     if( !alreadyExists ) pc = pOp->p2 - 1;
49010   }
49011   break;
49012 }
49013
49014 /* Opcode: IsUnique P1 P2 P3 P4 *
49015 **
49016 ** The P3 register contains an integer record number.  Call this
49017 ** record number R.  The P4 register contains an index key created
49018 ** using MakeRecord.  Call it K.
49019 **
49020 ** P1 is an index.  So it has no data and its key consists of a
49021 ** record generated by OP_MakeRecord where the last field is the 
49022 ** rowid of the entry that the index refers to.
49023 ** 
49024 ** This instruction asks if there is an entry in P1 where the
49025 ** fields matches K but the rowid is different from R.
49026 ** If there is no such entry, then there is an immediate
49027 ** jump to P2.  If any entry does exist where the index string
49028 ** matches K but the record number is not R, then the record
49029 ** number for that entry is written into P3 and control
49030 ** falls through to the next instruction.
49031 **
49032 ** See also: NotFound, NotExists, Found
49033 */
49034 case OP_IsUnique: {        /* jump, in3 */
49035   int i = pOp->p1;
49036   Cursor *pCx;
49037   BtCursor *pCrsr;
49038   Mem *pK;
49039   i64 R;
49040
49041   /* Pop the value R off the top of the stack
49042   */
49043   assert( pOp->p4type==P4_INT32 );
49044   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
49045   pK = &p->aMem[pOp->p4.i];
49046   sqlite3VdbeMemIntegerify(pIn3);
49047   R = pIn3->u.i;
49048   assert( i>=0 && i<p->nCursor );
49049   pCx = p->apCsr[i];
49050   assert( pCx!=0 );
49051   pCrsr = pCx->pCursor;
49052   if( pCrsr!=0 ){
49053     int res;
49054     i64 v;                     /* The record number that matches K */
49055     UnpackedRecord *pIdxKey;   /* Unpacked version of P4 */
49056
49057     /* Make sure K is a string and make zKey point to K
49058     */
49059     assert( pK->flags & MEM_Blob );
49060     pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
49061                                       aTempRec, sizeof(aTempRec));
49062     if( pIdxKey==0 ){
49063       goto no_mem;
49064     }
49065     pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
49066
49067     /* Search for an entry in P1 where all but the last rowid match K
49068     ** If there is no such entry, jump immediately to P2.
49069     */
49070     assert( pCx->deferredMoveto==0 );
49071     pCx->cacheStatus = CACHE_STALE;
49072     rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
49073     if( rc!=SQLITE_OK ){
49074       sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49075       goto abort_due_to_error;
49076     }
49077     if( res<0 ){
49078       rc = sqlite3BtreeNext(pCrsr, &res);
49079       if( res ){
49080         pc = pOp->p2 - 1;
49081         sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49082         break;
49083       }
49084     }
49085     rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res); 
49086     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
49087     if( rc!=SQLITE_OK ) goto abort_due_to_error;
49088     if( res>0 ){
49089       pc = pOp->p2 - 1;
49090       break;
49091     }
49092
49093     /* At this point, pCrsr is pointing to an entry in P1 where all but
49094     ** the final entry (the rowid) matches K.  Check to see if the
49095     ** final rowid column is different from R.  If it equals R then jump
49096     ** immediately to P2.
49097     */
49098     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
49099     if( rc!=SQLITE_OK ){
49100       goto abort_due_to_error;
49101     }
49102     if( v==R ){
49103       pc = pOp->p2 - 1;
49104       break;
49105     }
49106
49107     /* The final varint of the key is different from R.  Store it back
49108     ** into register R3.  (The record number of an entry that violates
49109     ** a UNIQUE constraint.)
49110     */
49111     pIn3->u.i = v;
49112     assert( pIn3->flags&MEM_Int );
49113   }
49114   break;
49115 }
49116
49117 /* Opcode: NotExists P1 P2 P3 * *
49118 **
49119 ** Use the content of register P3 as a integer key.  If a record 
49120 ** with that key does not exist in table of P1, then jump to P2. 
49121 ** If the record does exist, then fall thru.  The cursor is left 
49122 ** pointing to the record if it exists.
49123 **
49124 ** The difference between this operation and NotFound is that this
49125 ** operation assumes the key is an integer and that P1 is a table whereas
49126 ** NotFound assumes key is a blob constructed from MakeRecord and
49127 ** P1 is an index.
49128 **
49129 ** See also: Found, NotFound, IsUnique
49130 */
49131 case OP_NotExists: {        /* jump, in3 */
49132   int i = pOp->p1;
49133   Cursor *pC;
49134   BtCursor *pCrsr;
49135   assert( i>=0 && i<p->nCursor );
49136   assert( p->apCsr[i]!=0 );
49137   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49138     int res;
49139     u64 iKey;
49140     assert( pIn3->flags & MEM_Int );
49141     assert( p->apCsr[i]->isTable );
49142     iKey = intToKey(pIn3->u.i);
49143     rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
49144     pC->lastRowid = pIn3->u.i;
49145     pC->rowidIsValid = res==0;
49146     pC->nullRow = 0;
49147     pC->cacheStatus = CACHE_STALE;
49148     /* res might be uninitialized if rc!=SQLITE_OK.  But if rc!=SQLITE_OK
49149     ** processing is about to abort so we really do not care whether or not
49150     ** the following jump is taken.  (In other words, do not stress over
49151     ** the error that valgrind sometimes shows on the next statement when
49152     ** running ioerr.test and similar failure-recovery test scripts.) */
49153     if( res!=0 ){
49154       pc = pOp->p2 - 1;
49155       assert( pC->rowidIsValid==0 );
49156     }
49157   }else if( !pC->pseudoTable ){
49158     /* This happens when an attempt to open a read cursor on the 
49159     ** sqlite_master table returns SQLITE_EMPTY.
49160     */
49161     assert( pC->isTable );
49162     pc = pOp->p2 - 1;
49163     assert( pC->rowidIsValid==0 );
49164   }
49165   break;
49166 }
49167
49168 /* Opcode: Sequence P1 P2 * * *
49169 **
49170 ** Find the next available sequence number for cursor P1.
49171 ** Write the sequence number into register P2.
49172 ** The sequence number on the cursor is incremented after this
49173 ** instruction.  
49174 */
49175 case OP_Sequence: {           /* out2-prerelease */
49176   int i = pOp->p1;
49177   assert( i>=0 && i<p->nCursor );
49178   assert( p->apCsr[i]!=0 );
49179   pOut->u.i = p->apCsr[i]->seqCount++;
49180   MemSetTypeFlag(pOut, MEM_Int);
49181   break;
49182 }
49183
49184
49185 /* Opcode: NewRowid P1 P2 P3 * *
49186 **
49187 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
49188 ** The record number is not previously used as a key in the database
49189 ** table that cursor P1 points to.  The new record number is written
49190 ** written to register P2.
49191 **
49192 ** If P3>0 then P3 is a register that holds the largest previously
49193 ** generated record number.  No new record numbers are allowed to be less
49194 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
49195 ** error is generated.  The P3 register is updated with the generated
49196 ** record number.  This P3 mechanism is used to help implement the
49197 ** AUTOINCREMENT feature.
49198 */
49199 case OP_NewRowid: {           /* out2-prerelease */
49200   int i = pOp->p1;
49201   i64 v = 0;
49202   Cursor *pC;
49203   assert( i>=0 && i<p->nCursor );
49204   assert( p->apCsr[i]!=0 );
49205   if( (pC = p->apCsr[i])->pCursor==0 ){
49206     /* The zero initialization above is all that is needed */
49207   }else{
49208     /* The next rowid or record number (different terms for the same
49209     ** thing) is obtained in a two-step algorithm.
49210     **
49211     ** First we attempt to find the largest existing rowid and add one
49212     ** to that.  But if the largest existing rowid is already the maximum
49213     ** positive integer, we have to fall through to the second
49214     ** probabilistic algorithm
49215     **
49216     ** The second algorithm is to select a rowid at random and see if
49217     ** it already exists in the table.  If it does not exist, we have
49218     ** succeeded.  If the random rowid does exist, we select a new one
49219     ** and try again, up to 1000 times.
49220     **
49221     ** For a table with less than 2 billion entries, the probability
49222     ** of not finding a unused rowid is about 1.0e-300.  This is a 
49223     ** non-zero probability, but it is still vanishingly small and should
49224     ** never cause a problem.  You are much, much more likely to have a
49225     ** hardware failure than for this algorithm to fail.
49226     **
49227     ** The analysis in the previous paragraph assumes that you have a good
49228     ** source of random numbers.  Is a library function like lrand48()
49229     ** good enough?  Maybe. Maybe not. It's hard to know whether there
49230     ** might be subtle bugs is some implementations of lrand48() that
49231     ** could cause problems. To avoid uncertainty, SQLite uses its own 
49232     ** random number generator based on the RC4 algorithm.
49233     **
49234     ** To promote locality of reference for repetitive inserts, the
49235     ** first few attempts at choosing a random rowid pick values just a little
49236     ** larger than the previous rowid.  This has been shown experimentally
49237     ** to double the speed of the COPY operation.
49238     */
49239     int res, rx=SQLITE_OK, cnt;
49240     i64 x;
49241     cnt = 0;
49242     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
49243           BTREE_INTKEY ){
49244       rc = SQLITE_CORRUPT_BKPT;
49245       goto abort_due_to_error;
49246     }
49247     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
49248     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
49249
49250 #ifdef SQLITE_32BIT_ROWID
49251 #   define MAX_ROWID 0x7fffffff
49252 #else
49253     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
49254     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
49255     ** to provide the constant while making all compilers happy.
49256     */
49257 #   define MAX_ROWID  ( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
49258 #endif
49259
49260     if( !pC->useRandomRowid ){
49261       if( pC->nextRowidValid ){
49262         v = pC->nextRowid;
49263       }else{
49264         rc = sqlite3BtreeLast(pC->pCursor, &res);
49265         if( rc!=SQLITE_OK ){
49266           goto abort_due_to_error;
49267         }
49268         if( res ){
49269           v = 1;
49270         }else{
49271           sqlite3BtreeKeySize(pC->pCursor, &v);
49272           v = keyToInt(v);
49273           if( v==MAX_ROWID ){
49274             pC->useRandomRowid = 1;
49275           }else{
49276             v++;
49277           }
49278         }
49279       }
49280
49281 #ifndef SQLITE_OMIT_AUTOINCREMENT
49282       if( pOp->p3 ){
49283         Mem *pMem;
49284         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
49285         pMem = &p->aMem[pOp->p3];
49286         REGISTER_TRACE(pOp->p3, pMem);
49287         sqlite3VdbeMemIntegerify(pMem);
49288         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
49289         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
49290           rc = SQLITE_FULL;
49291           goto abort_due_to_error;
49292         }
49293         if( v<pMem->u.i+1 ){
49294           v = pMem->u.i + 1;
49295         }
49296         pMem->u.i = v;
49297       }
49298 #endif
49299
49300       if( v<MAX_ROWID ){
49301         pC->nextRowidValid = 1;
49302         pC->nextRowid = v+1;
49303       }else{
49304         pC->nextRowidValid = 0;
49305       }
49306     }
49307     if( pC->useRandomRowid ){
49308       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
49309       v = db->priorNewRowid;
49310       cnt = 0;
49311       do{
49312         if( cnt==0 && (v&0xffffff)==v ){
49313           v++;
49314         }else{
49315           sqlite3_randomness(sizeof(v), &v);
49316           if( cnt<5 ) v &= 0xffffff;
49317         }
49318         if( v==0 ) continue;
49319         x = intToKey(v);
49320         rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
49321         cnt++;
49322       }while( cnt<100 && rx==SQLITE_OK && res==0 );
49323       db->priorNewRowid = v;
49324       if( rx==SQLITE_OK && res==0 ){
49325         rc = SQLITE_FULL;
49326         goto abort_due_to_error;
49327       }
49328     }
49329     pC->rowidIsValid = 0;
49330     pC->deferredMoveto = 0;
49331     pC->cacheStatus = CACHE_STALE;
49332   }
49333   MemSetTypeFlag(pOut, MEM_Int);
49334   pOut->u.i = v;
49335   break;
49336 }
49337
49338 /* Opcode: Insert P1 P2 P3 P4 P5
49339 **
49340 ** Write an entry into the table of cursor P1.  A new entry is
49341 ** created if it doesn't already exist or the data for an existing
49342 ** entry is overwritten.  The data is the value stored register
49343 ** number P2. The key is stored in register P3. The key must
49344 ** be an integer.
49345 **
49346 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
49347 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
49348 ** then rowid is stored for subsequent return by the
49349 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
49350 **
49351 ** Parameter P4 may point to a string containing the table-name, or
49352 ** may be NULL. If it is not NULL, then the update-hook 
49353 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
49354 **
49355 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
49356 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
49357 ** and register P2 becomes ephemeral.  If the cursor is changed, the
49358 ** value of register P2 will then change.  Make sure this does not
49359 ** cause any problems.)
49360 **
49361 ** This instruction only works on tables.  The equivalent instruction
49362 ** for indices is OP_IdxInsert.
49363 */
49364 case OP_Insert: {
49365   Mem *pData = &p->aMem[pOp->p2];
49366   Mem *pKey = &p->aMem[pOp->p3];
49367
49368   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
49369   int i = pOp->p1;
49370   Cursor *pC;
49371   assert( i>=0 && i<p->nCursor );
49372   pC = p->apCsr[i];
49373   assert( pC!=0 );
49374   assert( pC->pCursor!=0 || pC->pseudoTable );
49375   assert( pKey->flags & MEM_Int );
49376   assert( pC->isTable );
49377   REGISTER_TRACE(pOp->p2, pData);
49378   REGISTER_TRACE(pOp->p3, pKey);
49379
49380   iKey = intToKey(pKey->u.i);
49381   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
49382   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
49383   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
49384     pC->nextRowidValid = 0;
49385   }
49386   if( pData->flags & MEM_Null ){
49387     pData->z = 0;
49388     pData->n = 0;
49389   }else{
49390     assert( pData->flags & (MEM_Blob|MEM_Str) );
49391   }
49392   if( pC->pseudoTable ){
49393     if( !pC->ephemPseudoTable ){
49394       sqlite3DbFree(db, pC->pData);
49395     }
49396     pC->iKey = iKey;
49397     pC->nData = pData->n;
49398     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
49399       pC->pData = pData->z;
49400       if( !pC->ephemPseudoTable ){
49401         pData->flags &= ~MEM_Dyn;
49402         pData->flags |= MEM_Ephem;
49403         pData->zMalloc = 0;
49404       }
49405     }else{
49406       pC->pData = sqlite3Malloc( pC->nData+2 );
49407       if( !pC->pData ) goto no_mem;
49408       memcpy(pC->pData, pData->z, pC->nData);
49409       pC->pData[pC->nData] = 0;
49410       pC->pData[pC->nData+1] = 0;
49411     }
49412     pC->nullRow = 0;
49413   }else{
49414     int nZero;
49415     if( pData->flags & MEM_Zero ){
49416       nZero = pData->u.i;
49417     }else{
49418       nZero = 0;
49419     }
49420     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
49421                             pData->z, pData->n, nZero,
49422                             pOp->p5 & OPFLAG_APPEND);
49423   }
49424   
49425   pC->rowidIsValid = 0;
49426   pC->deferredMoveto = 0;
49427   pC->cacheStatus = CACHE_STALE;
49428
49429   /* Invoke the update-hook if required. */
49430   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49431     const char *zDb = db->aDb[pC->iDb].zName;
49432     const char *zTbl = pOp->p4.z;
49433     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
49434     assert( pC->isTable );
49435     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
49436     assert( pC->iDb>=0 );
49437   }
49438   break;
49439 }
49440
49441 /* Opcode: Delete P1 P2 * P4 *
49442 **
49443 ** Delete the record at which the P1 cursor is currently pointing.
49444 **
49445 ** The cursor will be left pointing at either the next or the previous
49446 ** record in the table. If it is left pointing at the next record, then
49447 ** the next Next instruction will be a no-op.  Hence it is OK to delete
49448 ** a record from within an Next loop.
49449 **
49450 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
49451 ** incremented (otherwise not).
49452 **
49453 ** P1 must not be pseudo-table.  It has to be a real table with
49454 ** multiple rows.
49455 **
49456 ** If P4 is not NULL, then it is the name of the table that P1 is
49457 ** pointing to.  The update hook will be invoked, if it exists.
49458 ** If P4 is not NULL then the P1 cursor must have been positioned
49459 ** using OP_NotFound prior to invoking this opcode.
49460 */
49461 case OP_Delete: {
49462   int i = pOp->p1;
49463   i64 iKey;
49464   Cursor *pC;
49465
49466   assert( i>=0 && i<p->nCursor );
49467   pC = p->apCsr[i];
49468   assert( pC!=0 );
49469   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
49470
49471   /* If the update-hook will be invoked, set iKey to the rowid of the
49472   ** row being deleted.
49473   */
49474   if( db->xUpdateCallback && pOp->p4.z ){
49475     assert( pC->isTable );
49476     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
49477     iKey = pC->lastRowid;
49478   }
49479
49480   rc = sqlite3VdbeCursorMoveto(pC);
49481   if( rc ) goto abort_due_to_error;
49482   rc = sqlite3BtreeDelete(pC->pCursor);
49483   pC->nextRowidValid = 0;
49484   pC->cacheStatus = CACHE_STALE;
49485
49486   /* Invoke the update-hook if required. */
49487   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
49488     const char *zDb = db->aDb[pC->iDb].zName;
49489     const char *zTbl = pOp->p4.z;
49490     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
49491     assert( pC->iDb>=0 );
49492   }
49493   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
49494   break;
49495 }
49496
49497 /* Opcode: ResetCount P1 * *
49498 **
49499 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
49500 ** then the value of the change counter is copied to the database handle
49501 ** change counter (returned by subsequent calls to sqlite3_changes())
49502 ** before it is reset. This is used by trigger programs.
49503 */
49504 case OP_ResetCount: {
49505   if( pOp->p1 ){
49506     sqlite3VdbeSetChanges(db, p->nChange);
49507   }
49508   p->nChange = 0;
49509   break;
49510 }
49511
49512 /* Opcode: RowData P1 P2 * * *
49513 **
49514 ** Write into register P2 the complete row data for cursor P1.
49515 ** There is no interpretation of the data.  
49516 ** It is just copied onto the P2 register exactly as 
49517 ** it is found in the database file.
49518 **
49519 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49520 ** of a real table, not a pseudo-table.
49521 */
49522 /* Opcode: RowKey P1 P2 * * *
49523 **
49524 ** Write into register P2 the complete row key for cursor P1.
49525 ** There is no interpretation of the data.  
49526 ** The key is copied onto the P3 register exactly as 
49527 ** it is found in the database file.
49528 **
49529 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
49530 ** of a real table, not a pseudo-table.
49531 */
49532 case OP_RowKey:
49533 case OP_RowData: {
49534   int i = pOp->p1;
49535   Cursor *pC;
49536   BtCursor *pCrsr;
49537   u32 n;
49538
49539   pOut = &p->aMem[pOp->p2];
49540
49541   /* Note that RowKey and RowData are really exactly the same instruction */
49542   assert( i>=0 && i<p->nCursor );
49543   pC = p->apCsr[i];
49544   assert( pC->isTable || pOp->opcode==OP_RowKey );
49545   assert( pC->isIndex || pOp->opcode==OP_RowData );
49546   assert( pC!=0 );
49547   assert( pC->nullRow==0 );
49548   assert( pC->pseudoTable==0 );
49549   assert( pC->pCursor!=0 );
49550   pCrsr = pC->pCursor;
49551   rc = sqlite3VdbeCursorMoveto(pC);
49552   if( rc ) goto abort_due_to_error;
49553   if( pC->isIndex ){
49554     i64 n64;
49555     assert( !pC->isTable );
49556     sqlite3BtreeKeySize(pCrsr, &n64);
49557     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
49558       goto too_big;
49559     }
49560     n = n64;
49561   }else{
49562     sqlite3BtreeDataSize(pCrsr, &n);
49563     if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
49564       goto too_big;
49565     }
49566   }
49567   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
49568     goto no_mem;
49569   }
49570   pOut->n = n;
49571   MemSetTypeFlag(pOut, MEM_Blob);
49572   if( pC->isIndex ){
49573     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
49574   }else{
49575     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
49576   }
49577   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
49578   UPDATE_MAX_BLOBSIZE(pOut);
49579   break;
49580 }
49581
49582 /* Opcode: Rowid P1 P2 * * *
49583 **
49584 ** Store in register P2 an integer which is the key of the table entry that
49585 ** P1 is currently point to.
49586 */
49587 case OP_Rowid: {                 /* out2-prerelease */
49588   int i = pOp->p1;
49589   Cursor *pC;
49590   i64 v;
49591
49592   assert( i>=0 && i<p->nCursor );
49593   pC = p->apCsr[i];
49594   assert( pC!=0 );
49595   rc = sqlite3VdbeCursorMoveto(pC);
49596   if( rc ) goto abort_due_to_error;
49597   if( pC->rowidIsValid ){
49598     v = pC->lastRowid;
49599   }else if( pC->pseudoTable ){
49600     v = keyToInt(pC->iKey);
49601   }else if( pC->nullRow ){
49602     /* Leave the rowid set to a NULL */
49603     break;
49604   }else{
49605     assert( pC->pCursor!=0 );
49606     sqlite3BtreeKeySize(pC->pCursor, &v);
49607     v = keyToInt(v);
49608   }
49609   pOut->u.i = v;
49610   MemSetTypeFlag(pOut, MEM_Int);
49611   break;
49612 }
49613
49614 /* Opcode: NullRow P1 * * * *
49615 **
49616 ** Move the cursor P1 to a null row.  Any OP_Column operations
49617 ** that occur while the cursor is on the null row will always
49618 ** write a NULL.
49619 */
49620 case OP_NullRow: {
49621   int i = pOp->p1;
49622   Cursor *pC;
49623
49624   assert( i>=0 && i<p->nCursor );
49625   pC = p->apCsr[i];
49626   assert( pC!=0 );
49627   pC->nullRow = 1;
49628   pC->rowidIsValid = 0;
49629   if( pC->pCursor ){
49630     sqlite3BtreeClearCursor(pC->pCursor);
49631   }
49632   break;
49633 }
49634
49635 /* Opcode: Last P1 P2 * * *
49636 **
49637 ** The next use of the Rowid or Column or Next instruction for P1 
49638 ** will refer to the last entry in the database table or index.
49639 ** If the table or index is empty and P2>0, then jump immediately to P2.
49640 ** If P2 is 0 or if the table or index is not empty, fall through
49641 ** to the following instruction.
49642 */
49643 case OP_Last: {        /* jump */
49644   int i = pOp->p1;
49645   Cursor *pC;
49646   BtCursor *pCrsr;
49647   int res;
49648
49649   assert( i>=0 && i<p->nCursor );
49650   pC = p->apCsr[i];
49651   assert( pC!=0 );
49652   pCrsr = pC->pCursor;
49653   assert( pCrsr!=0 );
49654   rc = sqlite3BtreeLast(pCrsr, &res);
49655   pC->nullRow = res;
49656   pC->deferredMoveto = 0;
49657   pC->cacheStatus = CACHE_STALE;
49658   if( res && pOp->p2>0 ){
49659     pc = pOp->p2 - 1;
49660   }
49661   break;
49662 }
49663
49664
49665 /* Opcode: Sort P1 P2 * * *
49666 **
49667 ** This opcode does exactly the same thing as OP_Rewind except that
49668 ** it increments an undocumented global variable used for testing.
49669 **
49670 ** Sorting is accomplished by writing records into a sorting index,
49671 ** then rewinding that index and playing it back from beginning to
49672 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
49673 ** rewinding so that the global variable will be incremented and
49674 ** regression tests can determine whether or not the optimizer is
49675 ** correctly optimizing out sorts.
49676 */
49677 case OP_Sort: {        /* jump */
49678 #ifdef SQLITE_TEST
49679   sqlite3_sort_count++;
49680   sqlite3_search_count--;
49681 #endif
49682   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
49683   /* Fall through into OP_Rewind */
49684 }
49685 /* Opcode: Rewind P1 P2 * * *
49686 **
49687 ** The next use of the Rowid or Column or Next instruction for P1 
49688 ** will refer to the first entry in the database table or index.
49689 ** If the table or index is empty and P2>0, then jump immediately to P2.
49690 ** If P2 is 0 or if the table or index is not empty, fall through
49691 ** to the following instruction.
49692 */
49693 case OP_Rewind: {        /* jump */
49694   int i = pOp->p1;
49695   Cursor *pC;
49696   BtCursor *pCrsr;
49697   int res;
49698
49699   assert( i>=0 && i<p->nCursor );
49700   pC = p->apCsr[i];
49701   assert( pC!=0 );
49702   if( (pCrsr = pC->pCursor)!=0 ){
49703     rc = sqlite3BtreeFirst(pCrsr, &res);
49704     pC->atFirst = res==0;
49705     pC->deferredMoveto = 0;
49706     pC->cacheStatus = CACHE_STALE;
49707   }else{
49708     res = 1;
49709   }
49710   pC->nullRow = res;
49711   assert( pOp->p2>0 && pOp->p2<p->nOp );
49712   if( res ){
49713     pc = pOp->p2 - 1;
49714   }
49715   break;
49716 }
49717
49718 /* Opcode: Next P1 P2 * * *
49719 **
49720 ** Advance cursor P1 so that it points to the next key/data pair in its
49721 ** table or index.  If there are no more key/value pairs then fall through
49722 ** to the following instruction.  But if the cursor advance was successful,
49723 ** jump immediately to P2.
49724 **
49725 ** The P1 cursor must be for a real table, not a pseudo-table.
49726 **
49727 ** See also: Prev
49728 */
49729 /* Opcode: Prev P1 P2 * * *
49730 **
49731 ** Back up cursor P1 so that it points to the previous key/data pair in its
49732 ** table or index.  If there is no previous key/value pairs then fall through
49733 ** to the following instruction.  But if the cursor backup was successful,
49734 ** jump immediately to P2.
49735 **
49736 ** The P1 cursor must be for a real table, not a pseudo-table.
49737 */
49738 case OP_Prev:          /* jump */
49739 case OP_Next: {        /* jump */
49740   Cursor *pC;
49741   BtCursor *pCrsr;
49742   int res;
49743
49744   CHECK_FOR_INTERRUPT;
49745   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
49746   pC = p->apCsr[pOp->p1];
49747   if( pC==0 ){
49748     break;  /* See ticket #2273 */
49749   }
49750   pCrsr = pC->pCursor;
49751   assert( pCrsr );
49752   res = 1;
49753   assert( pC->deferredMoveto==0 );
49754   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
49755                               sqlite3BtreePrevious(pCrsr, &res);
49756   pC->nullRow = res;
49757   pC->cacheStatus = CACHE_STALE;
49758   if( res==0 ){
49759     pc = pOp->p2 - 1;
49760     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
49761 #ifdef SQLITE_TEST
49762     sqlite3_search_count++;
49763 #endif
49764   }
49765   pC->rowidIsValid = 0;
49766   break;
49767 }
49768
49769 /* Opcode: IdxInsert P1 P2 P3 * *
49770 **
49771 ** Register P2 holds a SQL index key made using the
49772 ** MakeIdxRec instructions.  This opcode writes that key
49773 ** into the index P1.  Data for the entry is nil.
49774 **
49775 ** P3 is a flag that provides a hint to the b-tree layer that this
49776 ** insert is likely to be an append.
49777 **
49778 ** This instruction only works for indices.  The equivalent instruction
49779 ** for tables is OP_Insert.
49780 */
49781 case OP_IdxInsert: {        /* in2 */
49782   int i = pOp->p1;
49783   Cursor *pC;
49784   BtCursor *pCrsr;
49785   assert( i>=0 && i<p->nCursor );
49786   assert( p->apCsr[i]!=0 );
49787   assert( pIn2->flags & MEM_Blob );
49788   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49789     assert( pC->isTable==0 );
49790     rc = ExpandBlob(pIn2);
49791     if( rc==SQLITE_OK ){
49792       int nKey = pIn2->n;
49793       const char *zKey = pIn2->z;
49794       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
49795       assert( pC->deferredMoveto==0 );
49796       pC->cacheStatus = CACHE_STALE;
49797     }
49798   }
49799   break;
49800 }
49801
49802 /* Opcode: IdxDelete P1 P2 P3 * *
49803 **
49804 ** The content of P3 registers starting at register P2 form
49805 ** an unpacked index key. This opcode removes that entry from the 
49806 ** index opened by cursor P1.
49807 */
49808 case OP_IdxDelete: {
49809   int i = pOp->p1;
49810   Cursor *pC;
49811   BtCursor *pCrsr;
49812   assert( pOp->p3>0 );
49813   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
49814   assert( i>=0 && i<p->nCursor );
49815   assert( p->apCsr[i]!=0 );
49816   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49817     int res;
49818     UnpackedRecord r;
49819     r.pKeyInfo = pC->pKeyInfo;
49820     r.nField = pOp->p3;
49821     r.flags = 0;
49822     r.aMem = &p->aMem[pOp->p2];
49823     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
49824     if( rc==SQLITE_OK && res==0 ){
49825       rc = sqlite3BtreeDelete(pCrsr);
49826     }
49827     assert( pC->deferredMoveto==0 );
49828     pC->cacheStatus = CACHE_STALE;
49829   }
49830   break;
49831 }
49832
49833 /* Opcode: IdxRowid P1 P2 * * *
49834 **
49835 ** Write into register P2 an integer which is the last entry in the record at
49836 ** the end of the index key pointed to by cursor P1.  This integer should be
49837 ** the rowid of the table entry to which this index entry points.
49838 **
49839 ** See also: Rowid, MakeIdxRec.
49840 */
49841 case OP_IdxRowid: {              /* out2-prerelease */
49842   int i = pOp->p1;
49843   BtCursor *pCrsr;
49844   Cursor *pC;
49845
49846   assert( i>=0 && i<p->nCursor );
49847   assert( p->apCsr[i]!=0 );
49848   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
49849     i64 rowid;
49850
49851     assert( pC->deferredMoveto==0 );
49852     assert( pC->isTable==0 );
49853     if( !pC->nullRow ){
49854       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
49855       if( rc!=SQLITE_OK ){
49856         goto abort_due_to_error;
49857       }
49858       MemSetTypeFlag(pOut, MEM_Int);
49859       pOut->u.i = rowid;
49860     }
49861   }
49862   break;
49863 }
49864
49865 /* Opcode: IdxGE P1 P2 P3 P4 P5
49866 **
49867 ** The P4 register values beginning with P3 form an unpacked index 
49868 ** key that omits the ROWID.  Compare this key value against the index 
49869 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
49870 **
49871 ** If the P1 index entry is greater than or equal to the key value
49872 ** then jump to P2.  Otherwise fall through to the next instruction.
49873 **
49874 ** If P5 is non-zero then the key value is increased by an epsilon 
49875 ** prior to the comparison.  This make the opcode work like IdxGT except
49876 ** that if the key from register P3 is a prefix of the key in the cursor,
49877 ** the result is false whereas it would be true with IdxGT.
49878 */
49879 /* Opcode: IdxLT P1 P2 P3 * P5
49880 **
49881 ** The P4 register values beginning with P3 form an unpacked index 
49882 ** key that omits the ROWID.  Compare this key value against the index 
49883 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
49884 **
49885 ** If the P1 index entry is less than the key value then jump to P2.
49886 ** Otherwise fall through to the next instruction.
49887 **
49888 ** If P5 is non-zero then the key value is increased by an epsilon prior 
49889 ** to the comparison.  This makes the opcode work like IdxLE.
49890 */
49891 case OP_IdxLT:          /* jump, in3 */
49892 case OP_IdxGE: {        /* jump, in3 */
49893   int i= pOp->p1;
49894   Cursor *pC;
49895
49896   assert( i>=0 && i<p->nCursor );
49897   assert( p->apCsr[i]!=0 );
49898   if( (pC = p->apCsr[i])->pCursor!=0 ){
49899     int res;
49900     UnpackedRecord r;
49901     assert( pC->deferredMoveto==0 );
49902     assert( pOp->p5==0 || pOp->p5==1 );
49903     assert( pOp->p4type==P4_INT32 );
49904     r.pKeyInfo = pC->pKeyInfo;
49905     r.nField = pOp->p4.i;
49906     if( pOp->p5 ){
49907       r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
49908     }else{
49909       r.flags = UNPACKED_IGNORE_ROWID;
49910     }
49911     r.aMem = &p->aMem[pOp->p3];
49912     rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
49913     if( pOp->opcode==OP_IdxLT ){
49914       res = -res;
49915     }else{
49916       assert( pOp->opcode==OP_IdxGE );
49917       res++;
49918     }
49919     if( res>0 ){
49920       pc = pOp->p2 - 1 ;
49921     }
49922   }
49923   break;
49924 }
49925
49926 /* Opcode: Destroy P1 P2 P3 * *
49927 **
49928 ** Delete an entire database table or index whose root page in the database
49929 ** file is given by P1.
49930 **
49931 ** The table being destroyed is in the main database file if P3==0.  If
49932 ** P3==1 then the table to be clear is in the auxiliary database file
49933 ** that is used to store tables create using CREATE TEMPORARY TABLE.
49934 **
49935 ** If AUTOVACUUM is enabled then it is possible that another root page
49936 ** might be moved into the newly deleted root page in order to keep all
49937 ** root pages contiguous at the beginning of the database.  The former
49938 ** value of the root page that moved - its value before the move occurred -
49939 ** is stored in register P2.  If no page 
49940 ** movement was required (because the table being dropped was already 
49941 ** the last one in the database) then a zero is stored in register P2.
49942 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
49943 **
49944 ** See also: Clear
49945 */
49946 case OP_Destroy: {     /* out2-prerelease */
49947   int iMoved;
49948   int iCnt;
49949 #ifndef SQLITE_OMIT_VIRTUALTABLE
49950   Vdbe *pVdbe;
49951   iCnt = 0;
49952   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
49953     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
49954       iCnt++;
49955     }
49956   }
49957 #else
49958   iCnt = db->activeVdbeCnt;
49959 #endif
49960   if( iCnt>1 ){
49961     rc = SQLITE_LOCKED;
49962     p->errorAction = OE_Abort;
49963   }else{
49964     int iDb = pOp->p3;
49965     assert( iCnt==1 );
49966     assert( (p->btreeMask & (1<<iDb))!=0 );
49967     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
49968     MemSetTypeFlag(pOut, MEM_Int);
49969     pOut->u.i = iMoved;
49970 #ifndef SQLITE_OMIT_AUTOVACUUM
49971     if( rc==SQLITE_OK && iMoved!=0 ){
49972       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
49973     }
49974 #endif
49975   }
49976   break;
49977 }
49978
49979 /* Opcode: Clear P1 P2 *
49980 **
49981 ** Delete all contents of the database table or index whose root page
49982 ** in the database file is given by P1.  But, unlike Destroy, do not
49983 ** remove the table or index from the database file.
49984 **
49985 ** The table being clear is in the main database file if P2==0.  If
49986 ** P2==1 then the table to be clear is in the auxiliary database file
49987 ** that is used to store tables create using CREATE TEMPORARY TABLE.
49988 **
49989 ** See also: Destroy
49990 */
49991 case OP_Clear: {
49992   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
49993   rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
49994   break;
49995 }
49996
49997 /* Opcode: CreateTable P1 P2 * * *
49998 **
49999 ** Allocate a new table in the main database file if P1==0 or in the
50000 ** auxiliary database file if P1==1 or in an attached database if
50001 ** P1>1.  Write the root page number of the new table into
50002 ** register P2
50003 **
50004 ** The difference between a table and an index is this:  A table must
50005 ** have a 4-byte integer key and can have arbitrary data.  An index
50006 ** has an arbitrary key but no data.
50007 **
50008 ** See also: CreateIndex
50009 */
50010 /* Opcode: CreateIndex P1 P2 * * *
50011 **
50012 ** Allocate a new index in the main database file if P1==0 or in the
50013 ** auxiliary database file if P1==1 or in an attached database if
50014 ** P1>1.  Write the root page number of the new table into
50015 ** register P2.
50016 **
50017 ** See documentation on OP_CreateTable for additional information.
50018 */
50019 case OP_CreateIndex:            /* out2-prerelease */
50020 case OP_CreateTable: {          /* out2-prerelease */
50021   int pgno;
50022   int flags;
50023   Db *pDb;
50024   assert( pOp->p1>=0 && pOp->p1<db->nDb );
50025   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
50026   pDb = &db->aDb[pOp->p1];
50027   assert( pDb->pBt!=0 );
50028   if( pOp->opcode==OP_CreateTable ){
50029     /* flags = BTREE_INTKEY; */
50030     flags = BTREE_LEAFDATA|BTREE_INTKEY;
50031   }else{
50032     flags = BTREE_ZERODATA;
50033   }
50034   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
50035   if( rc==SQLITE_OK ){
50036     pOut->u.i = pgno;
50037     MemSetTypeFlag(pOut, MEM_Int);
50038   }
50039   break;
50040 }
50041
50042 /* Opcode: ParseSchema P1 P2 * P4 *
50043 **
50044 ** Read and parse all entries from the SQLITE_MASTER table of database P1
50045 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
50046 ** the parsing if P2 is true.  If P2 is false, then this routine is a
50047 ** no-op if the schema is not currently loaded.  In other words, if P2
50048 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
50049 ** schema is already loaded into the symbol table.
50050 **
50051 ** This opcode invokes the parser to create a new virtual machine,
50052 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
50053 */
50054 case OP_ParseSchema: {
50055   char *zSql;
50056   int iDb = pOp->p1;
50057   const char *zMaster;
50058   InitData initData;
50059
50060   assert( iDb>=0 && iDb<db->nDb );
50061   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
50062     break;
50063   }
50064   zMaster = SCHEMA_TABLE(iDb);
50065   initData.db = db;
50066   initData.iDb = pOp->p1;
50067   initData.pzErrMsg = &p->zErrMsg;
50068   zSql = sqlite3MPrintf(db,
50069      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
50070      db->aDb[iDb].zName, zMaster, pOp->p4.z);
50071   if( zSql==0 ) goto no_mem;
50072   (void)sqlite3SafetyOff(db);
50073   assert( db->init.busy==0 );
50074   db->init.busy = 1;
50075   initData.rc = SQLITE_OK;
50076   assert( !db->mallocFailed );
50077   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
50078   if( rc==SQLITE_OK ) rc = initData.rc;
50079   sqlite3DbFree(db, zSql);
50080   db->init.busy = 0;
50081   (void)sqlite3SafetyOn(db);
50082   if( rc==SQLITE_NOMEM ){
50083     goto no_mem;
50084   }
50085   break;  
50086 }
50087
50088 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
50089 /* Opcode: LoadAnalysis P1 * * * *
50090 **
50091 ** Read the sqlite_stat1 table for database P1 and load the content
50092 ** of that table into the internal index hash table.  This will cause
50093 ** the analysis to be used when preparing all subsequent queries.
50094 */
50095 case OP_LoadAnalysis: {
50096   int iDb = pOp->p1;
50097   assert( iDb>=0 && iDb<db->nDb );
50098   rc = sqlite3AnalysisLoad(db, iDb);
50099   break;  
50100 }
50101 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
50102
50103 /* Opcode: DropTable P1 * * P4 *
50104 **
50105 ** Remove the internal (in-memory) data structures that describe
50106 ** the table named P4 in database P1.  This is called after a table
50107 ** is dropped in order to keep the internal representation of the
50108 ** schema consistent with what is on disk.
50109 */
50110 case OP_DropTable: {
50111   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
50112   break;
50113 }
50114
50115 /* Opcode: DropIndex P1 * * P4 *
50116 **
50117 ** Remove the internal (in-memory) data structures that describe
50118 ** the index named P4 in database P1.  This is called after an index
50119 ** is dropped in order to keep the internal representation of the
50120 ** schema consistent with what is on disk.
50121 */
50122 case OP_DropIndex: {
50123   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
50124   break;
50125 }
50126
50127 /* Opcode: DropTrigger P1 * * P4 *
50128 **
50129 ** Remove the internal (in-memory) data structures that describe
50130 ** the trigger named P4 in database P1.  This is called after a trigger
50131 ** is dropped in order to keep the internal representation of the
50132 ** schema consistent with what is on disk.
50133 */
50134 case OP_DropTrigger: {
50135   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
50136   break;
50137 }
50138
50139
50140 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
50141 /* Opcode: IntegrityCk P1 P2 P3 * P5
50142 **
50143 ** Do an analysis of the currently open database.  Store in
50144 ** register P1 the text of an error message describing any problems.
50145 ** If no problems are found, store a NULL in register P1.
50146 **
50147 ** The register P3 contains the maximum number of allowed errors.
50148 ** At most reg(P3) errors will be reported.
50149 ** In other words, the analysis stops as soon as reg(P1) errors are 
50150 ** seen.  Reg(P1) is updated with the number of errors remaining.
50151 **
50152 ** The root page numbers of all tables in the database are integer
50153 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
50154 ** total.
50155 **
50156 ** If P5 is not zero, the check is done on the auxiliary database
50157 ** file, not the main database file.
50158 **
50159 ** This opcode is used to implement the integrity_check pragma.
50160 */
50161 case OP_IntegrityCk: {
50162   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
50163   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
50164   int j;          /* Loop counter */
50165   int nErr;       /* Number of errors reported */
50166   char *z;        /* Text of the error report */
50167   Mem *pnErr;     /* Register keeping track of errors remaining */
50168   
50169   nRoot = pOp->p2;
50170   assert( nRoot>0 );
50171   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
50172   if( aRoot==0 ) goto no_mem;
50173   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50174   pnErr = &p->aMem[pOp->p3];
50175   assert( (pnErr->flags & MEM_Int)!=0 );
50176   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
50177   pIn1 = &p->aMem[pOp->p1];
50178   for(j=0; j<nRoot; j++){
50179     aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]);
50180   }
50181   aRoot[j] = 0;
50182   assert( pOp->p5<db->nDb );
50183   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
50184   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
50185                                  pnErr->u.i, &nErr);
50186   sqlite3DbFree(db, aRoot);
50187   pnErr->u.i -= nErr;
50188   sqlite3VdbeMemSetNull(pIn1);
50189   if( nErr==0 ){
50190     assert( z==0 );
50191   }else if( z==0 ){
50192     goto no_mem;
50193   }else{
50194     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
50195   }
50196   UPDATE_MAX_BLOBSIZE(pIn1);
50197   sqlite3VdbeChangeEncoding(pIn1, encoding);
50198   break;
50199 }
50200 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
50201
50202 /* Opcode: FifoWrite P1 * * * *
50203 **
50204 ** Write the integer from register P1 into the Fifo.
50205 */
50206 case OP_FifoWrite: {        /* in1 */
50207   p->sFifo.db = db;
50208   if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){
50209     goto no_mem;
50210   }
50211   break;
50212 }
50213
50214 /* Opcode: FifoRead P1 P2 * * *
50215 **
50216 ** Attempt to read a single integer from the Fifo.  Store that
50217 ** integer in register P1.
50218 ** 
50219 ** If the Fifo is empty jump to P2.
50220 */
50221 case OP_FifoRead: {         /* jump */
50222   CHECK_FOR_INTERRUPT;
50223   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50224   pOut = &p->aMem[pOp->p1];
50225   MemSetTypeFlag(pOut, MEM_Int);
50226   if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){
50227     pc = pOp->p2 - 1;
50228   }
50229   break;
50230 }
50231
50232 #ifndef SQLITE_OMIT_TRIGGER
50233 /* Opcode: ContextPush * * * 
50234 **
50235 ** Save the current Vdbe context such that it can be restored by a ContextPop
50236 ** opcode. The context stores the last insert row id, the last statement change
50237 ** count, and the current statement change count.
50238 */
50239 case OP_ContextPush: {
50240   int i = p->contextStackTop++;
50241   Context *pContext;
50242
50243   assert( i>=0 );
50244   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
50245   if( i>=p->contextStackDepth ){
50246     p->contextStackDepth = i+1;
50247     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
50248                                           sizeof(Context)*(i+1));
50249     if( p->contextStack==0 ) goto no_mem;
50250   }
50251   pContext = &p->contextStack[i];
50252   pContext->lastRowid = db->lastRowid;
50253   pContext->nChange = p->nChange;
50254   pContext->sFifo = p->sFifo;
50255   sqlite3VdbeFifoInit(&p->sFifo, db);
50256   break;
50257 }
50258
50259 /* Opcode: ContextPop * * * 
50260 **
50261 ** Restore the Vdbe context to the state it was in when contextPush was last
50262 ** executed. The context stores the last insert row id, the last statement
50263 ** change count, and the current statement change count.
50264 */
50265 case OP_ContextPop: {
50266   Context *pContext = &p->contextStack[--p->contextStackTop];
50267   assert( p->contextStackTop>=0 );
50268   db->lastRowid = pContext->lastRowid;
50269   p->nChange = pContext->nChange;
50270   sqlite3VdbeFifoClear(&p->sFifo);
50271   p->sFifo = pContext->sFifo;
50272   break;
50273 }
50274 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
50275
50276 #ifndef SQLITE_OMIT_AUTOINCREMENT
50277 /* Opcode: MemMax P1 P2 * * *
50278 **
50279 ** Set the value of register P1 to the maximum of its current value
50280 ** and the value in register P2.
50281 **
50282 ** This instruction throws an error if the memory cell is not initially
50283 ** an integer.
50284 */
50285 case OP_MemMax: {        /* in1, in2 */
50286   sqlite3VdbeMemIntegerify(pIn1);
50287   sqlite3VdbeMemIntegerify(pIn2);
50288   if( pIn1->u.i<pIn2->u.i){
50289     pIn1->u.i = pIn2->u.i;
50290   }
50291   break;
50292 }
50293 #endif /* SQLITE_OMIT_AUTOINCREMENT */
50294
50295 /* Opcode: IfPos P1 P2 * * *
50296 **
50297 ** If the value of register P1 is 1 or greater, jump to P2.
50298 **
50299 ** It is illegal to use this instruction on a register that does
50300 ** not contain an integer.  An assertion fault will result if you try.
50301 */
50302 case OP_IfPos: {        /* jump, in1 */
50303   assert( pIn1->flags&MEM_Int );
50304   if( pIn1->u.i>0 ){
50305      pc = pOp->p2 - 1;
50306   }
50307   break;
50308 }
50309
50310 /* Opcode: IfNeg P1 P2 * * *
50311 **
50312 ** If the value of register P1 is less than zero, jump to P2. 
50313 **
50314 ** It is illegal to use this instruction on a register that does
50315 ** not contain an integer.  An assertion fault will result if you try.
50316 */
50317 case OP_IfNeg: {        /* jump, in1 */
50318   assert( pIn1->flags&MEM_Int );
50319   if( pIn1->u.i<0 ){
50320      pc = pOp->p2 - 1;
50321   }
50322   break;
50323 }
50324
50325 /* Opcode: IfZero P1 P2 * * *
50326 **
50327 ** If the value of register P1 is exactly 0, jump to P2. 
50328 **
50329 ** It is illegal to use this instruction on a register that does
50330 ** not contain an integer.  An assertion fault will result if you try.
50331 */
50332 case OP_IfZero: {        /* jump, in1 */
50333   assert( pIn1->flags&MEM_Int );
50334   if( pIn1->u.i==0 ){
50335      pc = pOp->p2 - 1;
50336   }
50337   break;
50338 }
50339
50340 /* Opcode: AggStep * P2 P3 P4 P5
50341 **
50342 ** Execute the step function for an aggregate.  The
50343 ** function has P5 arguments.   P4 is a pointer to the FuncDef
50344 ** structure that specifies the function.  Use register
50345 ** P3 as the accumulator.
50346 **
50347 ** The P5 arguments are taken from register P2 and its
50348 ** successors.
50349 */
50350 case OP_AggStep: {
50351   int n = pOp->p5;
50352   int i;
50353   Mem *pMem, *pRec;
50354   sqlite3_context ctx;
50355   sqlite3_value **apVal;
50356
50357   assert( n>=0 );
50358   pRec = &p->aMem[pOp->p2];
50359   apVal = p->apArg;
50360   assert( apVal || n==0 );
50361   for(i=0; i<n; i++, pRec++){
50362     apVal[i] = pRec;
50363     storeTypeInfo(pRec, encoding);
50364   }
50365   ctx.pFunc = pOp->p4.pFunc;
50366   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50367   ctx.pMem = pMem = &p->aMem[pOp->p3];
50368   pMem->n++;
50369   ctx.s.flags = MEM_Null;
50370   ctx.s.z = 0;
50371   ctx.s.zMalloc = 0;
50372   ctx.s.xDel = 0;
50373   ctx.s.db = db;
50374   ctx.isError = 0;
50375   ctx.pColl = 0;
50376   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
50377     assert( pOp>p->aOp );
50378     assert( pOp[-1].p4type==P4_COLLSEQ );
50379     assert( pOp[-1].opcode==OP_CollSeq );
50380     ctx.pColl = pOp[-1].p4.pColl;
50381   }
50382   (ctx.pFunc->xStep)(&ctx, n, apVal);
50383   if( ctx.isError ){
50384     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
50385     rc = ctx.isError;
50386   }
50387   sqlite3VdbeMemRelease(&ctx.s);
50388   break;
50389 }
50390
50391 /* Opcode: AggFinal P1 P2 * P4 *
50392 **
50393 ** Execute the finalizer function for an aggregate.  P1 is
50394 ** the memory location that is the accumulator for the aggregate.
50395 **
50396 ** P2 is the number of arguments that the step function takes and
50397 ** P4 is a pointer to the FuncDef for this function.  The P2
50398 ** argument is not used by this opcode.  It is only there to disambiguate
50399 ** functions that can take varying numbers of arguments.  The
50400 ** P4 argument is only needed for the degenerate case where
50401 ** the step function was not previously called.
50402 */
50403 case OP_AggFinal: {
50404   Mem *pMem;
50405   assert( pOp->p1>0 && pOp->p1<=p->nMem );
50406   pMem = &p->aMem[pOp->p1];
50407   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
50408   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
50409   if( rc==SQLITE_ERROR ){
50410     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
50411   }
50412   sqlite3VdbeChangeEncoding(pMem, encoding);
50413   UPDATE_MAX_BLOBSIZE(pMem);
50414   if( sqlite3VdbeMemTooBig(pMem) ){
50415     goto too_big;
50416   }
50417   break;
50418 }
50419
50420
50421 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
50422 /* Opcode: Vacuum * * * * *
50423 **
50424 ** Vacuum the entire database.  This opcode will cause other virtual
50425 ** machines to be created and run.  It may not be called from within
50426 ** a transaction.
50427 */
50428 case OP_Vacuum: {
50429   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
50430   rc = sqlite3RunVacuum(&p->zErrMsg, db);
50431   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50432   break;
50433 }
50434 #endif
50435
50436 #if !defined(SQLITE_OMIT_AUTOVACUUM)
50437 /* Opcode: IncrVacuum P1 P2 * * *
50438 **
50439 ** Perform a single step of the incremental vacuum procedure on
50440 ** the P1 database. If the vacuum has finished, jump to instruction
50441 ** P2. Otherwise, fall through to the next instruction.
50442 */
50443 case OP_IncrVacuum: {        /* jump */
50444   Btree *pBt;
50445
50446   assert( pOp->p1>=0 && pOp->p1<db->nDb );
50447   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
50448   pBt = db->aDb[pOp->p1].pBt;
50449   rc = sqlite3BtreeIncrVacuum(pBt);
50450   if( rc==SQLITE_DONE ){
50451     pc = pOp->p2 - 1;
50452     rc = SQLITE_OK;
50453   }
50454   break;
50455 }
50456 #endif
50457
50458 /* Opcode: Expire P1 * * * *
50459 **
50460 ** Cause precompiled statements to become expired. An expired statement
50461 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
50462 ** (via sqlite3_step()).
50463 ** 
50464 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
50465 ** then only the currently executing statement is affected. 
50466 */
50467 case OP_Expire: {
50468   if( !pOp->p1 ){
50469     sqlite3ExpirePreparedStatements(db);
50470   }else{
50471     p->expired = 1;
50472   }
50473   break;
50474 }
50475
50476 #ifndef SQLITE_OMIT_SHARED_CACHE
50477 /* Opcode: TableLock P1 P2 P3 P4 *
50478 **
50479 ** Obtain a lock on a particular table. This instruction is only used when
50480 ** the shared-cache feature is enabled. 
50481 **
50482 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
50483 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
50484 ** a write lock if P3==1.
50485 **
50486 ** P2 contains the root-page of the table to lock.
50487 **
50488 ** P4 contains a pointer to the name of the table being locked. This is only
50489 ** used to generate an error message if the lock cannot be obtained.
50490 */
50491 case OP_TableLock: {
50492   int p1 = pOp->p1; 
50493   u8 isWriteLock = pOp->p3;
50494   assert( p1>=0 && p1<db->nDb );
50495   assert( (p->btreeMask & (1<<p1))!=0 );
50496   assert( isWriteLock==0 || isWriteLock==1 );
50497   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
50498   if( rc==SQLITE_LOCKED ){
50499     const char *z = pOp->p4.z;
50500     sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
50501   }
50502   break;
50503 }
50504 #endif /* SQLITE_OMIT_SHARED_CACHE */
50505
50506 #ifndef SQLITE_OMIT_VIRTUALTABLE
50507 /* Opcode: VBegin * * * P4 *
50508 **
50509 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
50510 ** xBegin method for that table.
50511 **
50512 ** Also, whether or not P4 is set, check that this is not being called from
50513 ** within a callback to a virtual table xSync() method. If it is, set the
50514 ** error code to SQLITE_LOCKED.
50515 */
50516 case OP_VBegin: {
50517   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50518   rc = sqlite3VtabBegin(db, pVtab);
50519   if( pVtab ){
50520     sqlite3DbFree(db, p->zErrMsg);
50521     p->zErrMsg = pVtab->zErrMsg;
50522     pVtab->zErrMsg = 0;
50523   }
50524   break;
50525 }
50526 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50527
50528 #ifndef SQLITE_OMIT_VIRTUALTABLE
50529 /* Opcode: VCreate P1 * * P4 *
50530 **
50531 ** P4 is the name of a virtual table in database P1. Call the xCreate method
50532 ** for that table.
50533 */
50534 case OP_VCreate: {
50535   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
50536   break;
50537 }
50538 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50539
50540 #ifndef SQLITE_OMIT_VIRTUALTABLE
50541 /* Opcode: VDestroy P1 * * P4 *
50542 **
50543 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
50544 ** of that table.
50545 */
50546 case OP_VDestroy: {
50547   p->inVtabMethod = 2;
50548   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
50549   p->inVtabMethod = 0;
50550   break;
50551 }
50552 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50553
50554 #ifndef SQLITE_OMIT_VIRTUALTABLE
50555 /* Opcode: VOpen P1 * * P4 *
50556 **
50557 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50558 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
50559 ** table and stores that cursor in P1.
50560 */
50561 case OP_VOpen: {
50562   Cursor *pCur = 0;
50563   sqlite3_vtab_cursor *pVtabCursor = 0;
50564
50565   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50566   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
50567
50568   assert(pVtab && pModule);
50569   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50570   rc = pModule->xOpen(pVtab, &pVtabCursor);
50571   sqlite3DbFree(db, p->zErrMsg);
50572   p->zErrMsg = pVtab->zErrMsg;
50573   pVtab->zErrMsg = 0;
50574   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50575   if( SQLITE_OK==rc ){
50576     /* Initialize sqlite3_vtab_cursor base class */
50577     pVtabCursor->pVtab = pVtab;
50578
50579     /* Initialise vdbe cursor object */
50580     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
50581     if( pCur ){
50582       pCur->pVtabCursor = pVtabCursor;
50583       pCur->pModule = pVtabCursor->pVtab->pModule;
50584     }else{
50585       db->mallocFailed = 1;
50586       pModule->xClose(pVtabCursor);
50587     }
50588   }
50589   break;
50590 }
50591 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50592
50593 #ifndef SQLITE_OMIT_VIRTUALTABLE
50594 /* Opcode: VFilter P1 P2 P3 P4 *
50595 **
50596 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
50597 ** the filtered result set is empty.
50598 **
50599 ** P4 is either NULL or a string that was generated by the xBestIndex
50600 ** method of the module.  The interpretation of the P4 string is left
50601 ** to the module implementation.
50602 **
50603 ** This opcode invokes the xFilter method on the virtual table specified
50604 ** by P1.  The integer query plan parameter to xFilter is stored in register
50605 ** P3. Register P3+1 stores the argc parameter to be passed to the
50606 ** xFilter method. Registers P3+2..P3+1+argc are the argc
50607 ** additional parameters which are passed to
50608 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
50609 **
50610 ** A jump is made to P2 if the result set after filtering would be empty.
50611 */
50612 case OP_VFilter: {   /* jump */
50613   int nArg;
50614   int iQuery;
50615   const sqlite3_module *pModule;
50616   Mem *pQuery = &p->aMem[pOp->p3];
50617   Mem *pArgc = &pQuery[1];
50618   sqlite3_vtab_cursor *pVtabCursor;
50619   sqlite3_vtab *pVtab;
50620
50621   Cursor *pCur = p->apCsr[pOp->p1];
50622
50623   REGISTER_TRACE(pOp->p3, pQuery);
50624   assert( pCur->pVtabCursor );
50625   pVtabCursor = pCur->pVtabCursor;
50626   pVtab = pVtabCursor->pVtab;
50627   pModule = pVtab->pModule;
50628
50629   /* Grab the index number and argc parameters */
50630   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
50631   nArg = pArgc->u.i;
50632   iQuery = pQuery->u.i;
50633
50634   /* Invoke the xFilter method */
50635   {
50636     int res = 0;
50637     int i;
50638     Mem **apArg = p->apArg;
50639     for(i = 0; i<nArg; i++){
50640       apArg[i] = &pArgc[i+1];
50641       storeTypeInfo(apArg[i], 0);
50642     }
50643
50644     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50645     sqlite3VtabLock(pVtab);
50646     p->inVtabMethod = 1;
50647     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
50648     p->inVtabMethod = 0;
50649     sqlite3DbFree(db, p->zErrMsg);
50650     p->zErrMsg = pVtab->zErrMsg;
50651     pVtab->zErrMsg = 0;
50652     sqlite3VtabUnlock(db, pVtab);
50653     if( rc==SQLITE_OK ){
50654       res = pModule->xEof(pVtabCursor);
50655     }
50656     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50657
50658     if( res ){
50659       pc = pOp->p2 - 1;
50660     }
50661   }
50662   pCur->nullRow = 0;
50663
50664   break;
50665 }
50666 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50667
50668 #ifndef SQLITE_OMIT_VIRTUALTABLE
50669 /* Opcode: VRowid P1 P2 * * *
50670 **
50671 ** Store into register P2  the rowid of
50672 ** the virtual-table that the P1 cursor is pointing to.
50673 */
50674 case OP_VRowid: {             /* out2-prerelease */
50675   sqlite3_vtab *pVtab;
50676   const sqlite3_module *pModule;
50677   sqlite_int64 iRow;
50678   Cursor *pCur = p->apCsr[pOp->p1];
50679
50680   assert( pCur->pVtabCursor );
50681   if( pCur->nullRow ){
50682     break;
50683   }
50684   pVtab = pCur->pVtabCursor->pVtab;
50685   pModule = pVtab->pModule;
50686   assert( pModule->xRowid );
50687   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50688   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
50689   sqlite3DbFree(db, p->zErrMsg);
50690   p->zErrMsg = pVtab->zErrMsg;
50691   pVtab->zErrMsg = 0;
50692   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50693   MemSetTypeFlag(pOut, MEM_Int);
50694   pOut->u.i = iRow;
50695   break;
50696 }
50697 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50698
50699 #ifndef SQLITE_OMIT_VIRTUALTABLE
50700 /* Opcode: VColumn P1 P2 P3 * *
50701 **
50702 ** Store the value of the P2-th column of
50703 ** the row of the virtual-table that the 
50704 ** P1 cursor is pointing to into register P3.
50705 */
50706 case OP_VColumn: {
50707   sqlite3_vtab *pVtab;
50708   const sqlite3_module *pModule;
50709   Mem *pDest;
50710   sqlite3_context sContext;
50711
50712   Cursor *pCur = p->apCsr[pOp->p1];
50713   assert( pCur->pVtabCursor );
50714   assert( pOp->p3>0 && pOp->p3<=p->nMem );
50715   pDest = &p->aMem[pOp->p3];
50716   if( pCur->nullRow ){
50717     sqlite3VdbeMemSetNull(pDest);
50718     break;
50719   }
50720   pVtab = pCur->pVtabCursor->pVtab;
50721   pModule = pVtab->pModule;
50722   assert( pModule->xColumn );
50723   memset(&sContext, 0, sizeof(sContext));
50724
50725   /* The output cell may already have a buffer allocated. Move
50726   ** the current contents to sContext.s so in case the user-function 
50727   ** can use the already allocated buffer instead of allocating a 
50728   ** new one.
50729   */
50730   sqlite3VdbeMemMove(&sContext.s, pDest);
50731   MemSetTypeFlag(&sContext.s, MEM_Null);
50732
50733   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50734   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
50735   sqlite3DbFree(db, p->zErrMsg);
50736   p->zErrMsg = pVtab->zErrMsg;
50737   pVtab->zErrMsg = 0;
50738
50739   /* Copy the result of the function to the P3 register. We
50740   ** do this regardless of whether or not an error occured to ensure any
50741   ** dynamic allocation in sContext.s (a Mem struct) is  released.
50742   */
50743   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
50744   REGISTER_TRACE(pOp->p3, pDest);
50745   sqlite3VdbeMemMove(pDest, &sContext.s);
50746   UPDATE_MAX_BLOBSIZE(pDest);
50747
50748   if( sqlite3SafetyOn(db) ){
50749     goto abort_due_to_misuse;
50750   }
50751   if( sqlite3VdbeMemTooBig(pDest) ){
50752     goto too_big;
50753   }
50754   break;
50755 }
50756 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50757
50758 #ifndef SQLITE_OMIT_VIRTUALTABLE
50759 /* Opcode: VNext P1 P2 * * *
50760 **
50761 ** Advance virtual table P1 to the next row in its result set and
50762 ** jump to instruction P2.  Or, if the virtual table has reached
50763 ** the end of its result set, then fall through to the next instruction.
50764 */
50765 case OP_VNext: {   /* jump */
50766   sqlite3_vtab *pVtab;
50767   const sqlite3_module *pModule;
50768   int res = 0;
50769
50770   Cursor *pCur = p->apCsr[pOp->p1];
50771   assert( pCur->pVtabCursor );
50772   if( pCur->nullRow ){
50773     break;
50774   }
50775   pVtab = pCur->pVtabCursor->pVtab;
50776   pModule = pVtab->pModule;
50777   assert( pModule->xNext );
50778
50779   /* Invoke the xNext() method of the module. There is no way for the
50780   ** underlying implementation to return an error if one occurs during
50781   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
50782   ** data is available) and the error code returned when xColumn or
50783   ** some other method is next invoked on the save virtual table cursor.
50784   */
50785   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50786   sqlite3VtabLock(pVtab);
50787   p->inVtabMethod = 1;
50788   rc = pModule->xNext(pCur->pVtabCursor);
50789   p->inVtabMethod = 0;
50790   sqlite3DbFree(db, p->zErrMsg);
50791   p->zErrMsg = pVtab->zErrMsg;
50792   pVtab->zErrMsg = 0;
50793   sqlite3VtabUnlock(db, pVtab);
50794   if( rc==SQLITE_OK ){
50795     res = pModule->xEof(pCur->pVtabCursor);
50796   }
50797   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50798
50799   if( !res ){
50800     /* If there is data, jump to P2 */
50801     pc = pOp->p2 - 1;
50802   }
50803   break;
50804 }
50805 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50806
50807 #ifndef SQLITE_OMIT_VIRTUALTABLE
50808 /* Opcode: VRename P1 * * P4 *
50809 **
50810 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50811 ** This opcode invokes the corresponding xRename method. The value
50812 ** in register P1 is passed as the zName argument to the xRename method.
50813 */
50814 case OP_VRename: {
50815   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50816   Mem *pName = &p->aMem[pOp->p1];
50817   assert( pVtab->pModule->xRename );
50818   REGISTER_TRACE(pOp->p1, pName);
50819
50820   Stringify(pName, encoding);
50821
50822   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50823   sqlite3VtabLock(pVtab);
50824   rc = pVtab->pModule->xRename(pVtab, pName->z);
50825   sqlite3DbFree(db, p->zErrMsg);
50826   p->zErrMsg = pVtab->zErrMsg;
50827   pVtab->zErrMsg = 0;
50828   sqlite3VtabUnlock(db, pVtab);
50829   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50830
50831   break;
50832 }
50833 #endif
50834
50835 #ifndef SQLITE_OMIT_VIRTUALTABLE
50836 /* Opcode: VUpdate P1 P2 P3 P4 *
50837 **
50838 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
50839 ** This opcode invokes the corresponding xUpdate method. P2 values
50840 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
50841 ** invocation. The value in register (P3+P2-1) corresponds to the 
50842 ** p2th element of the argv array passed to xUpdate.
50843 **
50844 ** The xUpdate method will do a DELETE or an INSERT or both.
50845 ** The argv[0] element (which corresponds to memory cell P3)
50846 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
50847 ** deletion occurs.  The argv[1] element is the rowid of the new 
50848 ** row.  This can be NULL to have the virtual table select the new 
50849 ** rowid for itself.  The subsequent elements in the array are 
50850 ** the values of columns in the new row.
50851 **
50852 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
50853 ** a row to delete.
50854 **
50855 ** P1 is a boolean flag. If it is set to true and the xUpdate call
50856 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
50857 ** is set to the value of the rowid for the row just inserted.
50858 */
50859 case OP_VUpdate: {
50860   sqlite3_vtab *pVtab = pOp->p4.pVtab;
50861   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
50862   int nArg = pOp->p2;
50863   assert( pOp->p4type==P4_VTAB );
50864   if( pModule->xUpdate==0 ){
50865     sqlite3SetString(&p->zErrMsg, db, "read-only table");
50866     rc = SQLITE_ERROR;
50867   }else{
50868     int i;
50869     sqlite_int64 rowid;
50870     Mem **apArg = p->apArg;
50871     Mem *pX = &p->aMem[pOp->p3];
50872     for(i=0; i<nArg; i++){
50873       storeTypeInfo(pX, 0);
50874       apArg[i] = pX;
50875       pX++;
50876     }
50877     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
50878     sqlite3VtabLock(pVtab);
50879     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
50880     sqlite3DbFree(db, p->zErrMsg);
50881     p->zErrMsg = pVtab->zErrMsg;
50882     pVtab->zErrMsg = 0;
50883     sqlite3VtabUnlock(db, pVtab);
50884     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
50885     if( pOp->p1 && rc==SQLITE_OK ){
50886       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
50887       db->lastRowid = rowid;
50888     }
50889     p->nChange++;
50890   }
50891   break;
50892 }
50893 #endif /* SQLITE_OMIT_VIRTUALTABLE */
50894
50895 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
50896 /* Opcode: Pagecount P1 P2 * * *
50897 **
50898 ** Write the current number of pages in database P1 to memory cell P2.
50899 */
50900 case OP_Pagecount: {            /* out2-prerelease */
50901   int p1 = pOp->p1; 
50902   int nPage;
50903   Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
50904
50905   rc = sqlite3PagerPagecount(pPager, &nPage);
50906   if( rc==SQLITE_OK ){
50907     pOut->flags = MEM_Int;
50908     pOut->u.i = nPage;
50909   }
50910   break;
50911 }
50912 #endif
50913
50914 #ifndef SQLITE_OMIT_TRACE
50915 /* Opcode: Trace * * * P4 *
50916 **
50917 ** If tracing is enabled (by the sqlite3_trace()) interface, then
50918 ** the UTF-8 string contained in P4 is emitted on the trace callback.
50919 */
50920 case OP_Trace: {
50921   if( pOp->p4.z ){
50922     if( db->xTrace ){
50923       db->xTrace(db->pTraceArg, pOp->p4.z);
50924     }
50925 #ifdef SQLITE_DEBUG
50926     if( (db->flags & SQLITE_SqlTrace)!=0 ){
50927       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
50928     }
50929 #endif /* SQLITE_DEBUG */
50930   }
50931   break;
50932 }
50933 #endif
50934
50935
50936 /* Opcode: Noop * * * * *
50937 **
50938 ** Do nothing.  This instruction is often useful as a jump
50939 ** destination.
50940 */
50941 /*
50942 ** The magic Explain opcode are only inserted when explain==2 (which
50943 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
50944 ** This opcode records information from the optimizer.  It is the
50945 ** the same as a no-op.  This opcodesnever appears in a real VM program.
50946 */
50947 default: {          /* This is really OP_Noop and OP_Explain */
50948   break;
50949 }
50950
50951 /*****************************************************************************
50952 ** The cases of the switch statement above this line should all be indented
50953 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
50954 ** readability.  From this point on down, the normal indentation rules are
50955 ** restored.
50956 *****************************************************************************/
50957     }
50958
50959 #ifdef VDBE_PROFILE
50960     {
50961       u64 elapsed = sqlite3Hwtime() - start;
50962       pOp->cycles += elapsed;
50963       pOp->cnt++;
50964 #if 0
50965         fprintf(stdout, "%10llu ", elapsed);
50966         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
50967 #endif
50968     }
50969 #endif
50970
50971     /* The following code adds nothing to the actual functionality
50972     ** of the program.  It is only here for testing and debugging.
50973     ** On the other hand, it does burn CPU cycles every time through
50974     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
50975     */
50976 #ifndef NDEBUG
50977     assert( pc>=-1 && pc<p->nOp );
50978
50979 #ifdef SQLITE_DEBUG
50980     if( p->trace ){
50981       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
50982       if( opProperty & OPFLG_OUT2_PRERELEASE ){
50983         registerTrace(p->trace, pOp->p2, pOut);
50984       }
50985       if( opProperty & OPFLG_OUT3 ){
50986         registerTrace(p->trace, pOp->p3, pOut);
50987       }
50988     }
50989 #endif  /* SQLITE_DEBUG */
50990 #endif  /* NDEBUG */
50991   }  /* The end of the for(;;) loop the loops through opcodes */
50992
50993   /* If we reach this point, it means that execution is finished with
50994   ** an error of some kind.
50995   */
50996 vdbe_error_halt:
50997   assert( rc );
50998   p->rc = rc;
50999   sqlite3VdbeHalt(p);
51000   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
51001   rc = SQLITE_ERROR;
51002
51003   /* This is the only way out of this procedure.  We have to
51004   ** release the mutexes on btrees that were acquired at the
51005   ** top. */
51006 vdbe_return:
51007   sqlite3BtreeMutexArrayLeave(&p->aMutex);
51008   return rc;
51009
51010   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
51011   ** is encountered.
51012   */
51013 too_big:
51014   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
51015   rc = SQLITE_TOOBIG;
51016   goto vdbe_error_halt;
51017
51018   /* Jump to here if a malloc() fails.
51019   */
51020 no_mem:
51021   db->mallocFailed = 1;
51022   sqlite3SetString(&p->zErrMsg, db, "out of memory");
51023   rc = SQLITE_NOMEM;
51024   goto vdbe_error_halt;
51025
51026   /* Jump to here for an SQLITE_MISUSE error.
51027   */
51028 abort_due_to_misuse:
51029   rc = SQLITE_MISUSE;
51030   /* Fall thru into abort_due_to_error */
51031
51032   /* Jump to here for any other kind of fatal error.  The "rc" variable
51033   ** should hold the error number.
51034   */
51035 abort_due_to_error:
51036   assert( p->zErrMsg==0 );
51037   if( db->mallocFailed ) rc = SQLITE_NOMEM;
51038   if( rc!=SQLITE_IOERR_NOMEM ){
51039     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
51040   }
51041   goto vdbe_error_halt;
51042
51043   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
51044   ** flag.
51045   */
51046 abort_due_to_interrupt:
51047   assert( db->u1.isInterrupted );
51048   rc = SQLITE_INTERRUPT;
51049   p->rc = rc;
51050   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
51051   goto vdbe_error_halt;
51052 }
51053
51054 /************** End of vdbe.c ************************************************/
51055 /************** Begin file vdbeblob.c ****************************************/
51056 /*
51057 ** 2007 May 1
51058 **
51059 ** The author disclaims copyright to this source code.  In place of
51060 ** a legal notice, here is a blessing:
51061 **
51062 **    May you do good and not evil.
51063 **    May you find forgiveness for yourself and forgive others.
51064 **    May you share freely, never taking more than you give.
51065 **
51066 *************************************************************************
51067 **
51068 ** This file contains code used to implement incremental BLOB I/O.
51069 **
51070 ** $Id: vdbeblob.c,v 1.26 2008/10/02 14:49:02 danielk1977 Exp $
51071 */
51072
51073
51074 #ifndef SQLITE_OMIT_INCRBLOB
51075
51076 /*
51077 ** Valid sqlite3_blob* handles point to Incrblob structures.
51078 */
51079 typedef struct Incrblob Incrblob;
51080 struct Incrblob {
51081   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
51082   int nByte;              /* Size of open blob, in bytes */
51083   int iOffset;            /* Byte offset of blob in cursor data */
51084   BtCursor *pCsr;         /* Cursor pointing at blob row */
51085   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
51086   sqlite3 *db;            /* The associated database */
51087 };
51088
51089 /*
51090 ** Open a blob handle.
51091 */
51092 SQLITE_API int sqlite3_blob_open(
51093   sqlite3* db,            /* The database connection */
51094   const char *zDb,        /* The attached database containing the blob */
51095   const char *zTable,     /* The table containing the blob */
51096   const char *zColumn,    /* The column containing the blob */
51097   sqlite_int64 iRow,      /* The row containing the glob */
51098   int flags,              /* True -> read/write access, false -> read-only */
51099   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
51100 ){
51101   int nAttempt = 0;
51102   int iCol;               /* Index of zColumn in row-record */
51103
51104   /* This VDBE program seeks a btree cursor to the identified 
51105   ** db/table/row entry. The reason for using a vdbe program instead
51106   ** of writing code to use the b-tree layer directly is that the
51107   ** vdbe program will take advantage of the various transaction,
51108   ** locking and error handling infrastructure built into the vdbe.
51109   **
51110   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
51111   ** Code external to the Vdbe then "borrows" the b-tree cursor and
51112   ** uses it to implement the blob_read(), blob_write() and 
51113   ** blob_bytes() functions.
51114   **
51115   ** The sqlite3_blob_close() function finalizes the vdbe program,
51116   ** which closes the b-tree cursor and (possibly) commits the 
51117   ** transaction.
51118   */
51119   static const VdbeOpList openBlob[] = {
51120     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
51121     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
51122
51123     /* One of the following two instructions is replaced by an
51124     ** OP_Noop before exection.
51125     */
51126     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
51127     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
51128     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
51129     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
51130
51131     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
51132     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
51133     {OP_Column, 0, 0, 1},          /* 8  */
51134     {OP_ResultRow, 1, 0, 0},       /* 9  */
51135     {OP_Close, 0, 0, 0},           /* 10  */
51136     {OP_Halt, 0, 0, 0},            /* 11 */
51137   };
51138
51139   Vdbe *v = 0;
51140   int rc = SQLITE_OK;
51141   char zErr[128];
51142
51143   zErr[0] = 0;
51144   sqlite3_mutex_enter(db->mutex);
51145   do {
51146     Parse sParse;
51147     Table *pTab;
51148
51149     memset(&sParse, 0, sizeof(Parse));
51150     sParse.db = db;
51151
51152     if( sqlite3SafetyOn(db) ){
51153       sqlite3_mutex_leave(db->mutex);
51154       return SQLITE_MISUSE;
51155     }
51156
51157     sqlite3BtreeEnterAll(db);
51158     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
51159     if( pTab && IsVirtual(pTab) ){
51160       pTab = 0;
51161       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
51162     }
51163 #ifndef SQLITE_OMIT_VIEW
51164     if( pTab && pTab->pSelect ){
51165       pTab = 0;
51166       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
51167     }
51168 #endif
51169     if( !pTab ){
51170       if( sParse.zErrMsg ){
51171         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
51172       }
51173       sqlite3DbFree(db, sParse.zErrMsg);
51174       rc = SQLITE_ERROR;
51175       (void)sqlite3SafetyOff(db);
51176       sqlite3BtreeLeaveAll(db);
51177       goto blob_open_out;
51178     }
51179
51180     /* Now search pTab for the exact column. */
51181     for(iCol=0; iCol < pTab->nCol; iCol++) {
51182       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
51183         break;
51184       }
51185     }
51186     if( iCol==pTab->nCol ){
51187       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
51188       rc = SQLITE_ERROR;
51189       (void)sqlite3SafetyOff(db);
51190       sqlite3BtreeLeaveAll(db);
51191       goto blob_open_out;
51192     }
51193
51194     /* If the value is being opened for writing, check that the
51195     ** column is not indexed. It is against the rules to open an
51196     ** indexed column for writing.
51197     */
51198     if( flags ){
51199       Index *pIdx;
51200       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
51201         int j;
51202         for(j=0; j<pIdx->nColumn; j++){
51203           if( pIdx->aiColumn[j]==iCol ){
51204             sqlite3_snprintf(sizeof(zErr), zErr,
51205                              "cannot open indexed column for writing");
51206             rc = SQLITE_ERROR;
51207             (void)sqlite3SafetyOff(db);
51208             sqlite3BtreeLeaveAll(db);
51209             goto blob_open_out;
51210           }
51211         }
51212       }
51213     }
51214
51215     v = sqlite3VdbeCreate(db);
51216     if( v ){
51217       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51218       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
51219
51220       /* Configure the OP_Transaction */
51221       sqlite3VdbeChangeP1(v, 0, iDb);
51222       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
51223
51224       /* Configure the OP_VerifyCookie */
51225       sqlite3VdbeChangeP1(v, 1, iDb);
51226       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
51227
51228       /* Make sure a mutex is held on the table to be accessed */
51229       sqlite3VdbeUsesBtree(v, iDb); 
51230
51231       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
51232       ** parameter of the other to pTab->tnum. 
51233       */
51234       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
51235       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
51236       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
51237
51238       /* Configure the OP_SetNumColumns. Configure the cursor to
51239       ** think that the table has one more column than it really
51240       ** does. An OP_Column to retrieve this imaginary column will
51241       ** always return an SQL NULL. This is useful because it means
51242       ** we can invoke OP_Column to fill in the vdbe cursors type 
51243       ** and offset cache without causing any IO.
51244       */
51245       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
51246       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
51247       if( !db->mallocFailed ){
51248         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
51249       }
51250     }
51251    
51252     sqlite3BtreeLeaveAll(db);
51253     rc = sqlite3SafetyOff(db);
51254     if( rc!=SQLITE_OK || db->mallocFailed ){
51255       goto blob_open_out;
51256     }
51257
51258     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
51259     rc = sqlite3_step((sqlite3_stmt *)v);
51260     if( rc!=SQLITE_ROW ){
51261       nAttempt++;
51262       rc = sqlite3_finalize((sqlite3_stmt *)v);
51263       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
51264       v = 0;
51265     }
51266   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
51267
51268   if( rc==SQLITE_ROW ){
51269     /* The row-record has been opened successfully. Check that the
51270     ** column in question contains text or a blob. If it contains
51271     ** text, it is up to the caller to get the encoding right.
51272     */
51273     Incrblob *pBlob;
51274     u32 type = v->apCsr[0]->aType[iCol];
51275
51276     if( type<12 ){
51277       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
51278           type==0?"null": type==7?"real": "integer"
51279       );
51280       rc = SQLITE_ERROR;
51281       goto blob_open_out;
51282     }
51283     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
51284     if( db->mallocFailed ){
51285       sqlite3DbFree(db, pBlob);
51286       goto blob_open_out;
51287     }
51288     pBlob->flags = flags;
51289     pBlob->pCsr =  v->apCsr[0]->pCursor;
51290     sqlite3BtreeEnterCursor(pBlob->pCsr);
51291     sqlite3BtreeCacheOverflow(pBlob->pCsr);
51292     sqlite3BtreeLeaveCursor(pBlob->pCsr);
51293     pBlob->pStmt = (sqlite3_stmt *)v;
51294     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
51295     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
51296     pBlob->db = db;
51297     *ppBlob = (sqlite3_blob *)pBlob;
51298     rc = SQLITE_OK;
51299   }else if( rc==SQLITE_OK ){
51300     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
51301     rc = SQLITE_ERROR;
51302   }
51303
51304 blob_open_out:
51305   zErr[sizeof(zErr)-1] = '\0';
51306   if( rc!=SQLITE_OK || db->mallocFailed ){
51307     sqlite3_finalize((sqlite3_stmt *)v);
51308   }
51309   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
51310   rc = sqlite3ApiExit(db, rc);
51311   sqlite3_mutex_leave(db->mutex);
51312   return rc;
51313 }
51314
51315 /*
51316 ** Close a blob handle that was previously created using
51317 ** sqlite3_blob_open().
51318 */
51319 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
51320   Incrblob *p = (Incrblob *)pBlob;
51321   int rc;
51322
51323   rc = sqlite3_finalize(p->pStmt);
51324   sqlite3DbFree(p->db, p);
51325   return rc;
51326 }
51327
51328 /*
51329 ** Perform a read or write operation on a blob
51330 */
51331 static int blobReadWrite(
51332   sqlite3_blob *pBlob, 
51333   void *z, 
51334   int n, 
51335   int iOffset, 
51336   int (*xCall)(BtCursor*, u32, u32, void*)
51337 ){
51338   int rc;
51339   Incrblob *p = (Incrblob *)pBlob;
51340   Vdbe *v;
51341   sqlite3 *db = p->db;  
51342
51343   sqlite3_mutex_enter(db->mutex);
51344   v = (Vdbe*)p->pStmt;
51345
51346   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
51347     /* Request is out of range. Return a transient error. */
51348     rc = SQLITE_ERROR;
51349     sqlite3Error(db, SQLITE_ERROR, 0);
51350   } else if( v==0 ){
51351     /* If there is no statement handle, then the blob-handle has
51352     ** already been invalidated. Return SQLITE_ABORT in this case.
51353     */
51354     rc = SQLITE_ABORT;
51355   }else{
51356     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
51357     ** returned, clean-up the statement handle.
51358     */
51359     assert( db == v->db );
51360     sqlite3BtreeEnterCursor(p->pCsr);
51361     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
51362     sqlite3BtreeLeaveCursor(p->pCsr);
51363     if( rc==SQLITE_ABORT ){
51364       sqlite3VdbeFinalize(v);
51365       p->pStmt = 0;
51366     }else{
51367       db->errCode = rc;
51368       v->rc = rc;
51369     }
51370   }
51371   rc = sqlite3ApiExit(db, rc);
51372   sqlite3_mutex_leave(db->mutex);
51373   return rc;
51374 }
51375
51376 /*
51377 ** Read data from a blob handle.
51378 */
51379 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
51380   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
51381 }
51382
51383 /*
51384 ** Write data to a blob handle.
51385 */
51386 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
51387   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
51388 }
51389
51390 /*
51391 ** Query a blob handle for the size of the data.
51392 **
51393 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
51394 ** so no mutex is required for access.
51395 */
51396 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
51397   Incrblob *p = (Incrblob *)pBlob;
51398   return p->nByte;
51399 }
51400
51401 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
51402
51403 /************** End of vdbeblob.c ********************************************/
51404 /************** Begin file journal.c *****************************************/
51405 /*
51406 ** 2007 August 22
51407 **
51408 ** The author disclaims copyright to this source code.  In place of
51409 ** a legal notice, here is a blessing:
51410 **
51411 **    May you do good and not evil.
51412 **    May you find forgiveness for yourself and forgive others.
51413 **    May you share freely, never taking more than you give.
51414 **
51415 *************************************************************************
51416 **
51417 ** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
51418 */
51419
51420 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51421
51422 /*
51423 ** This file implements a special kind of sqlite3_file object used
51424 ** by SQLite to create journal files if the atomic-write optimization
51425 ** is enabled.
51426 **
51427 ** The distinctive characteristic of this sqlite3_file is that the
51428 ** actual on disk file is created lazily. When the file is created,
51429 ** the caller specifies a buffer size for an in-memory buffer to
51430 ** be used to service read() and write() requests. The actual file
51431 ** on disk is not created or populated until either:
51432 **
51433 **   1) The in-memory representation grows too large for the allocated 
51434 **      buffer, or
51435 **   2) The xSync() method is called.
51436 */
51437
51438
51439
51440 /*
51441 ** A JournalFile object is a subclass of sqlite3_file used by
51442 ** as an open file handle for journal files.
51443 */
51444 struct JournalFile {
51445   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
51446   int nBuf;                       /* Size of zBuf[] in bytes */
51447   char *zBuf;                     /* Space to buffer journal writes */
51448   int iSize;                      /* Amount of zBuf[] currently used */
51449   int flags;                      /* xOpen flags */
51450   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
51451   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
51452   const char *zJournal;           /* Name of the journal file */
51453 };
51454 typedef struct JournalFile JournalFile;
51455
51456 /*
51457 ** If it does not already exists, create and populate the on-disk file 
51458 ** for JournalFile p.
51459 */
51460 static int createFile(JournalFile *p){
51461   int rc = SQLITE_OK;
51462   if( !p->pReal ){
51463     sqlite3_file *pReal = (sqlite3_file *)&p[1];
51464     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
51465     if( rc==SQLITE_OK ){
51466       p->pReal = pReal;
51467       if( p->iSize>0 ){
51468         assert(p->iSize<=p->nBuf);
51469         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
51470       }
51471     }
51472   }
51473   return rc;
51474 }
51475
51476 /*
51477 ** Close the file.
51478 */
51479 static int jrnlClose(sqlite3_file *pJfd){
51480   JournalFile *p = (JournalFile *)pJfd;
51481   if( p->pReal ){
51482     sqlite3OsClose(p->pReal);
51483   }
51484   sqlite3_free(p->zBuf);
51485   return SQLITE_OK;
51486 }
51487
51488 /*
51489 ** Read data from the file.
51490 */
51491 static int jrnlRead(
51492   sqlite3_file *pJfd,    /* The journal file from which to read */
51493   void *zBuf,            /* Put the results here */
51494   int iAmt,              /* Number of bytes to read */
51495   sqlite_int64 iOfst     /* Begin reading at this offset */
51496 ){
51497   int rc = SQLITE_OK;
51498   JournalFile *p = (JournalFile *)pJfd;
51499   if( p->pReal ){
51500     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
51501   }else{
51502     assert( iAmt+iOfst<=p->iSize );
51503     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
51504   }
51505   return rc;
51506 }
51507
51508 /*
51509 ** Write data to the file.
51510 */
51511 static int jrnlWrite(
51512   sqlite3_file *pJfd,    /* The journal file into which to write */
51513   const void *zBuf,      /* Take data to be written from here */
51514   int iAmt,              /* Number of bytes to write */
51515   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
51516 ){
51517   int rc = SQLITE_OK;
51518   JournalFile *p = (JournalFile *)pJfd;
51519   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
51520     rc = createFile(p);
51521   }
51522   if( rc==SQLITE_OK ){
51523     if( p->pReal ){
51524       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
51525     }else{
51526       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
51527       if( p->iSize<(iOfst+iAmt) ){
51528         p->iSize = (iOfst+iAmt);
51529       }
51530     }
51531   }
51532   return rc;
51533 }
51534
51535 /*
51536 ** Truncate the file.
51537 */
51538 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
51539   int rc = SQLITE_OK;
51540   JournalFile *p = (JournalFile *)pJfd;
51541   if( p->pReal ){
51542     rc = sqlite3OsTruncate(p->pReal, size);
51543   }else if( size<p->iSize ){
51544     p->iSize = size;
51545   }
51546   return rc;
51547 }
51548
51549 /*
51550 ** Sync the file.
51551 */
51552 static int jrnlSync(sqlite3_file *pJfd, int flags){
51553   int rc;
51554   JournalFile *p = (JournalFile *)pJfd;
51555   if( p->pReal ){
51556     rc = sqlite3OsSync(p->pReal, flags);
51557   }else{
51558     rc = SQLITE_OK;
51559   }
51560   return rc;
51561 }
51562
51563 /*
51564 ** Query the size of the file in bytes.
51565 */
51566 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
51567   int rc = SQLITE_OK;
51568   JournalFile *p = (JournalFile *)pJfd;
51569   if( p->pReal ){
51570     rc = sqlite3OsFileSize(p->pReal, pSize);
51571   }else{
51572     *pSize = (sqlite_int64) p->iSize;
51573   }
51574   return rc;
51575 }
51576
51577 /*
51578 ** Table of methods for JournalFile sqlite3_file object.
51579 */
51580 static struct sqlite3_io_methods JournalFileMethods = {
51581   1,             /* iVersion */
51582   jrnlClose,     /* xClose */
51583   jrnlRead,      /* xRead */
51584   jrnlWrite,     /* xWrite */
51585   jrnlTruncate,  /* xTruncate */
51586   jrnlSync,      /* xSync */
51587   jrnlFileSize,  /* xFileSize */
51588   0,             /* xLock */
51589   0,             /* xUnlock */
51590   0,             /* xCheckReservedLock */
51591   0,             /* xFileControl */
51592   0,             /* xSectorSize */
51593   0              /* xDeviceCharacteristics */
51594 };
51595
51596 /* 
51597 ** Open a journal file.
51598 */
51599 SQLITE_PRIVATE int sqlite3JournalOpen(
51600   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
51601   const char *zName,         /* Name of the journal file */
51602   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
51603   int flags,                 /* Opening flags */
51604   int nBuf                   /* Bytes buffered before opening the file */
51605 ){
51606   JournalFile *p = (JournalFile *)pJfd;
51607   memset(p, 0, sqlite3JournalSize(pVfs));
51608   if( nBuf>0 ){
51609     p->zBuf = sqlite3MallocZero(nBuf);
51610     if( !p->zBuf ){
51611       return SQLITE_NOMEM;
51612     }
51613   }else{
51614     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
51615   }
51616   p->pMethod = &JournalFileMethods;
51617   p->nBuf = nBuf;
51618   p->flags = flags;
51619   p->zJournal = zName;
51620   p->pVfs = pVfs;
51621   return SQLITE_OK;
51622 }
51623
51624 /*
51625 ** If the argument p points to a JournalFile structure, and the underlying
51626 ** file has not yet been created, create it now.
51627 */
51628 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
51629   if( p->pMethods!=&JournalFileMethods ){
51630     return SQLITE_OK;
51631   }
51632   return createFile((JournalFile *)p);
51633 }
51634
51635 /* 
51636 ** Return the number of bytes required to store a JournalFile that uses vfs
51637 ** pVfs to create the underlying on-disk files.
51638 */
51639 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
51640   return (pVfs->szOsFile+sizeof(JournalFile));
51641 }
51642 #endif
51643
51644 /************** End of journal.c *********************************************/
51645 /************** Begin file walker.c ******************************************/
51646 /*
51647 ** 2008 August 16
51648 **
51649 ** The author disclaims copyright to this source code.  In place of
51650 ** a legal notice, here is a blessing:
51651 **
51652 **    May you do good and not evil.
51653 **    May you find forgiveness for yourself and forgive others.
51654 **    May you share freely, never taking more than you give.
51655 **
51656 *************************************************************************
51657 ** This file contains routines used for walking the parser tree for
51658 ** an SQL statement.
51659 **
51660 ** $Id: walker.c,v 1.1 2008/08/20 16:35:10 drh Exp $
51661 */
51662
51663
51664 /*
51665 ** Walk an expression tree.  Invoke the callback once for each node
51666 ** of the expression, while decending.  (In other words, the callback
51667 ** is invoked before visiting children.)
51668 **
51669 ** The return value from the callback should be one of the WRC_*
51670 ** constants to specify how to proceed with the walk.
51671 **
51672 **    WRC_Continue      Continue descending down the tree.
51673 **
51674 **    WRC_Prune         Do not descend into child nodes.  But allow
51675 **                      the walk to continue with sibling nodes.
51676 **
51677 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
51678 **                      return the top-level walk call.
51679 **
51680 ** The return value from this routine is WRC_Abort to abandon the tree walk
51681 ** and WRC_Continue to continue.
51682 */
51683 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
51684   int rc;
51685   if( pExpr==0 ) return WRC_Continue;
51686   rc = pWalker->xExprCallback(pWalker, pExpr);
51687   if( rc==WRC_Continue ){
51688     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
51689     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
51690     if( sqlite3WalkExprList(pWalker, pExpr->pList) ) return WRC_Abort;
51691     if( sqlite3WalkSelect(pWalker, pExpr->pSelect) ){
51692       return WRC_Abort;
51693     }
51694   }
51695   return rc & WRC_Abort;
51696 }
51697
51698 /*
51699 ** Call sqlite3WalkExpr() for every expression in list p or until
51700 ** an abort request is seen.
51701 */
51702 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
51703   int i, rc = WRC_Continue;
51704   struct ExprList_item *pItem;
51705   if( p ){
51706     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
51707       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
51708     }
51709   }
51710   return rc & WRC_Continue;
51711 }
51712
51713 /*
51714 ** Walk all expressions associated with SELECT statement p.  Do
51715 ** not invoke the SELECT callback on p, but do (of course) invoke
51716 ** any expr callbacks and SELECT callbacks that come from subqueries.
51717 ** Return WRC_Abort or WRC_Continue.
51718 */
51719 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
51720   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
51721   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
51722   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
51723   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
51724   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
51725   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
51726   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
51727   return WRC_Continue;
51728 }
51729
51730 /*
51731 ** Walk the parse trees associated with all subqueries in the
51732 ** FROM clause of SELECT statement p.  Do not invoke the select
51733 ** callback on p, but do invoke it on each FROM clause subquery
51734 ** and on any subqueries further down in the tree.  Return 
51735 ** WRC_Abort or WRC_Continue;
51736 */
51737 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
51738   SrcList *pSrc;
51739   int i;
51740   struct SrcList_item *pItem;
51741
51742   pSrc = p->pSrc;
51743   if( pSrc ){
51744     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
51745       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
51746         return WRC_Abort;
51747       }
51748     }
51749   }
51750   return WRC_Continue;
51751
51752
51753 /*
51754 ** Call sqlite3WalkExpr() for every expression in Select statement p.
51755 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
51756 ** on the compound select chain, p->pPrior.
51757 **
51758 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
51759 ** there is an abort request.
51760 **
51761 ** If the Walker does not have an xSelectCallback() then this routine
51762 ** is a no-op returning WRC_Continue.
51763 */
51764 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
51765   int rc;
51766   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
51767   rc = WRC_Continue;
51768   while( p  ){
51769     rc = pWalker->xSelectCallback(pWalker, p);
51770     if( rc ) break;
51771     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
51772     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
51773     p = p->pPrior;
51774   }
51775   return rc & WRC_Abort;
51776 }
51777
51778 /************** End of walker.c **********************************************/
51779 /************** Begin file resolve.c *****************************************/
51780 /*
51781 ** 2008 August 18
51782 **
51783 ** The author disclaims copyright to this source code.  In place of
51784 ** a legal notice, here is a blessing:
51785 **
51786 **    May you do good and not evil.
51787 **    May you find forgiveness for yourself and forgive others.
51788 **    May you share freely, never taking more than you give.
51789 **
51790 *************************************************************************
51791 **
51792 ** This file contains routines used for walking the parser tree and
51793 ** resolve all identifiers by associating them with a particular
51794 ** table and column.
51795 **
51796 ** $Id: resolve.c,v 1.9 2008/10/11 16:47:36 drh Exp $
51797 */
51798
51799 /*
51800 ** Turn the pExpr expression into an alias for the iCol-th column of the
51801 ** result set in pEList.
51802 **
51803 ** If the result set column is a simple column reference, then this routine
51804 ** makes an exact copy.  But for any other kind of expression, this
51805 ** routine make a copy of the result set column as the argument to the
51806 ** TK_AS operator.  The TK_AS operator causes the expression to be
51807 ** evaluated just once and then reused for each alias.
51808 **
51809 ** The reason for suppressing the TK_AS term when the expression is a simple
51810 ** column reference is so that the column reference will be recognized as
51811 ** usable by indices within the WHERE clause processing logic. 
51812 **
51813 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
51814 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
51815 **
51816 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
51817 **
51818 ** Is equivalent to:
51819 **
51820 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
51821 **
51822 ** The result of random()%5 in the GROUP BY clause is probably different
51823 ** from the result in the result-set.  We might fix this someday.  Or
51824 ** then again, we might not...
51825 */
51826 static void resolveAlias(
51827   Parse *pParse,         /* Parsing context */
51828   ExprList *pEList,      /* A result set */
51829   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
51830   Expr *pExpr,           /* Transform this into an alias to the result set */
51831   const char *zType      /* "GROUP" or "ORDER" or "" */
51832 ){
51833   Expr *pOrig;           /* The iCol-th column of the result set */
51834   Expr *pDup;            /* Copy of pOrig */
51835   sqlite3 *db;           /* The database connection */
51836
51837   assert( iCol>=0 && iCol<pEList->nExpr );
51838   pOrig = pEList->a[iCol].pExpr;
51839   assert( pOrig!=0 );
51840   assert( pOrig->flags & EP_Resolved );
51841   db = pParse->db;
51842   pDup = sqlite3ExprDup(db, pOrig);
51843   if( pDup==0 ) return;
51844   if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
51845     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
51846     if( pDup==0 ) return;
51847     if( pEList->a[iCol].iAlias==0 ){
51848       pEList->a[iCol].iAlias = ++pParse->nAlias;
51849     }
51850     pDup->iTable = pEList->a[iCol].iAlias;
51851   }
51852   if( pExpr->flags & EP_ExpCollate ){
51853     pDup->pColl = pExpr->pColl;
51854     pDup->flags |= EP_ExpCollate;
51855   }
51856   sqlite3ExprClear(db, pExpr);
51857   memcpy(pExpr, pDup, sizeof(*pExpr));
51858   sqlite3DbFree(db, pDup);
51859 }
51860
51861 /*
51862 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
51863 ** that name in the set of source tables in pSrcList and make the pExpr 
51864 ** expression node refer back to that source column.  The following changes
51865 ** are made to pExpr:
51866 **
51867 **    pExpr->iDb           Set the index in db->aDb[] of the database X
51868 **                         (even if X is implied).
51869 **    pExpr->iTable        Set to the cursor number for the table obtained
51870 **                         from pSrcList.
51871 **    pExpr->pTab          Points to the Table structure of X.Y (even if
51872 **                         X and/or Y are implied.)
51873 **    pExpr->iColumn       Set to the column number within the table.
51874 **    pExpr->op            Set to TK_COLUMN.
51875 **    pExpr->pLeft         Any expression this points to is deleted
51876 **    pExpr->pRight        Any expression this points to is deleted.
51877 **
51878 ** The pDbToken is the name of the database (the "X").  This value may be
51879 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
51880 ** can be used.  The pTableToken is the name of the table (the "Y").  This
51881 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
51882 ** means that the form of the name is Z and that columns from any table
51883 ** can be used.
51884 **
51885 ** If the name cannot be resolved unambiguously, leave an error message
51886 ** in pParse and return non-zero.  Return zero on success.
51887 */
51888 static int lookupName(
51889   Parse *pParse,       /* The parsing context */
51890   Token *pDbToken,     /* Name of the database containing table, or NULL */
51891   Token *pTableToken,  /* Name of table containing column, or NULL */
51892   Token *pColumnToken, /* Name of the column. */
51893   NameContext *pNC,    /* The name context used to resolve the name */
51894   Expr *pExpr          /* Make this EXPR node point to the selected column */
51895 ){
51896   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
51897   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
51898   char *zCol = 0;      /* Name of the column.  The "Z" */
51899   int i, j;            /* Loop counters */
51900   int cnt = 0;                      /* Number of matching column names */
51901   int cntTab = 0;                   /* Number of matching table names */
51902   sqlite3 *db = pParse->db;         /* The database connection */
51903   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
51904   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
51905   NameContext *pTopNC = pNC;        /* First namecontext in the list */
51906   Schema *pSchema = 0;              /* Schema of the expression */
51907
51908   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
51909
51910   /* Dequote and zero-terminate the names */
51911   zDb = sqlite3NameFromToken(db, pDbToken);
51912   zTab = sqlite3NameFromToken(db, pTableToken);
51913   zCol = sqlite3NameFromToken(db, pColumnToken);
51914   if( db->mallocFailed ){
51915     goto lookupname_end;
51916   }
51917
51918   /* Initialize the node to no-match */
51919   pExpr->iTable = -1;
51920   pExpr->pTab = 0;
51921
51922   /* Start at the inner-most context and move outward until a match is found */
51923   while( pNC && cnt==0 ){
51924     ExprList *pEList;
51925     SrcList *pSrcList = pNC->pSrcList;
51926
51927     if( pSrcList ){
51928       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
51929         Table *pTab;
51930         int iDb;
51931         Column *pCol;
51932   
51933         pTab = pItem->pTab;
51934         assert( pTab!=0 && pTab->zName!=0 );
51935         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
51936         assert( pTab->nCol>0 );
51937         if( zTab ){
51938           if( pItem->zAlias ){
51939             char *zTabName = pItem->zAlias;
51940             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51941           }else{
51942             char *zTabName = pTab->zName;
51943             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
51944             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
51945               continue;
51946             }
51947           }
51948         }
51949         if( 0==(cntTab++) ){
51950           pExpr->iTable = pItem->iCursor;
51951           pExpr->pTab = pTab;
51952           pSchema = pTab->pSchema;
51953           pMatch = pItem;
51954         }
51955         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
51956           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
51957             IdList *pUsing;
51958             cnt++;
51959             pExpr->iTable = pItem->iCursor;
51960             pExpr->pTab = pTab;
51961             pMatch = pItem;
51962             pSchema = pTab->pSchema;
51963             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
51964             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
51965             if( i<pSrcList->nSrc-1 ){
51966               if( pItem[1].jointype & JT_NATURAL ){
51967                 /* If this match occurred in the left table of a natural join,
51968                 ** then skip the right table to avoid a duplicate match */
51969                 pItem++;
51970                 i++;
51971               }else if( (pUsing = pItem[1].pUsing)!=0 ){
51972                 /* If this match occurs on a column that is in the USING clause
51973                 ** of a join, skip the search of the right table of the join
51974                 ** to avoid a duplicate match there. */
51975                 int k;
51976                 for(k=0; k<pUsing->nId; k++){
51977                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
51978                     pItem++;
51979                     i++;
51980                     break;
51981                   }
51982                 }
51983               }
51984             }
51985             break;
51986           }
51987         }
51988       }
51989     }
51990
51991 #ifndef SQLITE_OMIT_TRIGGER
51992     /* If we have not already resolved the name, then maybe 
51993     ** it is a new.* or old.* trigger argument reference
51994     */
51995     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
51996       TriggerStack *pTriggerStack = pParse->trigStack;
51997       Table *pTab = 0;
51998       u32 *piColMask;
51999       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
52000         pExpr->iTable = pTriggerStack->newIdx;
52001         assert( pTriggerStack->pTab );
52002         pTab = pTriggerStack->pTab;
52003         piColMask = &(pTriggerStack->newColMask);
52004       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
52005         pExpr->iTable = pTriggerStack->oldIdx;
52006         assert( pTriggerStack->pTab );
52007         pTab = pTriggerStack->pTab;
52008         piColMask = &(pTriggerStack->oldColMask);
52009       }
52010
52011       if( pTab ){ 
52012         int iCol;
52013         Column *pCol = pTab->aCol;
52014
52015         pSchema = pTab->pSchema;
52016         cntTab++;
52017         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
52018           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
52019             cnt++;
52020             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
52021             pExpr->pTab = pTab;
52022             if( iCol>=0 ){
52023               testcase( iCol==31 );
52024               testcase( iCol==32 );
52025               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
52026             }
52027             break;
52028           }
52029         }
52030       }
52031     }
52032 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
52033
52034     /*
52035     ** Perhaps the name is a reference to the ROWID
52036     */
52037     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
52038       cnt = 1;
52039       pExpr->iColumn = -1;
52040       pExpr->affinity = SQLITE_AFF_INTEGER;
52041     }
52042
52043     /*
52044     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
52045     ** might refer to an result-set alias.  This happens, for example, when
52046     ** we are resolving names in the WHERE clause of the following command:
52047     **
52048     **     SELECT a+b AS x FROM table WHERE x<10;
52049     **
52050     ** In cases like this, replace pExpr with a copy of the expression that
52051     ** forms the result set entry ("a+b" in the example) and return immediately.
52052     ** Note that the expression in the result set should have already been
52053     ** resolved by the time the WHERE clause is resolved.
52054     */
52055     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
52056       for(j=0; j<pEList->nExpr; j++){
52057         char *zAs = pEList->a[j].zName;
52058         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
52059           Expr *pOrig;
52060           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
52061           assert( pExpr->pList==0 );
52062           assert( pExpr->pSelect==0 );
52063           pOrig = pEList->a[j].pExpr;
52064           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
52065             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
52066             sqlite3DbFree(db, zCol);
52067             return 2;
52068           }
52069           resolveAlias(pParse, pEList, j, pExpr, "");
52070           cnt = 1;
52071           pMatch = 0;
52072           assert( zTab==0 && zDb==0 );
52073           goto lookupname_end_2;
52074         }
52075       } 
52076     }
52077
52078     /* Advance to the next name context.  The loop will exit when either
52079     ** we have a match (cnt>0) or when we run out of name contexts.
52080     */
52081     if( cnt==0 ){
52082       pNC = pNC->pNext;
52083     }
52084   }
52085
52086   /*
52087   ** If X and Y are NULL (in other words if only the column name Z is
52088   ** supplied) and the value of Z is enclosed in double-quotes, then
52089   ** Z is a string literal if it doesn't match any column names.  In that
52090   ** case, we need to return right away and not make any changes to
52091   ** pExpr.
52092   **
52093   ** Because no reference was made to outer contexts, the pNC->nRef
52094   ** fields are not changed in any context.
52095   */
52096   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
52097     sqlite3DbFree(db, zCol);
52098     pExpr->op = TK_STRING;
52099     return 0;
52100   }
52101
52102   /*
52103   ** cnt==0 means there was not match.  cnt>1 means there were two or
52104   ** more matches.  Either way, we have an error.
52105   */
52106   if( cnt!=1 ){
52107     const char *zErr;
52108     zErr = cnt==0 ? "no such column" : "ambiguous column name";
52109     if( zDb ){
52110       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
52111     }else if( zTab ){
52112       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
52113     }else{
52114       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
52115     }
52116     pTopNC->nErr++;
52117   }
52118
52119   /* If a column from a table in pSrcList is referenced, then record
52120   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
52121   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
52122   ** column number is greater than the number of bits in the bitmask
52123   ** then set the high-order bit of the bitmask.
52124   */
52125   if( pExpr->iColumn>=0 && pMatch!=0 ){
52126     int n = pExpr->iColumn;
52127     testcase( n==sizeof(Bitmask)*8-1 );
52128     if( n>=sizeof(Bitmask)*8 ){
52129       n = sizeof(Bitmask)*8-1;
52130     }
52131     assert( pMatch->iCursor==pExpr->iTable );
52132     pMatch->colUsed |= ((Bitmask)1)<<n;
52133   }
52134
52135 lookupname_end:
52136   /* Clean up and return
52137   */
52138   sqlite3DbFree(db, zDb);
52139   sqlite3DbFree(db, zTab);
52140   sqlite3ExprDelete(db, pExpr->pLeft);
52141   pExpr->pLeft = 0;
52142   sqlite3ExprDelete(db, pExpr->pRight);
52143   pExpr->pRight = 0;
52144   pExpr->op = TK_COLUMN;
52145 lookupname_end_2:
52146   sqlite3DbFree(db, zCol);
52147   if( cnt==1 ){
52148     assert( pNC!=0 );
52149     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
52150     /* Increment the nRef value on all name contexts from TopNC up to
52151     ** the point where the name matched. */
52152     for(;;){
52153       assert( pTopNC!=0 );
52154       pTopNC->nRef++;
52155       if( pTopNC==pNC ) break;
52156       pTopNC = pTopNC->pNext;
52157     }
52158     return 0;
52159   } else {
52160     return 1;
52161   }
52162 }
52163
52164 /*
52165 ** This routine is callback for sqlite3WalkExpr().
52166 **
52167 ** Resolve symbolic names into TK_COLUMN operators for the current
52168 ** node in the expression tree.  Return 0 to continue the search down
52169 ** the tree or 2 to abort the tree walk.
52170 **
52171 ** This routine also does error checking and name resolution for
52172 ** function names.  The operator for aggregate functions is changed
52173 ** to TK_AGG_FUNCTION.
52174 */
52175 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
52176   NameContext *pNC;
52177   Parse *pParse;
52178
52179   pNC = pWalker->u.pNC;
52180   assert( pNC!=0 );
52181   pParse = pNC->pParse;
52182   assert( pParse==pWalker->pParse );
52183
52184   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
52185   ExprSetProperty(pExpr, EP_Resolved);
52186 #ifndef NDEBUG
52187   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
52188     SrcList *pSrcList = pNC->pSrcList;
52189     int i;
52190     for(i=0; i<pNC->pSrcList->nSrc; i++){
52191       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
52192     }
52193   }
52194 #endif
52195   switch( pExpr->op ){
52196
52197 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
52198     /* The special operator TK_ROW means use the rowid for the first
52199     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
52200     ** clause processing on UPDATE and DELETE statements.
52201     */
52202     case TK_ROW: {
52203       SrcList *pSrcList = pNC->pSrcList;
52204       struct SrcList_item *pItem;
52205       assert( pSrcList && pSrcList->nSrc==1 );
52206       pItem = pSrcList->a; 
52207       pExpr->op = TK_COLUMN;
52208       pExpr->pTab = pItem->pTab;
52209       pExpr->iTable = pItem->iCursor;
52210       pExpr->iColumn = -1;
52211       pExpr->affinity = SQLITE_AFF_INTEGER;
52212       break;
52213     }
52214 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
52215
52216     /* A lone identifier is the name of a column.
52217     */
52218     case TK_ID: {
52219       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
52220       return WRC_Prune;
52221     }
52222   
52223     /* A table name and column name:     ID.ID
52224     ** Or a database, table and column:  ID.ID.ID
52225     */
52226     case TK_DOT: {
52227       Token *pColumn;
52228       Token *pTable;
52229       Token *pDb;
52230       Expr *pRight;
52231
52232       /* if( pSrcList==0 ) break; */
52233       pRight = pExpr->pRight;
52234       if( pRight->op==TK_ID ){
52235         pDb = 0;
52236         pTable = &pExpr->pLeft->token;
52237         pColumn = &pRight->token;
52238       }else{
52239         assert( pRight->op==TK_DOT );
52240         pDb = &pExpr->pLeft->token;
52241         pTable = &pRight->pLeft->token;
52242         pColumn = &pRight->pRight->token;
52243       }
52244       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
52245       return WRC_Prune;
52246     }
52247
52248     /* Resolve function names
52249     */
52250     case TK_CONST_FUNC:
52251     case TK_FUNCTION: {
52252       ExprList *pList = pExpr->pList;    /* The argument list */
52253       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
52254       int no_such_func = 0;       /* True if no such function exists */
52255       int wrong_num_args = 0;     /* True if wrong number of arguments */
52256       int is_agg = 0;             /* True if is an aggregate function */
52257       int auth;                   /* Authorization to use the function */
52258       int nId;                    /* Number of characters in function name */
52259       const char *zId;            /* The function name. */
52260       FuncDef *pDef;              /* Information about the function */
52261       int enc = ENC(pParse->db);  /* The database encoding */
52262
52263       zId = (char*)pExpr->token.z;
52264       nId = pExpr->token.n;
52265       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
52266       if( pDef==0 ){
52267         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
52268         if( pDef==0 ){
52269           no_such_func = 1;
52270         }else{
52271           wrong_num_args = 1;
52272         }
52273       }else{
52274         is_agg = pDef->xFunc==0;
52275       }
52276 #ifndef SQLITE_OMIT_AUTHORIZATION
52277       if( pDef ){
52278         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
52279         if( auth!=SQLITE_OK ){
52280           if( auth==SQLITE_DENY ){
52281             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
52282                                     pDef->zName);
52283             pNC->nErr++;
52284           }
52285           pExpr->op = TK_NULL;
52286           return WRC_Prune;
52287         }
52288       }
52289 #endif
52290       if( is_agg && !pNC->allowAgg ){
52291         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
52292         pNC->nErr++;
52293         is_agg = 0;
52294       }else if( no_such_func ){
52295         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
52296         pNC->nErr++;
52297       }else if( wrong_num_args ){
52298         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
52299              nId, zId);
52300         pNC->nErr++;
52301       }
52302       if( is_agg ){
52303         pExpr->op = TK_AGG_FUNCTION;
52304         pNC->hasAgg = 1;
52305       }
52306       if( is_agg ) pNC->allowAgg = 0;
52307       sqlite3WalkExprList(pWalker, pList);
52308       if( is_agg ) pNC->allowAgg = 1;
52309       /* FIX ME:  Compute pExpr->affinity based on the expected return
52310       ** type of the function 
52311       */
52312       return WRC_Prune;
52313     }
52314 #ifndef SQLITE_OMIT_SUBQUERY
52315     case TK_SELECT:
52316     case TK_EXISTS:
52317 #endif
52318     case TK_IN: {
52319       if( pExpr->pSelect ){
52320         int nRef = pNC->nRef;
52321 #ifndef SQLITE_OMIT_CHECK
52322         if( pNC->isCheck ){
52323           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
52324         }
52325 #endif
52326         sqlite3WalkSelect(pWalker, pExpr->pSelect);
52327         assert( pNC->nRef>=nRef );
52328         if( nRef!=pNC->nRef ){
52329           ExprSetProperty(pExpr, EP_VarSelect);
52330         }
52331       }
52332       break;
52333     }
52334 #ifndef SQLITE_OMIT_CHECK
52335     case TK_VARIABLE: {
52336       if( pNC->isCheck ){
52337         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
52338       }
52339       break;
52340     }
52341 #endif
52342   }
52343   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
52344 }
52345
52346 /*
52347 ** pEList is a list of expressions which are really the result set of the
52348 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
52349 ** This routine checks to see if pE is a simple identifier which corresponds
52350 ** to the AS-name of one of the terms of the expression list.  If it is,
52351 ** this routine return an integer between 1 and N where N is the number of
52352 ** elements in pEList, corresponding to the matching entry.  If there is
52353 ** no match, or if pE is not a simple identifier, then this routine
52354 ** return 0.
52355 **
52356 ** pEList has been resolved.  pE has not.
52357 */
52358 static int resolveAsName(
52359   Parse *pParse,     /* Parsing context for error messages */
52360   ExprList *pEList,  /* List of expressions to scan */
52361   Expr *pE           /* Expression we are trying to match */
52362 ){
52363   int i;             /* Loop counter */
52364
52365   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
52366     sqlite3 *db = pParse->db;
52367     char *zCol = sqlite3NameFromToken(db, &pE->token);
52368     if( zCol==0 ){
52369       return -1;
52370     }
52371     for(i=0; i<pEList->nExpr; i++){
52372       char *zAs = pEList->a[i].zName;
52373       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
52374         sqlite3DbFree(db, zCol);
52375         return i+1;
52376       }
52377     }
52378     sqlite3DbFree(db, zCol);
52379   }
52380   return 0;
52381 }
52382
52383 /*
52384 ** pE is a pointer to an expression which is a single term in the
52385 ** ORDER BY of a compound SELECT.  The expression has not been
52386 ** name resolved.
52387 **
52388 ** At the point this routine is called, we already know that the
52389 ** ORDER BY term is not an integer index into the result set.  That
52390 ** case is handled by the calling routine.
52391 **
52392 ** Attempt to match pE against result set columns in the left-most
52393 ** SELECT statement.  Return the index i of the matching column,
52394 ** as an indication to the caller that it should sort by the i-th column.
52395 ** The left-most column is 1.  In other words, the value returned is the
52396 ** same integer value that would be used in the SQL statement to indicate
52397 ** the column.
52398 **
52399 ** If there is no match, return 0.  Return -1 if an error occurs.
52400 */
52401 static int resolveOrderByTermToExprList(
52402   Parse *pParse,     /* Parsing context for error messages */
52403   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
52404   Expr *pE           /* The specific ORDER BY term */
52405 ){
52406   int i;             /* Loop counter */
52407   ExprList *pEList;  /* The columns of the result set */
52408   NameContext nc;    /* Name context for resolving pE */
52409
52410   assert( sqlite3ExprIsInteger(pE, &i)==0 );
52411   pEList = pSelect->pEList;
52412
52413   /* Resolve all names in the ORDER BY term expression
52414   */
52415   memset(&nc, 0, sizeof(nc));
52416   nc.pParse = pParse;
52417   nc.pSrcList = pSelect->pSrc;
52418   nc.pEList = pEList;
52419   nc.allowAgg = 1;
52420   nc.nErr = 0;
52421   if( sqlite3ResolveExprNames(&nc, pE) ){
52422     sqlite3ErrorClear(pParse);
52423     return 0;
52424   }
52425
52426   /* Try to match the ORDER BY expression against an expression
52427   ** in the result set.  Return an 1-based index of the matching
52428   ** result-set entry.
52429   */
52430   for(i=0; i<pEList->nExpr; i++){
52431     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
52432       return i+1;
52433     }
52434   }
52435
52436   /* If no match, return 0. */
52437   return 0;
52438 }
52439
52440 /*
52441 ** Generate an ORDER BY or GROUP BY term out-of-range error.
52442 */
52443 static void resolveOutOfRangeError(
52444   Parse *pParse,         /* The error context into which to write the error */
52445   const char *zType,     /* "ORDER" or "GROUP" */
52446   int i,                 /* The index (1-based) of the term out of range */
52447   int mx                 /* Largest permissible value of i */
52448 ){
52449   sqlite3ErrorMsg(pParse, 
52450     "%r %s BY term out of range - should be "
52451     "between 1 and %d", i, zType, mx);
52452 }
52453
52454 /*
52455 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
52456 ** each term of the ORDER BY clause is a constant integer between 1
52457 ** and N where N is the number of columns in the compound SELECT.
52458 **
52459 ** ORDER BY terms that are already an integer between 1 and N are
52460 ** unmodified.  ORDER BY terms that are integers outside the range of
52461 ** 1 through N generate an error.  ORDER BY terms that are expressions
52462 ** are matched against result set expressions of compound SELECT
52463 ** beginning with the left-most SELECT and working toward the right.
52464 ** At the first match, the ORDER BY expression is transformed into
52465 ** the integer column number.
52466 **
52467 ** Return the number of errors seen.
52468 */
52469 static int resolveCompoundOrderBy(
52470   Parse *pParse,        /* Parsing context.  Leave error messages here */
52471   Select *pSelect       /* The SELECT statement containing the ORDER BY */
52472 ){
52473   int i;
52474   ExprList *pOrderBy;
52475   ExprList *pEList;
52476   sqlite3 *db;
52477   int moreToDo = 1;
52478
52479   pOrderBy = pSelect->pOrderBy;
52480   if( pOrderBy==0 ) return 0;
52481   db = pParse->db;
52482 #if SQLITE_MAX_COLUMN
52483   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
52484     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
52485     return 1;
52486   }
52487 #endif
52488   for(i=0; i<pOrderBy->nExpr; i++){
52489     pOrderBy->a[i].done = 0;
52490   }
52491   pSelect->pNext = 0;
52492   while( pSelect->pPrior ){
52493     pSelect->pPrior->pNext = pSelect;
52494     pSelect = pSelect->pPrior;
52495   }
52496   while( pSelect && moreToDo ){
52497     struct ExprList_item *pItem;
52498     moreToDo = 0;
52499     pEList = pSelect->pEList;
52500     assert( pEList!=0 );
52501     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52502       int iCol = -1;
52503       Expr *pE, *pDup;
52504       if( pItem->done ) continue;
52505       pE = pItem->pExpr;
52506       if( sqlite3ExprIsInteger(pE, &iCol) ){
52507         if( iCol<0 || iCol>pEList->nExpr ){
52508           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
52509           return 1;
52510         }
52511       }else{
52512         iCol = resolveAsName(pParse, pEList, pE);
52513         if( iCol==0 ){
52514           pDup = sqlite3ExprDup(db, pE);
52515           if( !db->mallocFailed ){
52516             assert(pDup);
52517             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
52518           }
52519           sqlite3ExprDelete(db, pDup);
52520         }
52521         if( iCol<0 ){
52522           return 1;
52523         }
52524       }
52525       if( iCol>0 ){
52526         CollSeq *pColl = pE->pColl;
52527         int flags = pE->flags & EP_ExpCollate;
52528         sqlite3ExprDelete(db, pE);
52529         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
52530         if( pE==0 ) return 1;
52531         pE->pColl = pColl;
52532         pE->flags |= EP_IntValue | flags;
52533         pE->iTable = iCol;
52534         pItem->iCol = iCol;
52535         pItem->done = 1;
52536       }else{
52537         moreToDo = 1;
52538       }
52539     }
52540     pSelect = pSelect->pNext;
52541   }
52542   for(i=0; i<pOrderBy->nExpr; i++){
52543     if( pOrderBy->a[i].done==0 ){
52544       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
52545             "column in the result set", i+1);
52546       return 1;
52547     }
52548   }
52549   return 0;
52550 }
52551
52552 /*
52553 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
52554 ** the SELECT statement pSelect.  If any term is reference to a
52555 ** result set expression (as determined by the ExprList.a.iCol field)
52556 ** then convert that term into a copy of the corresponding result set
52557 ** column.
52558 **
52559 ** If any errors are detected, add an error message to pParse and
52560 ** return non-zero.  Return zero if no errors are seen.
52561 */
52562 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
52563   Parse *pParse,        /* Parsing context.  Leave error messages here */
52564   Select *pSelect,      /* The SELECT statement containing the clause */
52565   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
52566   const char *zType     /* "ORDER" or "GROUP" */
52567 ){
52568   int i;
52569   sqlite3 *db = pParse->db;
52570   ExprList *pEList;
52571   struct ExprList_item *pItem;
52572
52573   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
52574 #if SQLITE_MAX_COLUMN
52575   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
52576     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
52577     return 1;
52578   }
52579 #endif
52580   pEList = pSelect->pEList;
52581   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
52582   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52583     if( pItem->iCol ){
52584       if( pItem->iCol>pEList->nExpr ){
52585         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
52586         return 1;
52587       }
52588       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
52589     }
52590   }
52591   return 0;
52592 }
52593
52594 /*
52595 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
52596 ** The Name context of the SELECT statement is pNC.  zType is either
52597 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
52598 **
52599 ** This routine resolves each term of the clause into an expression.
52600 ** If the order-by term is an integer I between 1 and N (where N is the
52601 ** number of columns in the result set of the SELECT) then the expression
52602 ** in the resolution is a copy of the I-th result-set expression.  If
52603 ** the order-by term is an identify that corresponds to the AS-name of
52604 ** a result-set expression, then the term resolves to a copy of the
52605 ** result-set expression.  Otherwise, the expression is resolved in
52606 ** the usual way - using sqlite3ResolveExprNames().
52607 **
52608 ** This routine returns the number of errors.  If errors occur, then
52609 ** an appropriate error message might be left in pParse.  (OOM errors
52610 ** excepted.)
52611 */
52612 static int resolveOrderGroupBy(
52613   NameContext *pNC,     /* The name context of the SELECT statement */
52614   Select *pSelect,      /* The SELECT statement holding pOrderBy */
52615   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
52616   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
52617 ){
52618   int i;                         /* Loop counter */
52619   int iCol;                      /* Column number */
52620   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
52621   Parse *pParse;                 /* Parsing context */
52622   int nResult;                   /* Number of terms in the result set */
52623
52624   if( pOrderBy==0 ) return 0;
52625   nResult = pSelect->pEList->nExpr;
52626   pParse = pNC->pParse;
52627   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
52628     Expr *pE = pItem->pExpr;
52629     iCol = resolveAsName(pParse, pSelect->pEList, pE);
52630     if( iCol<0 ){
52631       return 1;  /* OOM error */
52632     }
52633     if( iCol>0 ){
52634       /* If an AS-name match is found, mark this ORDER BY column as being
52635       ** a copy of the iCol-th result-set column.  The subsequent call to
52636       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
52637       ** copy of the iCol-th result-set expression. */
52638       pItem->iCol = iCol;
52639       continue;
52640     }
52641     if( sqlite3ExprIsInteger(pE, &iCol) ){
52642       /* The ORDER BY term is an integer constant.  Again, set the column
52643       ** number so that sqlite3ResolveOrderGroupBy() will convert the
52644       ** order-by term to a copy of the result-set expression */
52645       if( iCol<1 ){
52646         resolveOutOfRangeError(pParse, zType, i+1, nResult);
52647         return 1;
52648       }
52649       pItem->iCol = iCol;
52650       continue;
52651     }
52652
52653     /* Otherwise, treat the ORDER BY term as an ordinary expression */
52654     pItem->iCol = 0;
52655     if( sqlite3ResolveExprNames(pNC, pE) ){
52656       return 1;
52657     }
52658   }
52659   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
52660 }
52661
52662 /*
52663 ** Resolve names in the SELECT statement p and all of its descendents.
52664 */
52665 static int resolveSelectStep(Walker *pWalker, Select *p){
52666   NameContext *pOuterNC;  /* Context that contains this SELECT */
52667   NameContext sNC;        /* Name context of this SELECT */
52668   int isCompound;         /* True if p is a compound select */
52669   int nCompound;          /* Number of compound terms processed so far */
52670   Parse *pParse;          /* Parsing context */
52671   ExprList *pEList;       /* Result set expression list */
52672   int i;                  /* Loop counter */
52673   ExprList *pGroupBy;     /* The GROUP BY clause */
52674   Select *pLeftmost;      /* Left-most of SELECT of a compound */
52675   sqlite3 *db;            /* Database connection */
52676   
52677
52678   assert( p!=0 );
52679   if( p->selFlags & SF_Resolved ){
52680     return WRC_Prune;
52681   }
52682   pOuterNC = pWalker->u.pNC;
52683   pParse = pWalker->pParse;
52684   db = pParse->db;
52685
52686   /* Normally sqlite3SelectExpand() will be called first and will have
52687   ** already expanded this SELECT.  However, if this is a subquery within
52688   ** an expression, sqlite3ResolveExprNames() will be called without a
52689   ** prior call to sqlite3SelectExpand().  When that happens, let
52690   ** sqlite3SelectPrep() do all of the processing for this SELECT.
52691   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
52692   ** this routine in the correct order.
52693   */
52694   if( (p->selFlags & SF_Expanded)==0 ){
52695     sqlite3SelectPrep(pParse, p, pOuterNC);
52696     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
52697   }
52698
52699   isCompound = p->pPrior!=0;
52700   nCompound = 0;
52701   pLeftmost = p;
52702   while( p ){
52703     assert( (p->selFlags & SF_Expanded)!=0 );
52704     assert( (p->selFlags & SF_Resolved)==0 );
52705     p->selFlags |= SF_Resolved;
52706
52707     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
52708     ** are not allowed to refer to any names, so pass an empty NameContext.
52709     */
52710     memset(&sNC, 0, sizeof(sNC));
52711     sNC.pParse = pParse;
52712     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
52713         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
52714       return WRC_Abort;
52715     }
52716   
52717     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
52718     ** resolve the result-set expression list.
52719     */
52720     sNC.allowAgg = 1;
52721     sNC.pSrcList = p->pSrc;
52722     sNC.pNext = pOuterNC;
52723   
52724     /* Resolve names in the result set. */
52725     pEList = p->pEList;
52726     assert( pEList!=0 );
52727     for(i=0; i<pEList->nExpr; i++){
52728       Expr *pX = pEList->a[i].pExpr;
52729       if( sqlite3ResolveExprNames(&sNC, pX) ){
52730         return WRC_Abort;
52731       }
52732     }
52733   
52734     /* Recursively resolve names in all subqueries
52735     */
52736     for(i=0; i<p->pSrc->nSrc; i++){
52737       struct SrcList_item *pItem = &p->pSrc->a[i];
52738       if( pItem->pSelect ){
52739         const char *zSavedContext = pParse->zAuthContext;
52740         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
52741         sqlite3ResolveSelectNames(pParse, pItem->pSelect, &sNC);
52742         pParse->zAuthContext = zSavedContext;
52743         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
52744       }
52745     }
52746   
52747     /* If there are no aggregate functions in the result-set, and no GROUP BY 
52748     ** expression, do not allow aggregates in any of the other expressions.
52749     */
52750     assert( (p->selFlags & SF_Aggregate)==0 );
52751     pGroupBy = p->pGroupBy;
52752     if( pGroupBy || sNC.hasAgg ){
52753       p->selFlags |= SF_Aggregate;
52754     }else{
52755       sNC.allowAgg = 0;
52756     }
52757   
52758     /* If a HAVING clause is present, then there must be a GROUP BY clause.
52759     */
52760     if( p->pHaving && !pGroupBy ){
52761       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
52762       return WRC_Abort;
52763     }
52764   
52765     /* Add the expression list to the name-context before parsing the
52766     ** other expressions in the SELECT statement. This is so that
52767     ** expressions in the WHERE clause (etc.) can refer to expressions by
52768     ** aliases in the result set.
52769     **
52770     ** Minor point: If this is the case, then the expression will be
52771     ** re-evaluated for each reference to it.
52772     */
52773     sNC.pEList = p->pEList;
52774     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
52775        sqlite3ResolveExprNames(&sNC, p->pHaving)
52776     ){
52777       return WRC_Abort;
52778     }
52779
52780     /* The ORDER BY and GROUP BY clauses may not refer to terms in
52781     ** outer queries 
52782     */
52783     sNC.pNext = 0;
52784     sNC.allowAgg = 1;
52785
52786     /* Process the ORDER BY clause for singleton SELECT statements.
52787     ** The ORDER BY clause for compounds SELECT statements is handled
52788     ** below, after all of the result-sets for all of the elements of
52789     ** the compound have been resolved.
52790     */
52791     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
52792       return WRC_Abort;
52793     }
52794     if( db->mallocFailed ){
52795       return WRC_Abort;
52796     }
52797   
52798     /* Resolve the GROUP BY clause.  At the same time, make sure 
52799     ** the GROUP BY clause does not contain aggregate functions.
52800     */
52801     if( pGroupBy ){
52802       struct ExprList_item *pItem;
52803     
52804       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
52805         return WRC_Abort;
52806       }
52807       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
52808         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
52809           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
52810               "the GROUP BY clause");
52811           return WRC_Abort;
52812         }
52813       }
52814     }
52815
52816     /* Advance to the next term of the compound
52817     */
52818     p = p->pPrior;
52819     nCompound++;
52820   }
52821
52822   /* Resolve the ORDER BY on a compound SELECT after all terms of
52823   ** the compound have been resolved.
52824   */
52825   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
52826     return WRC_Abort;
52827   }
52828
52829   return WRC_Prune;
52830 }
52831
52832 /*
52833 ** This routine walks an expression tree and resolves references to
52834 ** table columns and result-set columns.  At the same time, do error
52835 ** checking on function usage and set a flag if any aggregate functions
52836 ** are seen.
52837 **
52838 ** To resolve table columns references we look for nodes (or subtrees) of the 
52839 ** form X.Y.Z or Y.Z or just Z where
52840 **
52841 **      X:   The name of a database.  Ex:  "main" or "temp" or
52842 **           the symbolic name assigned to an ATTACH-ed database.
52843 **
52844 **      Y:   The name of a table in a FROM clause.  Or in a trigger
52845 **           one of the special names "old" or "new".
52846 **
52847 **      Z:   The name of a column in table Y.
52848 **
52849 ** The node at the root of the subtree is modified as follows:
52850 **
52851 **    Expr.op        Changed to TK_COLUMN
52852 **    Expr.pTab      Points to the Table object for X.Y
52853 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
52854 **    Expr.iTable    The VDBE cursor number for X.Y
52855 **
52856 **
52857 ** To resolve result-set references, look for expression nodes of the
52858 ** form Z (with no X and Y prefix) where the Z matches the right-hand
52859 ** size of an AS clause in the result-set of a SELECT.  The Z expression
52860 ** is replaced by a copy of the left-hand side of the result-set expression.
52861 ** Table-name and function resolution occurs on the substituted expression
52862 ** tree.  For example, in:
52863 **
52864 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
52865 **
52866 ** The "x" term of the order by is replaced by "a+b" to render:
52867 **
52868 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
52869 **
52870 ** Function calls are checked to make sure that the function is 
52871 ** defined and that the correct number of arguments are specified.
52872 ** If the function is an aggregate function, then the pNC->hasAgg is
52873 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
52874 ** If an expression contains aggregate functions then the EP_Agg
52875 ** property on the expression is set.
52876 **
52877 ** An error message is left in pParse if anything is amiss.  The number
52878 ** if errors is returned.
52879 */
52880 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
52881   NameContext *pNC,       /* Namespace to resolve expressions in. */
52882   Expr *pExpr             /* The expression to be analyzed. */
52883 ){
52884   int savedHasAgg;
52885   Walker w;
52886
52887   if( pExpr==0 ) return 0;
52888 #if SQLITE_MAX_EXPR_DEPTH>0
52889   {
52890     Parse *pParse = pNC->pParse;
52891     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
52892       return 1;
52893     }
52894     pParse->nHeight += pExpr->nHeight;
52895   }
52896 #endif
52897   savedHasAgg = pNC->hasAgg;
52898   pNC->hasAgg = 0;
52899   w.xExprCallback = resolveExprStep;
52900   w.xSelectCallback = resolveSelectStep;
52901   w.pParse = pNC->pParse;
52902   w.u.pNC = pNC;
52903   sqlite3WalkExpr(&w, pExpr);
52904 #if SQLITE_MAX_EXPR_DEPTH>0
52905   pNC->pParse->nHeight -= pExpr->nHeight;
52906 #endif
52907   if( pNC->nErr>0 ){
52908     ExprSetProperty(pExpr, EP_Error);
52909   }
52910   if( pNC->hasAgg ){
52911     ExprSetProperty(pExpr, EP_Agg);
52912   }else if( savedHasAgg ){
52913     pNC->hasAgg = 1;
52914   }
52915   return ExprHasProperty(pExpr, EP_Error);
52916 }
52917
52918
52919 /*
52920 ** Resolve all names in all expressions of a SELECT and in all
52921 ** decendents of the SELECT, including compounds off of p->pPrior,
52922 ** subqueries in expressions, and subqueries used as FROM clause
52923 ** terms.
52924 **
52925 ** See sqlite3ResolveExprNames() for a description of the kinds of
52926 ** transformations that occur.
52927 **
52928 ** All SELECT statements should have been expanded using
52929 ** sqlite3SelectExpand() prior to invoking this routine.
52930 */
52931 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
52932   Parse *pParse,         /* The parser context */
52933   Select *p,             /* The SELECT statement being coded. */
52934   NameContext *pOuterNC  /* Name context for parent SELECT statement */
52935 ){
52936   Walker w;
52937
52938   assert( p!=0 );
52939   w.xExprCallback = resolveExprStep;
52940   w.xSelectCallback = resolveSelectStep;
52941   w.pParse = pParse;
52942   w.u.pNC = pOuterNC;
52943   sqlite3WalkSelect(&w, p);
52944 }
52945
52946 /************** End of resolve.c *********************************************/
52947 /************** Begin file expr.c ********************************************/
52948 /*
52949 ** 2001 September 15
52950 **
52951 ** The author disclaims copyright to this source code.  In place of
52952 ** a legal notice, here is a blessing:
52953 **
52954 **    May you do good and not evil.
52955 **    May you find forgiveness for yourself and forgive others.
52956 **    May you share freely, never taking more than you give.
52957 **
52958 *************************************************************************
52959 ** This file contains routines used for analyzing expressions and
52960 ** for generating VDBE code that evaluates expressions in SQLite.
52961 **
52962 ** $Id: expr.c,v 1.399 2008/10/11 16:47:36 drh Exp $
52963 */
52964
52965 /*
52966 ** Return the 'affinity' of the expression pExpr if any.
52967 **
52968 ** If pExpr is a column, a reference to a column via an 'AS' alias,
52969 ** or a sub-select with a column as the return value, then the 
52970 ** affinity of that column is returned. Otherwise, 0x00 is returned,
52971 ** indicating no affinity for the expression.
52972 **
52973 ** i.e. the WHERE clause expresssions in the following statements all
52974 ** have an affinity:
52975 **
52976 ** CREATE TABLE t1(a);
52977 ** SELECT * FROM t1 WHERE a;
52978 ** SELECT a AS b FROM t1 WHERE b;
52979 ** SELECT * FROM t1 WHERE (select a from t1);
52980 */
52981 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
52982   int op = pExpr->op;
52983   if( op==TK_SELECT ){
52984     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
52985   }
52986 #ifndef SQLITE_OMIT_CAST
52987   if( op==TK_CAST ){
52988     return sqlite3AffinityType(&pExpr->token);
52989   }
52990 #endif
52991   if( (op==TK_COLUMN || op==TK_REGISTER) && pExpr->pTab!=0 ){
52992     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
52993     ** a TK_COLUMN but was previously evaluated and cached in a register */
52994     int j = pExpr->iColumn;
52995     if( j<0 ) return SQLITE_AFF_INTEGER;
52996     assert( pExpr->pTab && j<pExpr->pTab->nCol );
52997     return pExpr->pTab->aCol[j].affinity;
52998   }
52999   return pExpr->affinity;
53000 }
53001
53002 /*
53003 ** Set the collating sequence for expression pExpr to be the collating
53004 ** sequence named by pToken.   Return a pointer to the revised expression.
53005 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
53006 ** flag.  An explicit collating sequence will override implicit
53007 ** collating sequences.
53008 */
53009 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
53010   char *zColl = 0;            /* Dequoted name of collation sequence */
53011   CollSeq *pColl;
53012   sqlite3 *db = pParse->db;
53013   zColl = sqlite3NameFromToken(db, pCollName);
53014   if( pExpr && zColl ){
53015     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
53016     if( pColl ){
53017       pExpr->pColl = pColl;
53018       pExpr->flags |= EP_ExpCollate;
53019     }
53020   }
53021   sqlite3DbFree(db, zColl);
53022   return pExpr;
53023 }
53024
53025 /*
53026 ** Return the default collation sequence for the expression pExpr. If
53027 ** there is no default collation type, return 0.
53028 */
53029 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
53030   CollSeq *pColl = 0;
53031   Expr *p = pExpr;
53032   while( p ){
53033     int op;
53034     pColl = p->pColl;
53035     if( pColl ) break;
53036     op = p->op;
53037     if( (op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
53038       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
53039       ** a TK_COLUMN but was previously evaluated and cached in a register */
53040       const char *zColl;
53041       int j = p->iColumn;
53042       if( j>=0 ){
53043         sqlite3 *db = pParse->db;
53044         zColl = p->pTab->aCol[j].zColl;
53045         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
53046         pExpr->pColl = pColl;
53047       }
53048       break;
53049     }
53050     if( op!=TK_CAST && op!=TK_UPLUS ){
53051       break;
53052     }
53053     p = p->pLeft;
53054   }
53055   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
53056     pColl = 0;
53057   }
53058   return pColl;
53059 }
53060
53061 /*
53062 ** pExpr is an operand of a comparison operator.  aff2 is the
53063 ** type affinity of the other operand.  This routine returns the
53064 ** type affinity that should be used for the comparison operator.
53065 */
53066 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
53067   char aff1 = sqlite3ExprAffinity(pExpr);
53068   if( aff1 && aff2 ){
53069     /* Both sides of the comparison are columns. If one has numeric
53070     ** affinity, use that. Otherwise use no affinity.
53071     */
53072     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
53073       return SQLITE_AFF_NUMERIC;
53074     }else{
53075       return SQLITE_AFF_NONE;
53076     }
53077   }else if( !aff1 && !aff2 ){
53078     /* Neither side of the comparison is a column.  Compare the
53079     ** results directly.
53080     */
53081     return SQLITE_AFF_NONE;
53082   }else{
53083     /* One side is a column, the other is not. Use the columns affinity. */
53084     assert( aff1==0 || aff2==0 );
53085     return (aff1 + aff2);
53086   }
53087 }
53088
53089 /*
53090 ** pExpr is a comparison operator.  Return the type affinity that should
53091 ** be applied to both operands prior to doing the comparison.
53092 */
53093 static char comparisonAffinity(Expr *pExpr){
53094   char aff;
53095   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
53096           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
53097           pExpr->op==TK_NE );
53098   assert( pExpr->pLeft );
53099   aff = sqlite3ExprAffinity(pExpr->pLeft);
53100   if( pExpr->pRight ){
53101     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
53102   }
53103   else if( pExpr->pSelect ){
53104     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
53105   }
53106   else if( !aff ){
53107     aff = SQLITE_AFF_NONE;
53108   }
53109   return aff;
53110 }
53111
53112 /*
53113 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
53114 ** idx_affinity is the affinity of an indexed column. Return true
53115 ** if the index with affinity idx_affinity may be used to implement
53116 ** the comparison in pExpr.
53117 */
53118 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
53119   char aff = comparisonAffinity(pExpr);
53120   switch( aff ){
53121     case SQLITE_AFF_NONE:
53122       return 1;
53123     case SQLITE_AFF_TEXT:
53124       return idx_affinity==SQLITE_AFF_TEXT;
53125     default:
53126       return sqlite3IsNumericAffinity(idx_affinity);
53127   }
53128 }
53129
53130 /*
53131 ** Return the P5 value that should be used for a binary comparison
53132 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
53133 */
53134 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
53135   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
53136   aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
53137   return aff;
53138 }
53139
53140 /*
53141 ** Return a pointer to the collation sequence that should be used by
53142 ** a binary comparison operator comparing pLeft and pRight.
53143 **
53144 ** If the left hand expression has a collating sequence type, then it is
53145 ** used. Otherwise the collation sequence for the right hand expression
53146 ** is used, or the default (BINARY) if neither expression has a collating
53147 ** type.
53148 **
53149 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
53150 ** it is not considered.
53151 */
53152 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
53153   Parse *pParse, 
53154   Expr *pLeft, 
53155   Expr *pRight
53156 ){
53157   CollSeq *pColl;
53158   assert( pLeft );
53159   if( pLeft->flags & EP_ExpCollate ){
53160     assert( pLeft->pColl );
53161     pColl = pLeft->pColl;
53162   }else if( pRight && pRight->flags & EP_ExpCollate ){
53163     assert( pRight->pColl );
53164     pColl = pRight->pColl;
53165   }else{
53166     pColl = sqlite3ExprCollSeq(pParse, pLeft);
53167     if( !pColl ){
53168       pColl = sqlite3ExprCollSeq(pParse, pRight);
53169     }
53170   }
53171   return pColl;
53172 }
53173
53174 /*
53175 ** Generate the operands for a comparison operation.  Before
53176 ** generating the code for each operand, set the EP_AnyAff
53177 ** flag on the expression so that it will be able to used a
53178 ** cached column value that has previously undergone an
53179 ** affinity change.
53180 */
53181 static void codeCompareOperands(
53182   Parse *pParse,    /* Parsing and code generating context */
53183   Expr *pLeft,      /* The left operand */
53184   int *pRegLeft,    /* Register where left operand is stored */
53185   int *pFreeLeft,   /* Free this register when done */
53186   Expr *pRight,     /* The right operand */
53187   int *pRegRight,   /* Register where right operand is stored */
53188   int *pFreeRight   /* Write temp register for right operand there */
53189 ){
53190   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
53191   pLeft->flags |= EP_AnyAff;
53192   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
53193   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
53194   pRight->flags |= EP_AnyAff;
53195   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
53196 }
53197
53198 /*
53199 ** Generate code for a comparison operator.
53200 */
53201 static int codeCompare(
53202   Parse *pParse,    /* The parsing (and code generating) context */
53203   Expr *pLeft,      /* The left operand */
53204   Expr *pRight,     /* The right operand */
53205   int opcode,       /* The comparison opcode */
53206   int in1, int in2, /* Register holding operands */
53207   int dest,         /* Jump here if true.  */
53208   int jumpIfNull    /* If true, jump if either operand is NULL */
53209 ){
53210   int p5;
53211   int addr;
53212   CollSeq *p4;
53213
53214   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
53215   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
53216   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
53217                            (void*)p4, P4_COLLSEQ);
53218   sqlite3VdbeChangeP5(pParse->pVdbe, p5);
53219   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
53220     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
53221     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
53222   }
53223   return addr;
53224 }
53225
53226 #if SQLITE_MAX_EXPR_DEPTH>0
53227 /*
53228 ** Check that argument nHeight is less than or equal to the maximum
53229 ** expression depth allowed. If it is not, leave an error message in
53230 ** pParse.
53231 */
53232 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
53233   int rc = SQLITE_OK;
53234   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
53235   if( nHeight>mxHeight ){
53236     sqlite3ErrorMsg(pParse, 
53237        "Expression tree is too large (maximum depth %d)", mxHeight
53238     );
53239     rc = SQLITE_ERROR;
53240   }
53241   return rc;
53242 }
53243
53244 /* The following three functions, heightOfExpr(), heightOfExprList()
53245 ** and heightOfSelect(), are used to determine the maximum height
53246 ** of any expression tree referenced by the structure passed as the
53247 ** first argument.
53248 **
53249 ** If this maximum height is greater than the current value pointed
53250 ** to by pnHeight, the second parameter, then set *pnHeight to that
53251 ** value.
53252 */
53253 static void heightOfExpr(Expr *p, int *pnHeight){
53254   if( p ){
53255     if( p->nHeight>*pnHeight ){
53256       *pnHeight = p->nHeight;
53257     }
53258   }
53259 }
53260 static void heightOfExprList(ExprList *p, int *pnHeight){
53261   if( p ){
53262     int i;
53263     for(i=0; i<p->nExpr; i++){
53264       heightOfExpr(p->a[i].pExpr, pnHeight);
53265     }
53266   }
53267 }
53268 static void heightOfSelect(Select *p, int *pnHeight){
53269   if( p ){
53270     heightOfExpr(p->pWhere, pnHeight);
53271     heightOfExpr(p->pHaving, pnHeight);
53272     heightOfExpr(p->pLimit, pnHeight);
53273     heightOfExpr(p->pOffset, pnHeight);
53274     heightOfExprList(p->pEList, pnHeight);
53275     heightOfExprList(p->pGroupBy, pnHeight);
53276     heightOfExprList(p->pOrderBy, pnHeight);
53277     heightOfSelect(p->pPrior, pnHeight);
53278   }
53279 }
53280
53281 /*
53282 ** Set the Expr.nHeight variable in the structure passed as an 
53283 ** argument. An expression with no children, Expr.pList or 
53284 ** Expr.pSelect member has a height of 1. Any other expression
53285 ** has a height equal to the maximum height of any other 
53286 ** referenced Expr plus one.
53287 */
53288 static void exprSetHeight(Expr *p){
53289   int nHeight = 0;
53290   heightOfExpr(p->pLeft, &nHeight);
53291   heightOfExpr(p->pRight, &nHeight);
53292   heightOfExprList(p->pList, &nHeight);
53293   heightOfSelect(p->pSelect, &nHeight);
53294   p->nHeight = nHeight + 1;
53295 }
53296
53297 /*
53298 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
53299 ** the height is greater than the maximum allowed expression depth,
53300 ** leave an error in pParse.
53301 */
53302 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
53303   exprSetHeight(p);
53304   sqlite3ExprCheckHeight(pParse, p->nHeight);
53305 }
53306
53307 /*
53308 ** Return the maximum height of any expression tree referenced
53309 ** by the select statement passed as an argument.
53310 */
53311 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
53312   int nHeight = 0;
53313   heightOfSelect(p, &nHeight);
53314   return nHeight;
53315 }
53316 #else
53317   #define exprSetHeight(y)
53318 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
53319
53320 /*
53321 ** Construct a new expression node and return a pointer to it.  Memory
53322 ** for this node is obtained from sqlite3_malloc().  The calling function
53323 ** is responsible for making sure the node eventually gets freed.
53324 */
53325 SQLITE_PRIVATE Expr *sqlite3Expr(
53326   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
53327   int op,                 /* Expression opcode */
53328   Expr *pLeft,            /* Left operand */
53329   Expr *pRight,           /* Right operand */
53330   const Token *pToken     /* Argument token */
53331 ){
53332   Expr *pNew;
53333   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
53334   if( pNew==0 ){
53335     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
53336     ** this function must always be allocated with sqlite3Expr() for this 
53337     ** reason. 
53338     */
53339     sqlite3ExprDelete(db, pLeft);
53340     sqlite3ExprDelete(db, pRight);
53341     return 0;
53342   }
53343   pNew->op = op;
53344   pNew->pLeft = pLeft;
53345   pNew->pRight = pRight;
53346   pNew->iAgg = -1;
53347   pNew->span.z = (u8*)"";
53348   if( pToken ){
53349     assert( pToken->dyn==0 );
53350     pNew->span = pNew->token = *pToken;
53351   }else if( pLeft ){
53352     if( pRight ){
53353       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
53354         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
53355       }
53356       if( pRight->flags & EP_ExpCollate ){
53357         pNew->flags |= EP_ExpCollate;
53358         pNew->pColl = pRight->pColl;
53359       }
53360     }
53361     if( pLeft->flags & EP_ExpCollate ){
53362       pNew->flags |= EP_ExpCollate;
53363       pNew->pColl = pLeft->pColl;
53364     }
53365   }
53366
53367   exprSetHeight(pNew);
53368   return pNew;
53369 }
53370
53371 /*
53372 ** Works like sqlite3Expr() except that it takes an extra Parse*
53373 ** argument and notifies the associated connection object if malloc fails.
53374 */
53375 SQLITE_PRIVATE Expr *sqlite3PExpr(
53376   Parse *pParse,          /* Parsing context */
53377   int op,                 /* Expression opcode */
53378   Expr *pLeft,            /* Left operand */
53379   Expr *pRight,           /* Right operand */
53380   const Token *pToken     /* Argument token */
53381 ){
53382   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
53383   if( p ){
53384     sqlite3ExprCheckHeight(pParse, p->nHeight);
53385   }
53386   return p;
53387 }
53388
53389 /*
53390 ** When doing a nested parse, you can include terms in an expression
53391 ** that look like this:   #1 #2 ...  These terms refer to registers
53392 ** in the virtual machine.  #N is the N-th register.
53393 **
53394 ** This routine is called by the parser to deal with on of those terms.
53395 ** It immediately generates code to store the value in a memory location.
53396 ** The returns an expression that will code to extract the value from
53397 ** that memory location as needed.
53398 */
53399 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
53400   Vdbe *v = pParse->pVdbe;
53401   Expr *p;
53402   if( pParse->nested==0 ){
53403     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
53404     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
53405   }
53406   if( v==0 ) return 0;
53407   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
53408   if( p==0 ){
53409     return 0;  /* Malloc failed */
53410   }
53411   p->iTable = atoi((char*)&pToken->z[1]);
53412   return p;
53413 }
53414
53415 /*
53416 ** Join two expressions using an AND operator.  If either expression is
53417 ** NULL, then just return the other expression.
53418 */
53419 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
53420   if( pLeft==0 ){
53421     return pRight;
53422   }else if( pRight==0 ){
53423     return pLeft;
53424   }else{
53425     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
53426   }
53427 }
53428
53429 /*
53430 ** Set the Expr.span field of the given expression to span all
53431 ** text between the two given tokens.  Both tokens must be pointing
53432 ** at the same string.
53433 */
53434 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
53435   assert( pRight!=0 );
53436   assert( pLeft!=0 );
53437   if( pExpr ){
53438     pExpr->span.z = pLeft->z;
53439     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
53440   }
53441 }
53442
53443 /*
53444 ** Construct a new expression node for a function with multiple
53445 ** arguments.
53446 */
53447 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
53448   Expr *pNew;
53449   sqlite3 *db = pParse->db;
53450   assert( pToken );
53451   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
53452   if( pNew==0 ){
53453     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
53454     return 0;
53455   }
53456   pNew->op = TK_FUNCTION;
53457   pNew->pList = pList;
53458   assert( pToken->dyn==0 );
53459   pNew->token = *pToken;
53460   pNew->span = pNew->token;
53461
53462   sqlite3ExprSetHeight(pParse, pNew);
53463   return pNew;
53464 }
53465
53466 /*
53467 ** Assign a variable number to an expression that encodes a wildcard
53468 ** in the original SQL statement.  
53469 **
53470 ** Wildcards consisting of a single "?" are assigned the next sequential
53471 ** variable number.
53472 **
53473 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
53474 ** sure "nnn" is not too be to avoid a denial of service attack when
53475 ** the SQL statement comes from an external source.
53476 **
53477 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
53478 ** as the previous instance of the same wildcard.  Or if this is the first
53479 ** instance of the wildcard, the next sequenial variable number is
53480 ** assigned.
53481 */
53482 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
53483   Token *pToken;
53484   sqlite3 *db = pParse->db;
53485
53486   if( pExpr==0 ) return;
53487   pToken = &pExpr->token;
53488   assert( pToken->n>=1 );
53489   assert( pToken->z!=0 );
53490   assert( pToken->z[0]!=0 );
53491   if( pToken->n==1 ){
53492     /* Wildcard of the form "?".  Assign the next variable number */
53493     pExpr->iTable = ++pParse->nVar;
53494   }else if( pToken->z[0]=='?' ){
53495     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
53496     ** use it as the variable number */
53497     int i;
53498     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
53499     testcase( i==0 );
53500     testcase( i==1 );
53501     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
53502     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
53503     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
53504       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
53505           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
53506     }
53507     if( i>pParse->nVar ){
53508       pParse->nVar = i;
53509     }
53510   }else{
53511     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
53512     ** number as the prior appearance of the same name, or if the name
53513     ** has never appeared before, reuse the same variable number
53514     */
53515     int i, n;
53516     n = pToken->n;
53517     for(i=0; i<pParse->nVarExpr; i++){
53518       Expr *pE;
53519       if( (pE = pParse->apVarExpr[i])!=0
53520           && pE->token.n==n
53521           && memcmp(pE->token.z, pToken->z, n)==0 ){
53522         pExpr->iTable = pE->iTable;
53523         break;
53524       }
53525     }
53526     if( i>=pParse->nVarExpr ){
53527       pExpr->iTable = ++pParse->nVar;
53528       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
53529         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
53530         pParse->apVarExpr =
53531             sqlite3DbReallocOrFree(
53532               db,
53533               pParse->apVarExpr,
53534               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
53535             );
53536       }
53537       if( !db->mallocFailed ){
53538         assert( pParse->apVarExpr!=0 );
53539         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
53540       }
53541     }
53542   } 
53543   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
53544     sqlite3ErrorMsg(pParse, "too many SQL variables");
53545   }
53546 }
53547
53548 /*
53549 ** Clear an expression structure without deleting the structure itself.
53550 ** Substructure is deleted.
53551 */
53552 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3 *db, Expr *p){
53553   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
53554   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
53555   sqlite3ExprDelete(db, p->pLeft);
53556   sqlite3ExprDelete(db, p->pRight);
53557   sqlite3ExprListDelete(db, p->pList);
53558   sqlite3SelectDelete(db, p->pSelect);
53559 }
53560
53561 /*
53562 ** Recursively delete an expression tree.
53563 */
53564 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
53565   if( p==0 ) return;
53566   sqlite3ExprClear(db, p);
53567   sqlite3DbFree(db, p);
53568 }
53569
53570 /*
53571 ** The Expr.token field might be a string literal that is quoted.
53572 ** If so, remove the quotation marks.
53573 */
53574 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
53575   if( ExprHasAnyProperty(p, EP_Dequoted) ){
53576     return;
53577   }
53578   ExprSetProperty(p, EP_Dequoted);
53579   if( p->token.dyn==0 ){
53580     sqlite3TokenCopy(db, &p->token, &p->token);
53581   }
53582   sqlite3Dequote((char*)p->token.z);
53583 }
53584
53585 /*
53586 ** The following group of routines make deep copies of expressions,
53587 ** expression lists, ID lists, and select statements.  The copies can
53588 ** be deleted (by being passed to their respective ...Delete() routines)
53589 ** without effecting the originals.
53590 **
53591 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
53592 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
53593 ** by subsequent calls to sqlite*ListAppend() routines.
53594 **
53595 ** Any tables that the SrcList might point to are not duplicated.
53596 */
53597 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
53598   Expr *pNew;
53599   if( p==0 ) return 0;
53600   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
53601   if( pNew==0 ) return 0;
53602   memcpy(pNew, p, sizeof(*pNew));
53603   if( p->token.z!=0 ){
53604     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
53605     pNew->token.dyn = 1;
53606   }else{
53607     assert( pNew->token.z==0 );
53608   }
53609   pNew->span.z = 0;
53610   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
53611   pNew->pRight = sqlite3ExprDup(db, p->pRight);
53612   pNew->pList = sqlite3ExprListDup(db, p->pList);
53613   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
53614   return pNew;
53615 }
53616 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
53617   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
53618   if( pFrom->z ){
53619     pTo->n = pFrom->n;
53620     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
53621     pTo->dyn = 1;
53622   }else{
53623     pTo->z = 0;
53624   }
53625 }
53626 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
53627   ExprList *pNew;
53628   struct ExprList_item *pItem, *pOldItem;
53629   int i;
53630   if( p==0 ) return 0;
53631   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
53632   if( pNew==0 ) return 0;
53633   pNew->iECursor = 0;
53634   pNew->nExpr = pNew->nAlloc = p->nExpr;
53635   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
53636   if( pItem==0 ){
53637     sqlite3DbFree(db, pNew);
53638     return 0;
53639   } 
53640   pOldItem = p->a;
53641   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
53642     Expr *pNewExpr, *pOldExpr;
53643     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
53644     if( pOldExpr->span.z!=0 && pNewExpr ){
53645       /* Always make a copy of the span for top-level expressions in the
53646       ** expression list.  The logic in SELECT processing that determines
53647       ** the names of columns in the result set needs this information */
53648       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
53649     }
53650     assert( pNewExpr==0 || pNewExpr->span.z!=0 
53651             || pOldExpr->span.z==0
53652             || db->mallocFailed );
53653     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53654     pItem->sortOrder = pOldItem->sortOrder;
53655     pItem->done = 0;
53656     pItem->iCol = pOldItem->iCol;
53657     pItem->iAlias = pOldItem->iAlias;
53658   }
53659   return pNew;
53660 }
53661
53662 /*
53663 ** If cursors, triggers, views and subqueries are all omitted from
53664 ** the build, then none of the following routines, except for 
53665 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
53666 ** called with a NULL argument.
53667 */
53668 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
53669  || !defined(SQLITE_OMIT_SUBQUERY)
53670 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
53671   SrcList *pNew;
53672   int i;
53673   int nByte;
53674   if( p==0 ) return 0;
53675   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
53676   pNew = sqlite3DbMallocRaw(db, nByte );
53677   if( pNew==0 ) return 0;
53678   pNew->nSrc = pNew->nAlloc = p->nSrc;
53679   for(i=0; i<p->nSrc; i++){
53680     struct SrcList_item *pNewItem = &pNew->a[i];
53681     struct SrcList_item *pOldItem = &p->a[i];
53682     Table *pTab;
53683     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
53684     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53685     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
53686     pNewItem->jointype = pOldItem->jointype;
53687     pNewItem->iCursor = pOldItem->iCursor;
53688     pNewItem->isPopulated = pOldItem->isPopulated;
53689     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
53690     pNewItem->notIndexed = pOldItem->notIndexed;
53691     pNewItem->pIndex = pOldItem->pIndex;
53692     pTab = pNewItem->pTab = pOldItem->pTab;
53693     if( pTab ){
53694       pTab->nRef++;
53695     }
53696     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
53697     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
53698     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
53699     pNewItem->colUsed = pOldItem->colUsed;
53700   }
53701   return pNew;
53702 }
53703 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
53704   IdList *pNew;
53705   int i;
53706   if( p==0 ) return 0;
53707   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
53708   if( pNew==0 ) return 0;
53709   pNew->nId = pNew->nAlloc = p->nId;
53710   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
53711   if( pNew->a==0 ){
53712     sqlite3DbFree(db, pNew);
53713     return 0;
53714   }
53715   for(i=0; i<p->nId; i++){
53716     struct IdList_item *pNewItem = &pNew->a[i];
53717     struct IdList_item *pOldItem = &p->a[i];
53718     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
53719     pNewItem->idx = pOldItem->idx;
53720   }
53721   return pNew;
53722 }
53723 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
53724   Select *pNew;
53725   if( p==0 ) return 0;
53726   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
53727   if( pNew==0 ) return 0;
53728   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
53729   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
53730   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
53731   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
53732   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
53733   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
53734   pNew->op = p->op;
53735   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
53736   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
53737   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
53738   pNew->iLimit = 0;
53739   pNew->iOffset = 0;
53740   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
53741   pNew->pRightmost = 0;
53742   pNew->addrOpenEphm[0] = -1;
53743   pNew->addrOpenEphm[1] = -1;
53744   pNew->addrOpenEphm[2] = -1;
53745   return pNew;
53746 }
53747 #else
53748 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
53749   assert( p==0 );
53750   return 0;
53751 }
53752 #endif
53753
53754
53755 /*
53756 ** Add a new element to the end of an expression list.  If pList is
53757 ** initially NULL, then create a new expression list.
53758 */
53759 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
53760   Parse *pParse,          /* Parsing context */
53761   ExprList *pList,        /* List to which to append. Might be NULL */
53762   Expr *pExpr,            /* Expression to be appended */
53763   Token *pName            /* AS keyword for the expression */
53764 ){
53765   sqlite3 *db = pParse->db;
53766   if( pList==0 ){
53767     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
53768     if( pList==0 ){
53769       goto no_mem;
53770     }
53771     assert( pList->nAlloc==0 );
53772   }
53773   if( pList->nAlloc<=pList->nExpr ){
53774     struct ExprList_item *a;
53775     int n = pList->nAlloc*2 + 4;
53776     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
53777     if( a==0 ){
53778       goto no_mem;
53779     }
53780     pList->a = a;
53781     pList->nAlloc = n;
53782   }
53783   assert( pList->a!=0 );
53784   if( pExpr || pName ){
53785     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
53786     memset(pItem, 0, sizeof(*pItem));
53787     pItem->zName = sqlite3NameFromToken(db, pName);
53788     pItem->pExpr = pExpr;
53789     pItem->iAlias = 0;
53790   }
53791   return pList;
53792
53793 no_mem:     
53794   /* Avoid leaking memory if malloc has failed. */
53795   sqlite3ExprDelete(db, pExpr);
53796   sqlite3ExprListDelete(db, pList);
53797   return 0;
53798 }
53799
53800 /*
53801 ** If the expression list pEList contains more than iLimit elements,
53802 ** leave an error message in pParse.
53803 */
53804 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
53805   Parse *pParse,
53806   ExprList *pEList,
53807   const char *zObject
53808 ){
53809   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
53810   testcase( pEList && pEList->nExpr==mx );
53811   testcase( pEList && pEList->nExpr==mx+1 );
53812   if( pEList && pEList->nExpr>mx ){
53813     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
53814   }
53815 }
53816
53817 /*
53818 ** Delete an entire expression list.
53819 */
53820 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
53821   int i;
53822   struct ExprList_item *pItem;
53823   if( pList==0 ) return;
53824   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
53825   assert( pList->nExpr<=pList->nAlloc );
53826   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
53827     sqlite3ExprDelete(db, pItem->pExpr);
53828     sqlite3DbFree(db, pItem->zName);
53829   }
53830   sqlite3DbFree(db, pList->a);
53831   sqlite3DbFree(db, pList);
53832 }
53833
53834 /*
53835 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
53836 ** to an integer.  These routines are checking an expression to see
53837 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
53838 ** not constant.
53839 **
53840 ** These callback routines are used to implement the following:
53841 **
53842 **     sqlite3ExprIsConstant()
53843 **     sqlite3ExprIsConstantNotJoin()
53844 **     sqlite3ExprIsConstantOrFunction()
53845 **
53846 */
53847 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
53848
53849   /* If pWalker->u.i is 3 then any term of the expression that comes from
53850   ** the ON or USING clauses of a join disqualifies the expression
53851   ** from being considered constant. */
53852   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
53853     pWalker->u.i = 0;
53854     return WRC_Abort;
53855   }
53856
53857   switch( pExpr->op ){
53858     /* Consider functions to be constant if all their arguments are constant
53859     ** and pWalker->u.i==2 */
53860     case TK_FUNCTION:
53861       if( pWalker->u.i==2 ) return 0;
53862       /* Fall through */
53863     case TK_ID:
53864     case TK_COLUMN:
53865     case TK_DOT:
53866     case TK_AGG_FUNCTION:
53867     case TK_AGG_COLUMN:
53868 #ifndef SQLITE_OMIT_SUBQUERY
53869     case TK_SELECT:
53870     case TK_EXISTS:
53871       testcase( pExpr->op==TK_SELECT );
53872       testcase( pExpr->op==TK_EXISTS );
53873 #endif
53874       testcase( pExpr->op==TK_ID );
53875       testcase( pExpr->op==TK_COLUMN );
53876       testcase( pExpr->op==TK_DOT );
53877       testcase( pExpr->op==TK_AGG_FUNCTION );
53878       testcase( pExpr->op==TK_AGG_COLUMN );
53879       pWalker->u.i = 0;
53880       return WRC_Abort;
53881     default:
53882       return WRC_Continue;
53883   }
53884 }
53885 static int selectNodeIsConstant(Walker *pWalker, Select *pSelect){
53886   pWalker->u.i = 0;
53887   return WRC_Abort;
53888 }
53889 static int exprIsConst(Expr *p, int initFlag){
53890   Walker w;
53891   w.u.i = initFlag;
53892   w.xExprCallback = exprNodeIsConstant;
53893   w.xSelectCallback = selectNodeIsConstant;
53894   sqlite3WalkExpr(&w, p);
53895   return w.u.i;
53896 }
53897
53898 /*
53899 ** Walk an expression tree.  Return 1 if the expression is constant
53900 ** and 0 if it involves variables or function calls.
53901 **
53902 ** For the purposes of this function, a double-quoted string (ex: "abc")
53903 ** is considered a variable but a single-quoted string (ex: 'abc') is
53904 ** a constant.
53905 */
53906 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
53907   return exprIsConst(p, 1);
53908 }
53909
53910 /*
53911 ** Walk an expression tree.  Return 1 if the expression is constant
53912 ** that does no originate from the ON or USING clauses of a join.
53913 ** Return 0 if it involves variables or function calls or terms from
53914 ** an ON or USING clause.
53915 */
53916 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
53917   return exprIsConst(p, 3);
53918 }
53919
53920 /*
53921 ** Walk an expression tree.  Return 1 if the expression is constant
53922 ** or a function call with constant arguments.  Return and 0 if there
53923 ** are any variables.
53924 **
53925 ** For the purposes of this function, a double-quoted string (ex: "abc")
53926 ** is considered a variable but a single-quoted string (ex: 'abc') is
53927 ** a constant.
53928 */
53929 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
53930   return exprIsConst(p, 2);
53931 }
53932
53933 /*
53934 ** If the expression p codes a constant integer that is small enough
53935 ** to fit in a 32-bit integer, return 1 and put the value of the integer
53936 ** in *pValue.  If the expression is not an integer or if it is too big
53937 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
53938 */
53939 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
53940   int rc = 0;
53941   if( p->flags & EP_IntValue ){
53942     *pValue = p->iTable;
53943     return 1;
53944   }
53945   switch( p->op ){
53946     case TK_INTEGER: {
53947       rc = sqlite3GetInt32((char*)p->token.z, pValue);
53948       break;
53949     }
53950     case TK_UPLUS: {
53951       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
53952       break;
53953     }
53954     case TK_UMINUS: {
53955       int v;
53956       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
53957         *pValue = -v;
53958         rc = 1;
53959       }
53960       break;
53961     }
53962     default: break;
53963   }
53964   if( rc ){
53965     p->op = TK_INTEGER;
53966     p->flags |= EP_IntValue;
53967     p->iTable = *pValue;
53968   }
53969   return rc;
53970 }
53971
53972 /*
53973 ** Return TRUE if the given string is a row-id column name.
53974 */
53975 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
53976   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
53977   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
53978   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
53979   return 0;
53980 }
53981
53982 #ifdef SQLITE_TEST
53983   int sqlite3_enable_in_opt = 1;
53984 #else
53985   #define sqlite3_enable_in_opt 1
53986 #endif
53987
53988 /*
53989 ** Return true if the IN operator optimization is enabled and
53990 ** the SELECT statement p exists and is of the
53991 ** simple form:
53992 **
53993 **     SELECT <column> FROM <table>
53994 **
53995 ** If this is the case, it may be possible to use an existing table
53996 ** or index instead of generating an epheremal table.
53997 */
53998 #ifndef SQLITE_OMIT_SUBQUERY
53999 static int isCandidateForInOpt(Select *p){
54000   SrcList *pSrc;
54001   ExprList *pEList;
54002   Table *pTab;
54003   if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
54004   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
54005   if( p->pPrior ) return 0;              /* Not a compound SELECT */
54006   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
54007       return 0; /* No DISTINCT keyword and no aggregate functions */
54008   }
54009   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
54010   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
54011   if( p->pOffset ) return 0;
54012   if( p->pWhere ) return 0;              /* Has no WHERE clause */
54013   pSrc = p->pSrc;
54014   if( pSrc==0 ) return 0;                /* A single table in the FROM clause */
54015   if( pSrc->nSrc!=1 ) return 0;
54016   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
54017   pTab = pSrc->a[0].pTab;
54018   if( pTab==0 ) return 0;
54019   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
54020   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
54021   pEList = p->pEList;
54022   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
54023   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
54024   return 1;
54025 }
54026 #endif /* SQLITE_OMIT_SUBQUERY */
54027
54028 /*
54029 ** This function is used by the implementation of the IN (...) operator.
54030 ** It's job is to find or create a b-tree structure that may be used
54031 ** either to test for membership of the (...) set or to iterate through
54032 ** its members, skipping duplicates.
54033 **
54034 ** The cursor opened on the structure (database table, database index 
54035 ** or ephermal table) is stored in pX->iTable before this function returns.
54036 ** The returned value indicates the structure type, as follows:
54037 **
54038 **   IN_INDEX_ROWID - The cursor was opened on a database table.
54039 **   IN_INDEX_INDEX - The cursor was opened on a database index.
54040 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
54041 **                    populated epheremal table.
54042 **
54043 ** An existing structure may only be used if the SELECT is of the simple
54044 ** form:
54045 **
54046 **     SELECT <column> FROM <table>
54047 **
54048 ** If prNotFound parameter is 0, then the structure will be used to iterate
54049 ** through the set members, skipping any duplicates. In this case an
54050 ** epheremal table must be used unless the selected <column> is guaranteed
54051 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
54052 ** is unique by virtue of a constraint or implicit index.
54053 **
54054 ** If the prNotFound parameter is not 0, then the structure will be used 
54055 ** for fast set membership tests. In this case an epheremal table must 
54056 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
54057 ** be found with <column> as its left-most column.
54058 **
54059 ** When the structure is being used for set membership tests, the user
54060 ** needs to know whether or not the structure contains an SQL NULL 
54061 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
54062 ** If there is a chance that the structure may contain a NULL value at
54063 ** runtime, then a register is allocated and the register number written
54064 ** to *prNotFound. If there is no chance that the structure contains a
54065 ** NULL value, then *prNotFound is left unchanged.
54066 **
54067 ** If a register is allocated and its location stored in *prNotFound, then
54068 ** its initial value is NULL. If the structure does not remain constant
54069 ** for the duration of the query (i.e. the set is a correlated sub-select), 
54070 ** the value of the allocated register is reset to NULL each time the 
54071 ** structure is repopulated. This allows the caller to use vdbe code 
54072 ** equivalent to the following:
54073 **
54074 **   if( register==NULL ){
54075 **     has_null = <test if data structure contains null>
54076 **     register = 1
54077 **   }
54078 **
54079 ** in order to avoid running the <test if data structure contains null>
54080 ** test more often than is necessary.
54081 */
54082 #ifndef SQLITE_OMIT_SUBQUERY
54083 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
54084   Select *p;
54085   int eType = 0;
54086   int iTab = pParse->nTab++;
54087   int mustBeUnique = !prNotFound;
54088
54089   /* The follwing if(...) expression is true if the SELECT is of the 
54090   ** simple form:
54091   **
54092   **     SELECT <column> FROM <table>
54093   **
54094   ** If this is the case, it may be possible to use an existing table
54095   ** or index instead of generating an epheremal table.
54096   */
54097   p = pX->pSelect;
54098   if( isCandidateForInOpt(p) ){
54099     sqlite3 *db = pParse->db;
54100     Index *pIdx;
54101     Expr *pExpr = p->pEList->a[0].pExpr;
54102     int iCol = pExpr->iColumn;
54103     Vdbe *v = sqlite3GetVdbe(pParse);
54104
54105     /* This function is only called from two places. In both cases the vdbe
54106     ** has already been allocated. So assume sqlite3GetVdbe() is always
54107     ** successful here.
54108     */
54109     assert(v);
54110     if( iCol<0 ){
54111       int iMem = ++pParse->nMem;
54112       int iAddr;
54113       Table *pTab = p->pSrc->a[0].pTab;
54114       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
54115       sqlite3VdbeUsesBtree(v, iDb);
54116
54117       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
54118       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
54119
54120       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
54121       eType = IN_INDEX_ROWID;
54122
54123       sqlite3VdbeJumpHere(v, iAddr);
54124     }else{
54125       /* The collation sequence used by the comparison. If an index is to 
54126       ** be used in place of a temp-table, it must be ordered according
54127       ** to this collation sequence.
54128       */
54129       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
54130
54131       /* Check that the affinity that will be used to perform the 
54132       ** comparison is the same as the affinity of the column. If
54133       ** it is not, it is not possible to use any index.
54134       */
54135       Table *pTab = p->pSrc->a[0].pTab;
54136       char aff = comparisonAffinity(pX);
54137       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
54138
54139       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
54140         if( (pIdx->aiColumn[0]==iCol)
54141          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
54142          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
54143         ){
54144           int iDb;
54145           int iMem = ++pParse->nMem;
54146           int iAddr;
54147           char *pKey;
54148   
54149           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
54150           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
54151           sqlite3VdbeUsesBtree(v, iDb);
54152
54153           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
54154           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
54155   
54156           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
54157           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
54158                                pKey,P4_KEYINFO_HANDOFF);
54159           VdbeComment((v, "%s", pIdx->zName));
54160           eType = IN_INDEX_INDEX;
54161
54162           sqlite3VdbeJumpHere(v, iAddr);
54163           if( prNotFound && !pTab->aCol[iCol].notNull ){
54164             *prNotFound = ++pParse->nMem;
54165           }
54166         }
54167       }
54168     }
54169   }
54170
54171   if( eType==0 ){
54172     int rMayHaveNull = 0;
54173     eType = IN_INDEX_EPH;
54174     if( prNotFound ){
54175       *prNotFound = rMayHaveNull = ++pParse->nMem;
54176     }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
54177       eType = IN_INDEX_ROWID;
54178     }
54179     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
54180   }else{
54181     pX->iTable = iTab;
54182   }
54183   return eType;
54184 }
54185 #endif
54186
54187 /*
54188 ** Generate code for scalar subqueries used as an expression
54189 ** and IN operators.  Examples:
54190 **
54191 **     (SELECT a FROM b)          -- subquery
54192 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
54193 **     x IN (4,5,11)              -- IN operator with list on right-hand side
54194 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
54195 **
54196 ** The pExpr parameter describes the expression that contains the IN
54197 ** operator or subquery.
54198 **
54199 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
54200 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
54201 ** to some integer key column of a table B-Tree. In this case, use an
54202 ** intkey B-Tree to store the set of IN(...) values instead of the usual
54203 ** (slower) variable length keys B-Tree.
54204 */
54205 #ifndef SQLITE_OMIT_SUBQUERY
54206 SQLITE_PRIVATE void sqlite3CodeSubselect(
54207   Parse *pParse, 
54208   Expr *pExpr, 
54209   int rMayHaveNull,
54210   int isRowid
54211 ){
54212   int testAddr = 0;                       /* One-time test address */
54213   Vdbe *v = sqlite3GetVdbe(pParse);
54214   if( v==0 ) return;
54215
54216
54217   /* This code must be run in its entirety every time it is encountered
54218   ** if any of the following is true:
54219   **
54220   **    *  The right-hand side is a correlated subquery
54221   **    *  The right-hand side is an expression list containing variables
54222   **    *  We are inside a trigger
54223   **
54224   ** If all of the above are false, then we can run this code just once
54225   ** save the results, and reuse the same result on subsequent invocations.
54226   */
54227   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
54228     int mem = ++pParse->nMem;
54229     sqlite3VdbeAddOp1(v, OP_If, mem);
54230     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
54231     assert( testAddr>0 || pParse->db->mallocFailed );
54232   }
54233
54234   switch( pExpr->op ){
54235     case TK_IN: {
54236       char affinity;
54237       KeyInfo keyInfo;
54238       int addr;        /* Address of OP_OpenEphemeral instruction */
54239       Expr *pLeft = pExpr->pLeft;
54240
54241       if( rMayHaveNull ){
54242         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
54243       }
54244
54245       affinity = sqlite3ExprAffinity(pLeft);
54246
54247       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
54248       ** expression it is handled the same way. A virtual table is 
54249       ** filled with single-field index keys representing the results
54250       ** from the SELECT or the <exprlist>.
54251       **
54252       ** If the 'x' expression is a column value, or the SELECT...
54253       ** statement returns a column value, then the affinity of that
54254       ** column is used to build the index keys. If both 'x' and the
54255       ** SELECT... statement are columns, then numeric affinity is used
54256       ** if either column has NUMERIC or INTEGER affinity. If neither
54257       ** 'x' nor the SELECT... statement are columns, then numeric affinity
54258       ** is used.
54259       */
54260       pExpr->iTable = pParse->nTab++;
54261       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
54262       memset(&keyInfo, 0, sizeof(keyInfo));
54263       keyInfo.nField = 1;
54264
54265       if( pExpr->pSelect ){
54266         /* Case 1:     expr IN (SELECT ...)
54267         **
54268         ** Generate code to write the results of the select into the temporary
54269         ** table allocated and opened above.
54270         */
54271         SelectDest dest;
54272         ExprList *pEList;
54273
54274         assert( !isRowid );
54275         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
54276         dest.affinity = (int)affinity;
54277         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
54278         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
54279           return;
54280         }
54281         pEList = pExpr->pSelect->pEList;
54282         if( pEList && pEList->nExpr>0 ){ 
54283           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
54284               pEList->a[0].pExpr);
54285         }
54286       }else if( pExpr->pList ){
54287         /* Case 2:     expr IN (exprlist)
54288         **
54289         ** For each expression, build an index key from the evaluation and
54290         ** store it in the temporary table. If <expr> is a column, then use
54291         ** that columns affinity when building index keys. If <expr> is not
54292         ** a column, use numeric affinity.
54293         */
54294         int i;
54295         ExprList *pList = pExpr->pList;
54296         struct ExprList_item *pItem;
54297         int r1, r2, r3;
54298
54299         if( !affinity ){
54300           affinity = SQLITE_AFF_NONE;
54301         }
54302         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
54303
54304         /* Loop through each expression in <exprlist>. */
54305         r1 = sqlite3GetTempReg(pParse);
54306         r2 = sqlite3GetTempReg(pParse);
54307         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
54308         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
54309           Expr *pE2 = pItem->pExpr;
54310
54311           /* If the expression is not constant then we will need to
54312           ** disable the test that was generated above that makes sure
54313           ** this code only executes once.  Because for a non-constant
54314           ** expression we need to rerun this code each time.
54315           */
54316           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
54317             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
54318             testAddr = 0;
54319           }
54320
54321           /* Evaluate the expression and insert it into the temp table */
54322           pParse->disableColCache++;
54323           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
54324           assert( pParse->disableColCache>0 );
54325           pParse->disableColCache--;
54326
54327           if( isRowid ){
54328             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
54329             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
54330           }else{
54331             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
54332             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
54333             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
54334           }
54335         }
54336         sqlite3ReleaseTempReg(pParse, r1);
54337         sqlite3ReleaseTempReg(pParse, r2);
54338       }
54339       if( !isRowid ){
54340         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
54341       }
54342       break;
54343     }
54344
54345     case TK_EXISTS:
54346     case TK_SELECT: {
54347       /* This has to be a scalar SELECT.  Generate code to put the
54348       ** value of this select in a memory cell and record the number
54349       ** of the memory cell in iColumn.
54350       */
54351       static const Token one = { (u8*)"1", 0, 1 };
54352       Select *pSel;
54353       SelectDest dest;
54354
54355       pSel = pExpr->pSelect;
54356       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
54357       if( pExpr->op==TK_SELECT ){
54358         dest.eDest = SRT_Mem;
54359         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
54360         VdbeComment((v, "Init subquery result"));
54361       }else{
54362         dest.eDest = SRT_Exists;
54363         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
54364         VdbeComment((v, "Init EXISTS result"));
54365       }
54366       sqlite3ExprDelete(pParse->db, pSel->pLimit);
54367       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
54368       if( sqlite3Select(pParse, pSel, &dest) ){
54369         return;
54370       }
54371       pExpr->iColumn = dest.iParm;
54372       break;
54373     }
54374   }
54375
54376   if( testAddr ){
54377     sqlite3VdbeJumpHere(v, testAddr-1);
54378   }
54379
54380   return;
54381 }
54382 #endif /* SQLITE_OMIT_SUBQUERY */
54383
54384 /*
54385 ** Duplicate an 8-byte value
54386 */
54387 static char *dup8bytes(Vdbe *v, const char *in){
54388   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
54389   if( out ){
54390     memcpy(out, in, 8);
54391   }
54392   return out;
54393 }
54394
54395 /*
54396 ** Generate an instruction that will put the floating point
54397 ** value described by z[0..n-1] into register iMem.
54398 **
54399 ** The z[] string will probably not be zero-terminated.  But the 
54400 ** z[n] character is guaranteed to be something that does not look
54401 ** like the continuation of the number.
54402 */
54403 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
54404   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
54405   if( z ){
54406     double value;
54407     char *zV;
54408     assert( !isdigit(z[n]) );
54409     sqlite3AtoF(z, &value);
54410     if( sqlite3IsNaN(value) ){
54411       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
54412     }else{
54413       if( negateFlag ) value = -value;
54414       zV = dup8bytes(v, (char*)&value);
54415       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
54416     }
54417   }
54418 }
54419
54420
54421 /*
54422 ** Generate an instruction that will put the integer describe by
54423 ** text z[0..n-1] into register iMem.
54424 **
54425 ** The z[] string will probably not be zero-terminated.  But the 
54426 ** z[n] character is guaranteed to be something that does not look
54427 ** like the continuation of the number.
54428 */
54429 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
54430   const char *z;
54431   if( pExpr->flags & EP_IntValue ){
54432     int i = pExpr->iTable;
54433     if( negFlag ) i = -i;
54434     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
54435   }else if( (z = (char*)pExpr->token.z)!=0 ){
54436     int i;
54437     int n = pExpr->token.n;
54438     assert( !isdigit(z[n]) );
54439     if( sqlite3GetInt32(z, &i) ){
54440       if( negFlag ) i = -i;
54441       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
54442     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
54443       i64 value;
54444       char *zV;
54445       sqlite3Atoi64(z, &value);
54446       if( negFlag ) value = -value;
54447       zV = dup8bytes(v, (char*)&value);
54448       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
54449     }else{
54450       codeReal(v, z, n, negFlag, iMem);
54451     }
54452   }
54453 }
54454
54455
54456 /*
54457 ** Generate code that will extract the iColumn-th column from
54458 ** table pTab and store the column value in a register.  An effort
54459 ** is made to store the column value in register iReg, but this is
54460 ** not guaranteed.  The location of the column value is returned.
54461 **
54462 ** There must be an open cursor to pTab in iTable when this routine
54463 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
54464 **
54465 ** This routine might attempt to reuse the value of the column that
54466 ** has already been loaded into a register.  The value will always
54467 ** be used if it has not undergone any affinity changes.  But if
54468 ** an affinity change has occurred, then the cached value will only be
54469 ** used if allowAffChng is true.
54470 */
54471 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
54472   Parse *pParse,   /* Parsing and code generating context */
54473   Table *pTab,     /* Description of the table we are reading from */
54474   int iColumn,     /* Index of the table column */
54475   int iTable,      /* The cursor pointing to the table */
54476   int iReg,        /* Store results here */
54477   int allowAffChng /* True if prior affinity changes are OK */
54478 ){
54479   Vdbe *v = pParse->pVdbe;
54480   int i;
54481   struct yColCache *p;
54482
54483   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
54484     if( p->iTable==iTable && p->iColumn==iColumn
54485            && (!p->affChange || allowAffChng) ){
54486 #if 0
54487       sqlite3VdbeAddOp0(v, OP_Noop);
54488       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
54489 #endif
54490       return p->iReg;
54491     }
54492   }  
54493   assert( v!=0 );
54494   if( iColumn<0 ){
54495     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
54496     sqlite3VdbeAddOp2(v, op, iTable, iReg);
54497   }else if( pTab==0 ){
54498     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
54499   }else{
54500     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
54501     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
54502     sqlite3ColumnDefault(v, pTab, iColumn);
54503 #ifndef SQLITE_OMIT_FLOATING_POINT
54504     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
54505       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
54506     }
54507 #endif
54508   }
54509   if( pParse->disableColCache==0 ){
54510     i = pParse->iColCache;
54511     p = &pParse->aColCache[i];
54512     p->iTable = iTable;
54513     p->iColumn = iColumn;
54514     p->iReg = iReg;
54515     p->affChange = 0;
54516     i++;
54517     if( i>=ArraySize(pParse->aColCache) ) i = 0;
54518     if( i>pParse->nColCache ) pParse->nColCache = i;
54519     pParse->iColCache = i;
54520   }
54521   return iReg;
54522 }
54523
54524 /*
54525 ** Clear all column cache entries associated with the vdbe
54526 ** cursor with cursor number iTable.
54527 */
54528 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
54529   if( iTable<0 ){
54530     pParse->nColCache = 0;
54531     pParse->iColCache = 0;
54532   }else{
54533     int i;
54534     for(i=0; i<pParse->nColCache; i++){
54535       if( pParse->aColCache[i].iTable==iTable ){
54536         testcase( i==pParse->nColCache-1 );
54537         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
54538         pParse->iColCache = pParse->nColCache;
54539       }
54540     }
54541   }
54542 }
54543
54544 /*
54545 ** Record the fact that an affinity change has occurred on iCount
54546 ** registers starting with iStart.
54547 */
54548 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
54549   int iEnd = iStart + iCount - 1;
54550   int i;
54551   for(i=0; i<pParse->nColCache; i++){
54552     int r = pParse->aColCache[i].iReg;
54553     if( r>=iStart && r<=iEnd ){
54554       pParse->aColCache[i].affChange = 1;
54555     }
54556   }
54557 }
54558
54559 /*
54560 ** Generate code to move content from registers iFrom...iFrom+nReg-1
54561 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
54562 */
54563 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
54564   int i;
54565   if( iFrom==iTo ) return;
54566   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
54567   for(i=0; i<pParse->nColCache; i++){
54568     int x = pParse->aColCache[i].iReg;
54569     if( x>=iFrom && x<iFrom+nReg ){
54570       pParse->aColCache[i].iReg += iTo-iFrom;
54571     }
54572   }
54573 }
54574
54575 /*
54576 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
54577 ** over to iTo..iTo+nReg-1.
54578 */
54579 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
54580   int i;
54581   if( iFrom==iTo ) return;
54582   for(i=0; i<nReg; i++){
54583     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
54584   }
54585 }
54586
54587 /*
54588 ** Return true if any register in the range iFrom..iTo (inclusive)
54589 ** is used as part of the column cache.
54590 */
54591 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
54592   int i;
54593   for(i=0; i<pParse->nColCache; i++){
54594     int r = pParse->aColCache[i].iReg;
54595     if( r>=iFrom && r<=iTo ) return 1;
54596   }
54597   return 0;
54598 }
54599
54600 /*
54601 ** Theres is a value in register iCurrent.  We ultimately want
54602 ** the value to be in register iTarget.  It might be that
54603 ** iCurrent and iTarget are the same register.
54604 **
54605 ** We are going to modify the value, so we need to make sure it
54606 ** is not a cached register.  If iCurrent is a cached register,
54607 ** then try to move the value over to iTarget.  If iTarget is a
54608 ** cached register, then clear the corresponding cache line.
54609 **
54610 ** Return the register that the value ends up in.
54611 */
54612 SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
54613   int i;
54614   assert( pParse->pVdbe!=0 );
54615   if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
54616     return iCurrent;
54617   }
54618   if( iCurrent!=iTarget ){
54619     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
54620   }
54621   for(i=0; i<pParse->nColCache; i++){
54622     if( pParse->aColCache[i].iReg==iTarget ){
54623       pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
54624       pParse->iColCache = pParse->nColCache;
54625     }
54626   }
54627   return iTarget;
54628 }
54629
54630 /*
54631 ** If the last instruction coded is an ephemeral copy of any of
54632 ** the registers in the nReg registers beginning with iReg, then
54633 ** convert the last instruction from OP_SCopy to OP_Copy.
54634 */
54635 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
54636   int addr;
54637   VdbeOp *pOp;
54638   Vdbe *v;
54639
54640   v = pParse->pVdbe;
54641   addr = sqlite3VdbeCurrentAddr(v);
54642   pOp = sqlite3VdbeGetOp(v, addr-1);
54643   assert( pOp || pParse->db->mallocFailed );
54644   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
54645     pOp->opcode = OP_Copy;
54646   }
54647 }
54648
54649 /*
54650 ** Generate code to store the value of the iAlias-th alias in register
54651 ** target.  The first time this is called, pExpr is evaluated to compute
54652 ** the value of the alias.  The value is stored in an auxiliary register
54653 ** and the number of that register is returned.  On subsequent calls,
54654 ** the register number is returned without generating any code.
54655 **
54656 ** Note that in order for this to work, code must be generated in the
54657 ** same order that it is executed.
54658 **
54659 ** Aliases are numbered starting with 1.  So iAlias is in the range
54660 ** of 1 to pParse->nAlias inclusive.  
54661 **
54662 ** pParse->aAlias[iAlias-1] records the register number where the value
54663 ** of the iAlias-th alias is stored.  If zero, that means that the
54664 ** alias has not yet been computed.
54665 */
54666 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr){
54667   sqlite3 *db = pParse->db;
54668   int iReg;
54669   if( pParse->aAlias==0 ){
54670     pParse->aAlias = sqlite3DbMallocZero(db, 
54671                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
54672     if( db->mallocFailed ) return 0;
54673   }
54674   assert( iAlias>0 && iAlias<=pParse->nAlias );
54675   iReg = pParse->aAlias[iAlias-1];
54676   if( iReg==0 ){
54677     iReg = ++pParse->nMem;
54678     sqlite3ExprCode(pParse, pExpr, iReg);
54679     pParse->aAlias[iAlias-1] = iReg;
54680   }
54681   return iReg;
54682 }
54683
54684 /*
54685 ** Generate code into the current Vdbe to evaluate the given
54686 ** expression.  Attempt to store the results in register "target".
54687 ** Return the register where results are stored.
54688 **
54689 ** With this routine, there is no guarantee that results will
54690 ** be stored in target.  The result might be stored in some other
54691 ** register if it is convenient to do so.  The calling function
54692 ** must check the return code and move the results to the desired
54693 ** register.
54694 */
54695 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
54696   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
54697   int op;                   /* The opcode being coded */
54698   int inReg = target;       /* Results stored in register inReg */
54699   int regFree1 = 0;         /* If non-zero free this temporary register */
54700   int regFree2 = 0;         /* If non-zero free this temporary register */
54701   int r1, r2, r3, r4;       /* Various register numbers */
54702   sqlite3 *db;
54703
54704   db = pParse->db;
54705   assert( v!=0 || db->mallocFailed );
54706   assert( target>0 && target<=pParse->nMem );
54707   if( v==0 ) return 0;
54708
54709   if( pExpr==0 ){
54710     op = TK_NULL;
54711   }else{
54712     op = pExpr->op;
54713   }
54714   switch( op ){
54715     case TK_AGG_COLUMN: {
54716       AggInfo *pAggInfo = pExpr->pAggInfo;
54717       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
54718       if( !pAggInfo->directMode ){
54719         assert( pCol->iMem>0 );
54720         inReg = pCol->iMem;
54721         break;
54722       }else if( pAggInfo->useSortingIdx ){
54723         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
54724                               pCol->iSorterColumn, target);
54725         break;
54726       }
54727       /* Otherwise, fall thru into the TK_COLUMN case */
54728     }
54729     case TK_COLUMN: {
54730       if( pExpr->iTable<0 ){
54731         /* This only happens when coding check constraints */
54732         assert( pParse->ckBase>0 );
54733         inReg = pExpr->iColumn + pParse->ckBase;
54734       }else{
54735         testcase( (pExpr->flags & EP_AnyAff)!=0 );
54736         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
54737                                  pExpr->iColumn, pExpr->iTable, target,
54738                                  pExpr->flags & EP_AnyAff);
54739       }
54740       break;
54741     }
54742     case TK_INTEGER: {
54743       codeInteger(v, pExpr, 0, target);
54744       break;
54745     }
54746     case TK_FLOAT: {
54747       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
54748       break;
54749     }
54750     case TK_STRING: {
54751       sqlite3DequoteExpr(db, pExpr);
54752       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
54753                         (char*)pExpr->token.z, pExpr->token.n);
54754       break;
54755     }
54756     case TK_NULL: {
54757       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
54758       break;
54759     }
54760 #ifndef SQLITE_OMIT_BLOB_LITERAL
54761     case TK_BLOB: {
54762       int n;
54763       const char *z;
54764       char *zBlob;
54765       assert( pExpr->token.n>=3 );
54766       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
54767       assert( pExpr->token.z[1]=='\'' );
54768       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
54769       n = pExpr->token.n - 3;
54770       z = (char*)pExpr->token.z + 2;
54771       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
54772       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
54773       break;
54774     }
54775 #endif
54776     case TK_VARIABLE: {
54777       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
54778       if( pExpr->token.n>1 ){
54779         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
54780       }
54781       break;
54782     }
54783     case TK_REGISTER: {
54784       inReg = pExpr->iTable;
54785       break;
54786     }
54787     case TK_AS: {
54788       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft);
54789       break;
54790     }
54791 #ifndef SQLITE_OMIT_CAST
54792     case TK_CAST: {
54793       /* Expressions of the form:   CAST(pLeft AS token) */
54794       int aff, to_op;
54795       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
54796       aff = sqlite3AffinityType(&pExpr->token);
54797       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
54798       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
54799       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
54800       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
54801       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
54802       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
54803       testcase( to_op==OP_ToText );
54804       testcase( to_op==OP_ToBlob );
54805       testcase( to_op==OP_ToNumeric );
54806       testcase( to_op==OP_ToInt );
54807       testcase( to_op==OP_ToReal );
54808       sqlite3VdbeAddOp1(v, to_op, inReg);
54809       testcase( usedAsColumnCache(pParse, inReg, inReg) );
54810       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
54811       break;
54812     }
54813 #endif /* SQLITE_OMIT_CAST */
54814     case TK_LT:
54815     case TK_LE:
54816     case TK_GT:
54817     case TK_GE:
54818     case TK_NE:
54819     case TK_EQ: {
54820       assert( TK_LT==OP_Lt );
54821       assert( TK_LE==OP_Le );
54822       assert( TK_GT==OP_Gt );
54823       assert( TK_GE==OP_Ge );
54824       assert( TK_EQ==OP_Eq );
54825       assert( TK_NE==OP_Ne );
54826       testcase( op==TK_LT );
54827       testcase( op==TK_LE );
54828       testcase( op==TK_GT );
54829       testcase( op==TK_GE );
54830       testcase( op==TK_EQ );
54831       testcase( op==TK_NE );
54832       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
54833                                   pExpr->pRight, &r2, &regFree2);
54834       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
54835                   r1, r2, inReg, SQLITE_STOREP2);
54836       testcase( regFree1==0 );
54837       testcase( regFree2==0 );
54838       break;
54839     }
54840     case TK_AND:
54841     case TK_OR:
54842     case TK_PLUS:
54843     case TK_STAR:
54844     case TK_MINUS:
54845     case TK_REM:
54846     case TK_BITAND:
54847     case TK_BITOR:
54848     case TK_SLASH:
54849     case TK_LSHIFT:
54850     case TK_RSHIFT: 
54851     case TK_CONCAT: {
54852       assert( TK_AND==OP_And );
54853       assert( TK_OR==OP_Or );
54854       assert( TK_PLUS==OP_Add );
54855       assert( TK_MINUS==OP_Subtract );
54856       assert( TK_REM==OP_Remainder );
54857       assert( TK_BITAND==OP_BitAnd );
54858       assert( TK_BITOR==OP_BitOr );
54859       assert( TK_SLASH==OP_Divide );
54860       assert( TK_LSHIFT==OP_ShiftLeft );
54861       assert( TK_RSHIFT==OP_ShiftRight );
54862       assert( TK_CONCAT==OP_Concat );
54863       testcase( op==TK_AND );
54864       testcase( op==TK_OR );
54865       testcase( op==TK_PLUS );
54866       testcase( op==TK_MINUS );
54867       testcase( op==TK_REM );
54868       testcase( op==TK_BITAND );
54869       testcase( op==TK_BITOR );
54870       testcase( op==TK_SLASH );
54871       testcase( op==TK_LSHIFT );
54872       testcase( op==TK_RSHIFT );
54873       testcase( op==TK_CONCAT );
54874       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
54875       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
54876       sqlite3VdbeAddOp3(v, op, r2, r1, target);
54877       testcase( regFree1==0 );
54878       testcase( regFree2==0 );
54879       break;
54880     }
54881     case TK_UMINUS: {
54882       Expr *pLeft = pExpr->pLeft;
54883       assert( pLeft );
54884       if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
54885         if( pLeft->op==TK_FLOAT ){
54886           codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
54887         }else{
54888           codeInteger(v, pLeft, 1, target);
54889         }
54890       }else{
54891         regFree1 = r1 = sqlite3GetTempReg(pParse);
54892         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
54893         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
54894         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
54895         testcase( regFree2==0 );
54896       }
54897       inReg = target;
54898       break;
54899     }
54900     case TK_BITNOT:
54901     case TK_NOT: {
54902       assert( TK_BITNOT==OP_BitNot );
54903       assert( TK_NOT==OP_Not );
54904       testcase( op==TK_BITNOT );
54905       testcase( op==TK_NOT );
54906       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
54907       testcase( inReg==target );
54908       testcase( usedAsColumnCache(pParse, inReg, inReg) );
54909       inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
54910       sqlite3VdbeAddOp1(v, op, inReg);
54911       break;
54912     }
54913     case TK_ISNULL:
54914     case TK_NOTNULL: {
54915       int addr;
54916       assert( TK_ISNULL==OP_IsNull );
54917       assert( TK_NOTNULL==OP_NotNull );
54918       testcase( op==TK_ISNULL );
54919       testcase( op==TK_NOTNULL );
54920       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
54921       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
54922       testcase( regFree1==0 );
54923       addr = sqlite3VdbeAddOp1(v, op, r1);
54924       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
54925       sqlite3VdbeJumpHere(v, addr);
54926       break;
54927     }
54928     case TK_AGG_FUNCTION: {
54929       AggInfo *pInfo = pExpr->pAggInfo;
54930       if( pInfo==0 ){
54931         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
54932             &pExpr->span);
54933       }else{
54934         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
54935       }
54936       break;
54937     }
54938     case TK_CONST_FUNC:
54939     case TK_FUNCTION: {
54940       ExprList *pList = pExpr->pList;
54941       int nExpr = pList ? pList->nExpr : 0;
54942       FuncDef *pDef;
54943       int nId;
54944       const char *zId;
54945       int constMask = 0;
54946       int i;
54947       u8 enc = ENC(db);
54948       CollSeq *pColl = 0;
54949
54950       testcase( op==TK_CONST_FUNC );
54951       testcase( op==TK_FUNCTION );
54952       zId = (char*)pExpr->token.z;
54953       nId = pExpr->token.n;
54954       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
54955       assert( pDef!=0 );
54956       if( pList ){
54957         nExpr = pList->nExpr;
54958         r1 = sqlite3GetTempRange(pParse, nExpr);
54959         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
54960       }else{
54961         nExpr = r1 = 0;
54962       }
54963 #ifndef SQLITE_OMIT_VIRTUALTABLE
54964       /* Possibly overload the function if the first argument is
54965       ** a virtual table column.
54966       **
54967       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
54968       ** second argument, not the first, as the argument to test to
54969       ** see if it is a column in a virtual table.  This is done because
54970       ** the left operand of infix functions (the operand we want to
54971       ** control overloading) ends up as the second argument to the
54972       ** function.  The expression "A glob B" is equivalent to 
54973       ** "glob(B,A).  We want to use the A in "A glob B" to test
54974       ** for function overloading.  But we use the B term in "glob(B,A)".
54975       */
54976       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
54977         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
54978       }else if( nExpr>0 ){
54979         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
54980       }
54981 #endif
54982       for(i=0; i<nExpr && i<32; i++){
54983         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
54984           constMask |= (1<<i);
54985         }
54986         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
54987           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
54988         }
54989       }
54990       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
54991         if( !pColl ) pColl = db->pDfltColl; 
54992         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
54993       }
54994       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
54995                         (char*)pDef, P4_FUNCDEF);
54996       sqlite3VdbeChangeP5(v, nExpr);
54997       if( nExpr ){
54998         sqlite3ReleaseTempRange(pParse, r1, nExpr);
54999       }
55000       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
55001       break;
55002     }
55003 #ifndef SQLITE_OMIT_SUBQUERY
55004     case TK_EXISTS:
55005     case TK_SELECT: {
55006       testcase( op==TK_EXISTS );
55007       testcase( op==TK_SELECT );
55008       if( pExpr->iColumn==0 ){
55009         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
55010       }
55011       inReg = pExpr->iColumn;
55012       break;
55013     }
55014     case TK_IN: {
55015       int rNotFound = 0;
55016       int rMayHaveNull = 0;
55017       int j2, j3, j4, j5;
55018       char affinity;
55019       int eType;
55020
55021       VdbeNoopComment((v, "begin IN expr r%d", target));
55022       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
55023       if( rMayHaveNull ){
55024         rNotFound = ++pParse->nMem;
55025       }
55026
55027       /* Figure out the affinity to use to create a key from the results
55028       ** of the expression. affinityStr stores a static string suitable for
55029       ** P4 of OP_MakeRecord.
55030       */
55031       affinity = comparisonAffinity(pExpr);
55032
55033
55034       /* Code the <expr> from "<expr> IN (...)". The temporary table
55035       ** pExpr->iTable contains the values that make up the (...) set.
55036       */
55037       pParse->disableColCache++;
55038       sqlite3ExprCode(pParse, pExpr->pLeft, target);
55039       pParse->disableColCache--;
55040       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
55041       if( eType==IN_INDEX_ROWID ){
55042         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
55043         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
55044         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
55045         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
55046         sqlite3VdbeJumpHere(v, j3);
55047         sqlite3VdbeJumpHere(v, j4);
55048         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
55049       }else{
55050         r2 = regFree2 = sqlite3GetTempReg(pParse);
55051
55052         /* Create a record and test for set membership. If the set contains
55053         ** the value, then jump to the end of the test code. The target
55054         ** register still contains the true (1) value written to it earlier.
55055         */
55056         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
55057         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
55058         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
55059
55060         /* If the set membership test fails, then the result of the 
55061         ** "x IN (...)" expression must be either 0 or NULL. If the set
55062         ** contains no NULL values, then the result is 0. If the set 
55063         ** contains one or more NULL values, then the result of the
55064         ** expression is also NULL.
55065         */
55066         if( rNotFound==0 ){
55067           /* This branch runs if it is known at compile time (now) that 
55068           ** the set contains no NULL values. This happens as the result
55069           ** of a "NOT NULL" constraint in the database schema. No need
55070           ** to test the data structure at runtime in this case.
55071           */
55072           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
55073         }else{
55074           /* This block populates the rNotFound register with either NULL
55075           ** or 0 (an integer value). If the data structure contains one
55076           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
55077           ** to 0. If register rMayHaveNull is already set to some value
55078           ** other than NULL, then the test has already been run and 
55079           ** rNotFound is already populated.
55080           */
55081           static const char nullRecord[] = { 0x02, 0x00 };
55082           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
55083           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
55084           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
55085                              nullRecord, P4_STATIC);
55086           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
55087           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
55088           sqlite3VdbeJumpHere(v, j4);
55089           sqlite3VdbeJumpHere(v, j3);
55090
55091           /* Copy the value of register rNotFound (which is either NULL or 0)
55092           ** into the target register. This will be the result of the
55093           ** expression.
55094           */
55095           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
55096         }
55097       }
55098       sqlite3VdbeJumpHere(v, j2);
55099       sqlite3VdbeJumpHere(v, j5);
55100       VdbeComment((v, "end IN expr r%d", target));
55101       break;
55102     }
55103 #endif
55104     /*
55105     **    x BETWEEN y AND z
55106     **
55107     ** This is equivalent to
55108     **
55109     **    x>=y AND x<=z
55110     **
55111     ** X is stored in pExpr->pLeft.
55112     ** Y is stored in pExpr->pList->a[0].pExpr.
55113     ** Z is stored in pExpr->pList->a[1].pExpr.
55114     */
55115     case TK_BETWEEN: {
55116       Expr *pLeft = pExpr->pLeft;
55117       struct ExprList_item *pLItem = pExpr->pList->a;
55118       Expr *pRight = pLItem->pExpr;
55119
55120       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
55121                                   pRight, &r2, &regFree2);
55122       testcase( regFree1==0 );
55123       testcase( regFree2==0 );
55124       r3 = sqlite3GetTempReg(pParse);
55125       r4 = sqlite3GetTempReg(pParse);
55126       codeCompare(pParse, pLeft, pRight, OP_Ge,
55127                   r1, r2, r3, SQLITE_STOREP2);
55128       pLItem++;
55129       pRight = pLItem->pExpr;
55130       sqlite3ReleaseTempReg(pParse, regFree2);
55131       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
55132       testcase( regFree2==0 );
55133       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
55134       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
55135       sqlite3ReleaseTempReg(pParse, r3);
55136       sqlite3ReleaseTempReg(pParse, r4);
55137       break;
55138     }
55139     case TK_UPLUS: {
55140       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
55141       break;
55142     }
55143
55144     /*
55145     ** Form A:
55146     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
55147     **
55148     ** Form B:
55149     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
55150     **
55151     ** Form A is can be transformed into the equivalent form B as follows:
55152     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
55153     **        WHEN x=eN THEN rN ELSE y END
55154     **
55155     ** X (if it exists) is in pExpr->pLeft.
55156     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
55157     ** ELSE clause and no other term matches, then the result of the
55158     ** exprssion is NULL.
55159     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
55160     **
55161     ** The result of the expression is the Ri for the first matching Ei,
55162     ** or if there is no matching Ei, the ELSE term Y, or if there is
55163     ** no ELSE term, NULL.
55164     */
55165     case TK_CASE: {
55166       int endLabel;                     /* GOTO label for end of CASE stmt */
55167       int nextCase;                     /* GOTO label for next WHEN clause */
55168       int nExpr;                        /* 2x number of WHEN terms */
55169       int i;                            /* Loop counter */
55170       ExprList *pEList;                 /* List of WHEN terms */
55171       struct ExprList_item *aListelem;  /* Array of WHEN terms */
55172       Expr opCompare;                   /* The X==Ei expression */
55173       Expr cacheX;                      /* Cached expression X */
55174       Expr *pX;                         /* The X expression */
55175       Expr *pTest;                      /* X==Ei (form A) or just Ei (form B) */
55176
55177       assert(pExpr->pList);
55178       assert((pExpr->pList->nExpr % 2) == 0);
55179       assert(pExpr->pList->nExpr > 0);
55180       pEList = pExpr->pList;
55181       aListelem = pEList->a;
55182       nExpr = pEList->nExpr;
55183       endLabel = sqlite3VdbeMakeLabel(v);
55184       if( (pX = pExpr->pLeft)!=0 ){
55185         cacheX = *pX;
55186         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
55187         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
55188         testcase( regFree1==0 );
55189         cacheX.op = TK_REGISTER;
55190         opCompare.op = TK_EQ;
55191         opCompare.pLeft = &cacheX;
55192         pTest = &opCompare;
55193       }
55194       pParse->disableColCache++;
55195       for(i=0; i<nExpr; i=i+2){
55196         if( pX ){
55197           opCompare.pRight = aListelem[i].pExpr;
55198         }else{
55199           pTest = aListelem[i].pExpr;
55200         }
55201         nextCase = sqlite3VdbeMakeLabel(v);
55202         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
55203         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
55204         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
55205         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
55206         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
55207         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
55208         sqlite3VdbeResolveLabel(v, nextCase);
55209       }
55210       if( pExpr->pRight ){
55211         sqlite3ExprCode(pParse, pExpr->pRight, target);
55212       }else{
55213         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
55214       }
55215       sqlite3VdbeResolveLabel(v, endLabel);
55216       assert( pParse->disableColCache>0 );
55217       pParse->disableColCache--;
55218       break;
55219     }
55220 #ifndef SQLITE_OMIT_TRIGGER
55221     case TK_RAISE: {
55222       if( !pParse->trigStack ){
55223         sqlite3ErrorMsg(pParse,
55224                        "RAISE() may only be used within a trigger-program");
55225         return 0;
55226       }
55227       if( pExpr->iColumn!=OE_Ignore ){
55228          assert( pExpr->iColumn==OE_Rollback ||
55229                  pExpr->iColumn == OE_Abort ||
55230                  pExpr->iColumn == OE_Fail );
55231          sqlite3DequoteExpr(db, pExpr);
55232          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
55233                         (char*)pExpr->token.z, pExpr->token.n);
55234       } else {
55235          assert( pExpr->iColumn == OE_Ignore );
55236          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
55237          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
55238          VdbeComment((v, "raise(IGNORE)"));
55239       }
55240       break;
55241     }
55242 #endif
55243   }
55244   sqlite3ReleaseTempReg(pParse, regFree1);
55245   sqlite3ReleaseTempReg(pParse, regFree2);
55246   return inReg;
55247 }
55248
55249 /*
55250 ** Generate code to evaluate an expression and store the results
55251 ** into a register.  Return the register number where the results
55252 ** are stored.
55253 **
55254 ** If the register is a temporary register that can be deallocated,
55255 ** then write its number into *pReg.  If the result register is not
55256 ** a temporary, then set *pReg to zero.
55257 */
55258 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
55259   int r1 = sqlite3GetTempReg(pParse);
55260   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
55261   if( r2==r1 ){
55262     *pReg = r1;
55263   }else{
55264     sqlite3ReleaseTempReg(pParse, r1);
55265     *pReg = 0;
55266   }
55267   return r2;
55268 }
55269
55270 /*
55271 ** Generate code that will evaluate expression pExpr and store the
55272 ** results in register target.  The results are guaranteed to appear
55273 ** in register target.
55274 */
55275 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
55276   int inReg;
55277
55278   assert( target>0 && target<=pParse->nMem );
55279   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
55280   assert( pParse->pVdbe || pParse->db->mallocFailed );
55281   if( inReg!=target && pParse->pVdbe ){
55282     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
55283   }
55284   return target;
55285 }
55286
55287 /*
55288 ** Generate code that evalutes the given expression and puts the result
55289 ** in register target.
55290 **
55291 ** Also make a copy of the expression results into another "cache" register
55292 ** and modify the expression so that the next time it is evaluated,
55293 ** the result is a copy of the cache register.
55294 **
55295 ** This routine is used for expressions that are used multiple 
55296 ** times.  They are evaluated once and the results of the expression
55297 ** are reused.
55298 */
55299 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
55300   Vdbe *v = pParse->pVdbe;
55301   int inReg;
55302   inReg = sqlite3ExprCode(pParse, pExpr, target);
55303   assert( target>0 );
55304   if( pExpr->op!=TK_REGISTER ){  
55305     int iMem;
55306     iMem = ++pParse->nMem;
55307     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
55308     pExpr->iTable = iMem;
55309     pExpr->op = TK_REGISTER;
55310   }
55311   return inReg;
55312 }
55313
55314 /*
55315 ** Return TRUE if pExpr is an constant expression that is appropriate
55316 ** for factoring out of a loop.  Appropriate expressions are:
55317 **
55318 **    *  Any expression that evaluates to two or more opcodes.
55319 **
55320 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
55321 **       or OP_Variable that does not need to be placed in a 
55322 **       specific register.
55323 **
55324 ** There is no point in factoring out single-instruction constant
55325 ** expressions that need to be placed in a particular register.  
55326 ** We could factor them out, but then we would end up adding an
55327 ** OP_SCopy instruction to move the value into the correct register
55328 ** later.  We might as well just use the original instruction and
55329 ** avoid the OP_SCopy.
55330 */
55331 static int isAppropriateForFactoring(Expr *p){
55332   if( !sqlite3ExprIsConstantNotJoin(p) ){
55333     return 0;  /* Only constant expressions are appropriate for factoring */
55334   }
55335   if( (p->flags & EP_FixedDest)==0 ){
55336     return 1;  /* Any constant without a fixed destination is appropriate */
55337   }
55338   while( p->op==TK_UPLUS ) p = p->pLeft;
55339   switch( p->op ){
55340 #ifndef SQLITE_OMIT_BLOB_LITERAL
55341     case TK_BLOB:
55342 #endif
55343     case TK_VARIABLE:
55344     case TK_INTEGER:
55345     case TK_FLOAT:
55346     case TK_NULL:
55347     case TK_STRING: {
55348       testcase( p->op==TK_BLOB );
55349       testcase( p->op==TK_VARIABLE );
55350       testcase( p->op==TK_INTEGER );
55351       testcase( p->op==TK_FLOAT );
55352       testcase( p->op==TK_NULL );
55353       testcase( p->op==TK_STRING );
55354       /* Single-instruction constants with a fixed destination are
55355       ** better done in-line.  If we factor them, they will just end
55356       ** up generating an OP_SCopy to move the value to the destination
55357       ** register. */
55358       return 0;
55359     }
55360     case TK_UMINUS: {
55361        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
55362          return 0;
55363        }
55364        break;
55365     }
55366     default: {
55367       break;
55368     }
55369   }
55370   return 1;
55371 }
55372
55373 /*
55374 ** If pExpr is a constant expression that is appropriate for
55375 ** factoring out of a loop, then evaluate the expression
55376 ** into a register and convert the expression into a TK_REGISTER
55377 ** expression.
55378 */
55379 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
55380   Parse *pParse = pWalker->pParse;
55381   switch( pExpr->op ){
55382     case TK_REGISTER: {
55383       return 1;
55384     }
55385     case TK_FUNCTION:
55386     case TK_AGG_FUNCTION:
55387     case TK_CONST_FUNC: {
55388       /* The arguments to a function have a fixed destination.
55389       ** Mark them this way to avoid generated unneeded OP_SCopy
55390       ** instructions. 
55391       */
55392       ExprList *pList = pExpr->pList;
55393       if( pList ){
55394         int i = pList->nExpr;
55395         struct ExprList_item *pItem = pList->a;
55396         for(; i>0; i--, pItem++){
55397           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
55398         }
55399       }
55400       break;
55401     }
55402   }
55403   if( isAppropriateForFactoring(pExpr) ){
55404     int r1 = ++pParse->nMem;
55405     int r2;
55406     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
55407     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
55408     pExpr->op = TK_REGISTER;
55409     pExpr->iTable = r2;
55410     return WRC_Prune;
55411   }
55412   return WRC_Continue;
55413 }
55414
55415 /*
55416 ** Preevaluate constant subexpressions within pExpr and store the
55417 ** results in registers.  Modify pExpr so that the constant subexpresions
55418 ** are TK_REGISTER opcodes that refer to the precomputed values.
55419 */
55420 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
55421   Walker w;
55422   w.xExprCallback = evalConstExpr;
55423   w.xSelectCallback = 0;
55424   w.pParse = pParse;
55425   sqlite3WalkExpr(&w, pExpr);
55426 }
55427
55428
55429 /*
55430 ** Generate code that pushes the value of every element of the given
55431 ** expression list into a sequence of registers beginning at target.
55432 **
55433 ** Return the number of elements evaluated.
55434 */
55435 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
55436   Parse *pParse,     /* Parsing context */
55437   ExprList *pList,   /* The expression list to be coded */
55438   int target,        /* Where to write results */
55439   int doHardCopy     /* Make a hard copy of every element */
55440 ){
55441   struct ExprList_item *pItem;
55442   int i, n;
55443   assert( pList!=0 );
55444   assert( target>0 );
55445   n = pList->nExpr;
55446   for(pItem=pList->a, i=0; i<n; i++, pItem++){
55447     if( pItem->iAlias ){
55448       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr);
55449       Vdbe *v = sqlite3GetVdbe(pParse);
55450       sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
55451     }else{
55452       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
55453     }
55454     if( doHardCopy ){
55455       sqlite3ExprHardCopy(pParse, target, n);
55456     }
55457   }
55458   return n;
55459 }
55460
55461 /*
55462 ** Generate code for a boolean expression such that a jump is made
55463 ** to the label "dest" if the expression is true but execution
55464 ** continues straight thru if the expression is false.
55465 **
55466 ** If the expression evaluates to NULL (neither true nor false), then
55467 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
55468 **
55469 ** This code depends on the fact that certain token values (ex: TK_EQ)
55470 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
55471 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
55472 ** the make process cause these values to align.  Assert()s in the code
55473 ** below verify that the numbers are aligned correctly.
55474 */
55475 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
55476   Vdbe *v = pParse->pVdbe;
55477   int op = 0;
55478   int regFree1 = 0;
55479   int regFree2 = 0;
55480   int r1, r2;
55481
55482   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
55483   if( v==0 || pExpr==0 ) return;
55484   op = pExpr->op;
55485   switch( op ){
55486     case TK_AND: {
55487       int d2 = sqlite3VdbeMakeLabel(v);
55488       testcase( jumpIfNull==0 );
55489       testcase( pParse->disableColCache==0 );
55490       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
55491       pParse->disableColCache++;
55492       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
55493       assert( pParse->disableColCache>0 );
55494       pParse->disableColCache--;
55495       sqlite3VdbeResolveLabel(v, d2);
55496       break;
55497     }
55498     case TK_OR: {
55499       testcase( jumpIfNull==0 );
55500       testcase( pParse->disableColCache==0 );
55501       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
55502       pParse->disableColCache++;
55503       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
55504       assert( pParse->disableColCache>0 );
55505       pParse->disableColCache--;
55506       break;
55507     }
55508     case TK_NOT: {
55509       testcase( jumpIfNull==0 );
55510       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
55511       break;
55512     }
55513     case TK_LT:
55514     case TK_LE:
55515     case TK_GT:
55516     case TK_GE:
55517     case TK_NE:
55518     case TK_EQ: {
55519       assert( TK_LT==OP_Lt );
55520       assert( TK_LE==OP_Le );
55521       assert( TK_GT==OP_Gt );
55522       assert( TK_GE==OP_Ge );
55523       assert( TK_EQ==OP_Eq );
55524       assert( TK_NE==OP_Ne );
55525       testcase( op==TK_LT );
55526       testcase( op==TK_LE );
55527       testcase( op==TK_GT );
55528       testcase( op==TK_GE );
55529       testcase( op==TK_EQ );
55530       testcase( op==TK_NE );
55531       testcase( jumpIfNull==0 );
55532       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
55533                                   pExpr->pRight, &r2, &regFree2);
55534       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
55535                   r1, r2, dest, jumpIfNull);
55536       testcase( regFree1==0 );
55537       testcase( regFree2==0 );
55538       break;
55539     }
55540     case TK_ISNULL:
55541     case TK_NOTNULL: {
55542       assert( TK_ISNULL==OP_IsNull );
55543       assert( TK_NOTNULL==OP_NotNull );
55544       testcase( op==TK_ISNULL );
55545       testcase( op==TK_NOTNULL );
55546       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55547       sqlite3VdbeAddOp2(v, op, r1, dest);
55548       testcase( regFree1==0 );
55549       break;
55550     }
55551     case TK_BETWEEN: {
55552       /*    x BETWEEN y AND z
55553       **
55554       ** Is equivalent to 
55555       **
55556       **    x>=y AND x<=z
55557       **
55558       ** Code it as such, taking care to do the common subexpression
55559       ** elementation of x.
55560       */
55561       Expr exprAnd;
55562       Expr compLeft;
55563       Expr compRight;
55564       Expr exprX;
55565
55566       exprX = *pExpr->pLeft;
55567       exprAnd.op = TK_AND;
55568       exprAnd.pLeft = &compLeft;
55569       exprAnd.pRight = &compRight;
55570       compLeft.op = TK_GE;
55571       compLeft.pLeft = &exprX;
55572       compLeft.pRight = pExpr->pList->a[0].pExpr;
55573       compRight.op = TK_LE;
55574       compRight.pLeft = &exprX;
55575       compRight.pRight = pExpr->pList->a[1].pExpr;
55576       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
55577       testcase( regFree1==0 );
55578       exprX.op = TK_REGISTER;
55579       testcase( jumpIfNull==0 );
55580       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
55581       break;
55582     }
55583     default: {
55584       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
55585       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
55586       testcase( regFree1==0 );
55587       testcase( jumpIfNull==0 );
55588       break;
55589     }
55590   }
55591   sqlite3ReleaseTempReg(pParse, regFree1);
55592   sqlite3ReleaseTempReg(pParse, regFree2);  
55593 }
55594
55595 /*
55596 ** Generate code for a boolean expression such that a jump is made
55597 ** to the label "dest" if the expression is false but execution
55598 ** continues straight thru if the expression is true.
55599 **
55600 ** If the expression evaluates to NULL (neither true nor false) then
55601 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
55602 ** is 0.
55603 */
55604 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
55605   Vdbe *v = pParse->pVdbe;
55606   int op = 0;
55607   int regFree1 = 0;
55608   int regFree2 = 0;
55609   int r1, r2;
55610
55611   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
55612   if( v==0 || pExpr==0 ) return;
55613
55614   /* The value of pExpr->op and op are related as follows:
55615   **
55616   **       pExpr->op            op
55617   **       ---------          ----------
55618   **       TK_ISNULL          OP_NotNull
55619   **       TK_NOTNULL         OP_IsNull
55620   **       TK_NE              OP_Eq
55621   **       TK_EQ              OP_Ne
55622   **       TK_GT              OP_Le
55623   **       TK_LE              OP_Gt
55624   **       TK_GE              OP_Lt
55625   **       TK_LT              OP_Ge
55626   **
55627   ** For other values of pExpr->op, op is undefined and unused.
55628   ** The value of TK_ and OP_ constants are arranged such that we
55629   ** can compute the mapping above using the following expression.
55630   ** Assert()s verify that the computation is correct.
55631   */
55632   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
55633
55634   /* Verify correct alignment of TK_ and OP_ constants
55635   */
55636   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
55637   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
55638   assert( pExpr->op!=TK_NE || op==OP_Eq );
55639   assert( pExpr->op!=TK_EQ || op==OP_Ne );
55640   assert( pExpr->op!=TK_LT || op==OP_Ge );
55641   assert( pExpr->op!=TK_LE || op==OP_Gt );
55642   assert( pExpr->op!=TK_GT || op==OP_Le );
55643   assert( pExpr->op!=TK_GE || op==OP_Lt );
55644
55645   switch( pExpr->op ){
55646     case TK_AND: {
55647       testcase( jumpIfNull==0 );
55648       testcase( pParse->disableColCache==0 );
55649       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
55650       pParse->disableColCache++;
55651       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
55652       assert( pParse->disableColCache>0 );
55653       pParse->disableColCache--;
55654       break;
55655     }
55656     case TK_OR: {
55657       int d2 = sqlite3VdbeMakeLabel(v);
55658       testcase( jumpIfNull==0 );
55659       testcase( pParse->disableColCache==0 );
55660       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
55661       pParse->disableColCache++;
55662       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
55663       assert( pParse->disableColCache>0 );
55664       pParse->disableColCache--;
55665       sqlite3VdbeResolveLabel(v, d2);
55666       break;
55667     }
55668     case TK_NOT: {
55669       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
55670       break;
55671     }
55672     case TK_LT:
55673     case TK_LE:
55674     case TK_GT:
55675     case TK_GE:
55676     case TK_NE:
55677     case TK_EQ: {
55678       testcase( op==TK_LT );
55679       testcase( op==TK_LE );
55680       testcase( op==TK_GT );
55681       testcase( op==TK_GE );
55682       testcase( op==TK_EQ );
55683       testcase( op==TK_NE );
55684       testcase( jumpIfNull==0 );
55685       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
55686                                   pExpr->pRight, &r2, &regFree2);
55687       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
55688                   r1, r2, dest, jumpIfNull);
55689       testcase( regFree1==0 );
55690       testcase( regFree2==0 );
55691       break;
55692     }
55693     case TK_ISNULL:
55694     case TK_NOTNULL: {
55695       testcase( op==TK_ISNULL );
55696       testcase( op==TK_NOTNULL );
55697       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
55698       sqlite3VdbeAddOp2(v, op, r1, dest);
55699       testcase( regFree1==0 );
55700       break;
55701     }
55702     case TK_BETWEEN: {
55703       /*    x BETWEEN y AND z
55704       **
55705       ** Is equivalent to 
55706       **
55707       **    x>=y AND x<=z
55708       **
55709       ** Code it as such, taking care to do the common subexpression
55710       ** elementation of x.
55711       */
55712       Expr exprAnd;
55713       Expr compLeft;
55714       Expr compRight;
55715       Expr exprX;
55716
55717       exprX = *pExpr->pLeft;
55718       exprAnd.op = TK_AND;
55719       exprAnd.pLeft = &compLeft;
55720       exprAnd.pRight = &compRight;
55721       compLeft.op = TK_GE;
55722       compLeft.pLeft = &exprX;
55723       compLeft.pRight = pExpr->pList->a[0].pExpr;
55724       compRight.op = TK_LE;
55725       compRight.pLeft = &exprX;
55726       compRight.pRight = pExpr->pList->a[1].pExpr;
55727       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
55728       testcase( regFree1==0 );
55729       exprX.op = TK_REGISTER;
55730       testcase( jumpIfNull==0 );
55731       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
55732       break;
55733     }
55734     default: {
55735       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
55736       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
55737       testcase( regFree1==0 );
55738       testcase( jumpIfNull==0 );
55739       break;
55740     }
55741   }
55742   sqlite3ReleaseTempReg(pParse, regFree1);
55743   sqlite3ReleaseTempReg(pParse, regFree2);
55744 }
55745
55746 /*
55747 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
55748 ** if they are identical and return FALSE if they differ in any way.
55749 **
55750 ** Sometimes this routine will return FALSE even if the two expressions
55751 ** really are equivalent.  If we cannot prove that the expressions are
55752 ** identical, we return FALSE just to be safe.  So if this routine
55753 ** returns false, then you do not really know for certain if the two
55754 ** expressions are the same.  But if you get a TRUE return, then you
55755 ** can be sure the expressions are the same.  In the places where
55756 ** this routine is used, it does not hurt to get an extra FALSE - that
55757 ** just might result in some slightly slower code.  But returning
55758 ** an incorrect TRUE could lead to a malfunction.
55759 */
55760 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
55761   int i;
55762   if( pA==0||pB==0 ){
55763     return pB==pA;
55764   }
55765   if( pA->op!=pB->op ) return 0;
55766   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
55767   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
55768   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
55769   if( pA->pList ){
55770     if( pB->pList==0 ) return 0;
55771     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
55772     for(i=0; i<pA->pList->nExpr; i++){
55773       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
55774         return 0;
55775       }
55776     }
55777   }else if( pB->pList ){
55778     return 0;
55779   }
55780   if( pA->pSelect || pB->pSelect ) return 0;
55781   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
55782   if( pA->op!=TK_COLUMN && pA->token.z ){
55783     if( pB->token.z==0 ) return 0;
55784     if( pB->token.n!=pA->token.n ) return 0;
55785     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
55786       return 0;
55787     }
55788   }
55789   return 1;
55790 }
55791
55792
55793 /*
55794 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
55795 ** the new element.  Return a negative number if malloc fails.
55796 */
55797 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
55798   int i;
55799   pInfo->aCol = sqlite3ArrayAllocate(
55800        db,
55801        pInfo->aCol,
55802        sizeof(pInfo->aCol[0]),
55803        3,
55804        &pInfo->nColumn,
55805        &pInfo->nColumnAlloc,
55806        &i
55807   );
55808   return i;
55809 }    
55810
55811 /*
55812 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
55813 ** the new element.  Return a negative number if malloc fails.
55814 */
55815 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
55816   int i;
55817   pInfo->aFunc = sqlite3ArrayAllocate(
55818        db, 
55819        pInfo->aFunc,
55820        sizeof(pInfo->aFunc[0]),
55821        3,
55822        &pInfo->nFunc,
55823        &pInfo->nFuncAlloc,
55824        &i
55825   );
55826   return i;
55827 }    
55828
55829 /*
55830 ** This is the xExprCallback for a tree walker.  It is used to
55831 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
55832 ** for additional information.
55833 */
55834 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
55835   int i;
55836   NameContext *pNC = pWalker->u.pNC;
55837   Parse *pParse = pNC->pParse;
55838   SrcList *pSrcList = pNC->pSrcList;
55839   AggInfo *pAggInfo = pNC->pAggInfo;
55840
55841   switch( pExpr->op ){
55842     case TK_AGG_COLUMN:
55843     case TK_COLUMN: {
55844       testcase( pExpr->op==TK_AGG_COLUMN );
55845       testcase( pExpr->op==TK_COLUMN );
55846       /* Check to see if the column is in one of the tables in the FROM
55847       ** clause of the aggregate query */
55848       if( pSrcList ){
55849         struct SrcList_item *pItem = pSrcList->a;
55850         for(i=0; i<pSrcList->nSrc; i++, pItem++){
55851           struct AggInfo_col *pCol;
55852           if( pExpr->iTable==pItem->iCursor ){
55853             /* If we reach this point, it means that pExpr refers to a table
55854             ** that is in the FROM clause of the aggregate query.  
55855             **
55856             ** Make an entry for the column in pAggInfo->aCol[] if there
55857             ** is not an entry there already.
55858             */
55859             int k;
55860             pCol = pAggInfo->aCol;
55861             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
55862               if( pCol->iTable==pExpr->iTable &&
55863                   pCol->iColumn==pExpr->iColumn ){
55864                 break;
55865               }
55866             }
55867             if( (k>=pAggInfo->nColumn)
55868              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
55869             ){
55870               pCol = &pAggInfo->aCol[k];
55871               pCol->pTab = pExpr->pTab;
55872               pCol->iTable = pExpr->iTable;
55873               pCol->iColumn = pExpr->iColumn;
55874               pCol->iMem = ++pParse->nMem;
55875               pCol->iSorterColumn = -1;
55876               pCol->pExpr = pExpr;
55877               if( pAggInfo->pGroupBy ){
55878                 int j, n;
55879                 ExprList *pGB = pAggInfo->pGroupBy;
55880                 struct ExprList_item *pTerm = pGB->a;
55881                 n = pGB->nExpr;
55882                 for(j=0; j<n; j++, pTerm++){
55883                   Expr *pE = pTerm->pExpr;
55884                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
55885                       pE->iColumn==pExpr->iColumn ){
55886                     pCol->iSorterColumn = j;
55887                     break;
55888                   }
55889                 }
55890               }
55891               if( pCol->iSorterColumn<0 ){
55892                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
55893               }
55894             }
55895             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
55896             ** because it was there before or because we just created it).
55897             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
55898             ** pAggInfo->aCol[] entry.
55899             */
55900             pExpr->pAggInfo = pAggInfo;
55901             pExpr->op = TK_AGG_COLUMN;
55902             pExpr->iAgg = k;
55903             break;
55904           } /* endif pExpr->iTable==pItem->iCursor */
55905         } /* end loop over pSrcList */
55906       }
55907       return WRC_Prune;
55908     }
55909     case TK_AGG_FUNCTION: {
55910       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
55911       ** to be ignored */
55912       if( pNC->nDepth==0 ){
55913         /* Check to see if pExpr is a duplicate of another aggregate 
55914         ** function that is already in the pAggInfo structure
55915         */
55916         struct AggInfo_func *pItem = pAggInfo->aFunc;
55917         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
55918           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
55919             break;
55920           }
55921         }
55922         if( i>=pAggInfo->nFunc ){
55923           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
55924           */
55925           u8 enc = ENC(pParse->db);
55926           i = addAggInfoFunc(pParse->db, pAggInfo);
55927           if( i>=0 ){
55928             pItem = &pAggInfo->aFunc[i];
55929             pItem->pExpr = pExpr;
55930             pItem->iMem = ++pParse->nMem;
55931             pItem->pFunc = sqlite3FindFunction(pParse->db,
55932                    (char*)pExpr->token.z, pExpr->token.n,
55933                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
55934             if( pExpr->flags & EP_Distinct ){
55935               pItem->iDistinct = pParse->nTab++;
55936             }else{
55937               pItem->iDistinct = -1;
55938             }
55939           }
55940         }
55941         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
55942         */
55943         pExpr->iAgg = i;
55944         pExpr->pAggInfo = pAggInfo;
55945         return WRC_Prune;
55946       }
55947     }
55948   }
55949   return WRC_Continue;
55950 }
55951 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
55952   NameContext *pNC = pWalker->u.pNC;
55953   if( pNC->nDepth==0 ){
55954     pNC->nDepth++;
55955     sqlite3WalkSelect(pWalker, pSelect);
55956     pNC->nDepth--;
55957     return WRC_Prune;
55958   }else{
55959     return WRC_Continue;
55960   }
55961 }
55962
55963 /*
55964 ** Analyze the given expression looking for aggregate functions and
55965 ** for variables that need to be added to the pParse->aAgg[] array.
55966 ** Make additional entries to the pParse->aAgg[] array as necessary.
55967 **
55968 ** This routine should only be called after the expression has been
55969 ** analyzed by sqlite3ResolveExprNames().
55970 */
55971 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
55972   Walker w;
55973   w.xExprCallback = analyzeAggregate;
55974   w.xSelectCallback = analyzeAggregatesInSelect;
55975   w.u.pNC = pNC;
55976   sqlite3WalkExpr(&w, pExpr);
55977 }
55978
55979 /*
55980 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
55981 ** expression list.  Return the number of errors.
55982 **
55983 ** If an error is found, the analysis is cut short.
55984 */
55985 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
55986   struct ExprList_item *pItem;
55987   int i;
55988   if( pList ){
55989     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
55990       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
55991     }
55992   }
55993 }
55994
55995 /*
55996 ** Allocate or deallocate temporary use registers during code generation.
55997 */
55998 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
55999   if( pParse->nTempReg==0 ){
56000     return ++pParse->nMem;
56001   }
56002   return pParse->aTempReg[--pParse->nTempReg];
56003 }
56004 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
56005   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
56006     sqlite3ExprWritableRegister(pParse, iReg, iReg);
56007     pParse->aTempReg[pParse->nTempReg++] = iReg;
56008   }
56009 }
56010
56011 /*
56012 ** Allocate or deallocate a block of nReg consecutive registers
56013 */
56014 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
56015   int i, n;
56016   i = pParse->iRangeReg;
56017   n = pParse->nRangeReg;
56018   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
56019     pParse->iRangeReg += nReg;
56020     pParse->nRangeReg -= nReg;
56021   }else{
56022     i = pParse->nMem+1;
56023     pParse->nMem += nReg;
56024   }
56025   return i;
56026 }
56027 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
56028   if( nReg>pParse->nRangeReg ){
56029     pParse->nRangeReg = nReg;
56030     pParse->iRangeReg = iReg;
56031   }
56032 }
56033
56034 /************** End of expr.c ************************************************/
56035 /************** Begin file alter.c *******************************************/
56036 /*
56037 ** 2005 February 15
56038 **
56039 ** The author disclaims copyright to this source code.  In place of
56040 ** a legal notice, here is a blessing:
56041 **
56042 **    May you do good and not evil.
56043 **    May you find forgiveness for yourself and forgive others.
56044 **    May you share freely, never taking more than you give.
56045 **
56046 *************************************************************************
56047 ** This file contains C code routines that used to generate VDBE code
56048 ** that implements the ALTER TABLE command.
56049 **
56050 ** $Id: alter.c,v 1.48 2008/08/08 14:19:41 drh Exp $
56051 */
56052
56053 /*
56054 ** The code in this file only exists if we are not omitting the
56055 ** ALTER TABLE logic from the build.
56056 */
56057 #ifndef SQLITE_OMIT_ALTERTABLE
56058
56059
56060 /*
56061 ** This function is used by SQL generated to implement the 
56062 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
56063 ** CREATE INDEX command. The second is a table name. The table name in 
56064 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
56065 ** argument and the result returned. Examples:
56066 **
56067 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
56068 **     -> 'CREATE TABLE def(a, b, c)'
56069 **
56070 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
56071 **     -> 'CREATE INDEX i ON def(a, b, c)'
56072 */
56073 static void renameTableFunc(
56074   sqlite3_context *context,
56075   int argc,
56076   sqlite3_value **argv
56077 ){
56078   unsigned char const *zSql = sqlite3_value_text(argv[0]);
56079   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
56080
56081   int token;
56082   Token tname;
56083   unsigned char const *zCsr = zSql;
56084   int len = 0;
56085   char *zRet;
56086
56087   sqlite3 *db = sqlite3_context_db_handle(context);
56088
56089   /* The principle used to locate the table name in the CREATE TABLE 
56090   ** statement is that the table name is the first non-space token that
56091   ** is immediately followed by a TK_LP or TK_USING token.
56092   */
56093   if( zSql ){
56094     do {
56095       if( !*zCsr ){
56096         /* Ran out of input before finding an opening bracket. Return NULL. */
56097         return;
56098       }
56099
56100       /* Store the token that zCsr points to in tname. */
56101       tname.z = zCsr;
56102       tname.n = len;
56103
56104       /* Advance zCsr to the next token. Store that token type in 'token',
56105       ** and its length in 'len' (to be used next iteration of this loop).
56106       */
56107       do {
56108         zCsr += len;
56109         len = sqlite3GetToken(zCsr, &token);
56110       } while( token==TK_SPACE );
56111       assert( len>0 );
56112     } while( token!=TK_LP && token!=TK_USING );
56113
56114     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
56115        zTableName, tname.z+tname.n);
56116     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
56117   }
56118 }
56119
56120 #ifndef SQLITE_OMIT_TRIGGER
56121 /* This function is used by SQL generated to implement the
56122 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
56123 ** statement. The second is a table name. The table name in the CREATE 
56124 ** TRIGGER statement is replaced with the third argument and the result 
56125 ** returned. This is analagous to renameTableFunc() above, except for CREATE
56126 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
56127 */
56128 static void renameTriggerFunc(
56129   sqlite3_context *context,
56130   int argc,
56131   sqlite3_value **argv
56132 ){
56133   unsigned char const *zSql = sqlite3_value_text(argv[0]);
56134   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
56135
56136   int token;
56137   Token tname;
56138   int dist = 3;
56139   unsigned char const *zCsr = zSql;
56140   int len = 0;
56141   char *zRet;
56142
56143   sqlite3 *db = sqlite3_context_db_handle(context);
56144
56145   /* The principle used to locate the table name in the CREATE TRIGGER 
56146   ** statement is that the table name is the first token that is immediatedly
56147   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
56148   ** of TK_WHEN, TK_BEGIN or TK_FOR.
56149   */
56150   if( zSql ){
56151     do {
56152
56153       if( !*zCsr ){
56154         /* Ran out of input before finding the table name. Return NULL. */
56155         return;
56156       }
56157
56158       /* Store the token that zCsr points to in tname. */
56159       tname.z = zCsr;
56160       tname.n = len;
56161
56162       /* Advance zCsr to the next token. Store that token type in 'token',
56163       ** and its length in 'len' (to be used next iteration of this loop).
56164       */
56165       do {
56166         zCsr += len;
56167         len = sqlite3GetToken(zCsr, &token);
56168       }while( token==TK_SPACE );
56169       assert( len>0 );
56170
56171       /* Variable 'dist' stores the number of tokens read since the most
56172       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
56173       ** token is read and 'dist' equals 2, the condition stated above
56174       ** to be met.
56175       **
56176       ** Note that ON cannot be a database, table or column name, so
56177       ** there is no need to worry about syntax like 
56178       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
56179       */
56180       dist++;
56181       if( token==TK_DOT || token==TK_ON ){
56182         dist = 0;
56183       }
56184     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
56185
56186     /* Variable tname now contains the token that is the old table-name
56187     ** in the CREATE TRIGGER statement.
56188     */
56189     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
56190        zTableName, tname.z+tname.n);
56191     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
56192   }
56193 }
56194 #endif   /* !SQLITE_OMIT_TRIGGER */
56195
56196 /*
56197 ** Register built-in functions used to help implement ALTER TABLE
56198 */
56199 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
56200   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
56201                          renameTableFunc, 0, 0);
56202 #ifndef SQLITE_OMIT_TRIGGER
56203   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
56204                          renameTriggerFunc, 0, 0);
56205 #endif
56206 }
56207
56208 /*
56209 ** Generate the text of a WHERE expression which can be used to select all
56210 ** temporary triggers on table pTab from the sqlite_temp_master table. If
56211 ** table pTab has no temporary triggers, or is itself stored in the 
56212 ** temporary database, NULL is returned.
56213 */
56214 static char *whereTempTriggers(Parse *pParse, Table *pTab){
56215   Trigger *pTrig;
56216   char *zWhere = 0;
56217   char *tmp = 0;
56218   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
56219
56220   /* If the table is not located in the temp-db (in which case NULL is 
56221   ** returned, loop through the tables list of triggers. For each trigger
56222   ** that is not part of the temp-db schema, add a clause to the WHERE 
56223   ** expression being built up in zWhere.
56224   */
56225   if( pTab->pSchema!=pTempSchema ){
56226     sqlite3 *db = pParse->db;
56227     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
56228       if( pTrig->pSchema==pTempSchema ){
56229         if( !zWhere ){
56230           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
56231         }else{
56232           tmp = zWhere;
56233           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
56234           sqlite3DbFree(db, tmp);
56235         }
56236       }
56237     }
56238   }
56239   return zWhere;
56240 }
56241
56242 /*
56243 ** Generate code to drop and reload the internal representation of table
56244 ** pTab from the database, including triggers and temporary triggers.
56245 ** Argument zName is the name of the table in the database schema at
56246 ** the time the generated code is executed. This can be different from
56247 ** pTab->zName if this function is being called to code part of an 
56248 ** "ALTER TABLE RENAME TO" statement.
56249 */
56250 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
56251   Vdbe *v;
56252   char *zWhere;
56253   int iDb;                   /* Index of database containing pTab */
56254 #ifndef SQLITE_OMIT_TRIGGER
56255   Trigger *pTrig;
56256 #endif
56257
56258   v = sqlite3GetVdbe(pParse);
56259   if( !v ) return;
56260   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56261   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56262   assert( iDb>=0 );
56263
56264 #ifndef SQLITE_OMIT_TRIGGER
56265   /* Drop any table triggers from the internal schema. */
56266   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
56267     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
56268     assert( iTrigDb==iDb || iTrigDb==1 );
56269     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
56270   }
56271 #endif
56272
56273   /* Drop the table and index from the internal schema */
56274   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
56275
56276   /* Reload the table, index and permanent trigger schemas. */
56277   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
56278   if( !zWhere ) return;
56279   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
56280
56281 #ifndef SQLITE_OMIT_TRIGGER
56282   /* Now, if the table is not stored in the temp database, reload any temp 
56283   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
56284   */
56285   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
56286     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
56287   }
56288 #endif
56289 }
56290
56291 /*
56292 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
56293 ** command. 
56294 */
56295 SQLITE_PRIVATE void sqlite3AlterRenameTable(
56296   Parse *pParse,            /* Parser context. */
56297   SrcList *pSrc,            /* The table to rename. */
56298   Token *pName              /* The new table name. */
56299 ){
56300   int iDb;                  /* Database that contains the table */
56301   char *zDb;                /* Name of database iDb */
56302   Table *pTab;              /* Table being renamed */
56303   char *zName = 0;          /* NULL-terminated version of pName */ 
56304   sqlite3 *db = pParse->db; /* Database connection */
56305   int nTabName;             /* Number of UTF-8 characters in zTabName */
56306   const char *zTabName;     /* Original name of the table */
56307   Vdbe *v;
56308 #ifndef SQLITE_OMIT_TRIGGER
56309   char *zWhere = 0;         /* Where clause to locate temp triggers */
56310 #endif
56311   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
56312   
56313   if( db->mallocFailed ) goto exit_rename_table;
56314   assert( pSrc->nSrc==1 );
56315   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56316
56317   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
56318   if( !pTab ) goto exit_rename_table;
56319   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56320   zDb = db->aDb[iDb].zName;
56321
56322   /* Get a NULL terminated version of the new table name. */
56323   zName = sqlite3NameFromToken(db, pName);
56324   if( !zName ) goto exit_rename_table;
56325
56326   /* Check that a table or index named 'zName' does not already exist
56327   ** in database iDb. If so, this is an error.
56328   */
56329   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
56330     sqlite3ErrorMsg(pParse, 
56331         "there is already another table or index with this name: %s", zName);
56332     goto exit_rename_table;
56333   }
56334
56335   /* Make sure it is not a system table being altered, or a reserved name
56336   ** that the table is being renamed to.
56337   */
56338   if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
56339     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
56340     goto exit_rename_table;
56341   }
56342   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
56343     goto exit_rename_table;
56344   }
56345
56346 #ifndef SQLITE_OMIT_VIEW
56347   if( pTab->pSelect ){
56348     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
56349     goto exit_rename_table;
56350   }
56351 #endif
56352
56353 #ifndef SQLITE_OMIT_AUTHORIZATION
56354   /* Invoke the authorization callback. */
56355   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
56356     goto exit_rename_table;
56357   }
56358 #endif
56359
56360 #ifndef SQLITE_OMIT_VIRTUALTABLE
56361   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
56362     goto exit_rename_table;
56363   }
56364   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
56365     isVirtualRename = 1;
56366   }
56367 #endif
56368
56369   /* Begin a transaction and code the VerifyCookie for database iDb. 
56370   ** Then modify the schema cookie (since the ALTER TABLE modifies the
56371   ** schema). Open a statement transaction if the table is a virtual
56372   ** table.
56373   */
56374   v = sqlite3GetVdbe(pParse);
56375   if( v==0 ){
56376     goto exit_rename_table;
56377   }
56378   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
56379   sqlite3ChangeCookie(pParse, iDb);
56380
56381   /* If this is a virtual table, invoke the xRename() function if
56382   ** one is defined. The xRename() callback will modify the names
56383   ** of any resources used by the v-table implementation (including other
56384   ** SQLite tables) that are identified by the name of the virtual table.
56385   */
56386 #ifndef SQLITE_OMIT_VIRTUALTABLE
56387   if( isVirtualRename ){
56388     int i = ++pParse->nMem;
56389     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
56390     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
56391   }
56392 #endif
56393
56394   /* figure out how many UTF-8 characters are in zName */
56395   zTabName = pTab->zName;
56396   nTabName = sqlite3Utf8CharLen(zTabName, -1);
56397
56398   /* Modify the sqlite_master table to use the new table name. */
56399   sqlite3NestedParse(pParse,
56400       "UPDATE %Q.%s SET "
56401 #ifdef SQLITE_OMIT_TRIGGER
56402           "sql = sqlite_rename_table(sql, %Q), "
56403 #else
56404           "sql = CASE "
56405             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
56406             "ELSE sqlite_rename_table(sql, %Q) END, "
56407 #endif
56408           "tbl_name = %Q, "
56409           "name = CASE "
56410             "WHEN type='table' THEN %Q "
56411             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
56412              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
56413             "ELSE name END "
56414       "WHERE tbl_name=%Q AND "
56415           "(type='table' OR type='index' OR type='trigger');", 
56416       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
56417 #ifndef SQLITE_OMIT_TRIGGER
56418       zName,
56419 #endif
56420       zName, nTabName, zTabName
56421   );
56422
56423 #ifndef SQLITE_OMIT_AUTOINCREMENT
56424   /* If the sqlite_sequence table exists in this database, then update 
56425   ** it with the new table name.
56426   */
56427   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
56428     sqlite3NestedParse(pParse,
56429         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
56430         zDb, zName, pTab->zName);
56431   }
56432 #endif
56433
56434 #ifndef SQLITE_OMIT_TRIGGER
56435   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
56436   ** table. Don't do this if the table being ALTERed is itself located in
56437   ** the temp database.
56438   */
56439   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
56440     sqlite3NestedParse(pParse, 
56441         "UPDATE sqlite_temp_master SET "
56442             "sql = sqlite_rename_trigger(sql, %Q), "
56443             "tbl_name = %Q "
56444             "WHERE %s;", zName, zName, zWhere);
56445     sqlite3DbFree(db, zWhere);
56446   }
56447 #endif
56448
56449   /* Drop and reload the internal table schema. */
56450   reloadTableSchema(pParse, pTab, zName);
56451
56452 exit_rename_table:
56453   sqlite3SrcListDelete(db, pSrc);
56454   sqlite3DbFree(db, zName);
56455 }
56456
56457
56458 /*
56459 ** This function is called after an "ALTER TABLE ... ADD" statement
56460 ** has been parsed. Argument pColDef contains the text of the new
56461 ** column definition.
56462 **
56463 ** The Table structure pParse->pNewTable was extended to include
56464 ** the new column during parsing.
56465 */
56466 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
56467   Table *pNew;              /* Copy of pParse->pNewTable */
56468   Table *pTab;              /* Table being altered */
56469   int iDb;                  /* Database number */
56470   const char *zDb;          /* Database name */
56471   const char *zTab;         /* Table name */
56472   char *zCol;               /* Null-terminated column definition */
56473   Column *pCol;             /* The new column */
56474   Expr *pDflt;              /* Default value for the new column */
56475   sqlite3 *db;              /* The database connection; */
56476
56477   if( pParse->nErr ) return;
56478   pNew = pParse->pNewTable;
56479   assert( pNew );
56480
56481   db = pParse->db;
56482   assert( sqlite3BtreeHoldsAllMutexes(db) );
56483   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
56484   zDb = db->aDb[iDb].zName;
56485   zTab = pNew->zName;
56486   pCol = &pNew->aCol[pNew->nCol-1];
56487   pDflt = pCol->pDflt;
56488   pTab = sqlite3FindTable(db, zTab, zDb);
56489   assert( pTab );
56490
56491 #ifndef SQLITE_OMIT_AUTHORIZATION
56492   /* Invoke the authorization callback. */
56493   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
56494     return;
56495   }
56496 #endif
56497
56498   /* If the default value for the new column was specified with a 
56499   ** literal NULL, then set pDflt to 0. This simplifies checking
56500   ** for an SQL NULL default below.
56501   */
56502   if( pDflt && pDflt->op==TK_NULL ){
56503     pDflt = 0;
56504   }
56505
56506   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
56507   ** If there is a NOT NULL constraint, then the default value for the
56508   ** column must not be NULL.
56509   */
56510   if( pCol->isPrimKey ){
56511     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
56512     return;
56513   }
56514   if( pNew->pIndex ){
56515     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
56516     return;
56517   }
56518   if( pCol->notNull && !pDflt ){
56519     sqlite3ErrorMsg(pParse, 
56520         "Cannot add a NOT NULL column with default value NULL");
56521     return;
56522   }
56523
56524   /* Ensure the default expression is something that sqlite3ValueFromExpr()
56525   ** can handle (i.e. not CURRENT_TIME etc.)
56526   */
56527   if( pDflt ){
56528     sqlite3_value *pVal;
56529     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
56530       db->mallocFailed = 1;
56531       return;
56532     }
56533     if( !pVal ){
56534       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
56535       return;
56536     }
56537     sqlite3ValueFree(pVal);
56538   }
56539
56540   /* Modify the CREATE TABLE statement. */
56541   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
56542   if( zCol ){
56543     char *zEnd = &zCol[pColDef->n-1];
56544     while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
56545       *zEnd-- = '\0';
56546     }
56547     sqlite3NestedParse(pParse, 
56548         "UPDATE \"%w\".%s SET "
56549           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
56550         "WHERE type = 'table' AND name = %Q", 
56551       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
56552       zTab
56553     );
56554     sqlite3DbFree(db, zCol);
56555   }
56556
56557   /* If the default value of the new column is NULL, then set the file
56558   ** format to 2. If the default value of the new column is not NULL,
56559   ** the file format becomes 3.
56560   */
56561   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
56562
56563   /* Reload the schema of the modified table. */
56564   reloadTableSchema(pParse, pTab, pTab->zName);
56565 }
56566
56567 /*
56568 ** This function is called by the parser after the table-name in
56569 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
56570 ** pSrc is the full-name of the table being altered.
56571 **
56572 ** This routine makes a (partial) copy of the Table structure
56573 ** for the table being altered and sets Parse.pNewTable to point
56574 ** to it. Routines called by the parser as the column definition
56575 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
56576 ** the copy. The copy of the Table structure is deleted by tokenize.c 
56577 ** after parsing is finished.
56578 **
56579 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
56580 ** coding the "ALTER TABLE ... ADD" statement.
56581 */
56582 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
56583   Table *pNew;
56584   Table *pTab;
56585   Vdbe *v;
56586   int iDb;
56587   int i;
56588   int nAlloc;
56589   sqlite3 *db = pParse->db;
56590
56591   /* Look up the table being altered. */
56592   assert( pParse->pNewTable==0 );
56593   assert( sqlite3BtreeHoldsAllMutexes(db) );
56594   if( db->mallocFailed ) goto exit_begin_add_column;
56595   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
56596   if( !pTab ) goto exit_begin_add_column;
56597
56598 #ifndef SQLITE_OMIT_VIRTUALTABLE
56599   if( IsVirtual(pTab) ){
56600     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
56601     goto exit_begin_add_column;
56602   }
56603 #endif
56604
56605   /* Make sure this is not an attempt to ALTER a view. */
56606   if( pTab->pSelect ){
56607     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
56608     goto exit_begin_add_column;
56609   }
56610
56611   assert( pTab->addColOffset>0 );
56612   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
56613
56614   /* Put a copy of the Table struct in Parse.pNewTable for the
56615   ** sqlite3AddColumn() function and friends to modify.
56616   */
56617   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
56618   if( !pNew ) goto exit_begin_add_column;
56619   pParse->pNewTable = pNew;
56620   pNew->nRef = 1;
56621   pNew->db = db;
56622   pNew->nCol = pTab->nCol;
56623   assert( pNew->nCol>0 );
56624   nAlloc = (((pNew->nCol-1)/8)*8)+8;
56625   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
56626   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
56627   pNew->zName = sqlite3DbStrDup(db, pTab->zName);
56628   if( !pNew->aCol || !pNew->zName ){
56629     db->mallocFailed = 1;
56630     goto exit_begin_add_column;
56631   }
56632   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
56633   for(i=0; i<pNew->nCol; i++){
56634     Column *pCol = &pNew->aCol[i];
56635     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
56636     pCol->zColl = 0;
56637     pCol->zType = 0;
56638     pCol->pDflt = 0;
56639   }
56640   pNew->pSchema = db->aDb[iDb].pSchema;
56641   pNew->addColOffset = pTab->addColOffset;
56642   pNew->nRef = 1;
56643
56644   /* Begin a transaction and increment the schema cookie.  */
56645   sqlite3BeginWriteOperation(pParse, 0, iDb);
56646   v = sqlite3GetVdbe(pParse);
56647   if( !v ) goto exit_begin_add_column;
56648   sqlite3ChangeCookie(pParse, iDb);
56649
56650 exit_begin_add_column:
56651   sqlite3SrcListDelete(db, pSrc);
56652   return;
56653 }
56654 #endif  /* SQLITE_ALTER_TABLE */
56655
56656 /************** End of alter.c ***********************************************/
56657 /************** Begin file analyze.c *****************************************/
56658 /*
56659 ** 2005 July 8
56660 **
56661 ** The author disclaims copyright to this source code.  In place of
56662 ** a legal notice, here is a blessing:
56663 **
56664 **    May you do good and not evil.
56665 **    May you find forgiveness for yourself and forgive others.
56666 **    May you share freely, never taking more than you give.
56667 **
56668 *************************************************************************
56669 ** This file contains code associated with the ANALYZE command.
56670 **
56671 ** @(#) $Id: analyze.c,v 1.43 2008/07/28 19:34:53 drh Exp $
56672 */
56673 #ifndef SQLITE_OMIT_ANALYZE
56674
56675 /*
56676 ** This routine generates code that opens the sqlite_stat1 table on cursor
56677 ** iStatCur.
56678 **
56679 ** If the sqlite_stat1 tables does not previously exist, it is created.
56680 ** If it does previously exist, all entires associated with table zWhere
56681 ** are removed.  If zWhere==0 then all entries are removed.
56682 */
56683 static void openStatTable(
56684   Parse *pParse,          /* Parsing context */
56685   int iDb,                /* The database we are looking in */
56686   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
56687   const char *zWhere      /* Delete entries associated with this table */
56688 ){
56689   sqlite3 *db = pParse->db;
56690   Db *pDb;
56691   int iRootPage;
56692   int createStat1 = 0;
56693   Table *pStat;
56694   Vdbe *v = sqlite3GetVdbe(pParse);
56695
56696   if( v==0 ) return;
56697   assert( sqlite3BtreeHoldsAllMutexes(db) );
56698   assert( sqlite3VdbeDb(v)==db );
56699   pDb = &db->aDb[iDb];
56700   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
56701     /* The sqlite_stat1 tables does not exist.  Create it.  
56702     ** Note that a side-effect of the CREATE TABLE statement is to leave
56703     ** the rootpage of the new table in register pParse->regRoot.  This is
56704     ** important because the OpenWrite opcode below will be needing it. */
56705     sqlite3NestedParse(pParse,
56706       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
56707       pDb->zName
56708     );
56709     iRootPage = pParse->regRoot;
56710     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
56711   }else if( zWhere ){
56712     /* The sqlite_stat1 table exists.  Delete all entries associated with
56713     ** the table zWhere. */
56714     sqlite3NestedParse(pParse,
56715        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
56716        pDb->zName, zWhere
56717     );
56718     iRootPage = pStat->tnum;
56719   }else{
56720     /* The sqlite_stat1 table already exists.  Delete all rows. */
56721     iRootPage = pStat->tnum;
56722     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
56723   }
56724
56725   /* Open the sqlite_stat1 table for writing. Unless it was created
56726   ** by this vdbe program, lock it for writing at the shared-cache level. 
56727   ** If this vdbe did create the sqlite_stat1 table, then it must have 
56728   ** already obtained a schema-lock, making the write-lock redundant.
56729   */
56730   if( !createStat1 ){
56731     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
56732   }
56733   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
56734   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
56735   sqlite3VdbeChangeP5(v, createStat1);
56736 }
56737
56738 /*
56739 ** Generate code to do an analysis of all indices associated with
56740 ** a single table.
56741 */
56742 static void analyzeOneTable(
56743   Parse *pParse,   /* Parser context */
56744   Table *pTab,     /* Table whose indices are to be analyzed */
56745   int iStatCur,    /* Cursor that writes to the sqlite_stat1 table */
56746   int iMem         /* Available memory locations begin here */
56747 ){
56748   Index *pIdx;     /* An index to being analyzed */
56749   int iIdxCur;     /* Cursor number for index being analyzed */
56750   int nCol;        /* Number of columns in the index */
56751   Vdbe *v;         /* The virtual machine being built up */
56752   int i;           /* Loop counter */
56753   int topOfLoop;   /* The top of the loop */
56754   int endOfLoop;   /* The end of the loop */
56755   int addr;        /* The address of an instruction */
56756   int iDb;         /* Index of database containing pTab */
56757
56758   v = sqlite3GetVdbe(pParse);
56759   if( v==0 || pTab==0 || pTab->pIndex==0 ){
56760     /* Do no analysis for tables that have no indices */
56761     return;
56762   }
56763   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56764   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56765   assert( iDb>=0 );
56766 #ifndef SQLITE_OMIT_AUTHORIZATION
56767   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
56768       pParse->db->aDb[iDb].zName ) ){
56769     return;
56770   }
56771 #endif
56772
56773   /* Establish a read-lock on the table at the shared-cache level. */
56774   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
56775
56776   iIdxCur = pParse->nTab;
56777   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
56778     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
56779     int regFields;    /* Register block for building records */
56780     int regRec;       /* Register holding completed record */
56781     int regTemp;      /* Temporary use register */
56782     int regCol;       /* Content of a column from the table being analyzed */
56783     int regRowid;     /* Rowid for the inserted record */
56784     int regF2;
56785
56786     /* Open a cursor to the index to be analyzed
56787     */
56788     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
56789     nCol = pIdx->nColumn;
56790     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
56791     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
56792         (char *)pKey, P4_KEYINFO_HANDOFF);
56793     VdbeComment((v, "%s", pIdx->zName));
56794     regFields = iMem+nCol*2;
56795     regTemp = regRowid = regCol = regFields+3;
56796     regRec = regCol+1;
56797     if( regRec>pParse->nMem ){
56798       pParse->nMem = regRec;
56799     }
56800
56801     /* Memory cells are used as follows:
56802     **
56803     **    mem[iMem]:             The total number of rows in the table.
56804     **    mem[iMem+1]:           Number of distinct values in column 1
56805     **    ...
56806     **    mem[iMem+nCol]:        Number of distinct values in column N
56807     **    mem[iMem+nCol+1]       Last observed value of column 1
56808     **    ...
56809     **    mem[iMem+nCol+nCol]:   Last observed value of column N
56810     **
56811     ** Cells iMem through iMem+nCol are initialized to 0.  The others
56812     ** are initialized to NULL.
56813     */
56814     for(i=0; i<=nCol; i++){
56815       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
56816     }
56817     for(i=0; i<nCol; i++){
56818       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
56819     }
56820
56821     /* Do the analysis.
56822     */
56823     endOfLoop = sqlite3VdbeMakeLabel(v);
56824     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
56825     topOfLoop = sqlite3VdbeCurrentAddr(v);
56826     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
56827     for(i=0; i<nCol; i++){
56828       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
56829       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
56830       /**** TODO:  add collating sequence *****/
56831       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
56832     }
56833     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
56834     for(i=0; i<nCol; i++){
56835       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
56836       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
56837       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
56838     }
56839     sqlite3VdbeResolveLabel(v, endOfLoop);
56840     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
56841     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
56842
56843     /* Store the results.  
56844     **
56845     ** The result is a single row of the sqlite_stat1 table.  The first
56846     ** two columns are the names of the table and index.  The third column
56847     ** is a string composed of a list of integer statistics about the
56848     ** index.  The first integer in the list is the total number of entires
56849     ** in the index.  There is one additional integer in the list for each
56850     ** column of the table.  This additional integer is a guess of how many
56851     ** rows of the table the index will select.  If D is the count of distinct
56852     ** values and K is the total number of rows, then the integer is computed
56853     ** as:
56854     **
56855     **        I = (K+D-1)/D
56856     **
56857     ** If K==0 then no entry is made into the sqlite_stat1 table.  
56858     ** If K>0 then it is always the case the D>0 so division by zero
56859     ** is never possible.
56860     */
56861     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
56862     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
56863     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
56864     regF2 = regFields+2;
56865     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
56866     for(i=0; i<nCol; i++){
56867       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
56868       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
56869       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
56870       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
56871       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
56872       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
56873       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
56874     }
56875     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
56876     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
56877     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
56878     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
56879     sqlite3VdbeJumpHere(v, addr);
56880   }
56881 }
56882
56883 /*
56884 ** Generate code that will cause the most recent index analysis to
56885 ** be laoded into internal hash tables where is can be used.
56886 */
56887 static void loadAnalysis(Parse *pParse, int iDb){
56888   Vdbe *v = sqlite3GetVdbe(pParse);
56889   if( v ){
56890     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
56891   }
56892 }
56893
56894 /*
56895 ** Generate code that will do an analysis of an entire database
56896 */
56897 static void analyzeDatabase(Parse *pParse, int iDb){
56898   sqlite3 *db = pParse->db;
56899   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
56900   HashElem *k;
56901   int iStatCur;
56902   int iMem;
56903
56904   sqlite3BeginWriteOperation(pParse, 0, iDb);
56905   iStatCur = pParse->nTab++;
56906   openStatTable(pParse, iDb, iStatCur, 0);
56907   iMem = pParse->nMem+1;
56908   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
56909     Table *pTab = (Table*)sqliteHashData(k);
56910     analyzeOneTable(pParse, pTab, iStatCur, iMem);
56911   }
56912   loadAnalysis(pParse, iDb);
56913 }
56914
56915 /*
56916 ** Generate code that will do an analysis of a single table in
56917 ** a database.
56918 */
56919 static void analyzeTable(Parse *pParse, Table *pTab){
56920   int iDb;
56921   int iStatCur;
56922
56923   assert( pTab!=0 );
56924   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56925   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
56926   sqlite3BeginWriteOperation(pParse, 0, iDb);
56927   iStatCur = pParse->nTab++;
56928   openStatTable(pParse, iDb, iStatCur, pTab->zName);
56929   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
56930   loadAnalysis(pParse, iDb);
56931 }
56932
56933 /*
56934 ** Generate code for the ANALYZE command.  The parser calls this routine
56935 ** when it recognizes an ANALYZE command.
56936 **
56937 **        ANALYZE                            -- 1
56938 **        ANALYZE  <database>                -- 2
56939 **        ANALYZE  ?<database>.?<tablename>  -- 3
56940 **
56941 ** Form 1 causes all indices in all attached databases to be analyzed.
56942 ** Form 2 analyzes all indices the single database named.
56943 ** Form 3 analyzes all indices associated with the named table.
56944 */
56945 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
56946   sqlite3 *db = pParse->db;
56947   int iDb;
56948   int i;
56949   char *z, *zDb;
56950   Table *pTab;
56951   Token *pTableName;
56952
56953   /* Read the database schema. If an error occurs, leave an error message
56954   ** and code in pParse and return NULL. */
56955   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
56956   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
56957     return;
56958   }
56959
56960   if( pName1==0 ){
56961     /* Form 1:  Analyze everything */
56962     for(i=0; i<db->nDb; i++){
56963       if( i==1 ) continue;  /* Do not analyze the TEMP database */
56964       analyzeDatabase(pParse, i);
56965     }
56966   }else if( pName2==0 || pName2->n==0 ){
56967     /* Form 2:  Analyze the database or table named */
56968     iDb = sqlite3FindDb(db, pName1);
56969     if( iDb>=0 ){
56970       analyzeDatabase(pParse, iDb);
56971     }else{
56972       z = sqlite3NameFromToken(db, pName1);
56973       if( z ){
56974         pTab = sqlite3LocateTable(pParse, 0, z, 0);
56975         sqlite3DbFree(db, z);
56976         if( pTab ){
56977           analyzeTable(pParse, pTab);
56978         }
56979       }
56980     }
56981   }else{
56982     /* Form 3: Analyze the fully qualified table name */
56983     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
56984     if( iDb>=0 ){
56985       zDb = db->aDb[iDb].zName;
56986       z = sqlite3NameFromToken(db, pTableName);
56987       if( z ){
56988         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
56989         sqlite3DbFree(db, z);
56990         if( pTab ){
56991           analyzeTable(pParse, pTab);
56992         }
56993       }
56994     }   
56995   }
56996 }
56997
56998 /*
56999 ** Used to pass information from the analyzer reader through to the
57000 ** callback routine.
57001 */
57002 typedef struct analysisInfo analysisInfo;
57003 struct analysisInfo {
57004   sqlite3 *db;
57005   const char *zDatabase;
57006 };
57007
57008 /*
57009 ** This callback is invoked once for each index when reading the
57010 ** sqlite_stat1 table.  
57011 **
57012 **     argv[0] = name of the index
57013 **     argv[1] = results of analysis - on integer for each column
57014 */
57015 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
57016   analysisInfo *pInfo = (analysisInfo*)pData;
57017   Index *pIndex;
57018   int i, c;
57019   unsigned int v;
57020   const char *z;
57021
57022   assert( argc==2 );
57023   if( argv==0 || argv[0]==0 || argv[1]==0 ){
57024     return 0;
57025   }
57026   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
57027   if( pIndex==0 ){
57028     return 0;
57029   }
57030   z = argv[1];
57031   for(i=0; *z && i<=pIndex->nColumn; i++){
57032     v = 0;
57033     while( (c=z[0])>='0' && c<='9' ){
57034       v = v*10 + c - '0';
57035       z++;
57036     }
57037     pIndex->aiRowEst[i] = v;
57038     if( *z==' ' ) z++;
57039   }
57040   return 0;
57041 }
57042
57043 /*
57044 ** Load the content of the sqlite_stat1 table into the index hash tables.
57045 */
57046 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
57047   analysisInfo sInfo;
57048   HashElem *i;
57049   char *zSql;
57050   int rc;
57051
57052   assert( iDb>=0 && iDb<db->nDb );
57053   assert( db->aDb[iDb].pBt!=0 );
57054   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
57055
57056   /* Clear any prior statistics */
57057   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
57058     Index *pIdx = sqliteHashData(i);
57059     sqlite3DefaultRowEst(pIdx);
57060   }
57061
57062   /* Check to make sure the sqlite_stat1 table existss */
57063   sInfo.db = db;
57064   sInfo.zDatabase = db->aDb[iDb].zName;
57065   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
57066      return SQLITE_ERROR;
57067   }
57068
57069
57070   /* Load new statistics out of the sqlite_stat1 table */
57071   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
57072                         sInfo.zDatabase);
57073   (void)sqlite3SafetyOff(db);
57074   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
57075   (void)sqlite3SafetyOn(db);
57076   sqlite3DbFree(db, zSql);
57077   return rc;
57078 }
57079
57080
57081 #endif /* SQLITE_OMIT_ANALYZE */
57082
57083 /************** End of analyze.c *********************************************/
57084 /************** Begin file attach.c ******************************************/
57085 /*
57086 ** 2003 April 6
57087 **
57088 ** The author disclaims copyright to this source code.  In place of
57089 ** a legal notice, here is a blessing:
57090 **
57091 **    May you do good and not evil.
57092 **    May you find forgiveness for yourself and forgive others.
57093 **    May you share freely, never taking more than you give.
57094 **
57095 *************************************************************************
57096 ** This file contains code used to implement the ATTACH and DETACH commands.
57097 **
57098 ** $Id: attach.c,v 1.78 2008/08/20 16:35:10 drh Exp $
57099 */
57100
57101 #ifndef SQLITE_OMIT_ATTACH
57102 /*
57103 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
57104 ** is slightly different from resolving a normal SQL expression, because simple
57105 ** identifiers are treated as strings, not possible column names or aliases.
57106 **
57107 ** i.e. if the parser sees:
57108 **
57109 **     ATTACH DATABASE abc AS def
57110 **
57111 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
57112 ** looking for columns of the same name.
57113 **
57114 ** This only applies to the root node of pExpr, so the statement:
57115 **
57116 **     ATTACH DATABASE abc||def AS 'db2'
57117 **
57118 ** will fail because neither abc or def can be resolved.
57119 */
57120 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
57121 {
57122   int rc = SQLITE_OK;
57123   if( pExpr ){
57124     if( pExpr->op!=TK_ID ){
57125       rc = sqlite3ResolveExprNames(pName, pExpr);
57126       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
57127         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
57128         return SQLITE_ERROR;
57129       }
57130     }else{
57131       pExpr->op = TK_STRING;
57132     }
57133   }
57134   return rc;
57135 }
57136
57137 /*
57138 ** An SQL user-function registered to do the work of an ATTACH statement. The
57139 ** three arguments to the function come directly from an attach statement:
57140 **
57141 **     ATTACH DATABASE x AS y KEY z
57142 **
57143 **     SELECT sqlite_attach(x, y, z)
57144 **
57145 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
57146 ** third argument.
57147 */
57148 static void attachFunc(
57149   sqlite3_context *context,
57150   int argc,
57151   sqlite3_value **argv
57152 ){
57153   int i;
57154   int rc = 0;
57155   sqlite3 *db = sqlite3_context_db_handle(context);
57156   const char *zName;
57157   const char *zFile;
57158   Db *aNew;
57159   char *zErrDyn = 0;
57160   char zErr[128];
57161
57162   zFile = (const char *)sqlite3_value_text(argv[0]);
57163   zName = (const char *)sqlite3_value_text(argv[1]);
57164   if( zFile==0 ) zFile = "";
57165   if( zName==0 ) zName = "";
57166
57167   /* Check for the following errors:
57168   **
57169   **     * Too many attached databases,
57170   **     * Transaction currently open
57171   **     * Specified database name already being used.
57172   */
57173   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
57174     sqlite3_snprintf(
57175       sizeof(zErr), zErr, "too many attached databases - max %d", 
57176       db->aLimit[SQLITE_LIMIT_ATTACHED]
57177     );
57178     goto attach_error;
57179   }
57180   if( !db->autoCommit ){
57181     sqlite3_snprintf(sizeof(zErr), zErr,
57182                      "cannot ATTACH database within transaction");
57183     goto attach_error;
57184   }
57185   for(i=0; i<db->nDb; i++){
57186     char *z = db->aDb[i].zName;
57187     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
57188       sqlite3_snprintf(sizeof(zErr), zErr, 
57189                        "database %s is already in use", zName);
57190       goto attach_error;
57191     }
57192   }
57193
57194   /* Allocate the new entry in the db->aDb[] array and initialise the schema
57195   ** hash tables.
57196   */
57197   if( db->aDb==db->aDbStatic ){
57198     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
57199     if( aNew==0 ) return;
57200     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
57201   }else{
57202     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
57203     if( aNew==0 ) return;
57204   }
57205   db->aDb = aNew;
57206   aNew = &db->aDb[db->nDb++];
57207   memset(aNew, 0, sizeof(*aNew));
57208
57209   /* Open the database file. If the btree is successfully opened, use
57210   ** it to obtain the database schema. At this point the schema may
57211   ** or may not be initialised.
57212   */
57213   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
57214                            db->openFlags | SQLITE_OPEN_MAIN_DB,
57215                            &aNew->pBt);
57216   if( rc==SQLITE_OK ){
57217     Pager *pPager;
57218     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
57219     if( !aNew->pSchema ){
57220       rc = SQLITE_NOMEM;
57221     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
57222       sqlite3_snprintf(sizeof(zErr), zErr, 
57223         "attached databases must use the same text encoding as main database");
57224       goto attach_error;
57225     }
57226     pPager = sqlite3BtreePager(aNew->pBt);
57227     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
57228     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
57229   }
57230   aNew->zName = sqlite3DbStrDup(db, zName);
57231   aNew->safety_level = 3;
57232
57233 #if SQLITE_HAS_CODEC
57234   {
57235     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
57236     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
57237     int nKey;
57238     char *zKey;
57239     int t = sqlite3_value_type(argv[2]);
57240     switch( t ){
57241       case SQLITE_INTEGER:
57242       case SQLITE_FLOAT:
57243         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
57244         rc = SQLITE_ERROR;
57245         break;
57246         
57247       case SQLITE_TEXT:
57248       case SQLITE_BLOB:
57249         nKey = sqlite3_value_bytes(argv[2]);
57250         zKey = (char *)sqlite3_value_blob(argv[2]);
57251         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
57252         break;
57253
57254       case SQLITE_NULL:
57255         /* No key specified.  Use the key from the main database */
57256         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
57257         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
57258         break;
57259     }
57260   }
57261 #endif
57262
57263   /* If the file was opened successfully, read the schema for the new database.
57264   ** If this fails, or if opening the file failed, then close the file and 
57265   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
57266   ** we found it.
57267   */
57268   if( rc==SQLITE_OK ){
57269     (void)sqlite3SafetyOn(db);
57270     sqlite3BtreeEnterAll(db);
57271     rc = sqlite3Init(db, &zErrDyn);
57272     sqlite3BtreeLeaveAll(db);
57273     (void)sqlite3SafetyOff(db);
57274   }
57275   if( rc ){
57276     int iDb = db->nDb - 1;
57277     assert( iDb>=2 );
57278     if( db->aDb[iDb].pBt ){
57279       sqlite3BtreeClose(db->aDb[iDb].pBt);
57280       db->aDb[iDb].pBt = 0;
57281       db->aDb[iDb].pSchema = 0;
57282     }
57283     sqlite3ResetInternalSchema(db, 0);
57284     db->nDb = iDb;
57285     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
57286       db->mallocFailed = 1;
57287       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
57288     }else{
57289       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
57290     }
57291     goto attach_error;
57292   }
57293   
57294   return;
57295
57296 attach_error:
57297   /* Return an error if we get here */
57298   if( zErrDyn ){
57299     sqlite3_result_error(context, zErrDyn, -1);
57300     sqlite3DbFree(db, zErrDyn);
57301   }else{
57302     zErr[sizeof(zErr)-1] = 0;
57303     sqlite3_result_error(context, zErr, -1);
57304   }
57305   if( rc ) sqlite3_result_error_code(context, rc);
57306 }
57307
57308 /*
57309 ** An SQL user-function registered to do the work of an DETACH statement. The
57310 ** three arguments to the function come directly from a detach statement:
57311 **
57312 **     DETACH DATABASE x
57313 **
57314 **     SELECT sqlite_detach(x)
57315 */
57316 static void detachFunc(
57317   sqlite3_context *context,
57318   int argc,
57319   sqlite3_value **argv
57320 ){
57321   const char *zName = (const char *)sqlite3_value_text(argv[0]);
57322   sqlite3 *db = sqlite3_context_db_handle(context);
57323   int i;
57324   Db *pDb = 0;
57325   char zErr[128];
57326
57327   if( zName==0 ) zName = "";
57328   for(i=0; i<db->nDb; i++){
57329     pDb = &db->aDb[i];
57330     if( pDb->pBt==0 ) continue;
57331     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
57332   }
57333
57334   if( i>=db->nDb ){
57335     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
57336     goto detach_error;
57337   }
57338   if( i<2 ){
57339     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
57340     goto detach_error;
57341   }
57342   if( !db->autoCommit ){
57343     sqlite3_snprintf(sizeof(zErr), zErr,
57344                      "cannot DETACH database within transaction");
57345     goto detach_error;
57346   }
57347   if( sqlite3BtreeIsInReadTrans(pDb->pBt) ){
57348     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
57349     goto detach_error;
57350   }
57351
57352   sqlite3BtreeClose(pDb->pBt);
57353   pDb->pBt = 0;
57354   pDb->pSchema = 0;
57355   sqlite3ResetInternalSchema(db, 0);
57356   return;
57357
57358 detach_error:
57359   sqlite3_result_error(context, zErr, -1);
57360 }
57361
57362 /*
57363 ** This procedure generates VDBE code for a single invocation of either the
57364 ** sqlite_detach() or sqlite_attach() SQL user functions.
57365 */
57366 static void codeAttach(
57367   Parse *pParse,       /* The parser context */
57368   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
57369   const char *zFunc,   /* Either "sqlite_attach" or "sqlite_detach */
57370   int nFunc,           /* Number of args to pass to zFunc */
57371   Expr *pAuthArg,      /* Expression to pass to authorization callback */
57372   Expr *pFilename,     /* Name of database file */
57373   Expr *pDbname,       /* Name of the database to use internally */
57374   Expr *pKey           /* Database key for encryption extension */
57375 ){
57376   int rc;
57377   NameContext sName;
57378   Vdbe *v;
57379   FuncDef *pFunc;
57380   sqlite3* db = pParse->db;
57381   int regArgs;
57382
57383 #ifndef SQLITE_OMIT_AUTHORIZATION
57384   assert( db->mallocFailed || pAuthArg );
57385   if( pAuthArg ){
57386     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
57387     if( !zAuthArg ){
57388       goto attach_end;
57389     }
57390     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
57391     sqlite3DbFree(db, zAuthArg);
57392     if(rc!=SQLITE_OK ){
57393       goto attach_end;
57394     }
57395   }
57396 #endif /* SQLITE_OMIT_AUTHORIZATION */
57397
57398   memset(&sName, 0, sizeof(NameContext));
57399   sName.pParse = pParse;
57400
57401   if( 
57402       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
57403       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
57404       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
57405   ){
57406     pParse->nErr++;
57407     goto attach_end;
57408   }
57409
57410   v = sqlite3GetVdbe(pParse);
57411   regArgs = sqlite3GetTempRange(pParse, 4);
57412   sqlite3ExprCode(pParse, pFilename, regArgs);
57413   sqlite3ExprCode(pParse, pDbname, regArgs+1);
57414   sqlite3ExprCode(pParse, pKey, regArgs+2);
57415
57416   assert( v || db->mallocFailed );
57417   if( v ){
57418     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3);
57419     sqlite3VdbeChangeP5(v, nFunc);
57420     pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0);
57421     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
57422
57423     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
57424     ** statement only). For DETACH, set it to false (expire all existing
57425     ** statements).
57426     */
57427     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
57428   }
57429   
57430 attach_end:
57431   sqlite3ExprDelete(db, pFilename);
57432   sqlite3ExprDelete(db, pDbname);
57433   sqlite3ExprDelete(db, pKey);
57434 }
57435
57436 /*
57437 ** Called by the parser to compile a DETACH statement.
57438 **
57439 **     DETACH pDbname
57440 */
57441 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
57442   codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
57443 }
57444
57445 /*
57446 ** Called by the parser to compile an ATTACH statement.
57447 **
57448 **     ATTACH p AS pDbname KEY pKey
57449 */
57450 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
57451   codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
57452 }
57453 #endif /* SQLITE_OMIT_ATTACH */
57454
57455 /*
57456 ** Register the functions sqlite_attach and sqlite_detach.
57457 */
57458 SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
57459 #ifndef SQLITE_OMIT_ATTACH
57460   static const int enc = SQLITE_UTF8;
57461   sqlite3CreateFunc(db, "sqlite_attach", 3, enc, 0, attachFunc, 0, 0);
57462   sqlite3CreateFunc(db, "sqlite_detach", 1, enc, 0, detachFunc, 0, 0);
57463 #endif
57464 }
57465
57466 /*
57467 ** Initialize a DbFixer structure.  This routine must be called prior
57468 ** to passing the structure to one of the sqliteFixAAAA() routines below.
57469 **
57470 ** The return value indicates whether or not fixation is required.  TRUE
57471 ** means we do need to fix the database references, FALSE means we do not.
57472 */
57473 SQLITE_PRIVATE int sqlite3FixInit(
57474   DbFixer *pFix,      /* The fixer to be initialized */
57475   Parse *pParse,      /* Error messages will be written here */
57476   int iDb,            /* This is the database that must be used */
57477   const char *zType,  /* "view", "trigger", or "index" */
57478   const Token *pName  /* Name of the view, trigger, or index */
57479 ){
57480   sqlite3 *db;
57481
57482   if( iDb<0 || iDb==1 ) return 0;
57483   db = pParse->db;
57484   assert( db->nDb>iDb );
57485   pFix->pParse = pParse;
57486   pFix->zDb = db->aDb[iDb].zName;
57487   pFix->zType = zType;
57488   pFix->pName = pName;
57489   return 1;
57490 }
57491
57492 /*
57493 ** The following set of routines walk through the parse tree and assign
57494 ** a specific database to all table references where the database name
57495 ** was left unspecified in the original SQL statement.  The pFix structure
57496 ** must have been initialized by a prior call to sqlite3FixInit().
57497 **
57498 ** These routines are used to make sure that an index, trigger, or
57499 ** view in one database does not refer to objects in a different database.
57500 ** (Exception: indices, triggers, and views in the TEMP database are
57501 ** allowed to refer to anything.)  If a reference is explicitly made
57502 ** to an object in a different database, an error message is added to
57503 ** pParse->zErrMsg and these routines return non-zero.  If everything
57504 ** checks out, these routines return 0.
57505 */
57506 SQLITE_PRIVATE int sqlite3FixSrcList(
57507   DbFixer *pFix,       /* Context of the fixation */
57508   SrcList *pList       /* The Source list to check and modify */
57509 ){
57510   int i;
57511   const char *zDb;
57512   struct SrcList_item *pItem;
57513
57514   if( pList==0 ) return 0;
57515   zDb = pFix->zDb;
57516   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
57517     if( pItem->zDatabase==0 ){
57518       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
57519     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
57520       sqlite3ErrorMsg(pFix->pParse,
57521          "%s %T cannot reference objects in database %s",
57522          pFix->zType, pFix->pName, pItem->zDatabase);
57523       return 1;
57524     }
57525 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
57526     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
57527     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
57528 #endif
57529   }
57530   return 0;
57531 }
57532 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
57533 SQLITE_PRIVATE int sqlite3FixSelect(
57534   DbFixer *pFix,       /* Context of the fixation */
57535   Select *pSelect      /* The SELECT statement to be fixed to one database */
57536 ){
57537   while( pSelect ){
57538     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
57539       return 1;
57540     }
57541     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
57542       return 1;
57543     }
57544     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
57545       return 1;
57546     }
57547     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
57548       return 1;
57549     }
57550     pSelect = pSelect->pPrior;
57551   }
57552   return 0;
57553 }
57554 SQLITE_PRIVATE int sqlite3FixExpr(
57555   DbFixer *pFix,     /* Context of the fixation */
57556   Expr *pExpr        /* The expression to be fixed to one database */
57557 ){
57558   while( pExpr ){
57559     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
57560       return 1;
57561     }
57562     if( sqlite3FixExprList(pFix, pExpr->pList) ){
57563       return 1;
57564     }
57565     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
57566       return 1;
57567     }
57568     pExpr = pExpr->pLeft;
57569   }
57570   return 0;
57571 }
57572 SQLITE_PRIVATE int sqlite3FixExprList(
57573   DbFixer *pFix,     /* Context of the fixation */
57574   ExprList *pList    /* The expression to be fixed to one database */
57575 ){
57576   int i;
57577   struct ExprList_item *pItem;
57578   if( pList==0 ) return 0;
57579   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
57580     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
57581       return 1;
57582     }
57583   }
57584   return 0;
57585 }
57586 #endif
57587
57588 #ifndef SQLITE_OMIT_TRIGGER
57589 SQLITE_PRIVATE int sqlite3FixTriggerStep(
57590   DbFixer *pFix,     /* Context of the fixation */
57591   TriggerStep *pStep /* The trigger step be fixed to one database */
57592 ){
57593   while( pStep ){
57594     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
57595       return 1;
57596     }
57597     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
57598       return 1;
57599     }
57600     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
57601       return 1;
57602     }
57603     pStep = pStep->pNext;
57604   }
57605   return 0;
57606 }
57607 #endif
57608
57609 /************** End of attach.c **********************************************/
57610 /************** Begin file auth.c ********************************************/
57611 /*
57612 ** 2003 January 11
57613 **
57614 ** The author disclaims copyright to this source code.  In place of
57615 ** a legal notice, here is a blessing:
57616 **
57617 **    May you do good and not evil.
57618 **    May you find forgiveness for yourself and forgive others.
57619 **    May you share freely, never taking more than you give.
57620 **
57621 *************************************************************************
57622 ** This file contains code used to implement the sqlite3_set_authorizer()
57623 ** API.  This facility is an optional feature of the library.  Embedded
57624 ** systems that do not need this facility may omit it by recompiling
57625 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
57626 **
57627 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
57628 */
57629
57630 /*
57631 ** All of the code in this file may be omitted by defining a single
57632 ** macro.
57633 */
57634 #ifndef SQLITE_OMIT_AUTHORIZATION
57635
57636 /*
57637 ** Set or clear the access authorization function.
57638 **
57639 ** The access authorization function is be called during the compilation
57640 ** phase to verify that the user has read and/or write access permission on
57641 ** various fields of the database.  The first argument to the auth function
57642 ** is a copy of the 3rd argument to this routine.  The second argument
57643 ** to the auth function is one of these constants:
57644 **
57645 **       SQLITE_CREATE_INDEX
57646 **       SQLITE_CREATE_TABLE
57647 **       SQLITE_CREATE_TEMP_INDEX
57648 **       SQLITE_CREATE_TEMP_TABLE
57649 **       SQLITE_CREATE_TEMP_TRIGGER
57650 **       SQLITE_CREATE_TEMP_VIEW
57651 **       SQLITE_CREATE_TRIGGER
57652 **       SQLITE_CREATE_VIEW
57653 **       SQLITE_DELETE
57654 **       SQLITE_DROP_INDEX
57655 **       SQLITE_DROP_TABLE
57656 **       SQLITE_DROP_TEMP_INDEX
57657 **       SQLITE_DROP_TEMP_TABLE
57658 **       SQLITE_DROP_TEMP_TRIGGER
57659 **       SQLITE_DROP_TEMP_VIEW
57660 **       SQLITE_DROP_TRIGGER
57661 **       SQLITE_DROP_VIEW
57662 **       SQLITE_INSERT
57663 **       SQLITE_PRAGMA
57664 **       SQLITE_READ
57665 **       SQLITE_SELECT
57666 **       SQLITE_TRANSACTION
57667 **       SQLITE_UPDATE
57668 **
57669 ** The third and fourth arguments to the auth function are the name of
57670 ** the table and the column that are being accessed.  The auth function
57671 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
57672 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
57673 ** means that the SQL statement will never-run - the sqlite3_exec() call
57674 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
57675 ** should run but attempts to read the specified column will return NULL
57676 ** and attempts to write the column will be ignored.
57677 **
57678 ** Setting the auth function to NULL disables this hook.  The default
57679 ** setting of the auth function is NULL.
57680 */
57681 SQLITE_API int sqlite3_set_authorizer(
57682   sqlite3 *db,
57683   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
57684   void *pArg
57685 ){
57686   sqlite3_mutex_enter(db->mutex);
57687   db->xAuth = xAuth;
57688   db->pAuthArg = pArg;
57689   sqlite3ExpirePreparedStatements(db);
57690   sqlite3_mutex_leave(db->mutex);
57691   return SQLITE_OK;
57692 }
57693
57694 /*
57695 ** Write an error message into pParse->zErrMsg that explains that the
57696 ** user-supplied authorization function returned an illegal value.
57697 */
57698 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
57699   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
57700     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
57701     "or SQLITE_DENY", rc);
57702   pParse->rc = SQLITE_ERROR;
57703 }
57704
57705 /*
57706 ** The pExpr should be a TK_COLUMN expression.  The table referred to
57707 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
57708 ** Check to see if it is OK to read this particular column.
57709 **
57710 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
57711 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
57712 ** then generate an error.
57713 */
57714 SQLITE_PRIVATE void sqlite3AuthRead(
57715   Parse *pParse,        /* The parser context */
57716   Expr *pExpr,          /* The expression to check authorization on */
57717   Schema *pSchema,      /* The schema of the expression */
57718   SrcList *pTabList     /* All table that pExpr might refer to */
57719 ){
57720   sqlite3 *db = pParse->db;
57721   int rc;
57722   Table *pTab = 0;      /* The table being read */
57723   const char *zCol;     /* Name of the column of the table */
57724   int iSrc;             /* Index in pTabList->a[] of table being read */
57725   const char *zDBase;   /* Name of database being accessed */
57726   TriggerStack *pStack; /* The stack of current triggers */
57727   int iDb;              /* The index of the database the expression refers to */
57728
57729   if( db->xAuth==0 ) return;
57730   if( pExpr->op!=TK_COLUMN ) return;
57731   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
57732   if( iDb<0 ){
57733     /* An attempt to read a column out of a subquery or other
57734     ** temporary table. */
57735     return;
57736   }
57737   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
57738     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
57739   }
57740   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
57741     pTab = pTabList->a[iSrc].pTab;
57742   }else if( (pStack = pParse->trigStack)!=0 ){
57743     /* This must be an attempt to read the NEW or OLD pseudo-tables
57744     ** of a trigger.
57745     */
57746     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
57747     pTab = pStack->pTab;
57748   }
57749   if( pTab==0 ) return;
57750   if( pExpr->iColumn>=0 ){
57751     assert( pExpr->iColumn<pTab->nCol );
57752     zCol = pTab->aCol[pExpr->iColumn].zName;
57753   }else if( pTab->iPKey>=0 ){
57754     assert( pTab->iPKey<pTab->nCol );
57755     zCol = pTab->aCol[pTab->iPKey].zName;
57756   }else{
57757     zCol = "ROWID";
57758   }
57759   assert( iDb>=0 && iDb<db->nDb );
57760   zDBase = db->aDb[iDb].zName;
57761   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
57762                  pParse->zAuthContext);
57763   if( rc==SQLITE_IGNORE ){
57764     pExpr->op = TK_NULL;
57765   }else if( rc==SQLITE_DENY ){
57766     if( db->nDb>2 || iDb!=0 ){
57767       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
57768          zDBase, pTab->zName, zCol);
57769     }else{
57770       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
57771     }
57772     pParse->rc = SQLITE_AUTH;
57773   }else if( rc!=SQLITE_OK ){
57774     sqliteAuthBadReturnCode(pParse, rc);
57775   }
57776 }
57777
57778 /*
57779 ** Do an authorization check using the code and arguments given.  Return
57780 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
57781 ** is returned, then the error count and error message in pParse are
57782 ** modified appropriately.
57783 */
57784 SQLITE_PRIVATE int sqlite3AuthCheck(
57785   Parse *pParse,
57786   int code,
57787   const char *zArg1,
57788   const char *zArg2,
57789   const char *zArg3
57790 ){
57791   sqlite3 *db = pParse->db;
57792   int rc;
57793
57794   /* Don't do any authorization checks if the database is initialising
57795   ** or if the parser is being invoked from within sqlite3_declare_vtab.
57796   */
57797   if( db->init.busy || IN_DECLARE_VTAB ){
57798     return SQLITE_OK;
57799   }
57800
57801   if( db->xAuth==0 ){
57802     return SQLITE_OK;
57803   }
57804   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
57805   if( rc==SQLITE_DENY ){
57806     sqlite3ErrorMsg(pParse, "not authorized");
57807     pParse->rc = SQLITE_AUTH;
57808   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
57809     rc = SQLITE_DENY;
57810     sqliteAuthBadReturnCode(pParse, rc);
57811   }
57812   return rc;
57813 }
57814
57815 /*
57816 ** Push an authorization context.  After this routine is called, the
57817 ** zArg3 argument to authorization callbacks will be zContext until
57818 ** popped.  Or if pParse==0, this routine is a no-op.
57819 */
57820 SQLITE_PRIVATE void sqlite3AuthContextPush(
57821   Parse *pParse,
57822   AuthContext *pContext, 
57823   const char *zContext
57824 ){
57825   pContext->pParse = pParse;
57826   if( pParse ){
57827     pContext->zAuthContext = pParse->zAuthContext;
57828     pParse->zAuthContext = zContext;
57829   }
57830 }
57831
57832 /*
57833 ** Pop an authorization context that was previously pushed
57834 ** by sqlite3AuthContextPush
57835 */
57836 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
57837   if( pContext->pParse ){
57838     pContext->pParse->zAuthContext = pContext->zAuthContext;
57839     pContext->pParse = 0;
57840   }
57841 }
57842
57843 #endif /* SQLITE_OMIT_AUTHORIZATION */
57844
57845 /************** End of auth.c ************************************************/
57846 /************** Begin file build.c *******************************************/
57847 /*
57848 ** 2001 September 15
57849 **
57850 ** The author disclaims copyright to this source code.  In place of
57851 ** a legal notice, here is a blessing:
57852 **
57853 **    May you do good and not evil.
57854 **    May you find forgiveness for yourself and forgive others.
57855 **    May you share freely, never taking more than you give.
57856 **
57857 *************************************************************************
57858 ** This file contains C code routines that are called by the SQLite parser
57859 ** when syntax rules are reduced.  The routines in this file handle the
57860 ** following kinds of SQL syntax:
57861 **
57862 **     CREATE TABLE
57863 **     DROP TABLE
57864 **     CREATE INDEX
57865 **     DROP INDEX
57866 **     creating ID lists
57867 **     BEGIN TRANSACTION
57868 **     COMMIT
57869 **     ROLLBACK
57870 **
57871 ** $Id: build.c,v 1.498 2008/10/06 16:18:40 danielk1977 Exp $
57872 */
57873
57874 /*
57875 ** This routine is called when a new SQL statement is beginning to
57876 ** be parsed.  Initialize the pParse structure as needed.
57877 */
57878 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
57879   pParse->explain = explainFlag;
57880   pParse->nVar = 0;
57881 }
57882
57883 #ifndef SQLITE_OMIT_SHARED_CACHE
57884 /*
57885 ** The TableLock structure is only used by the sqlite3TableLock() and
57886 ** codeTableLocks() functions.
57887 */
57888 struct TableLock {
57889   int iDb;             /* The database containing the table to be locked */
57890   int iTab;            /* The root page of the table to be locked */
57891   u8 isWriteLock;      /* True for write lock.  False for a read lock */
57892   const char *zName;   /* Name of the table */
57893 };
57894
57895 /*
57896 ** Record the fact that we want to lock a table at run-time.  
57897 **
57898 ** The table to be locked has root page iTab and is found in database iDb.
57899 ** A read or a write lock can be taken depending on isWritelock.
57900 **
57901 ** This routine just records the fact that the lock is desired.  The
57902 ** code to make the lock occur is generated by a later call to
57903 ** codeTableLocks() which occurs during sqlite3FinishCoding().
57904 */
57905 SQLITE_PRIVATE void sqlite3TableLock(
57906   Parse *pParse,     /* Parsing context */
57907   int iDb,           /* Index of the database containing the table to lock */
57908   int iTab,          /* Root page number of the table to be locked */
57909   u8 isWriteLock,    /* True for a write lock */
57910   const char *zName  /* Name of the table to be locked */
57911 ){
57912   int i;
57913   int nBytes;
57914   TableLock *p;
57915
57916   if( iDb<0 ){
57917     return;
57918   }
57919
57920   for(i=0; i<pParse->nTableLock; i++){
57921     p = &pParse->aTableLock[i];
57922     if( p->iDb==iDb && p->iTab==iTab ){
57923       p->isWriteLock = (p->isWriteLock || isWriteLock);
57924       return;
57925     }
57926   }
57927
57928   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
57929   pParse->aTableLock = 
57930       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
57931   if( pParse->aTableLock ){
57932     p = &pParse->aTableLock[pParse->nTableLock++];
57933     p->iDb = iDb;
57934     p->iTab = iTab;
57935     p->isWriteLock = isWriteLock;
57936     p->zName = zName;
57937   }else{
57938     pParse->nTableLock = 0;
57939     pParse->db->mallocFailed = 1;
57940   }
57941 }
57942
57943 /*
57944 ** Code an OP_TableLock instruction for each table locked by the
57945 ** statement (configured by calls to sqlite3TableLock()).
57946 */
57947 static void codeTableLocks(Parse *pParse){
57948   int i;
57949   Vdbe *pVdbe; 
57950
57951   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
57952     return;
57953   }
57954
57955   for(i=0; i<pParse->nTableLock; i++){
57956     TableLock *p = &pParse->aTableLock[i];
57957     int p1 = p->iDb;
57958     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
57959                       p->zName, P4_STATIC);
57960   }
57961 }
57962 #else
57963   #define codeTableLocks(x)
57964 #endif
57965
57966 /*
57967 ** This routine is called after a single SQL statement has been
57968 ** parsed and a VDBE program to execute that statement has been
57969 ** prepared.  This routine puts the finishing touches on the
57970 ** VDBE program and resets the pParse structure for the next
57971 ** parse.
57972 **
57973 ** Note that if an error occurred, it might be the case that
57974 ** no VDBE code was generated.
57975 */
57976 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
57977   sqlite3 *db;
57978   Vdbe *v;
57979
57980   db = pParse->db;
57981   if( db->mallocFailed ) return;
57982   if( pParse->nested ) return;
57983   if( pParse->nErr ) return;
57984
57985   /* Begin by generating some termination code at the end of the
57986   ** vdbe program
57987   */
57988   v = sqlite3GetVdbe(pParse);
57989   if( v ){
57990     sqlite3VdbeAddOp0(v, OP_Halt);
57991
57992     /* The cookie mask contains one bit for each database file open.
57993     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
57994     ** set for each database that is used.  Generate code to start a
57995     ** transaction on each used database and to verify the schema cookie
57996     ** on each used database.
57997     */
57998     if( pParse->cookieGoto>0 ){
57999       u32 mask;
58000       int iDb;
58001       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
58002       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
58003         if( (mask & pParse->cookieMask)==0 ) continue;
58004         sqlite3VdbeUsesBtree(v, iDb);
58005         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
58006         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
58007       }
58008 #ifndef SQLITE_OMIT_VIRTUALTABLE
58009       {
58010         int i;
58011         for(i=0; i<pParse->nVtabLock; i++){
58012           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
58013           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
58014         }
58015         pParse->nVtabLock = 0;
58016       }
58017 #endif
58018
58019       /* Once all the cookies have been verified and transactions opened, 
58020       ** obtain the required table-locks. This is a no-op unless the 
58021       ** shared-cache feature is enabled.
58022       */
58023       codeTableLocks(pParse);
58024       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
58025     }
58026
58027 #ifndef SQLITE_OMIT_TRACE
58028     if( !db->init.busy ){
58029       /* Change the P4 argument of the first opcode (which will always be
58030       ** an OP_Trace) to be the complete text of the current SQL statement.
58031       */
58032       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
58033       if( pOp && pOp->opcode==OP_Trace ){
58034         sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
58035       }
58036     }
58037 #endif /* SQLITE_OMIT_TRACE */
58038   }
58039
58040
58041   /* Get the VDBE program ready for execution
58042   */
58043   if( v && pParse->nErr==0 && !db->mallocFailed ){
58044 #ifdef SQLITE_DEBUG
58045     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
58046     sqlite3VdbeTrace(v, trace);
58047 #endif
58048     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
58049     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
58050                          pParse->nTab+3, pParse->explain);
58051     pParse->rc = SQLITE_DONE;
58052     pParse->colNamesSet = 0;
58053   }else if( pParse->rc==SQLITE_OK ){
58054     pParse->rc = SQLITE_ERROR;
58055   }
58056   pParse->nTab = 0;
58057   pParse->nMem = 0;
58058   pParse->nSet = 0;
58059   pParse->nVar = 0;
58060   pParse->cookieMask = 0;
58061   pParse->cookieGoto = 0;
58062 }
58063
58064 /*
58065 ** Run the parser and code generator recursively in order to generate
58066 ** code for the SQL statement given onto the end of the pParse context
58067 ** currently under construction.  When the parser is run recursively
58068 ** this way, the final OP_Halt is not appended and other initialization
58069 ** and finalization steps are omitted because those are handling by the
58070 ** outermost parser.
58071 **
58072 ** Not everything is nestable.  This facility is designed to permit
58073 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
58074 ** care if you decide to try to use this routine for some other purposes.
58075 */
58076 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
58077   va_list ap;
58078   char *zSql;
58079   char *zErrMsg = 0;
58080   sqlite3 *db = pParse->db;
58081 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
58082   char saveBuf[SAVE_SZ];
58083
58084   if( pParse->nErr ) return;
58085   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
58086   va_start(ap, zFormat);
58087   zSql = sqlite3VMPrintf(db, zFormat, ap);
58088   va_end(ap);
58089   if( zSql==0 ){
58090     return;   /* A malloc must have failed */
58091   }
58092   pParse->nested++;
58093   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
58094   memset(&pParse->nVar, 0, SAVE_SZ);
58095   sqlite3RunParser(pParse, zSql, &zErrMsg);
58096   sqlite3DbFree(db, zErrMsg);
58097   sqlite3DbFree(db, zSql);
58098   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
58099   pParse->nested--;
58100 }
58101
58102 /*
58103 ** Locate the in-memory structure that describes a particular database
58104 ** table given the name of that table and (optionally) the name of the
58105 ** database containing the table.  Return NULL if not found.
58106 **
58107 ** If zDatabase is 0, all databases are searched for the table and the
58108 ** first matching table is returned.  (No checking for duplicate table
58109 ** names is done.)  The search order is TEMP first, then MAIN, then any
58110 ** auxiliary databases added using the ATTACH command.
58111 **
58112 ** See also sqlite3LocateTable().
58113 */
58114 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
58115   Table *p = 0;
58116   int i;
58117   int nName;
58118   assert( zName!=0 );
58119   nName = sqlite3Strlen(db, zName) + 1;
58120   for(i=OMIT_TEMPDB; i<db->nDb; i++){
58121     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
58122     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
58123     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
58124     if( p ) break;
58125   }
58126   return p;
58127 }
58128
58129 /*
58130 ** Locate the in-memory structure that describes a particular database
58131 ** table given the name of that table and (optionally) the name of the
58132 ** database containing the table.  Return NULL if not found.  Also leave an
58133 ** error message in pParse->zErrMsg.
58134 **
58135 ** The difference between this routine and sqlite3FindTable() is that this
58136 ** routine leaves an error message in pParse->zErrMsg where
58137 ** sqlite3FindTable() does not.
58138 */
58139 SQLITE_PRIVATE Table *sqlite3LocateTable(
58140   Parse *pParse,         /* context in which to report errors */
58141   int isView,            /* True if looking for a VIEW rather than a TABLE */
58142   const char *zName,     /* Name of the table we are looking for */
58143   const char *zDbase     /* Name of the database.  Might be NULL */
58144 ){
58145   Table *p;
58146
58147   /* Read the database schema. If an error occurs, leave an error message
58148   ** and code in pParse and return NULL. */
58149   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
58150     return 0;
58151   }
58152
58153   p = sqlite3FindTable(pParse->db, zName, zDbase);
58154   if( p==0 ){
58155     const char *zMsg = isView ? "no such view" : "no such table";
58156     if( zDbase ){
58157       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
58158     }else{
58159       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
58160     }
58161     pParse->checkSchema = 1;
58162   }
58163   return p;
58164 }
58165
58166 /*
58167 ** Locate the in-memory structure that describes 
58168 ** a particular index given the name of that index
58169 ** and the name of the database that contains the index.
58170 ** Return NULL if not found.
58171 **
58172 ** If zDatabase is 0, all databases are searched for the
58173 ** table and the first matching index is returned.  (No checking
58174 ** for duplicate index names is done.)  The search order is
58175 ** TEMP first, then MAIN, then any auxiliary databases added
58176 ** using the ATTACH command.
58177 */
58178 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
58179   Index *p = 0;
58180   int i;
58181   int nName = sqlite3Strlen(db, zName)+1;
58182   for(i=OMIT_TEMPDB; i<db->nDb; i++){
58183     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
58184     Schema *pSchema = db->aDb[j].pSchema;
58185     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
58186     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
58187     if( pSchema ){
58188       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
58189     }
58190     if( p ) break;
58191   }
58192   return p;
58193 }
58194
58195 /*
58196 ** Reclaim the memory used by an index
58197 */
58198 static void freeIndex(Index *p){
58199   sqlite3 *db = p->pTable->db;
58200   sqlite3DbFree(db, p->zColAff);
58201   sqlite3DbFree(db, p);
58202 }
58203
58204 /*
58205 ** Remove the given index from the index hash table, and free
58206 ** its memory structures.
58207 **
58208 ** The index is removed from the database hash tables but
58209 ** it is not unlinked from the Table that it indexes.
58210 ** Unlinking from the Table must be done by the calling function.
58211 */
58212 static void sqliteDeleteIndex(Index *p){
58213   Index *pOld;
58214   const char *zName = p->zName;
58215
58216   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
58217   assert( pOld==0 || pOld==p );
58218   freeIndex(p);
58219 }
58220
58221 /*
58222 ** For the index called zIdxName which is found in the database iDb,
58223 ** unlike that index from its Table then remove the index from
58224 ** the index hash table and free all memory structures associated
58225 ** with the index.
58226 */
58227 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
58228   Index *pIndex;
58229   int len;
58230   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
58231
58232   len = sqlite3Strlen(db, zIdxName);
58233   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
58234   if( pIndex ){
58235     if( pIndex->pTable->pIndex==pIndex ){
58236       pIndex->pTable->pIndex = pIndex->pNext;
58237     }else{
58238       Index *p;
58239       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
58240       if( p && p->pNext==pIndex ){
58241         p->pNext = pIndex->pNext;
58242       }
58243     }
58244     freeIndex(pIndex);
58245   }
58246   db->flags |= SQLITE_InternChanges;
58247 }
58248
58249 /*
58250 ** Erase all schema information from the in-memory hash tables of
58251 ** a single database.  This routine is called to reclaim memory
58252 ** before the database closes.  It is also called during a rollback
58253 ** if there were schema changes during the transaction or if a
58254 ** schema-cookie mismatch occurs.
58255 **
58256 ** If iDb<=0 then reset the internal schema tables for all database
58257 ** files.  If iDb>=2 then reset the internal schema for only the
58258 ** single file indicated.
58259 */
58260 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
58261   int i, j;
58262   assert( iDb>=0 && iDb<db->nDb );
58263
58264   if( iDb==0 ){
58265     sqlite3BtreeEnterAll(db);
58266   }
58267   for(i=iDb; i<db->nDb; i++){
58268     Db *pDb = &db->aDb[i];
58269     if( pDb->pSchema ){
58270       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
58271       sqlite3SchemaFree(pDb->pSchema);
58272     }
58273     if( iDb>0 ) return;
58274   }
58275   assert( iDb==0 );
58276   db->flags &= ~SQLITE_InternChanges;
58277   sqlite3BtreeLeaveAll(db);
58278
58279   /* If one or more of the auxiliary database files has been closed,
58280   ** then remove them from the auxiliary database list.  We take the
58281   ** opportunity to do this here since we have just deleted all of the
58282   ** schema hash tables and therefore do not have to make any changes
58283   ** to any of those tables.
58284   */
58285   for(i=0; i<db->nDb; i++){
58286     struct Db *pDb = &db->aDb[i];
58287     if( pDb->pBt==0 ){
58288       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
58289       pDb->pAux = 0;
58290     }
58291   }
58292   for(i=j=2; i<db->nDb; i++){
58293     struct Db *pDb = &db->aDb[i];
58294     if( pDb->pBt==0 ){
58295       sqlite3DbFree(db, pDb->zName);
58296       pDb->zName = 0;
58297       continue;
58298     }
58299     if( j<i ){
58300       db->aDb[j] = db->aDb[i];
58301     }
58302     j++;
58303   }
58304   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
58305   db->nDb = j;
58306   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
58307     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
58308     sqlite3DbFree(db, db->aDb);
58309     db->aDb = db->aDbStatic;
58310   }
58311 }
58312
58313 /*
58314 ** This routine is called when a commit occurs.
58315 */
58316 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
58317   db->flags &= ~SQLITE_InternChanges;
58318 }
58319
58320 /*
58321 ** Clear the column names from a table or view.
58322 */
58323 static void sqliteResetColumnNames(Table *pTable){
58324   int i;
58325   Column *pCol;
58326   sqlite3 *db = pTable->db;
58327   assert( pTable!=0 );
58328   if( (pCol = pTable->aCol)!=0 ){
58329     for(i=0; i<pTable->nCol; i++, pCol++){
58330       sqlite3DbFree(db, pCol->zName);
58331       sqlite3ExprDelete(db, pCol->pDflt);
58332       sqlite3DbFree(db, pCol->zType);
58333       sqlite3DbFree(db, pCol->zColl);
58334     }
58335     sqlite3DbFree(db, pTable->aCol);
58336   }
58337   pTable->aCol = 0;
58338   pTable->nCol = 0;
58339 }
58340
58341 /*
58342 ** Remove the memory data structures associated with the given
58343 ** Table.  No changes are made to disk by this routine.
58344 **
58345 ** This routine just deletes the data structure.  It does not unlink
58346 ** the table data structure from the hash table.  Nor does it remove
58347 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
58348 ** memory structures of the indices and foreign keys associated with 
58349 ** the table.
58350 */
58351 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
58352   Index *pIndex, *pNext;
58353   FKey *pFKey, *pNextFKey;
58354   sqlite3 *db;
58355
58356   if( pTable==0 ) return;
58357   db = pTable->db;
58358
58359   /* Do not delete the table until the reference count reaches zero. */
58360   pTable->nRef--;
58361   if( pTable->nRef>0 ){
58362     return;
58363   }
58364   assert( pTable->nRef==0 );
58365
58366   /* Delete all indices associated with this table
58367   */
58368   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
58369     pNext = pIndex->pNext;
58370     assert( pIndex->pSchema==pTable->pSchema );
58371     sqliteDeleteIndex(pIndex);
58372   }
58373
58374 #ifndef SQLITE_OMIT_FOREIGN_KEY
58375   /* Delete all foreign keys associated with this table.  The keys
58376   ** should have already been unlinked from the pSchema->aFKey hash table 
58377   */
58378   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
58379     pNextFKey = pFKey->pNextFrom;
58380     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
58381                            pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
58382     sqlite3DbFree(db, pFKey);
58383   }
58384 #endif
58385
58386   /* Delete the Table structure itself.
58387   */
58388   sqliteResetColumnNames(pTable);
58389   sqlite3DbFree(db, pTable->zName);
58390   sqlite3DbFree(db, pTable->zColAff);
58391   sqlite3SelectDelete(db, pTable->pSelect);
58392 #ifndef SQLITE_OMIT_CHECK
58393   sqlite3ExprDelete(db, pTable->pCheck);
58394 #endif
58395   sqlite3VtabClear(pTable);
58396   sqlite3DbFree(db, pTable);
58397 }
58398
58399 /*
58400 ** Unlink the given table from the hash tables and the delete the
58401 ** table structure with all its indices and foreign keys.
58402 */
58403 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
58404   Table *p;
58405   FKey *pF1, *pF2;
58406   Db *pDb;
58407
58408   assert( db!=0 );
58409   assert( iDb>=0 && iDb<db->nDb );
58410   assert( zTabName && zTabName[0] );
58411   pDb = &db->aDb[iDb];
58412   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
58413   if( p ){
58414 #ifndef SQLITE_OMIT_FOREIGN_KEY
58415     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
58416       int nTo = strlen(pF1->zTo) + 1;
58417       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
58418       if( pF2==pF1 ){
58419         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
58420       }else{
58421         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
58422         if( pF2 ){
58423           pF2->pNextTo = pF1->pNextTo;
58424         }
58425       }
58426     }
58427 #endif
58428     sqlite3DeleteTable(p);
58429   }
58430   db->flags |= SQLITE_InternChanges;
58431 }
58432
58433 /*
58434 ** Given a token, return a string that consists of the text of that
58435 ** token with any quotations removed.  Space to hold the returned string
58436 ** is obtained from sqliteMalloc() and must be freed by the calling
58437 ** function.
58438 **
58439 ** Tokens are often just pointers into the original SQL text and so
58440 ** are not \000 terminated and are not persistent.  The returned string
58441 ** is \000 terminated and is persistent.
58442 */
58443 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
58444   char *zName;
58445   if( pName ){
58446     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
58447     sqlite3Dequote(zName);
58448   }else{
58449     zName = 0;
58450   }
58451   return zName;
58452 }
58453
58454 /*
58455 ** Open the sqlite_master table stored in database number iDb for
58456 ** writing. The table is opened using cursor 0.
58457 */
58458 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
58459   Vdbe *v = sqlite3GetVdbe(p);
58460   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
58461   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
58462   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
58463 }
58464
58465 /*
58466 ** The token *pName contains the name of a database (either "main" or
58467 ** "temp" or the name of an attached db). This routine returns the
58468 ** index of the named database in db->aDb[], or -1 if the named db 
58469 ** does not exist.
58470 */
58471 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
58472   int i = -1;    /* Database number */
58473   int n;         /* Number of characters in the name */
58474   Db *pDb;       /* A database whose name space is being searched */
58475   char *zName;   /* Name we are searching for */
58476
58477   zName = sqlite3NameFromToken(db, pName);
58478   if( zName ){
58479     n = strlen(zName);
58480     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
58481       if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) && 
58482           0==sqlite3StrICmp(pDb->zName, zName) ){
58483         break;
58484       }
58485     }
58486     sqlite3DbFree(db, zName);
58487   }
58488   return i;
58489 }
58490
58491 /* The table or view or trigger name is passed to this routine via tokens
58492 ** pName1 and pName2. If the table name was fully qualified, for example:
58493 **
58494 ** CREATE TABLE xxx.yyy (...);
58495 ** 
58496 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
58497 ** the table name is not fully qualified, i.e.:
58498 **
58499 ** CREATE TABLE yyy(...);
58500 **
58501 ** Then pName1 is set to "yyy" and pName2 is "".
58502 **
58503 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
58504 ** pName2) that stores the unqualified table name.  The index of the
58505 ** database "xxx" is returned.
58506 */
58507 SQLITE_PRIVATE int sqlite3TwoPartName(
58508   Parse *pParse,      /* Parsing and code generating context */
58509   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
58510   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
58511   Token **pUnqual     /* Write the unqualified object name here */
58512 ){
58513   int iDb;                    /* Database holding the object */
58514   sqlite3 *db = pParse->db;
58515
58516   if( pName2 && pName2->n>0 ){
58517     assert( !db->init.busy );
58518     *pUnqual = pName2;
58519     iDb = sqlite3FindDb(db, pName1);
58520     if( iDb<0 ){
58521       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
58522       pParse->nErr++;
58523       return -1;
58524     }
58525   }else{
58526     assert( db->init.iDb==0 || db->init.busy );
58527     iDb = db->init.iDb;
58528     *pUnqual = pName1;
58529   }
58530   return iDb;
58531 }
58532
58533 /*
58534 ** This routine is used to check if the UTF-8 string zName is a legal
58535 ** unqualified name for a new schema object (table, index, view or
58536 ** trigger). All names are legal except those that begin with the string
58537 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
58538 ** is reserved for internal use.
58539 */
58540 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
58541   if( !pParse->db->init.busy && pParse->nested==0 
58542           && (pParse->db->flags & SQLITE_WriteSchema)==0
58543           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
58544     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
58545     return SQLITE_ERROR;
58546   }
58547   return SQLITE_OK;
58548 }
58549
58550 /*
58551 ** Begin constructing a new table representation in memory.  This is
58552 ** the first of several action routines that get called in response
58553 ** to a CREATE TABLE statement.  In particular, this routine is called
58554 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
58555 ** flag is true if the table should be stored in the auxiliary database
58556 ** file instead of in the main database file.  This is normally the case
58557 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
58558 ** CREATE and TABLE.
58559 **
58560 ** The new table record is initialized and put in pParse->pNewTable.
58561 ** As more of the CREATE TABLE statement is parsed, additional action
58562 ** routines will be called to add more information to this record.
58563 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
58564 ** is called to complete the construction of the new table record.
58565 */
58566 SQLITE_PRIVATE void sqlite3StartTable(
58567   Parse *pParse,   /* Parser context */
58568   Token *pName1,   /* First part of the name of the table or view */
58569   Token *pName2,   /* Second part of the name of the table or view */
58570   int isTemp,      /* True if this is a TEMP table */
58571   int isView,      /* True if this is a VIEW */
58572   int isVirtual,   /* True if this is a VIRTUAL table */
58573   int noErr        /* Do nothing if table already exists */
58574 ){
58575   Table *pTable;
58576   char *zName = 0; /* The name of the new table */
58577   sqlite3 *db = pParse->db;
58578   Vdbe *v;
58579   int iDb;         /* Database number to create the table in */
58580   Token *pName;    /* Unqualified name of the table to create */
58581
58582   /* The table or view name to create is passed to this routine via tokens
58583   ** pName1 and pName2. If the table name was fully qualified, for example:
58584   **
58585   ** CREATE TABLE xxx.yyy (...);
58586   ** 
58587   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
58588   ** the table name is not fully qualified, i.e.:
58589   **
58590   ** CREATE TABLE yyy(...);
58591   **
58592   ** Then pName1 is set to "yyy" and pName2 is "".
58593   **
58594   ** The call below sets the pName pointer to point at the token (pName1 or
58595   ** pName2) that stores the unqualified table name. The variable iDb is
58596   ** set to the index of the database that the table or view is to be
58597   ** created in.
58598   */
58599   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
58600   if( iDb<0 ) return;
58601   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
58602     /* If creating a temp table, the name may not be qualified */
58603     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
58604     return;
58605   }
58606   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
58607
58608   pParse->sNameToken = *pName;
58609   zName = sqlite3NameFromToken(db, pName);
58610   if( zName==0 ) return;
58611   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
58612     goto begin_table_error;
58613   }
58614   if( db->init.iDb==1 ) isTemp = 1;
58615 #ifndef SQLITE_OMIT_AUTHORIZATION
58616   assert( (isTemp & 1)==isTemp );
58617   {
58618     int code;
58619     char *zDb = db->aDb[iDb].zName;
58620     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
58621       goto begin_table_error;
58622     }
58623     if( isView ){
58624       if( !OMIT_TEMPDB && isTemp ){
58625         code = SQLITE_CREATE_TEMP_VIEW;
58626       }else{
58627         code = SQLITE_CREATE_VIEW;
58628       }
58629     }else{
58630       if( !OMIT_TEMPDB && isTemp ){
58631         code = SQLITE_CREATE_TEMP_TABLE;
58632       }else{
58633         code = SQLITE_CREATE_TABLE;
58634       }
58635     }
58636     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
58637       goto begin_table_error;
58638     }
58639   }
58640 #endif
58641
58642   /* Make sure the new table name does not collide with an existing
58643   ** index or table name in the same database.  Issue an error message if
58644   ** it does. The exception is if the statement being parsed was passed
58645   ** to an sqlite3_declare_vtab() call. In that case only the column names
58646   ** and types will be used, so there is no need to test for namespace
58647   ** collisions.
58648   */
58649   if( !IN_DECLARE_VTAB ){
58650     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
58651       goto begin_table_error;
58652     }
58653     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
58654     if( pTable ){
58655       if( !noErr ){
58656         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
58657       }
58658       goto begin_table_error;
58659     }
58660     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
58661       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
58662       goto begin_table_error;
58663     }
58664   }
58665
58666   pTable = sqlite3DbMallocZero(db, sizeof(Table));
58667   if( pTable==0 ){
58668     db->mallocFailed = 1;
58669     pParse->rc = SQLITE_NOMEM;
58670     pParse->nErr++;
58671     goto begin_table_error;
58672   }
58673   pTable->zName = zName;
58674   pTable->iPKey = -1;
58675   pTable->pSchema = db->aDb[iDb].pSchema;
58676   pTable->nRef = 1;
58677   pTable->db = db;
58678   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
58679   pParse->pNewTable = pTable;
58680
58681   /* If this is the magic sqlite_sequence table used by autoincrement,
58682   ** then record a pointer to this table in the main database structure
58683   ** so that INSERT can find the table easily.
58684   */
58685 #ifndef SQLITE_OMIT_AUTOINCREMENT
58686   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
58687     pTable->pSchema->pSeqTab = pTable;
58688   }
58689 #endif
58690
58691   /* Begin generating the code that will insert the table record into
58692   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
58693   ** and allocate the record number for the table entry now.  Before any
58694   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
58695   ** indices to be created and the table record must come before the 
58696   ** indices.  Hence, the record number for the table must be allocated
58697   ** now.
58698   */
58699   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
58700     int j1;
58701     int fileFormat;
58702     int reg1, reg2, reg3;
58703     sqlite3BeginWriteOperation(pParse, 0, iDb);
58704
58705 #ifndef SQLITE_OMIT_VIRTUALTABLE
58706     if( isVirtual ){
58707       sqlite3VdbeAddOp0(v, OP_VBegin);
58708     }
58709 #endif
58710
58711     /* If the file format and encoding in the database have not been set, 
58712     ** set them now.
58713     */
58714     reg1 = pParse->regRowid = ++pParse->nMem;
58715     reg2 = pParse->regRoot = ++pParse->nMem;
58716     reg3 = ++pParse->nMem;
58717     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
58718     sqlite3VdbeUsesBtree(v, iDb);
58719     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
58720     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
58721                   1 : SQLITE_MAX_FILE_FORMAT;
58722     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
58723     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
58724     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
58725     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
58726     sqlite3VdbeJumpHere(v, j1);
58727
58728     /* This just creates a place-holder record in the sqlite_master table.
58729     ** The record created does not contain anything yet.  It will be replaced
58730     ** by the real entry in code generated at sqlite3EndTable().
58731     **
58732     ** The rowid for the new entry is left on the top of the stack.
58733     ** The rowid value is needed by the code that sqlite3EndTable will
58734     ** generate.
58735     */
58736 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
58737     if( isView || isVirtual ){
58738       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
58739     }else
58740 #endif
58741     {
58742       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
58743     }
58744     sqlite3OpenMasterTable(pParse, iDb);
58745     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
58746     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
58747     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
58748     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
58749     sqlite3VdbeAddOp0(v, OP_Close);
58750   }
58751
58752   /* Normal (non-error) return. */
58753   return;
58754
58755   /* If an error occurs, we jump here */
58756 begin_table_error:
58757   sqlite3DbFree(db, zName);
58758   return;
58759 }
58760
58761 /*
58762 ** This macro is used to compare two strings in a case-insensitive manner.
58763 ** It is slightly faster than calling sqlite3StrICmp() directly, but
58764 ** produces larger code.
58765 **
58766 ** WARNING: This macro is not compatible with the strcmp() family. It
58767 ** returns true if the two strings are equal, otherwise false.
58768 */
58769 #define STRICMP(x, y) (\
58770 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
58771 sqlite3UpperToLower[*(unsigned char *)(y)]     \
58772 && sqlite3StrICmp((x)+1,(y)+1)==0 )
58773
58774 /*
58775 ** Add a new column to the table currently being constructed.
58776 **
58777 ** The parser calls this routine once for each column declaration
58778 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
58779 ** first to get things going.  Then this routine is called for each
58780 ** column.
58781 */
58782 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
58783   Table *p;
58784   int i;
58785   char *z;
58786   Column *pCol;
58787   sqlite3 *db = pParse->db;
58788   if( (p = pParse->pNewTable)==0 ) return;
58789 #if SQLITE_MAX_COLUMN
58790   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
58791     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
58792     return;
58793   }
58794 #endif
58795   z = sqlite3NameFromToken(pParse->db, pName);
58796   if( z==0 ) return;
58797   for(i=0; i<p->nCol; i++){
58798     if( STRICMP(z, p->aCol[i].zName) ){
58799       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
58800       sqlite3DbFree(db, z);
58801       return;
58802     }
58803   }
58804   if( (p->nCol & 0x7)==0 ){
58805     Column *aNew;
58806     aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
58807     if( aNew==0 ){
58808       sqlite3DbFree(db, z);
58809       return;
58810     }
58811     p->aCol = aNew;
58812   }
58813   pCol = &p->aCol[p->nCol];
58814   memset(pCol, 0, sizeof(p->aCol[0]));
58815   pCol->zName = z;
58816  
58817   /* If there is no type specified, columns have the default affinity
58818   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
58819   ** be called next to set pCol->affinity correctly.
58820   */
58821   pCol->affinity = SQLITE_AFF_NONE;
58822   p->nCol++;
58823 }
58824
58825 /*
58826 ** This routine is called by the parser while in the middle of
58827 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
58828 ** been seen on a column.  This routine sets the notNull flag on
58829 ** the column currently under construction.
58830 */
58831 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
58832   Table *p;
58833   int i;
58834   if( (p = pParse->pNewTable)==0 ) return;
58835   i = p->nCol-1;
58836   if( i>=0 ) p->aCol[i].notNull = onError;
58837 }
58838
58839 /*
58840 ** Scan the column type name zType (length nType) and return the
58841 ** associated affinity type.
58842 **
58843 ** This routine does a case-independent search of zType for the 
58844 ** substrings in the following table. If one of the substrings is
58845 ** found, the corresponding affinity is returned. If zType contains
58846 ** more than one of the substrings, entries toward the top of 
58847 ** the table take priority. For example, if zType is 'BLOBINT', 
58848 ** SQLITE_AFF_INTEGER is returned.
58849 **
58850 ** Substring     | Affinity
58851 ** --------------------------------
58852 ** 'INT'         | SQLITE_AFF_INTEGER
58853 ** 'CHAR'        | SQLITE_AFF_TEXT
58854 ** 'CLOB'        | SQLITE_AFF_TEXT
58855 ** 'TEXT'        | SQLITE_AFF_TEXT
58856 ** 'BLOB'        | SQLITE_AFF_NONE
58857 ** 'REAL'        | SQLITE_AFF_REAL
58858 ** 'FLOA'        | SQLITE_AFF_REAL
58859 ** 'DOUB'        | SQLITE_AFF_REAL
58860 **
58861 ** If none of the substrings in the above table are found,
58862 ** SQLITE_AFF_NUMERIC is returned.
58863 */
58864 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
58865   u32 h = 0;
58866   char aff = SQLITE_AFF_NUMERIC;
58867   const unsigned char *zIn = pType->z;
58868   const unsigned char *zEnd = &pType->z[pType->n];
58869
58870   while( zIn!=zEnd ){
58871     h = (h<<8) + sqlite3UpperToLower[*zIn];
58872     zIn++;
58873     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
58874       aff = SQLITE_AFF_TEXT; 
58875     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
58876       aff = SQLITE_AFF_TEXT;
58877     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
58878       aff = SQLITE_AFF_TEXT;
58879     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
58880         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
58881       aff = SQLITE_AFF_NONE;
58882 #ifndef SQLITE_OMIT_FLOATING_POINT
58883     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
58884         && aff==SQLITE_AFF_NUMERIC ){
58885       aff = SQLITE_AFF_REAL;
58886     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
58887         && aff==SQLITE_AFF_NUMERIC ){
58888       aff = SQLITE_AFF_REAL;
58889     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
58890         && aff==SQLITE_AFF_NUMERIC ){
58891       aff = SQLITE_AFF_REAL;
58892 #endif
58893     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
58894       aff = SQLITE_AFF_INTEGER;
58895       break;
58896     }
58897   }
58898
58899   return aff;
58900 }
58901
58902 /*
58903 ** This routine is called by the parser while in the middle of
58904 ** parsing a CREATE TABLE statement.  The pFirst token is the first
58905 ** token in the sequence of tokens that describe the type of the
58906 ** column currently under construction.   pLast is the last token
58907 ** in the sequence.  Use this information to construct a string
58908 ** that contains the typename of the column and store that string
58909 ** in zType.
58910 */ 
58911 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
58912   Table *p;
58913   int i;
58914   Column *pCol;
58915   sqlite3 *db;
58916
58917   if( (p = pParse->pNewTable)==0 ) return;
58918   i = p->nCol-1;
58919   if( i<0 ) return;
58920   pCol = &p->aCol[i];
58921   db = pParse->db;
58922   sqlite3DbFree(db, pCol->zType);
58923   pCol->zType = sqlite3NameFromToken(db, pType);
58924   pCol->affinity = sqlite3AffinityType(pType);
58925 }
58926
58927 /*
58928 ** The expression is the default value for the most recently added column
58929 ** of the table currently under construction.
58930 **
58931 ** Default value expressions must be constant.  Raise an exception if this
58932 ** is not the case.
58933 **
58934 ** This routine is called by the parser while in the middle of
58935 ** parsing a CREATE TABLE statement.
58936 */
58937 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
58938   Table *p;
58939   Column *pCol;
58940   sqlite3 *db = pParse->db;
58941   if( (p = pParse->pNewTable)!=0 ){
58942     pCol = &(p->aCol[p->nCol-1]);
58943     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
58944       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
58945           pCol->zName);
58946     }else{
58947       Expr *pCopy;
58948       sqlite3ExprDelete(db, pCol->pDflt);
58949       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
58950       if( pCopy ){
58951         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
58952       }
58953     }
58954   }
58955   sqlite3ExprDelete(db, pExpr);
58956 }
58957
58958 /*
58959 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
58960 ** of columns that form the primary key.  If pList is NULL, then the
58961 ** most recently added column of the table is the primary key.
58962 **
58963 ** A table can have at most one primary key.  If the table already has
58964 ** a primary key (and this is the second primary key) then create an
58965 ** error.
58966 **
58967 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
58968 ** then we will try to use that column as the rowid.  Set the Table.iPKey
58969 ** field of the table under construction to be the index of the
58970 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
58971 ** no INTEGER PRIMARY KEY.
58972 **
58973 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
58974 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
58975 */
58976 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
58977   Parse *pParse,    /* Parsing context */
58978   ExprList *pList,  /* List of field names to be indexed */
58979   int onError,      /* What to do with a uniqueness conflict */
58980   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
58981   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
58982 ){
58983   Table *pTab = pParse->pNewTable;
58984   char *zType = 0;
58985   int iCol = -1, i;
58986   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
58987   if( pTab->tabFlags & TF_HasPrimaryKey ){
58988     sqlite3ErrorMsg(pParse, 
58989       "table \"%s\" has more than one primary key", pTab->zName);
58990     goto primary_key_exit;
58991   }
58992   pTab->tabFlags |= TF_HasPrimaryKey;
58993   if( pList==0 ){
58994     iCol = pTab->nCol - 1;
58995     pTab->aCol[iCol].isPrimKey = 1;
58996   }else{
58997     for(i=0; i<pList->nExpr; i++){
58998       for(iCol=0; iCol<pTab->nCol; iCol++){
58999         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
59000           break;
59001         }
59002       }
59003       if( iCol<pTab->nCol ){
59004         pTab->aCol[iCol].isPrimKey = 1;
59005       }
59006     }
59007     if( pList->nExpr>1 ) iCol = -1;
59008   }
59009   if( iCol>=0 && iCol<pTab->nCol ){
59010     zType = pTab->aCol[iCol].zType;
59011   }
59012   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
59013         && sortOrder==SQLITE_SO_ASC ){
59014     pTab->iPKey = iCol;
59015     pTab->keyConf = onError;
59016     assert( autoInc==0 || autoInc==1 );
59017     pTab->tabFlags |= autoInc*TF_Autoincrement;
59018   }else if( autoInc ){
59019 #ifndef SQLITE_OMIT_AUTOINCREMENT
59020     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
59021        "INTEGER PRIMARY KEY");
59022 #endif
59023   }else{
59024     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
59025     pList = 0;
59026   }
59027
59028 primary_key_exit:
59029   sqlite3ExprListDelete(pParse->db, pList);
59030   return;
59031 }
59032
59033 /*
59034 ** Add a new CHECK constraint to the table currently under construction.
59035 */
59036 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
59037   Parse *pParse,    /* Parsing context */
59038   Expr *pCheckExpr  /* The check expression */
59039 ){
59040   sqlite3 *db = pParse->db;
59041 #ifndef SQLITE_OMIT_CHECK
59042   Table *pTab = pParse->pNewTable;
59043   if( pTab && !IN_DECLARE_VTAB ){
59044     /* The CHECK expression must be duplicated so that tokens refer
59045     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
59046     ** statement */
59047     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
59048                                   sqlite3ExprDup(db, pCheckExpr));
59049   }
59050 #endif
59051   sqlite3ExprDelete(db, pCheckExpr);
59052 }
59053
59054 /*
59055 ** Set the collation function of the most recently parsed table column
59056 ** to the CollSeq given.
59057 */
59058 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
59059   Table *p;
59060   int i;
59061   char *zColl;              /* Dequoted name of collation sequence */
59062   sqlite3 *db;
59063
59064   if( (p = pParse->pNewTable)==0 ) return;
59065   i = p->nCol-1;
59066   db = pParse->db;
59067   zColl = sqlite3NameFromToken(db, pToken);
59068   if( !zColl ) return;
59069
59070   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
59071     Index *pIdx;
59072     p->aCol[i].zColl = zColl;
59073   
59074     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
59075     ** then an index may have been created on this column before the
59076     ** collation type was added. Correct this if it is the case.
59077     */
59078     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
59079       assert( pIdx->nColumn==1 );
59080       if( pIdx->aiColumn[0]==i ){
59081         pIdx->azColl[0] = p->aCol[i].zColl;
59082       }
59083     }
59084   }else{
59085     sqlite3DbFree(db, zColl);
59086   }
59087 }
59088
59089 /*
59090 ** This function returns the collation sequence for database native text
59091 ** encoding identified by the string zName, length nName.
59092 **
59093 ** If the requested collation sequence is not available, or not available
59094 ** in the database native encoding, the collation factory is invoked to
59095 ** request it. If the collation factory does not supply such a sequence,
59096 ** and the sequence is available in another text encoding, then that is
59097 ** returned instead.
59098 **
59099 ** If no versions of the requested collations sequence are available, or
59100 ** another error occurs, NULL is returned and an error message written into
59101 ** pParse.
59102 **
59103 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
59104 ** invokes the collation factory if the named collation cannot be found
59105 ** and generates an error message.
59106 */
59107 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
59108   sqlite3 *db = pParse->db;
59109   u8 enc = ENC(db);
59110   u8 initbusy = db->init.busy;
59111   CollSeq *pColl;
59112
59113   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
59114   if( !initbusy && (!pColl || !pColl->xCmp) ){
59115     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
59116     if( !pColl ){
59117       if( nName<0 ){
59118         nName = sqlite3Strlen(db, zName);
59119       }
59120       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
59121       pColl = 0;
59122     }
59123   }
59124
59125   return pColl;
59126 }
59127
59128
59129 /*
59130 ** Generate code that will increment the schema cookie.
59131 **
59132 ** The schema cookie is used to determine when the schema for the
59133 ** database changes.  After each schema change, the cookie value
59134 ** changes.  When a process first reads the schema it records the
59135 ** cookie.  Thereafter, whenever it goes to access the database,
59136 ** it checks the cookie to make sure the schema has not changed
59137 ** since it was last read.
59138 **
59139 ** This plan is not completely bullet-proof.  It is possible for
59140 ** the schema to change multiple times and for the cookie to be
59141 ** set back to prior value.  But schema changes are infrequent
59142 ** and the probability of hitting the same cookie value is only
59143 ** 1 chance in 2^32.  So we're safe enough.
59144 */
59145 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
59146   int r1 = sqlite3GetTempReg(pParse);
59147   sqlite3 *db = pParse->db;
59148   Vdbe *v = pParse->pVdbe;
59149   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
59150   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
59151   sqlite3ReleaseTempReg(pParse, r1);
59152 }
59153
59154 /*
59155 ** Measure the number of characters needed to output the given
59156 ** identifier.  The number returned includes any quotes used
59157 ** but does not include the null terminator.
59158 **
59159 ** The estimate is conservative.  It might be larger that what is
59160 ** really needed.
59161 */
59162 static int identLength(const char *z){
59163   int n;
59164   for(n=0; *z; n++, z++){
59165     if( *z=='"' ){ n++; }
59166   }
59167   return n + 2;
59168 }
59169
59170 /*
59171 ** Write an identifier onto the end of the given string.  Add
59172 ** quote characters as needed.
59173 */
59174 static void identPut(char *z, int *pIdx, char *zSignedIdent){
59175   unsigned char *zIdent = (unsigned char*)zSignedIdent;
59176   int i, j, needQuote;
59177   i = *pIdx;
59178   for(j=0; zIdent[j]; j++){
59179     if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
59180   }
59181   needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
59182                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
59183   if( needQuote ) z[i++] = '"';
59184   for(j=0; zIdent[j]; j++){
59185     z[i++] = zIdent[j];
59186     if( zIdent[j]=='"' ) z[i++] = '"';
59187   }
59188   if( needQuote ) z[i++] = '"';
59189   z[i] = 0;
59190   *pIdx = i;
59191 }
59192
59193 /*
59194 ** Generate a CREATE TABLE statement appropriate for the given
59195 ** table.  Memory to hold the text of the statement is obtained
59196 ** from sqliteMalloc() and must be freed by the calling function.
59197 */
59198 static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
59199   int i, k, n;
59200   char *zStmt;
59201   char *zSep, *zSep2, *zEnd, *z;
59202   Column *pCol;
59203   n = 0;
59204   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
59205     n += identLength(pCol->zName);
59206     z = pCol->zType;
59207     if( z ){
59208       n += (strlen(z) + 1);
59209     }
59210   }
59211   n += identLength(p->zName);
59212   if( n<50 ){
59213     zSep = "";
59214     zSep2 = ",";
59215     zEnd = ")";
59216   }else{
59217     zSep = "\n  ";
59218     zSep2 = ",\n  ";
59219     zEnd = "\n)";
59220   }
59221   n += 35 + 6*p->nCol;
59222   zStmt = sqlite3Malloc( n );
59223   if( zStmt==0 ){
59224     db->mallocFailed = 1;
59225     return 0;
59226   }
59227   sqlite3_snprintf(n, zStmt,
59228                   !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
59229   k = strlen(zStmt);
59230   identPut(zStmt, &k, p->zName);
59231   zStmt[k++] = '(';
59232   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
59233     sqlite3_snprintf(n-k, &zStmt[k], zSep);
59234     k += strlen(&zStmt[k]);
59235     zSep = zSep2;
59236     identPut(zStmt, &k, pCol->zName);
59237     if( (z = pCol->zType)!=0 ){
59238       zStmt[k++] = ' ';
59239       assert( strlen(z)+k+1<=n );
59240       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
59241       k += strlen(z);
59242     }
59243   }
59244   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
59245   return zStmt;
59246 }
59247
59248 /*
59249 ** This routine is called to report the final ")" that terminates
59250 ** a CREATE TABLE statement.
59251 **
59252 ** The table structure that other action routines have been building
59253 ** is added to the internal hash tables, assuming no errors have
59254 ** occurred.
59255 **
59256 ** An entry for the table is made in the master table on disk, unless
59257 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
59258 ** it means we are reading the sqlite_master table because we just
59259 ** connected to the database or because the sqlite_master table has
59260 ** recently changed, so the entry for this table already exists in
59261 ** the sqlite_master table.  We do not want to create it again.
59262 **
59263 ** If the pSelect argument is not NULL, it means that this routine
59264 ** was called to create a table generated from a 
59265 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
59266 ** the new table will match the result set of the SELECT.
59267 */
59268 SQLITE_PRIVATE void sqlite3EndTable(
59269   Parse *pParse,          /* Parse context */
59270   Token *pCons,           /* The ',' token after the last column defn. */
59271   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
59272   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
59273 ){
59274   Table *p;
59275   sqlite3 *db = pParse->db;
59276   int iDb;
59277
59278   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
59279     return;
59280   }
59281   p = pParse->pNewTable;
59282   if( p==0 ) return;
59283
59284   assert( !db->init.busy || !pSelect );
59285
59286   iDb = sqlite3SchemaToIndex(db, p->pSchema);
59287
59288 #ifndef SQLITE_OMIT_CHECK
59289   /* Resolve names in all CHECK constraint expressions.
59290   */
59291   if( p->pCheck ){
59292     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
59293     NameContext sNC;                /* Name context for pParse->pNewTable */
59294
59295     memset(&sNC, 0, sizeof(sNC));
59296     memset(&sSrc, 0, sizeof(sSrc));
59297     sSrc.nSrc = 1;
59298     sSrc.a[0].zName = p->zName;
59299     sSrc.a[0].pTab = p;
59300     sSrc.a[0].iCursor = -1;
59301     sNC.pParse = pParse;
59302     sNC.pSrcList = &sSrc;
59303     sNC.isCheck = 1;
59304     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
59305       return;
59306     }
59307   }
59308 #endif /* !defined(SQLITE_OMIT_CHECK) */
59309
59310   /* If the db->init.busy is 1 it means we are reading the SQL off the
59311   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
59312   ** So do not write to the disk again.  Extract the root page number
59313   ** for the table from the db->init.newTnum field.  (The page number
59314   ** should have been put there by the sqliteOpenCb routine.)
59315   */
59316   if( db->init.busy ){
59317     p->tnum = db->init.newTnum;
59318   }
59319
59320   /* If not initializing, then create a record for the new table
59321   ** in the SQLITE_MASTER table of the database.  The record number
59322   ** for the new table entry should already be on the stack.
59323   **
59324   ** If this is a TEMPORARY table, write the entry into the auxiliary
59325   ** file instead of into the main database file.
59326   */
59327   if( !db->init.busy ){
59328     int n;
59329     Vdbe *v;
59330     char *zType;    /* "view" or "table" */
59331     char *zType2;   /* "VIEW" or "TABLE" */
59332     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
59333
59334     v = sqlite3GetVdbe(pParse);
59335     if( v==0 ) return;
59336
59337     sqlite3VdbeAddOp1(v, OP_Close, 0);
59338
59339     /* Create the rootpage for the new table and push it onto the stack.
59340     ** A view has no rootpage, so just push a zero onto the stack for
59341     ** views.  Initialize zType at the same time.
59342     */
59343     if( p->pSelect==0 ){
59344       /* A regular table */
59345       zType = "table";
59346       zType2 = "TABLE";
59347 #ifndef SQLITE_OMIT_VIEW
59348     }else{
59349       /* A view */
59350       zType = "view";
59351       zType2 = "VIEW";
59352 #endif
59353     }
59354
59355     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
59356     ** statement to populate the new table. The root-page number for the
59357     ** new table is on the top of the vdbe stack.
59358     **
59359     ** Once the SELECT has been coded by sqlite3Select(), it is in a
59360     ** suitable state to query for the column names and types to be used
59361     ** by the new table.
59362     **
59363     ** A shared-cache write-lock is not required to write to the new table,
59364     ** as a schema-lock must have already been obtained to create it. Since
59365     ** a schema-lock excludes all other database users, the write-lock would
59366     ** be redundant.
59367     */
59368     if( pSelect ){
59369       SelectDest dest;
59370       Table *pSelTab;
59371
59372       assert(pParse->nTab==0);
59373       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
59374       sqlite3VdbeChangeP5(v, 1);
59375       pParse->nTab = 2;
59376       sqlite3SelectDestInit(&dest, SRT_Table, 1);
59377       sqlite3Select(pParse, pSelect, &dest);
59378       sqlite3VdbeAddOp1(v, OP_Close, 1);
59379       if( pParse->nErr==0 ){
59380         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
59381         if( pSelTab==0 ) return;
59382         assert( p->aCol==0 );
59383         p->nCol = pSelTab->nCol;
59384         p->aCol = pSelTab->aCol;
59385         pSelTab->nCol = 0;
59386         pSelTab->aCol = 0;
59387         sqlite3DeleteTable(pSelTab);
59388       }
59389     }
59390
59391     /* Compute the complete text of the CREATE statement */
59392     if( pSelect ){
59393       zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
59394     }else{
59395       n = pEnd->z - pParse->sNameToken.z + 1;
59396       zStmt = sqlite3MPrintf(db, 
59397           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
59398       );
59399     }
59400
59401     /* A slot for the record has already been allocated in the 
59402     ** SQLITE_MASTER table.  We just need to update that slot with all
59403     ** the information we've collected.  The rowid for the preallocated
59404     ** slot is the 2nd item on the stack.  The top of the stack is the
59405     ** root page for the new table (or a 0 if this is a view).
59406     */
59407     sqlite3NestedParse(pParse,
59408       "UPDATE %Q.%s "
59409          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
59410        "WHERE rowid=#%d",
59411       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
59412       zType,
59413       p->zName,
59414       p->zName,
59415       pParse->regRoot,
59416       zStmt,
59417       pParse->regRowid
59418     );
59419     sqlite3DbFree(db, zStmt);
59420     sqlite3ChangeCookie(pParse, iDb);
59421
59422 #ifndef SQLITE_OMIT_AUTOINCREMENT
59423     /* Check to see if we need to create an sqlite_sequence table for
59424     ** keeping track of autoincrement keys.
59425     */
59426     if( p->tabFlags & TF_Autoincrement ){
59427       Db *pDb = &db->aDb[iDb];
59428       if( pDb->pSchema->pSeqTab==0 ){
59429         sqlite3NestedParse(pParse,
59430           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
59431           pDb->zName
59432         );
59433       }
59434     }
59435 #endif
59436
59437     /* Reparse everything to update our internal data structures */
59438     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
59439         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
59440   }
59441
59442
59443   /* Add the table to the in-memory representation of the database.
59444   */
59445   if( db->init.busy && pParse->nErr==0 ){
59446     Table *pOld;
59447     FKey *pFKey; 
59448     Schema *pSchema = p->pSchema;
59449     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
59450     if( pOld ){
59451       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
59452       db->mallocFailed = 1;
59453       return;
59454     }
59455 #ifndef SQLITE_OMIT_FOREIGN_KEY
59456     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
59457       void *data;
59458       int nTo = strlen(pFKey->zTo) + 1;
59459       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
59460       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
59461       if( data==(void *)pFKey ){
59462         db->mallocFailed = 1;
59463       }
59464     }
59465 #endif
59466     pParse->pNewTable = 0;
59467     db->nTable++;
59468     db->flags |= SQLITE_InternChanges;
59469
59470 #ifndef SQLITE_OMIT_ALTERTABLE
59471     if( !p->pSelect ){
59472       const char *zName = (const char *)pParse->sNameToken.z;
59473       int nName;
59474       assert( !pSelect && pCons && pEnd );
59475       if( pCons->z==0 ){
59476         pCons = pEnd;
59477       }
59478       nName = (const char *)pCons->z - zName;
59479       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
59480     }
59481 #endif
59482   }
59483 }
59484
59485 #ifndef SQLITE_OMIT_VIEW
59486 /*
59487 ** The parser calls this routine in order to create a new VIEW
59488 */
59489 SQLITE_PRIVATE void sqlite3CreateView(
59490   Parse *pParse,     /* The parsing context */
59491   Token *pBegin,     /* The CREATE token that begins the statement */
59492   Token *pName1,     /* The token that holds the name of the view */
59493   Token *pName2,     /* The token that holds the name of the view */
59494   Select *pSelect,   /* A SELECT statement that will become the new view */
59495   int isTemp,        /* TRUE for a TEMPORARY view */
59496   int noErr          /* Suppress error messages if VIEW already exists */
59497 ){
59498   Table *p;
59499   int n;
59500   const unsigned char *z;
59501   Token sEnd;
59502   DbFixer sFix;
59503   Token *pName;
59504   int iDb;
59505   sqlite3 *db = pParse->db;
59506
59507   if( pParse->nVar>0 ){
59508     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
59509     sqlite3SelectDelete(db, pSelect);
59510     return;
59511   }
59512   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
59513   p = pParse->pNewTable;
59514   if( p==0 || pParse->nErr ){
59515     sqlite3SelectDelete(db, pSelect);
59516     return;
59517   }
59518   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
59519   iDb = sqlite3SchemaToIndex(db, p->pSchema);
59520   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
59521     && sqlite3FixSelect(&sFix, pSelect)
59522   ){
59523     sqlite3SelectDelete(db, pSelect);
59524     return;
59525   }
59526
59527   /* Make a copy of the entire SELECT statement that defines the view.
59528   ** This will force all the Expr.token.z values to be dynamically
59529   ** allocated rather than point to the input string - which means that
59530   ** they will persist after the current sqlite3_exec() call returns.
59531   */
59532   p->pSelect = sqlite3SelectDup(db, pSelect);
59533   sqlite3SelectDelete(db, pSelect);
59534   if( db->mallocFailed ){
59535     return;
59536   }
59537   if( !db->init.busy ){
59538     sqlite3ViewGetColumnNames(pParse, p);
59539   }
59540
59541   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
59542   ** the end.
59543   */
59544   sEnd = pParse->sLastToken;
59545   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
59546     sEnd.z += sEnd.n;
59547   }
59548   sEnd.n = 0;
59549   n = sEnd.z - pBegin->z;
59550   z = (const unsigned char*)pBegin->z;
59551   while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
59552   sEnd.z = &z[n-1];
59553   sEnd.n = 1;
59554
59555   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
59556   sqlite3EndTable(pParse, 0, &sEnd, 0);
59557   return;
59558 }
59559 #endif /* SQLITE_OMIT_VIEW */
59560
59561 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
59562 /*
59563 ** The Table structure pTable is really a VIEW.  Fill in the names of
59564 ** the columns of the view in the pTable structure.  Return the number
59565 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
59566 */
59567 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
59568   Table *pSelTab;   /* A fake table from which we get the result set */
59569   Select *pSel;     /* Copy of the SELECT that implements the view */
59570   int nErr = 0;     /* Number of errors encountered */
59571   int n;            /* Temporarily holds the number of cursors assigned */
59572   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
59573   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
59574
59575   assert( pTable );
59576
59577 #ifndef SQLITE_OMIT_VIRTUALTABLE
59578   if( sqlite3VtabCallConnect(pParse, pTable) ){
59579     return SQLITE_ERROR;
59580   }
59581   if( IsVirtual(pTable) ) return 0;
59582 #endif
59583
59584 #ifndef SQLITE_OMIT_VIEW
59585   /* A positive nCol means the columns names for this view are
59586   ** already known.
59587   */
59588   if( pTable->nCol>0 ) return 0;
59589
59590   /* A negative nCol is a special marker meaning that we are currently
59591   ** trying to compute the column names.  If we enter this routine with
59592   ** a negative nCol, it means two or more views form a loop, like this:
59593   **
59594   **     CREATE VIEW one AS SELECT * FROM two;
59595   **     CREATE VIEW two AS SELECT * FROM one;
59596   **
59597   ** Actually, this error is caught previously and so the following test
59598   ** should always fail.  But we will leave it in place just to be safe.
59599   */
59600   if( pTable->nCol<0 ){
59601     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
59602     return 1;
59603   }
59604   assert( pTable->nCol>=0 );
59605
59606   /* If we get this far, it means we need to compute the table names.
59607   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
59608   ** "*" elements in the results set of the view and will assign cursors
59609   ** to the elements of the FROM clause.  But we do not want these changes
59610   ** to be permanent.  So the computation is done on a copy of the SELECT
59611   ** statement that defines the view.
59612   */
59613   assert( pTable->pSelect );
59614   pSel = sqlite3SelectDup(db, pTable->pSelect);
59615   if( pSel ){
59616     n = pParse->nTab;
59617     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
59618     pTable->nCol = -1;
59619 #ifndef SQLITE_OMIT_AUTHORIZATION
59620     xAuth = db->xAuth;
59621     db->xAuth = 0;
59622     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
59623     db->xAuth = xAuth;
59624 #else
59625     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
59626 #endif
59627     pParse->nTab = n;
59628     if( pSelTab ){
59629       assert( pTable->aCol==0 );
59630       pTable->nCol = pSelTab->nCol;
59631       pTable->aCol = pSelTab->aCol;
59632       pSelTab->nCol = 0;
59633       pSelTab->aCol = 0;
59634       sqlite3DeleteTable(pSelTab);
59635       pTable->pSchema->flags |= DB_UnresetViews;
59636     }else{
59637       pTable->nCol = 0;
59638       nErr++;
59639     }
59640     sqlite3SelectDelete(db, pSel);
59641   } else {
59642     nErr++;
59643   }
59644 #endif /* SQLITE_OMIT_VIEW */
59645   return nErr;  
59646 }
59647 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
59648
59649 #ifndef SQLITE_OMIT_VIEW
59650 /*
59651 ** Clear the column names from every VIEW in database idx.
59652 */
59653 static void sqliteViewResetAll(sqlite3 *db, int idx){
59654   HashElem *i;
59655   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
59656   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
59657     Table *pTab = sqliteHashData(i);
59658     if( pTab->pSelect ){
59659       sqliteResetColumnNames(pTab);
59660     }
59661   }
59662   DbClearProperty(db, idx, DB_UnresetViews);
59663 }
59664 #else
59665 # define sqliteViewResetAll(A,B)
59666 #endif /* SQLITE_OMIT_VIEW */
59667
59668 /*
59669 ** This function is called by the VDBE to adjust the internal schema
59670 ** used by SQLite when the btree layer moves a table root page. The
59671 ** root-page of a table or index in database iDb has changed from iFrom
59672 ** to iTo.
59673 **
59674 ** Ticket #1728:  The symbol table might still contain information
59675 ** on tables and/or indices that are the process of being deleted.
59676 ** If you are unlucky, one of those deleted indices or tables might
59677 ** have the same rootpage number as the real table or index that is
59678 ** being moved.  So we cannot stop searching after the first match 
59679 ** because the first match might be for one of the deleted indices
59680 ** or tables and not the table/index that is actually being moved.
59681 ** We must continue looping until all tables and indices with
59682 ** rootpage==iFrom have been converted to have a rootpage of iTo
59683 ** in order to be certain that we got the right one.
59684 */
59685 #ifndef SQLITE_OMIT_AUTOVACUUM
59686 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
59687   HashElem *pElem;
59688   Hash *pHash;
59689
59690   pHash = &pDb->pSchema->tblHash;
59691   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
59692     Table *pTab = sqliteHashData(pElem);
59693     if( pTab->tnum==iFrom ){
59694       pTab->tnum = iTo;
59695     }
59696   }
59697   pHash = &pDb->pSchema->idxHash;
59698   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
59699     Index *pIdx = sqliteHashData(pElem);
59700     if( pIdx->tnum==iFrom ){
59701       pIdx->tnum = iTo;
59702     }
59703   }
59704 }
59705 #endif
59706
59707 /*
59708 ** Write code to erase the table with root-page iTable from database iDb.
59709 ** Also write code to modify the sqlite_master table and internal schema
59710 ** if a root-page of another table is moved by the btree-layer whilst
59711 ** erasing iTable (this can happen with an auto-vacuum database).
59712 */ 
59713 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
59714   Vdbe *v = sqlite3GetVdbe(pParse);
59715   int r1 = sqlite3GetTempReg(pParse);
59716   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
59717 #ifndef SQLITE_OMIT_AUTOVACUUM
59718   /* OP_Destroy stores an in integer r1. If this integer
59719   ** is non-zero, then it is the root page number of a table moved to
59720   ** location iTable. The following code modifies the sqlite_master table to
59721   ** reflect this.
59722   **
59723   ** The "#%d" in the SQL is a special constant that means whatever value
59724   ** is on the top of the stack.  See sqlite3RegisterExpr().
59725   */
59726   sqlite3NestedParse(pParse, 
59727      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
59728      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
59729 #endif
59730   sqlite3ReleaseTempReg(pParse, r1);
59731 }
59732
59733 /*
59734 ** Write VDBE code to erase table pTab and all associated indices on disk.
59735 ** Code to update the sqlite_master tables and internal schema definitions
59736 ** in case a root-page belonging to another table is moved by the btree layer
59737 ** is also added (this can happen with an auto-vacuum database).
59738 */
59739 static void destroyTable(Parse *pParse, Table *pTab){
59740 #ifdef SQLITE_OMIT_AUTOVACUUM
59741   Index *pIdx;
59742   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59743   destroyRootPage(pParse, pTab->tnum, iDb);
59744   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
59745     destroyRootPage(pParse, pIdx->tnum, iDb);
59746   }
59747 #else
59748   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
59749   ** is not defined), then it is important to call OP_Destroy on the
59750   ** table and index root-pages in order, starting with the numerically 
59751   ** largest root-page number. This guarantees that none of the root-pages
59752   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
59753   ** following were coded:
59754   **
59755   ** OP_Destroy 4 0
59756   ** ...
59757   ** OP_Destroy 5 0
59758   **
59759   ** and root page 5 happened to be the largest root-page number in the
59760   ** database, then root page 5 would be moved to page 4 by the 
59761   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
59762   ** a free-list page.
59763   */
59764   int iTab = pTab->tnum;
59765   int iDestroyed = 0;
59766
59767   while( 1 ){
59768     Index *pIdx;
59769     int iLargest = 0;
59770
59771     if( iDestroyed==0 || iTab<iDestroyed ){
59772       iLargest = iTab;
59773     }
59774     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
59775       int iIdx = pIdx->tnum;
59776       assert( pIdx->pSchema==pTab->pSchema );
59777       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
59778         iLargest = iIdx;
59779       }
59780     }
59781     if( iLargest==0 ){
59782       return;
59783     }else{
59784       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
59785       destroyRootPage(pParse, iLargest, iDb);
59786       iDestroyed = iLargest;
59787     }
59788   }
59789 #endif
59790 }
59791
59792 /*
59793 ** This routine is called to do the work of a DROP TABLE statement.
59794 ** pName is the name of the table to be dropped.
59795 */
59796 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
59797   Table *pTab;
59798   Vdbe *v;
59799   sqlite3 *db = pParse->db;
59800   int iDb;
59801
59802   if( pParse->nErr || db->mallocFailed ){
59803     goto exit_drop_table;
59804   }
59805   assert( pName->nSrc==1 );
59806   pTab = sqlite3LocateTable(pParse, isView, 
59807                             pName->a[0].zName, pName->a[0].zDatabase);
59808
59809   if( pTab==0 ){
59810     if( noErr ){
59811       sqlite3ErrorClear(pParse);
59812     }
59813     goto exit_drop_table;
59814   }
59815   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59816   assert( iDb>=0 && iDb<db->nDb );
59817
59818   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
59819   ** it is initialized.
59820   */
59821   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
59822     goto exit_drop_table;
59823   }
59824 #ifndef SQLITE_OMIT_AUTHORIZATION
59825   {
59826     int code;
59827     const char *zTab = SCHEMA_TABLE(iDb);
59828     const char *zDb = db->aDb[iDb].zName;
59829     const char *zArg2 = 0;
59830     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
59831       goto exit_drop_table;
59832     }
59833     if( isView ){
59834       if( !OMIT_TEMPDB && iDb==1 ){
59835         code = SQLITE_DROP_TEMP_VIEW;
59836       }else{
59837         code = SQLITE_DROP_VIEW;
59838       }
59839 #ifndef SQLITE_OMIT_VIRTUALTABLE
59840     }else if( IsVirtual(pTab) ){
59841       code = SQLITE_DROP_VTABLE;
59842       zArg2 = pTab->pMod->zName;
59843 #endif
59844     }else{
59845       if( !OMIT_TEMPDB && iDb==1 ){
59846         code = SQLITE_DROP_TEMP_TABLE;
59847       }else{
59848         code = SQLITE_DROP_TABLE;
59849       }
59850     }
59851     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
59852       goto exit_drop_table;
59853     }
59854     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
59855       goto exit_drop_table;
59856     }
59857   }
59858 #endif
59859   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
59860     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
59861     goto exit_drop_table;
59862   }
59863
59864 #ifndef SQLITE_OMIT_VIEW
59865   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
59866   ** on a table.
59867   */
59868   if( isView && pTab->pSelect==0 ){
59869     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
59870     goto exit_drop_table;
59871   }
59872   if( !isView && pTab->pSelect ){
59873     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
59874     goto exit_drop_table;
59875   }
59876 #endif
59877
59878   /* Generate code to remove the table from the master table
59879   ** on disk.
59880   */
59881   v = sqlite3GetVdbe(pParse);
59882   if( v ){
59883     Trigger *pTrigger;
59884     Db *pDb = &db->aDb[iDb];
59885     sqlite3BeginWriteOperation(pParse, 1, iDb);
59886
59887 #ifndef SQLITE_OMIT_VIRTUALTABLE
59888     if( IsVirtual(pTab) ){
59889       Vdbe *v = sqlite3GetVdbe(pParse);
59890       if( v ){
59891         sqlite3VdbeAddOp0(v, OP_VBegin);
59892       }
59893     }
59894 #endif
59895
59896     /* Drop all triggers associated with the table being dropped. Code
59897     ** is generated to remove entries from sqlite_master and/or
59898     ** sqlite_temp_master if required.
59899     */
59900     pTrigger = pTab->pTrigger;
59901     while( pTrigger ){
59902       assert( pTrigger->pSchema==pTab->pSchema || 
59903           pTrigger->pSchema==db->aDb[1].pSchema );
59904       sqlite3DropTriggerPtr(pParse, pTrigger);
59905       pTrigger = pTrigger->pNext;
59906     }
59907
59908 #ifndef SQLITE_OMIT_AUTOINCREMENT
59909     /* Remove any entries of the sqlite_sequence table associated with
59910     ** the table being dropped. This is done before the table is dropped
59911     ** at the btree level, in case the sqlite_sequence table needs to
59912     ** move as a result of the drop (can happen in auto-vacuum mode).
59913     */
59914     if( pTab->tabFlags & TF_Autoincrement ){
59915       sqlite3NestedParse(pParse,
59916         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
59917         pDb->zName, pTab->zName
59918       );
59919     }
59920 #endif
59921
59922     /* Drop all SQLITE_MASTER table and index entries that refer to the
59923     ** table. The program name loops through the master table and deletes
59924     ** every row that refers to a table of the same name as the one being
59925     ** dropped. Triggers are handled seperately because a trigger can be
59926     ** created in the temp database that refers to a table in another
59927     ** database.
59928     */
59929     sqlite3NestedParse(pParse, 
59930         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
59931         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
59932
59933     /* Drop any statistics from the sqlite_stat1 table, if it exists */
59934     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
59935       sqlite3NestedParse(pParse,
59936         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
59937       );
59938     }
59939
59940     if( !isView && !IsVirtual(pTab) ){
59941       destroyTable(pParse, pTab);
59942     }
59943
59944     /* Remove the table entry from SQLite's internal schema and modify
59945     ** the schema cookie.
59946     */
59947     if( IsVirtual(pTab) ){
59948       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
59949     }
59950     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
59951     sqlite3ChangeCookie(pParse, iDb);
59952   }
59953   sqliteViewResetAll(db, iDb);
59954
59955 exit_drop_table:
59956   sqlite3SrcListDelete(db, pName);
59957 }
59958
59959 /*
59960 ** This routine is called to create a new foreign key on the table
59961 ** currently under construction.  pFromCol determines which columns
59962 ** in the current table point to the foreign key.  If pFromCol==0 then
59963 ** connect the key to the last column inserted.  pTo is the name of
59964 ** the table referred to.  pToCol is a list of tables in the other
59965 ** pTo table that the foreign key points to.  flags contains all
59966 ** information about the conflict resolution algorithms specified
59967 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
59968 **
59969 ** An FKey structure is created and added to the table currently
59970 ** under construction in the pParse->pNewTable field.  The new FKey
59971 ** is not linked into db->aFKey at this point - that does not happen
59972 ** until sqlite3EndTable().
59973 **
59974 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
59975 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
59976 */
59977 SQLITE_PRIVATE void sqlite3CreateForeignKey(
59978   Parse *pParse,       /* Parsing context */
59979   ExprList *pFromCol,  /* Columns in this table that point to other table */
59980   Token *pTo,          /* Name of the other table */
59981   ExprList *pToCol,    /* Columns in the other table */
59982   int flags            /* Conflict resolution algorithms. */
59983 ){
59984   sqlite3 *db = pParse->db;
59985 #ifndef SQLITE_OMIT_FOREIGN_KEY
59986   FKey *pFKey = 0;
59987   Table *p = pParse->pNewTable;
59988   int nByte;
59989   int i;
59990   int nCol;
59991   char *z;
59992
59993   assert( pTo!=0 );
59994   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
59995   if( pFromCol==0 ){
59996     int iCol = p->nCol-1;
59997     if( iCol<0 ) goto fk_end;
59998     if( pToCol && pToCol->nExpr!=1 ){
59999       sqlite3ErrorMsg(pParse, "foreign key on %s"
60000          " should reference only one column of table %T",
60001          p->aCol[iCol].zName, pTo);
60002       goto fk_end;
60003     }
60004     nCol = 1;
60005   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
60006     sqlite3ErrorMsg(pParse,
60007         "number of columns in foreign key does not match the number of "
60008         "columns in the referenced table");
60009     goto fk_end;
60010   }else{
60011     nCol = pFromCol->nExpr;
60012   }
60013   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
60014   if( pToCol ){
60015     for(i=0; i<pToCol->nExpr; i++){
60016       nByte += strlen(pToCol->a[i].zName) + 1;
60017     }
60018   }
60019   pFKey = sqlite3DbMallocZero(db, nByte );
60020   if( pFKey==0 ){
60021     goto fk_end;
60022   }
60023   pFKey->pFrom = p;
60024   pFKey->pNextFrom = p->pFKey;
60025   z = (char*)&pFKey[1];
60026   pFKey->aCol = (struct sColMap*)z;
60027   z += sizeof(struct sColMap)*nCol;
60028   pFKey->zTo = z;
60029   memcpy(z, pTo->z, pTo->n);
60030   z[pTo->n] = 0;
60031   z += pTo->n+1;
60032   pFKey->pNextTo = 0;
60033   pFKey->nCol = nCol;
60034   if( pFromCol==0 ){
60035     pFKey->aCol[0].iFrom = p->nCol-1;
60036   }else{
60037     for(i=0; i<nCol; i++){
60038       int j;
60039       for(j=0; j<p->nCol; j++){
60040         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
60041           pFKey->aCol[i].iFrom = j;
60042           break;
60043         }
60044       }
60045       if( j>=p->nCol ){
60046         sqlite3ErrorMsg(pParse, 
60047           "unknown column \"%s\" in foreign key definition", 
60048           pFromCol->a[i].zName);
60049         goto fk_end;
60050       }
60051     }
60052   }
60053   if( pToCol ){
60054     for(i=0; i<nCol; i++){
60055       int n = strlen(pToCol->a[i].zName);
60056       pFKey->aCol[i].zCol = z;
60057       memcpy(z, pToCol->a[i].zName, n);
60058       z[n] = 0;
60059       z += n+1;
60060     }
60061   }
60062   pFKey->isDeferred = 0;
60063   pFKey->deleteConf = flags & 0xff;
60064   pFKey->updateConf = (flags >> 8 ) & 0xff;
60065   pFKey->insertConf = (flags >> 16 ) & 0xff;
60066
60067   /* Link the foreign key to the table as the last step.
60068   */
60069   p->pFKey = pFKey;
60070   pFKey = 0;
60071
60072 fk_end:
60073   sqlite3DbFree(db, pFKey);
60074 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
60075   sqlite3ExprListDelete(db, pFromCol);
60076   sqlite3ExprListDelete(db, pToCol);
60077 }
60078
60079 /*
60080 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
60081 ** clause is seen as part of a foreign key definition.  The isDeferred
60082 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
60083 ** The behavior of the most recently created foreign key is adjusted
60084 ** accordingly.
60085 */
60086 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
60087 #ifndef SQLITE_OMIT_FOREIGN_KEY
60088   Table *pTab;
60089   FKey *pFKey;
60090   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
60091   pFKey->isDeferred = isDeferred;
60092 #endif
60093 }
60094
60095 /*
60096 ** Generate code that will erase and refill index *pIdx.  This is
60097 ** used to initialize a newly created index or to recompute the
60098 ** content of an index in response to a REINDEX command.
60099 **
60100 ** if memRootPage is not negative, it means that the index is newly
60101 ** created.  The register specified by memRootPage contains the
60102 ** root page number of the index.  If memRootPage is negative, then
60103 ** the index already exists and must be cleared before being refilled and
60104 ** the root page number of the index is taken from pIndex->tnum.
60105 */
60106 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
60107   Table *pTab = pIndex->pTable;  /* The table that is indexed */
60108   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
60109   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
60110   int addr1;                     /* Address of top of loop */
60111   int tnum;                      /* Root page of index */
60112   Vdbe *v;                       /* Generate code into this virtual machine */
60113   KeyInfo *pKey;                 /* KeyInfo for index */
60114   int regIdxKey;                 /* Registers containing the index key */
60115   int regRecord;                 /* Register holding assemblied index record */
60116   sqlite3 *db = pParse->db;      /* The database connection */
60117   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
60118
60119 #ifndef SQLITE_OMIT_AUTHORIZATION
60120   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
60121       db->aDb[iDb].zName ) ){
60122     return;
60123   }
60124 #endif
60125
60126   /* Require a write-lock on the table to perform this operation */
60127   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
60128
60129   v = sqlite3GetVdbe(pParse);
60130   if( v==0 ) return;
60131   if( memRootPage>=0 ){
60132     tnum = memRootPage;
60133   }else{
60134     tnum = pIndex->tnum;
60135     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
60136   }
60137   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
60138   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
60139                     (char *)pKey, P4_KEYINFO_HANDOFF);
60140   if( memRootPage>=0 ){
60141     sqlite3VdbeChangeP5(v, 1);
60142   }
60143   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
60144   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
60145   regRecord = sqlite3GetTempReg(pParse);
60146   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
60147   if( pIndex->onError!=OE_None ){
60148     int j1, j2;
60149     int regRowid;
60150
60151     regRowid = regIdxKey + pIndex->nColumn;
60152     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
60153     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
60154                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
60155     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
60156                     "indexed columns are not unique", P4_STATIC);
60157     sqlite3VdbeJumpHere(v, j1);
60158     sqlite3VdbeJumpHere(v, j2);
60159   }
60160   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
60161   sqlite3ReleaseTempReg(pParse, regRecord);
60162   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
60163   sqlite3VdbeJumpHere(v, addr1);
60164   sqlite3VdbeAddOp1(v, OP_Close, iTab);
60165   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
60166 }
60167
60168 /*
60169 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
60170 ** and pTblList is the name of the table that is to be indexed.  Both will 
60171 ** be NULL for a primary key or an index that is created to satisfy a
60172 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
60173 ** as the table to be indexed.  pParse->pNewTable is a table that is
60174 ** currently being constructed by a CREATE TABLE statement.
60175 **
60176 ** pList is a list of columns to be indexed.  pList will be NULL if this
60177 ** is a primary key or unique-constraint on the most recent column added
60178 ** to the table currently under construction.  
60179 */
60180 SQLITE_PRIVATE void sqlite3CreateIndex(
60181   Parse *pParse,     /* All information about this parse */
60182   Token *pName1,     /* First part of index name. May be NULL */
60183   Token *pName2,     /* Second part of index name. May be NULL */
60184   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
60185   ExprList *pList,   /* A list of columns to be indexed */
60186   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
60187   Token *pStart,     /* The CREATE token that begins this statement */
60188   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
60189   int sortOrder,     /* Sort order of primary key when pList==NULL */
60190   int ifNotExist     /* Omit error if index already exists */
60191 ){
60192   Table *pTab = 0;     /* Table to be indexed */
60193   Index *pIndex = 0;   /* The index to be created */
60194   char *zName = 0;     /* Name of the index */
60195   int nName;           /* Number of characters in zName */
60196   int i, j;
60197   Token nullId;        /* Fake token for an empty ID list */
60198   DbFixer sFix;        /* For assigning database names to pTable */
60199   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
60200   sqlite3 *db = pParse->db;
60201   Db *pDb;             /* The specific table containing the indexed database */
60202   int iDb;             /* Index of the database that is being written */
60203   Token *pName = 0;    /* Unqualified name of the index to create */
60204   struct ExprList_item *pListItem; /* For looping over pList */
60205   int nCol;
60206   int nExtra = 0;
60207   char *zExtra;
60208
60209   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
60210     goto exit_create_index;
60211   }
60212
60213   /*
60214   ** Find the table that is to be indexed.  Return early if not found.
60215   */
60216   if( pTblName!=0 ){
60217
60218     /* Use the two-part index name to determine the database 
60219     ** to search for the table. 'Fix' the table name to this db
60220     ** before looking up the table.
60221     */
60222     assert( pName1 && pName2 );
60223     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
60224     if( iDb<0 ) goto exit_create_index;
60225
60226 #ifndef SQLITE_OMIT_TEMPDB
60227     /* If the index name was unqualified, check if the the table
60228     ** is a temp table. If so, set the database to 1. Do not do this
60229     ** if initialising a database schema.
60230     */
60231     if( !db->init.busy ){
60232       pTab = sqlite3SrcListLookup(pParse, pTblName);
60233       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
60234         iDb = 1;
60235       }
60236     }
60237 #endif
60238
60239     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
60240         sqlite3FixSrcList(&sFix, pTblName)
60241     ){
60242       /* Because the parser constructs pTblName from a single identifier,
60243       ** sqlite3FixSrcList can never fail. */
60244       assert(0);
60245     }
60246     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
60247         pTblName->a[0].zDatabase);
60248     if( !pTab ) goto exit_create_index;
60249     assert( db->aDb[iDb].pSchema==pTab->pSchema );
60250   }else{
60251     assert( pName==0 );
60252     pTab = pParse->pNewTable;
60253     if( !pTab ) goto exit_create_index;
60254     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
60255   }
60256   pDb = &db->aDb[iDb];
60257
60258   if( pTab==0 || pParse->nErr ) goto exit_create_index;
60259   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
60260     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
60261     goto exit_create_index;
60262   }
60263 #ifndef SQLITE_OMIT_VIEW
60264   if( pTab->pSelect ){
60265     sqlite3ErrorMsg(pParse, "views may not be indexed");
60266     goto exit_create_index;
60267   }
60268 #endif
60269 #ifndef SQLITE_OMIT_VIRTUALTABLE
60270   if( IsVirtual(pTab) ){
60271     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
60272     goto exit_create_index;
60273   }
60274 #endif
60275
60276   /*
60277   ** Find the name of the index.  Make sure there is not already another
60278   ** index or table with the same name.  
60279   **
60280   ** Exception:  If we are reading the names of permanent indices from the
60281   ** sqlite_master table (because some other process changed the schema) and
60282   ** one of the index names collides with the name of a temporary table or
60283   ** index, then we will continue to process this index.
60284   **
60285   ** If pName==0 it means that we are
60286   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
60287   ** own name.
60288   */
60289   if( pName ){
60290     zName = sqlite3NameFromToken(db, pName);
60291     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
60292     if( zName==0 ) goto exit_create_index;
60293     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
60294       goto exit_create_index;
60295     }
60296     if( !db->init.busy ){
60297       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
60298       if( sqlite3FindTable(db, zName, 0)!=0 ){
60299         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
60300         goto exit_create_index;
60301       }
60302     }
60303     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
60304       if( !ifNotExist ){
60305         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
60306       }
60307       goto exit_create_index;
60308     }
60309   }else{
60310     int n;
60311     Index *pLoop;
60312     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
60313     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
60314     if( zName==0 ){
60315       goto exit_create_index;
60316     }
60317   }
60318
60319   /* Check for authorization to create an index.
60320   */
60321 #ifndef SQLITE_OMIT_AUTHORIZATION
60322   {
60323     const char *zDb = pDb->zName;
60324     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
60325       goto exit_create_index;
60326     }
60327     i = SQLITE_CREATE_INDEX;
60328     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
60329     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
60330       goto exit_create_index;
60331     }
60332   }
60333 #endif
60334
60335   /* If pList==0, it means this routine was called to make a primary
60336   ** key out of the last column added to the table under construction.
60337   ** So create a fake list to simulate this.
60338   */
60339   if( pList==0 ){
60340     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
60341     nullId.n = strlen((char*)nullId.z);
60342     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
60343     if( pList==0 ) goto exit_create_index;
60344     pList->a[0].sortOrder = sortOrder;
60345   }
60346
60347   /* Figure out how many bytes of space are required to store explicitly
60348   ** specified collation sequence names.
60349   */
60350   for(i=0; i<pList->nExpr; i++){
60351     Expr *pExpr;
60352     CollSeq *pColl;
60353     if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
60354       nExtra += (1 + strlen(pColl->zName));
60355     }
60356   }
60357
60358   /* 
60359   ** Allocate the index structure. 
60360   */
60361   nName = strlen(zName);
60362   nCol = pList->nExpr;
60363   pIndex = sqlite3DbMallocZero(db, 
60364       sizeof(Index) +              /* Index structure  */
60365       sizeof(int)*nCol +           /* Index.aiColumn   */
60366       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
60367       sizeof(char *)*nCol +        /* Index.azColl     */
60368       sizeof(u8)*nCol +            /* Index.aSortOrder */
60369       nName + 1 +                  /* Index.zName      */
60370       nExtra                       /* Collation sequence names */
60371   );
60372   if( db->mallocFailed ){
60373     goto exit_create_index;
60374   }
60375   pIndex->azColl = (char**)(&pIndex[1]);
60376   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
60377   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
60378   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
60379   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
60380   zExtra = (char *)(&pIndex->zName[nName+1]);
60381   memcpy(pIndex->zName, zName, nName+1);
60382   pIndex->pTable = pTab;
60383   pIndex->nColumn = pList->nExpr;
60384   pIndex->onError = onError;
60385   pIndex->autoIndex = pName==0;
60386   pIndex->pSchema = db->aDb[iDb].pSchema;
60387
60388   /* Check to see if we should honor DESC requests on index columns
60389   */
60390   if( pDb->pSchema->file_format>=4 ){
60391     sortOrderMask = -1;   /* Honor DESC */
60392   }else{
60393     sortOrderMask = 0;    /* Ignore DESC */
60394   }
60395
60396   /* Scan the names of the columns of the table to be indexed and
60397   ** load the column indices into the Index structure.  Report an error
60398   ** if any column is not found.
60399   */
60400   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
60401     const char *zColName = pListItem->zName;
60402     Column *pTabCol;
60403     int requestedSortOrder;
60404     char *zColl;                   /* Collation sequence name */
60405
60406     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
60407       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
60408     }
60409     if( j>=pTab->nCol ){
60410       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
60411         pTab->zName, zColName);
60412       goto exit_create_index;
60413     }
60414     /* TODO:  Add a test to make sure that the same column is not named
60415     ** more than once within the same index.  Only the first instance of
60416     ** the column will ever be used by the optimizer.  Note that using the
60417     ** same column more than once cannot be an error because that would 
60418     ** break backwards compatibility - it needs to be a warning.
60419     */
60420     pIndex->aiColumn[i] = j;
60421     if( pListItem->pExpr && pListItem->pExpr->pColl ){
60422       assert( pListItem->pExpr->pColl );
60423       zColl = zExtra;
60424       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
60425       zExtra += (strlen(zColl) + 1);
60426     }else{
60427       zColl = pTab->aCol[j].zColl;
60428       if( !zColl ){
60429         zColl = db->pDfltColl->zName;
60430       }
60431     }
60432     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
60433       goto exit_create_index;
60434     }
60435     pIndex->azColl[i] = zColl;
60436     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
60437     pIndex->aSortOrder[i] = requestedSortOrder;
60438   }
60439   sqlite3DefaultRowEst(pIndex);
60440
60441   if( pTab==pParse->pNewTable ){
60442     /* This routine has been called to create an automatic index as a
60443     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
60444     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
60445     ** i.e. one of:
60446     **
60447     ** CREATE TABLE t(x PRIMARY KEY, y);
60448     ** CREATE TABLE t(x, y, UNIQUE(x, y));
60449     **
60450     ** Either way, check to see if the table already has such an index. If
60451     ** so, don't bother creating this one. This only applies to
60452     ** automatically created indices. Users can do as they wish with
60453     ** explicit indices.
60454     */
60455     Index *pIdx;
60456     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
60457       int k;
60458       assert( pIdx->onError!=OE_None );
60459       assert( pIdx->autoIndex );
60460       assert( pIndex->onError!=OE_None );
60461
60462       if( pIdx->nColumn!=pIndex->nColumn ) continue;
60463       for(k=0; k<pIdx->nColumn; k++){
60464         const char *z1 = pIdx->azColl[k];
60465         const char *z2 = pIndex->azColl[k];
60466         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
60467         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
60468         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
60469       }
60470       if( k==pIdx->nColumn ){
60471         if( pIdx->onError!=pIndex->onError ){
60472           /* This constraint creates the same index as a previous
60473           ** constraint specified somewhere in the CREATE TABLE statement.
60474           ** However the ON CONFLICT clauses are different. If both this 
60475           ** constraint and the previous equivalent constraint have explicit
60476           ** ON CONFLICT clauses this is an error. Otherwise, use the
60477           ** explicitly specified behaviour for the index.
60478           */
60479           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
60480             sqlite3ErrorMsg(pParse, 
60481                 "conflicting ON CONFLICT clauses specified", 0);
60482           }
60483           if( pIdx->onError==OE_Default ){
60484             pIdx->onError = pIndex->onError;
60485           }
60486         }
60487         goto exit_create_index;
60488       }
60489     }
60490   }
60491
60492   /* Link the new Index structure to its table and to the other
60493   ** in-memory database structures. 
60494   */
60495   if( db->init.busy ){
60496     Index *p;
60497     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
60498                          pIndex->zName, strlen(pIndex->zName)+1, pIndex);
60499     if( p ){
60500       assert( p==pIndex );  /* Malloc must have failed */
60501       db->mallocFailed = 1;
60502       goto exit_create_index;
60503     }
60504     db->flags |= SQLITE_InternChanges;
60505     if( pTblName!=0 ){
60506       pIndex->tnum = db->init.newTnum;
60507     }
60508   }
60509
60510   /* If the db->init.busy is 0 then create the index on disk.  This
60511   ** involves writing the index into the master table and filling in the
60512   ** index with the current table contents.
60513   **
60514   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
60515   ** command.  db->init.busy is 1 when a database is opened and 
60516   ** CREATE INDEX statements are read out of the master table.  In
60517   ** the latter case the index already exists on disk, which is why
60518   ** we don't want to recreate it.
60519   **
60520   ** If pTblName==0 it means this index is generated as a primary key
60521   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
60522   ** has just been created, it contains no data and the index initialization
60523   ** step can be skipped.
60524   */
60525   else if( db->init.busy==0 ){
60526     Vdbe *v;
60527     char *zStmt;
60528     int iMem = ++pParse->nMem;
60529
60530     v = sqlite3GetVdbe(pParse);
60531     if( v==0 ) goto exit_create_index;
60532
60533
60534     /* Create the rootpage for the index
60535     */
60536     sqlite3BeginWriteOperation(pParse, 1, iDb);
60537     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
60538
60539     /* Gather the complete text of the CREATE INDEX statement into
60540     ** the zStmt variable
60541     */
60542     if( pStart && pEnd ){
60543       /* A named index with an explicit CREATE INDEX statement */
60544       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
60545         onError==OE_None ? "" : " UNIQUE",
60546         pEnd->z - pName->z + 1,
60547         pName->z);
60548     }else{
60549       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
60550       /* zStmt = sqlite3MPrintf(""); */
60551       zStmt = 0;
60552     }
60553
60554     /* Add an entry in sqlite_master for this index
60555     */
60556     sqlite3NestedParse(pParse, 
60557         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
60558         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
60559         pIndex->zName,
60560         pTab->zName,
60561         iMem,
60562         zStmt
60563     );
60564     sqlite3DbFree(db, zStmt);
60565
60566     /* Fill the index with data and reparse the schema. Code an OP_Expire
60567     ** to invalidate all pre-compiled statements.
60568     */
60569     if( pTblName ){
60570       sqlite3RefillIndex(pParse, pIndex, iMem);
60571       sqlite3ChangeCookie(pParse, iDb);
60572       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
60573          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
60574       sqlite3VdbeAddOp1(v, OP_Expire, 0);
60575     }
60576   }
60577
60578   /* When adding an index to the list of indices for a table, make
60579   ** sure all indices labeled OE_Replace come after all those labeled
60580   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
60581   ** and INSERT.
60582   */
60583   if( db->init.busy || pTblName==0 ){
60584     if( onError!=OE_Replace || pTab->pIndex==0
60585          || pTab->pIndex->onError==OE_Replace){
60586       pIndex->pNext = pTab->pIndex;
60587       pTab->pIndex = pIndex;
60588     }else{
60589       Index *pOther = pTab->pIndex;
60590       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
60591         pOther = pOther->pNext;
60592       }
60593       pIndex->pNext = pOther->pNext;
60594       pOther->pNext = pIndex;
60595     }
60596     pIndex = 0;
60597   }
60598
60599   /* Clean up before exiting */
60600 exit_create_index:
60601   if( pIndex ){
60602     freeIndex(pIndex);
60603   }
60604   sqlite3ExprListDelete(db, pList);
60605   sqlite3SrcListDelete(db, pTblName);
60606   sqlite3DbFree(db, zName);
60607   return;
60608 }
60609
60610 /*
60611 ** Generate code to make sure the file format number is at least minFormat.
60612 ** The generated code will increase the file format number if necessary.
60613 */
60614 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
60615   Vdbe *v;
60616   v = sqlite3GetVdbe(pParse);
60617   if( v ){
60618     int r1 = sqlite3GetTempReg(pParse);
60619     int r2 = sqlite3GetTempReg(pParse);
60620     int j1;
60621     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
60622     sqlite3VdbeUsesBtree(v, iDb);
60623     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
60624     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
60625     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
60626     sqlite3VdbeJumpHere(v, j1);
60627     sqlite3ReleaseTempReg(pParse, r1);
60628     sqlite3ReleaseTempReg(pParse, r2);
60629   }
60630 }
60631
60632 /*
60633 ** Fill the Index.aiRowEst[] array with default information - information
60634 ** to be used when we have not run the ANALYZE command.
60635 **
60636 ** aiRowEst[0] is suppose to contain the number of elements in the index.
60637 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
60638 ** number of rows in the table that match any particular value of the
60639 ** first column of the index.  aiRowEst[2] is an estimate of the number
60640 ** of rows that match any particular combiniation of the first 2 columns
60641 ** of the index.  And so forth.  It must always be the case that
60642 *
60643 **           aiRowEst[N]<=aiRowEst[N-1]
60644 **           aiRowEst[N]>=1
60645 **
60646 ** Apart from that, we have little to go on besides intuition as to
60647 ** how aiRowEst[] should be initialized.  The numbers generated here
60648 ** are based on typical values found in actual indices.
60649 */
60650 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
60651   unsigned *a = pIdx->aiRowEst;
60652   int i;
60653   assert( a!=0 );
60654   a[0] = 1000000;
60655   for(i=pIdx->nColumn; i>=5; i--){
60656     a[i] = 5;
60657   }
60658   while( i>=1 ){
60659     a[i] = 11 - i;
60660     i--;
60661   }
60662   if( pIdx->onError!=OE_None ){
60663     a[pIdx->nColumn] = 1;
60664   }
60665 }
60666
60667 /*
60668 ** This routine will drop an existing named index.  This routine
60669 ** implements the DROP INDEX statement.
60670 */
60671 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
60672   Index *pIndex;
60673   Vdbe *v;
60674   sqlite3 *db = pParse->db;
60675   int iDb;
60676
60677   if( pParse->nErr || db->mallocFailed ){
60678     goto exit_drop_index;
60679   }
60680   assert( pName->nSrc==1 );
60681   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
60682     goto exit_drop_index;
60683   }
60684   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
60685   if( pIndex==0 ){
60686     if( !ifExists ){
60687       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
60688     }
60689     pParse->checkSchema = 1;
60690     goto exit_drop_index;
60691   }
60692   if( pIndex->autoIndex ){
60693     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
60694       "or PRIMARY KEY constraint cannot be dropped", 0);
60695     goto exit_drop_index;
60696   }
60697   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
60698 #ifndef SQLITE_OMIT_AUTHORIZATION
60699   {
60700     int code = SQLITE_DROP_INDEX;
60701     Table *pTab = pIndex->pTable;
60702     const char *zDb = db->aDb[iDb].zName;
60703     const char *zTab = SCHEMA_TABLE(iDb);
60704     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
60705       goto exit_drop_index;
60706     }
60707     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
60708     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
60709       goto exit_drop_index;
60710     }
60711   }
60712 #endif
60713
60714   /* Generate code to remove the index and from the master table */
60715   v = sqlite3GetVdbe(pParse);
60716   if( v ){
60717     sqlite3BeginWriteOperation(pParse, 1, iDb);
60718     sqlite3NestedParse(pParse,
60719        "DELETE FROM %Q.%s WHERE name=%Q",
60720        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
60721        pIndex->zName
60722     );
60723     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
60724       sqlite3NestedParse(pParse,
60725         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
60726         db->aDb[iDb].zName, pIndex->zName
60727       );
60728     }
60729     sqlite3ChangeCookie(pParse, iDb);
60730     destroyRootPage(pParse, pIndex->tnum, iDb);
60731     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
60732   }
60733
60734 exit_drop_index:
60735   sqlite3SrcListDelete(db, pName);
60736 }
60737
60738 /*
60739 ** pArray is a pointer to an array of objects.  Each object in the
60740 ** array is szEntry bytes in size.  This routine allocates a new
60741 ** object on the end of the array.
60742 **
60743 ** *pnEntry is the number of entries already in use.  *pnAlloc is
60744 ** the previously allocated size of the array.  initSize is the
60745 ** suggested initial array size allocation.
60746 **
60747 ** The index of the new entry is returned in *pIdx.
60748 **
60749 ** This routine returns a pointer to the array of objects.  This
60750 ** might be the same as the pArray parameter or it might be a different
60751 ** pointer if the array was resized.
60752 */
60753 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
60754   sqlite3 *db,      /* Connection to notify of malloc failures */
60755   void *pArray,     /* Array of objects.  Might be reallocated */
60756   int szEntry,      /* Size of each object in the array */
60757   int initSize,     /* Suggested initial allocation, in elements */
60758   int *pnEntry,     /* Number of objects currently in use */
60759   int *pnAlloc,     /* Current size of the allocation, in elements */
60760   int *pIdx         /* Write the index of a new slot here */
60761 ){
60762   char *z;
60763   if( *pnEntry >= *pnAlloc ){
60764     void *pNew;
60765     int newSize;
60766     newSize = (*pnAlloc)*2 + initSize;
60767     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
60768     if( pNew==0 ){
60769       *pIdx = -1;
60770       return pArray;
60771     }
60772     *pnAlloc = newSize;
60773     pArray = pNew;
60774   }
60775   z = (char*)pArray;
60776   memset(&z[*pnEntry * szEntry], 0, szEntry);
60777   *pIdx = *pnEntry;
60778   ++*pnEntry;
60779   return pArray;
60780 }
60781
60782 /*
60783 ** Append a new element to the given IdList.  Create a new IdList if
60784 ** need be.
60785 **
60786 ** A new IdList is returned, or NULL if malloc() fails.
60787 */
60788 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
60789   int i;
60790   if( pList==0 ){
60791     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
60792     if( pList==0 ) return 0;
60793     pList->nAlloc = 0;
60794   }
60795   pList->a = sqlite3ArrayAllocate(
60796       db,
60797       pList->a,
60798       sizeof(pList->a[0]),
60799       5,
60800       &pList->nId,
60801       &pList->nAlloc,
60802       &i
60803   );
60804   if( i<0 ){
60805     sqlite3IdListDelete(db, pList);
60806     return 0;
60807   }
60808   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
60809   return pList;
60810 }
60811
60812 /*
60813 ** Delete an IdList.
60814 */
60815 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
60816   int i;
60817   if( pList==0 ) return;
60818   for(i=0; i<pList->nId; i++){
60819     sqlite3DbFree(db, pList->a[i].zName);
60820   }
60821   sqlite3DbFree(db, pList->a);
60822   sqlite3DbFree(db, pList);
60823 }
60824
60825 /*
60826 ** Return the index in pList of the identifier named zId.  Return -1
60827 ** if not found.
60828 */
60829 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
60830   int i;
60831   if( pList==0 ) return -1;
60832   for(i=0; i<pList->nId; i++){
60833     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
60834   }
60835   return -1;
60836 }
60837
60838 /*
60839 ** Append a new table name to the given SrcList.  Create a new SrcList if
60840 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
60841 **
60842 ** A new SrcList is returned, or NULL if malloc() fails.
60843 **
60844 ** If pDatabase is not null, it means that the table has an optional
60845 ** database name prefix.  Like this:  "database.table".  The pDatabase
60846 ** points to the table name and the pTable points to the database name.
60847 ** The SrcList.a[].zName field is filled with the table name which might
60848 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
60849 ** SrcList.a[].zDatabase is filled with the database name from pTable,
60850 ** or with NULL if no database is specified.
60851 **
60852 ** In other words, if call like this:
60853 **
60854 **         sqlite3SrcListAppend(D,A,B,0);
60855 **
60856 ** Then B is a table name and the database name is unspecified.  If called
60857 ** like this:
60858 **
60859 **         sqlite3SrcListAppend(D,A,B,C);
60860 **
60861 ** Then C is the table name and B is the database name.
60862 */
60863 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
60864   sqlite3 *db,        /* Connection to notify of malloc failures */
60865   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
60866   Token *pTable,      /* Table to append */
60867   Token *pDatabase    /* Database of the table */
60868 ){
60869   struct SrcList_item *pItem;
60870   if( pList==0 ){
60871     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
60872     if( pList==0 ) return 0;
60873     pList->nAlloc = 1;
60874   }
60875   if( pList->nSrc>=pList->nAlloc ){
60876     SrcList *pNew;
60877     pList->nAlloc *= 2;
60878     pNew = sqlite3DbRealloc(db, pList,
60879                sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
60880     if( pNew==0 ){
60881       sqlite3SrcListDelete(db, pList);
60882       return 0;
60883     }
60884     pList = pNew;
60885   }
60886   pItem = &pList->a[pList->nSrc];
60887   memset(pItem, 0, sizeof(pList->a[0]));
60888   if( pDatabase && pDatabase->z==0 ){
60889     pDatabase = 0;
60890   }
60891   if( pDatabase && pTable ){
60892     Token *pTemp = pDatabase;
60893     pDatabase = pTable;
60894     pTable = pTemp;
60895   }
60896   pItem->zName = sqlite3NameFromToken(db, pTable);
60897   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
60898   pItem->iCursor = -1;
60899   pList->nSrc++;
60900   return pList;
60901 }
60902
60903 /*
60904 ** Assign cursors to all tables in a SrcList
60905 */
60906 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
60907   int i;
60908   struct SrcList_item *pItem;
60909   assert(pList || pParse->db->mallocFailed );
60910   if( pList ){
60911     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
60912       if( pItem->iCursor>=0 ) break;
60913       pItem->iCursor = pParse->nTab++;
60914       if( pItem->pSelect ){
60915         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
60916       }
60917     }
60918   }
60919 }
60920
60921 /*
60922 ** Delete an entire SrcList including all its substructure.
60923 */
60924 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
60925   int i;
60926   struct SrcList_item *pItem;
60927   if( pList==0 ) return;
60928   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
60929     sqlite3DbFree(db, pItem->zDatabase);
60930     sqlite3DbFree(db, pItem->zName);
60931     sqlite3DbFree(db, pItem->zAlias);
60932     sqlite3DbFree(db, pItem->zIndex);
60933     sqlite3DeleteTable(pItem->pTab);
60934     sqlite3SelectDelete(db, pItem->pSelect);
60935     sqlite3ExprDelete(db, pItem->pOn);
60936     sqlite3IdListDelete(db, pItem->pUsing);
60937   }
60938   sqlite3DbFree(db, pList);
60939 }
60940
60941 /*
60942 ** This routine is called by the parser to add a new term to the
60943 ** end of a growing FROM clause.  The "p" parameter is the part of
60944 ** the FROM clause that has already been constructed.  "p" is NULL
60945 ** if this is the first term of the FROM clause.  pTable and pDatabase
60946 ** are the name of the table and database named in the FROM clause term.
60947 ** pDatabase is NULL if the database name qualifier is missing - the
60948 ** usual case.  If the term has a alias, then pAlias points to the
60949 ** alias token.  If the term is a subquery, then pSubquery is the
60950 ** SELECT statement that the subquery encodes.  The pTable and
60951 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
60952 ** parameters are the content of the ON and USING clauses.
60953 **
60954 ** Return a new SrcList which encodes is the FROM with the new
60955 ** term added.
60956 */
60957 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
60958   Parse *pParse,          /* Parsing context */
60959   SrcList *p,             /* The left part of the FROM clause already seen */
60960   Token *pTable,          /* Name of the table to add to the FROM clause */
60961   Token *pDatabase,       /* Name of the database containing pTable */
60962   Token *pAlias,          /* The right-hand side of the AS subexpression */
60963   Select *pSubquery,      /* A subquery used in place of a table name */
60964   Expr *pOn,              /* The ON clause of a join */
60965   IdList *pUsing          /* The USING clause of a join */
60966 ){
60967   struct SrcList_item *pItem;
60968   sqlite3 *db = pParse->db;
60969   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
60970   if( p==0 || p->nSrc==0 ){
60971     sqlite3ExprDelete(db, pOn);
60972     sqlite3IdListDelete(db, pUsing);
60973     sqlite3SelectDelete(db, pSubquery);
60974     return p;
60975   }
60976   pItem = &p->a[p->nSrc-1];
60977   if( pAlias && pAlias->n ){
60978     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
60979   }
60980   pItem->pSelect = pSubquery;
60981   pItem->pOn = pOn;
60982   pItem->pUsing = pUsing;
60983   return p;
60984 }
60985
60986 /*
60987 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
60988 ** element of the source-list passed as the second argument.
60989 */
60990 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
60991   if( pIndexedBy && p && p->nSrc>0 ){
60992     struct SrcList_item *pItem = &p->a[p->nSrc-1];
60993     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
60994     if( pIndexedBy->n==1 && !pIndexedBy->z ){
60995       /* A "NOT INDEXED" clause was supplied. See parse.y 
60996       ** construct "indexed_opt" for details. */
60997       pItem->notIndexed = 1;
60998     }else{
60999       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
61000     }
61001   }
61002 }
61003
61004 /*
61005 ** When building up a FROM clause in the parser, the join operator
61006 ** is initially attached to the left operand.  But the code generator
61007 ** expects the join operator to be on the right operand.  This routine
61008 ** Shifts all join operators from left to right for an entire FROM
61009 ** clause.
61010 **
61011 ** Example: Suppose the join is like this:
61012 **
61013 **           A natural cross join B
61014 **
61015 ** The operator is "natural cross join".  The A and B operands are stored
61016 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
61017 ** operator with A.  This routine shifts that operator over to B.
61018 */
61019 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
61020   if( p && p->a ){
61021     int i;
61022     for(i=p->nSrc-1; i>0; i--){
61023       p->a[i].jointype = p->a[i-1].jointype;
61024     }
61025     p->a[0].jointype = 0;
61026   }
61027 }
61028
61029 /*
61030 ** Begin a transaction
61031 */
61032 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
61033   sqlite3 *db;
61034   Vdbe *v;
61035   int i;
61036
61037   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61038   if( pParse->nErr || db->mallocFailed ) return;
61039   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
61040
61041   v = sqlite3GetVdbe(pParse);
61042   if( !v ) return;
61043   if( type!=TK_DEFERRED ){
61044     for(i=0; i<db->nDb; i++){
61045       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
61046       sqlite3VdbeUsesBtree(v, i);
61047     }
61048   }
61049   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
61050 }
61051
61052 /*
61053 ** Commit a transaction
61054 */
61055 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
61056   sqlite3 *db;
61057   Vdbe *v;
61058
61059   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61060   if( pParse->nErr || db->mallocFailed ) return;
61061   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
61062
61063   v = sqlite3GetVdbe(pParse);
61064   if( v ){
61065     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
61066   }
61067 }
61068
61069 /*
61070 ** Rollback a transaction
61071 */
61072 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
61073   sqlite3 *db;
61074   Vdbe *v;
61075
61076   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
61077   if( pParse->nErr || db->mallocFailed ) return;
61078   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
61079
61080   v = sqlite3GetVdbe(pParse);
61081   if( v ){
61082     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
61083   }
61084 }
61085
61086 /*
61087 ** Make sure the TEMP database is open and available for use.  Return
61088 ** the number of errors.  Leave any error messages in the pParse structure.
61089 */
61090 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
61091   sqlite3 *db = pParse->db;
61092   if( db->aDb[1].pBt==0 && !pParse->explain ){
61093     int rc;
61094     static const int flags = 
61095           SQLITE_OPEN_READWRITE |
61096           SQLITE_OPEN_CREATE |
61097           SQLITE_OPEN_EXCLUSIVE |
61098           SQLITE_OPEN_DELETEONCLOSE |
61099           SQLITE_OPEN_TEMP_DB;
61100
61101     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
61102                                  &db->aDb[1].pBt);
61103     if( rc!=SQLITE_OK ){
61104       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
61105         "file for storing temporary tables");
61106       pParse->rc = rc;
61107       return 1;
61108     }
61109     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
61110     assert( db->aDb[1].pSchema );
61111     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
61112                             db->dfltJournalMode);
61113   }
61114   return 0;
61115 }
61116
61117 /*
61118 ** Generate VDBE code that will verify the schema cookie and start
61119 ** a read-transaction for all named database files.
61120 **
61121 ** It is important that all schema cookies be verified and all
61122 ** read transactions be started before anything else happens in
61123 ** the VDBE program.  But this routine can be called after much other
61124 ** code has been generated.  So here is what we do:
61125 **
61126 ** The first time this routine is called, we code an OP_Goto that
61127 ** will jump to a subroutine at the end of the program.  Then we
61128 ** record every database that needs its schema verified in the
61129 ** pParse->cookieMask field.  Later, after all other code has been
61130 ** generated, the subroutine that does the cookie verifications and
61131 ** starts the transactions will be coded and the OP_Goto P2 value
61132 ** will be made to point to that subroutine.  The generation of the
61133 ** cookie verification subroutine code happens in sqlite3FinishCoding().
61134 **
61135 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
61136 ** schema on any databases.  This can be used to position the OP_Goto
61137 ** early in the code, before we know if any database tables will be used.
61138 */
61139 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
61140   sqlite3 *db;
61141   Vdbe *v;
61142   int mask;
61143
61144   v = sqlite3GetVdbe(pParse);
61145   if( v==0 ) return;  /* This only happens if there was a prior error */
61146   db = pParse->db;
61147   if( pParse->cookieGoto==0 ){
61148     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
61149   }
61150   if( iDb>=0 ){
61151     assert( iDb<db->nDb );
61152     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
61153     assert( iDb<SQLITE_MAX_ATTACHED+2 );
61154     mask = 1<<iDb;
61155     if( (pParse->cookieMask & mask)==0 ){
61156       pParse->cookieMask |= mask;
61157       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
61158       if( !OMIT_TEMPDB && iDb==1 ){
61159         sqlite3OpenTempDatabase(pParse);
61160       }
61161     }
61162   }
61163 }
61164
61165 /*
61166 ** Generate VDBE code that prepares for doing an operation that
61167 ** might change the database.
61168 **
61169 ** This routine starts a new transaction if we are not already within
61170 ** a transaction.  If we are already within a transaction, then a checkpoint
61171 ** is set if the setStatement parameter is true.  A checkpoint should
61172 ** be set for operations that might fail (due to a constraint) part of
61173 ** the way through and which will need to undo some writes without having to
61174 ** rollback the whole transaction.  For operations where all constraints
61175 ** can be checked before any changes are made to the database, it is never
61176 ** necessary to undo a write and the checkpoint should not be set.
61177 **
61178 ** Only database iDb and the temp database are made writable by this call.
61179 ** If iDb==0, then the main and temp databases are made writable.   If
61180 ** iDb==1 then only the temp database is made writable.  If iDb>1 then the
61181 ** specified auxiliary database and the temp database are made writable.
61182 */
61183 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
61184   Vdbe *v = sqlite3GetVdbe(pParse);
61185   if( v==0 ) return;
61186   sqlite3CodeVerifySchema(pParse, iDb);
61187   pParse->writeMask |= 1<<iDb;
61188   if( setStatement && pParse->nested==0 ){
61189     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
61190   }
61191   if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
61192     sqlite3BeginWriteOperation(pParse, setStatement, 1);
61193   }
61194 }
61195
61196 /*
61197 ** Check to see if pIndex uses the collating sequence pColl.  Return
61198 ** true if it does and false if it does not.
61199 */
61200 #ifndef SQLITE_OMIT_REINDEX
61201 static int collationMatch(const char *zColl, Index *pIndex){
61202   int i;
61203   for(i=0; i<pIndex->nColumn; i++){
61204     const char *z = pIndex->azColl[i];
61205     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
61206       return 1;
61207     }
61208   }
61209   return 0;
61210 }
61211 #endif
61212
61213 /*
61214 ** Recompute all indices of pTab that use the collating sequence pColl.
61215 ** If pColl==0 then recompute all indices of pTab.
61216 */
61217 #ifndef SQLITE_OMIT_REINDEX
61218 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
61219   Index *pIndex;              /* An index associated with pTab */
61220
61221   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
61222     if( zColl==0 || collationMatch(zColl, pIndex) ){
61223       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61224       sqlite3BeginWriteOperation(pParse, 0, iDb);
61225       sqlite3RefillIndex(pParse, pIndex, -1);
61226     }
61227   }
61228 }
61229 #endif
61230
61231 /*
61232 ** Recompute all indices of all tables in all databases where the
61233 ** indices use the collating sequence pColl.  If pColl==0 then recompute
61234 ** all indices everywhere.
61235 */
61236 #ifndef SQLITE_OMIT_REINDEX
61237 static void reindexDatabases(Parse *pParse, char const *zColl){
61238   Db *pDb;                    /* A single database */
61239   int iDb;                    /* The database index number */
61240   sqlite3 *db = pParse->db;   /* The database connection */
61241   HashElem *k;                /* For looping over tables in pDb */
61242   Table *pTab;                /* A table in the database */
61243
61244   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
61245     assert( pDb!=0 );
61246     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
61247       pTab = (Table*)sqliteHashData(k);
61248       reindexTable(pParse, pTab, zColl);
61249     }
61250   }
61251 }
61252 #endif
61253
61254 /*
61255 ** Generate code for the REINDEX command.
61256 **
61257 **        REINDEX                            -- 1
61258 **        REINDEX  <collation>               -- 2
61259 **        REINDEX  ?<database>.?<tablename>  -- 3
61260 **        REINDEX  ?<database>.?<indexname>  -- 4
61261 **
61262 ** Form 1 causes all indices in all attached databases to be rebuilt.
61263 ** Form 2 rebuilds all indices in all databases that use the named
61264 ** collating function.  Forms 3 and 4 rebuild the named index or all
61265 ** indices associated with the named table.
61266 */
61267 #ifndef SQLITE_OMIT_REINDEX
61268 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
61269   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
61270   char *z;                    /* Name of a table or index */
61271   const char *zDb;            /* Name of the database */
61272   Table *pTab;                /* A table in the database */
61273   Index *pIndex;              /* An index associated with pTab */
61274   int iDb;                    /* The database index number */
61275   sqlite3 *db = pParse->db;   /* The database connection */
61276   Token *pObjName;            /* Name of the table or index to be reindexed */
61277
61278   /* Read the database schema. If an error occurs, leave an error message
61279   ** and code in pParse and return NULL. */
61280   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61281     return;
61282   }
61283
61284   if( pName1==0 || pName1->z==0 ){
61285     reindexDatabases(pParse, 0);
61286     return;
61287   }else if( pName2==0 || pName2->z==0 ){
61288     char *zColl;
61289     assert( pName1->z );
61290     zColl = sqlite3NameFromToken(pParse->db, pName1);
61291     if( !zColl ) return;
61292     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
61293     if( pColl ){
61294       if( zColl ){
61295         reindexDatabases(pParse, zColl);
61296         sqlite3DbFree(db, zColl);
61297       }
61298       return;
61299     }
61300     sqlite3DbFree(db, zColl);
61301   }
61302   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
61303   if( iDb<0 ) return;
61304   z = sqlite3NameFromToken(db, pObjName);
61305   if( z==0 ) return;
61306   zDb = db->aDb[iDb].zName;
61307   pTab = sqlite3FindTable(db, z, zDb);
61308   if( pTab ){
61309     reindexTable(pParse, pTab, 0);
61310     sqlite3DbFree(db, z);
61311     return;
61312   }
61313   pIndex = sqlite3FindIndex(db, z, zDb);
61314   sqlite3DbFree(db, z);
61315   if( pIndex ){
61316     sqlite3BeginWriteOperation(pParse, 0, iDb);
61317     sqlite3RefillIndex(pParse, pIndex, -1);
61318     return;
61319   }
61320   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
61321 }
61322 #endif
61323
61324 /*
61325 ** Return a dynamicly allocated KeyInfo structure that can be used
61326 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
61327 **
61328 ** If successful, a pointer to the new structure is returned. In this case
61329 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
61330 ** pointer. If an error occurs (out of memory or missing collation 
61331 ** sequence), NULL is returned and the state of pParse updated to reflect
61332 ** the error.
61333 */
61334 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
61335   int i;
61336   int nCol = pIdx->nColumn;
61337   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
61338   sqlite3 *db = pParse->db;
61339   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
61340
61341   if( pKey ){
61342     pKey->db = pParse->db;
61343     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
61344     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
61345     for(i=0; i<nCol; i++){
61346       char *zColl = pIdx->azColl[i];
61347       assert( zColl );
61348       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
61349       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
61350     }
61351     pKey->nField = nCol;
61352   }
61353
61354   if( pParse->nErr ){
61355     sqlite3DbFree(db, pKey);
61356     pKey = 0;
61357   }
61358   return pKey;
61359 }
61360
61361 /************** End of build.c ***********************************************/
61362 /************** Begin file callback.c ****************************************/
61363 /*
61364 ** 2005 May 23 
61365 **
61366 ** The author disclaims copyright to this source code.  In place of
61367 ** a legal notice, here is a blessing:
61368 **
61369 **    May you do good and not evil.
61370 **    May you find forgiveness for yourself and forgive others.
61371 **    May you share freely, never taking more than you give.
61372 **
61373 *************************************************************************
61374 **
61375 ** This file contains functions used to access the internal hash tables
61376 ** of user defined functions and collation sequences.
61377 **
61378 ** $Id: callback.c,v 1.32 2008/10/10 17:41:29 drh Exp $
61379 */
61380
61381
61382 /*
61383 ** Invoke the 'collation needed' callback to request a collation sequence
61384 ** in the database text encoding of name zName, length nName.
61385 ** If the collation sequence
61386 */
61387 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
61388   assert( !db->xCollNeeded || !db->xCollNeeded16 );
61389   if( nName<0 ) nName = sqlite3Strlen(db, zName);
61390   if( db->xCollNeeded ){
61391     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
61392     if( !zExternal ) return;
61393     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
61394     sqlite3DbFree(db, zExternal);
61395   }
61396 #ifndef SQLITE_OMIT_UTF16
61397   if( db->xCollNeeded16 ){
61398     char const *zExternal;
61399     sqlite3_value *pTmp = sqlite3ValueNew(db);
61400     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
61401     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
61402     if( zExternal ){
61403       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
61404     }
61405     sqlite3ValueFree(pTmp);
61406   }
61407 #endif
61408 }
61409
61410 /*
61411 ** This routine is called if the collation factory fails to deliver a
61412 ** collation function in the best encoding but there may be other versions
61413 ** of this collation function (for other text encodings) available. Use one
61414 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
61415 ** possible.
61416 */
61417 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
61418   CollSeq *pColl2;
61419   char *z = pColl->zName;
61420   int n = strlen(z);
61421   int i;
61422   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
61423   for(i=0; i<3; i++){
61424     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
61425     if( pColl2->xCmp!=0 ){
61426       memcpy(pColl, pColl2, sizeof(CollSeq));
61427       pColl->xDel = 0;         /* Do not copy the destructor */
61428       return SQLITE_OK;
61429     }
61430   }
61431   return SQLITE_ERROR;
61432 }
61433
61434 /*
61435 ** This function is responsible for invoking the collation factory callback
61436 ** or substituting a collation sequence of a different encoding when the
61437 ** requested collation sequence is not available in the database native
61438 ** encoding.
61439 ** 
61440 ** If it is not NULL, then pColl must point to the database native encoding 
61441 ** collation sequence with name zName, length nName.
61442 **
61443 ** The return value is either the collation sequence to be used in database
61444 ** db for collation type name zName, length nName, or NULL, if no collation
61445 ** sequence can be found.
61446 */
61447 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
61448   sqlite3* db, 
61449   CollSeq *pColl, 
61450   const char *zName, 
61451   int nName
61452 ){
61453   CollSeq *p;
61454
61455   p = pColl;
61456   if( !p ){
61457     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
61458   }
61459   if( !p || !p->xCmp ){
61460     /* No collation sequence of this type for this encoding is registered.
61461     ** Call the collation factory to see if it can supply us with one.
61462     */
61463     callCollNeeded(db, zName, nName);
61464     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
61465   }
61466   if( p && !p->xCmp && synthCollSeq(db, p) ){
61467     p = 0;
61468   }
61469   assert( !p || p->xCmp );
61470   return p;
61471 }
61472
61473 /*
61474 ** This routine is called on a collation sequence before it is used to
61475 ** check that it is defined. An undefined collation sequence exists when
61476 ** a database is loaded that contains references to collation sequences
61477 ** that have not been defined by sqlite3_create_collation() etc.
61478 **
61479 ** If required, this routine calls the 'collation needed' callback to
61480 ** request a definition of the collating sequence. If this doesn't work, 
61481 ** an equivalent collating sequence that uses a text encoding different
61482 ** from the main database is substituted, if one is available.
61483 */
61484 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
61485   if( pColl ){
61486     const char *zName = pColl->zName;
61487     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
61488     if( !p ){
61489       if( pParse->nErr==0 ){
61490         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
61491       }
61492       pParse->nErr++;
61493       return SQLITE_ERROR;
61494     }
61495     assert( p==pColl );
61496   }
61497   return SQLITE_OK;
61498 }
61499
61500
61501
61502 /*
61503 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
61504 ** specified by zName and nName is not found and parameter 'create' is
61505 ** true, then create a new entry. Otherwise return NULL.
61506 **
61507 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
61508 ** array of three CollSeq structures. The first is the collation sequence
61509 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
61510 **
61511 ** Stored immediately after the three collation sequences is a copy of
61512 ** the collation sequence name. A pointer to this string is stored in
61513 ** each collation sequence structure.
61514 */
61515 static CollSeq *findCollSeqEntry(
61516   sqlite3 *db,
61517   const char *zName,
61518   int nName,
61519   int create
61520 ){
61521   CollSeq *pColl;
61522   if( nName<0 ) nName = sqlite3Strlen(db, zName);
61523   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
61524
61525   if( 0==pColl && create ){
61526     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
61527     if( pColl ){
61528       CollSeq *pDel = 0;
61529       pColl[0].zName = (char*)&pColl[3];
61530       pColl[0].enc = SQLITE_UTF8;
61531       pColl[1].zName = (char*)&pColl[3];
61532       pColl[1].enc = SQLITE_UTF16LE;
61533       pColl[2].zName = (char*)&pColl[3];
61534       pColl[2].enc = SQLITE_UTF16BE;
61535       memcpy(pColl[0].zName, zName, nName);
61536       pColl[0].zName[nName] = 0;
61537       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
61538
61539       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
61540       ** return the pColl pointer to be deleted (because it wasn't added
61541       ** to the hash table).
61542       */
61543       assert( pDel==0 || pDel==pColl );
61544       if( pDel!=0 ){
61545         db->mallocFailed = 1;
61546         sqlite3DbFree(db, pDel);
61547         pColl = 0;
61548       }
61549     }
61550   }
61551   return pColl;
61552 }
61553
61554 /*
61555 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
61556 ** Return the CollSeq* pointer for the collation sequence named zName
61557 ** for the encoding 'enc' from the database 'db'.
61558 **
61559 ** If the entry specified is not found and 'create' is true, then create a
61560 ** new entry.  Otherwise return NULL.
61561 **
61562 ** A separate function sqlite3LocateCollSeq() is a wrapper around
61563 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
61564 ** if necessary and generates an error message if the collating sequence
61565 ** cannot be found.
61566 */
61567 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
61568   sqlite3 *db,
61569   u8 enc,
61570   const char *zName,
61571   int nName,
61572   int create
61573 ){
61574   CollSeq *pColl;
61575   if( zName ){
61576     pColl = findCollSeqEntry(db, zName, nName, create);
61577   }else{
61578     pColl = db->pDfltColl;
61579   }
61580   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
61581   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
61582   if( pColl ) pColl += enc-1;
61583   return pColl;
61584 }
61585
61586 /* During the search for the best function definition, this procedure
61587 ** is called to test how well the function passed as the first argument
61588 ** matches the request for a function with nArg arguments in a system
61589 ** that uses encoding enc. The value returned indicates how well the
61590 ** request is matched. A higher value indicates a better match.
61591 **
61592 ** The returned value is always between 1 and 6, as follows:
61593 **
61594 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
61595 **    encoding is requested, or vice versa.
61596 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
61597 **    requested, or vice versa.
61598 ** 3: A variable arguments function using the same text encoding.
61599 ** 4: A function with the exact number of arguments requested that
61600 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
61601 ** 5: A function with the exact number of arguments requested that
61602 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
61603 ** 6: An exact match.
61604 **
61605 */
61606 static int matchQuality(FuncDef *p, int nArg, u8 enc){
61607   int match = 0;
61608   if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){
61609     match = 1;
61610     if( p->nArg==nArg || nArg==-1 ){
61611       match = 4;
61612     }
61613     if( enc==p->iPrefEnc ){
61614       match += 2;
61615     }
61616     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
61617              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
61618       match += 1;
61619     }
61620   }
61621   return match;
61622 }
61623
61624 /*
61625 ** Search a FuncDefHash for a function with the given name.  Return
61626 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
61627 */
61628 static FuncDef *functionSearch(
61629   FuncDefHash *pHash,  /* Hash table to search */
61630   int h,               /* Hash of the name */
61631   const char *zFunc,   /* Name of function */
61632   int nFunc            /* Number of bytes in zFunc */
61633 ){
61634   FuncDef *p;
61635   for(p=pHash->a[h]; p; p=p->pHash){
61636     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
61637       return p;
61638     }
61639   }
61640   return 0;
61641 }
61642
61643 /*
61644 ** Insert a new FuncDef into a FuncDefHash hash table.
61645 */
61646 SQLITE_PRIVATE void sqlite3FuncDefInsert(
61647   FuncDefHash *pHash,  /* The hash table into which to insert */
61648   FuncDef *pDef        /* The function definition to insert */
61649 ){
61650   FuncDef *pOther;
61651   int nName = strlen(pDef->zName);
61652   u8 c1 = (u8)pDef->zName[0];
61653   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
61654   pOther = functionSearch(pHash, h, pDef->zName, nName);
61655   if( pOther ){
61656     pDef->pNext = pOther->pNext;
61657     pOther->pNext = pDef;
61658   }else{
61659     pDef->pNext = 0;
61660     pDef->pHash = pHash->a[h];
61661     pHash->a[h] = pDef;
61662   }
61663 }
61664   
61665   
61666
61667 /*
61668 ** Locate a user function given a name, a number of arguments and a flag
61669 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
61670 ** pointer to the FuncDef structure that defines that function, or return
61671 ** NULL if the function does not exist.
61672 **
61673 ** If the createFlag argument is true, then a new (blank) FuncDef
61674 ** structure is created and liked into the "db" structure if a
61675 ** no matching function previously existed.  When createFlag is true
61676 ** and the nArg parameter is -1, then only a function that accepts
61677 ** any number of arguments will be returned.
61678 **
61679 ** If createFlag is false and nArg is -1, then the first valid
61680 ** function found is returned.  A function is valid if either xFunc
61681 ** or xStep is non-zero.
61682 **
61683 ** If createFlag is false, then a function with the required name and
61684 ** number of arguments may be returned even if the eTextRep flag does not
61685 ** match that requested.
61686 */
61687 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
61688   sqlite3 *db,       /* An open database */
61689   const char *zName, /* Name of the function.  Not null-terminated */
61690   int nName,         /* Number of characters in the name */
61691   int nArg,          /* Number of arguments.  -1 means any number */
61692   u8 enc,            /* Preferred text encoding */
61693   int createFlag     /* Create new entry if true and does not otherwise exist */
61694 ){
61695   FuncDef *p;         /* Iterator variable */
61696   FuncDef *pBest = 0; /* Best match found so far */
61697   int bestScore = 0;  /* Score of best match */
61698   int h;              /* Hash value */
61699
61700
61701   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
61702   if( nArg<-1 ) nArg = -1;
61703   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
61704
61705   /* First search for a match amongst the application-defined functions.
61706   */
61707   p = functionSearch(&db->aFunc, h, zName, nName);
61708   while( p ){
61709     int score = matchQuality(p, nArg, enc);
61710     if( score>bestScore ){
61711       pBest = p;
61712       bestScore = score;
61713     }
61714     p = p->pNext;
61715   }
61716
61717   /* If no match is found, search the built-in functions.
61718   **
61719   ** Except, if createFlag is true, that means that we are trying to
61720   ** install a new function.  Whatever FuncDef structure is returned will
61721   ** have fields overwritten with new information appropriate for the
61722   ** new function.  But the FuncDefs for built-in functions are read-only.
61723   ** So we must not search for built-ins when creating a new function.
61724   */ 
61725   if( !createFlag && !pBest ){
61726     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
61727     p = functionSearch(pHash, h, zName, nName);
61728     while( p ){
61729       int score = matchQuality(p, nArg, enc);
61730       if( score>bestScore ){
61731         pBest = p;
61732         bestScore = score;
61733       }
61734       p = p->pNext;
61735     }
61736   }
61737
61738   /* If the createFlag parameter is true and the search did not reveal an
61739   ** exact match for the name, number of arguments and encoding, then add a
61740   ** new entry to the hash table and return it.
61741   */
61742   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
61743       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
61744     pBest->zName = (char *)&pBest[1];
61745     pBest->nArg = nArg;
61746     pBest->iPrefEnc = enc;
61747     memcpy(pBest->zName, zName, nName);
61748     pBest->zName[nName] = 0;
61749     sqlite3FuncDefInsert(&db->aFunc, pBest);
61750   }
61751
61752   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
61753     return pBest;
61754   }
61755   return 0;
61756 }
61757
61758 /*
61759 ** Free all resources held by the schema structure. The void* argument points
61760 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
61761 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
61762 ** of the schema hash tables).
61763 **
61764 ** The Schema.cache_size variable is not cleared.
61765 */
61766 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
61767   Hash temp1;
61768   Hash temp2;
61769   HashElem *pElem;
61770   Schema *pSchema = (Schema *)p;
61771
61772   temp1 = pSchema->tblHash;
61773   temp2 = pSchema->trigHash;
61774   sqlite3HashInit(&pSchema->trigHash, 0);
61775   sqlite3HashClear(&pSchema->aFKey);
61776   sqlite3HashClear(&pSchema->idxHash);
61777   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
61778     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
61779   }
61780   sqlite3HashClear(&temp2);
61781   sqlite3HashInit(&pSchema->tblHash, 0);
61782   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
61783     Table *pTab = sqliteHashData(pElem);
61784     sqlite3DeleteTable(pTab);
61785   }
61786   sqlite3HashClear(&temp1);
61787   pSchema->pSeqTab = 0;
61788   pSchema->flags &= ~DB_SchemaLoaded;
61789 }
61790
61791 /*
61792 ** Find and return the schema associated with a BTree.  Create
61793 ** a new one if necessary.
61794 */
61795 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
61796   Schema * p;
61797   if( pBt ){
61798     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
61799   }else{
61800     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
61801   }
61802   if( !p ){
61803     db->mallocFailed = 1;
61804   }else if ( 0==p->file_format ){
61805     sqlite3HashInit(&p->tblHash, 0);
61806     sqlite3HashInit(&p->idxHash, 0);
61807     sqlite3HashInit(&p->trigHash, 0);
61808     sqlite3HashInit(&p->aFKey, 1);
61809     p->enc = SQLITE_UTF8;
61810   }
61811   return p;
61812 }
61813
61814 /************** End of callback.c ********************************************/
61815 /************** Begin file delete.c ******************************************/
61816 /*
61817 ** 2001 September 15
61818 **
61819 ** The author disclaims copyright to this source code.  In place of
61820 ** a legal notice, here is a blessing:
61821 **
61822 **    May you do good and not evil.
61823 **    May you find forgiveness for yourself and forgive others.
61824 **    May you share freely, never taking more than you give.
61825 **
61826 *************************************************************************
61827 ** This file contains C code routines that are called by the parser
61828 ** in order to generate code for DELETE FROM statements.
61829 **
61830 ** $Id: delete.c,v 1.182 2008/10/10 23:48:26 drh Exp $
61831 */
61832
61833 /*
61834 ** Look up every table that is named in pSrc.  If any table is not found,
61835 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
61836 ** are found, return a pointer to the last table.
61837 */
61838 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
61839   struct SrcList_item *pItem = pSrc->a;
61840   Table *pTab;
61841   assert( pItem && pSrc->nSrc==1 );
61842   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
61843   sqlite3DeleteTable(pItem->pTab);
61844   pItem->pTab = pTab;
61845   if( pTab ){
61846     pTab->nRef++;
61847   }
61848   if( sqlite3IndexedByLookup(pParse, pItem) ){
61849     pTab = 0;
61850   }
61851   return pTab;
61852 }
61853
61854 /*
61855 ** Check to make sure the given table is writable.  If it is not
61856 ** writable, generate an error message and return 1.  If it is
61857 ** writable return 0;
61858 */
61859 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
61860   if( ((pTab->tabFlags & TF_Readonly)!=0
61861         && (pParse->db->flags & SQLITE_WriteSchema)==0
61862         && pParse->nested==0) 
61863 #ifndef SQLITE_OMIT_VIRTUALTABLE
61864       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
61865 #endif
61866   ){
61867     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
61868     return 1;
61869   }
61870 #ifndef SQLITE_OMIT_VIEW
61871   if( !viewOk && pTab->pSelect ){
61872     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
61873     return 1;
61874   }
61875 #endif
61876   return 0;
61877 }
61878
61879 /*
61880 ** Generate code that will open a table for reading.
61881 */
61882 SQLITE_PRIVATE void sqlite3OpenTable(
61883   Parse *p,       /* Generate code into this VDBE */
61884   int iCur,       /* The cursor number of the table */
61885   int iDb,        /* The database index in sqlite3.aDb[] */
61886   Table *pTab,    /* The table to be opened */
61887   int opcode      /* OP_OpenRead or OP_OpenWrite */
61888 ){
61889   Vdbe *v;
61890   if( IsVirtual(pTab) ) return;
61891   v = sqlite3GetVdbe(p);
61892   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
61893   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName);
61894   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
61895   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
61896   VdbeComment((v, "%s", pTab->zName));
61897 }
61898
61899
61900 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
61901 /*
61902 ** Evaluate a view and store its result in an ephemeral table.  The
61903 ** pWhere argument is an optional WHERE clause that restricts the
61904 ** set of rows in the view that are to be added to the ephemeral table.
61905 */
61906 SQLITE_PRIVATE void sqlite3MaterializeView(
61907   Parse *pParse,       /* Parsing context */
61908   Table *pView,        /* View definition */
61909   Expr *pWhere,        /* Optional WHERE clause to be added */
61910   int iCur             /* Cursor number for ephemerial table */
61911 ){
61912   SelectDest dest;
61913   Select *pDup;
61914   sqlite3 *db = pParse->db;
61915
61916   pDup = sqlite3SelectDup(db, pView->pSelect);
61917   if( pWhere ){
61918     SrcList *pFrom;
61919     Token viewName;
61920     
61921     pWhere = sqlite3ExprDup(db, pWhere);
61922     viewName.z = (u8*)pView->zName;
61923     viewName.n = (unsigned int)strlen((const char*)viewName.z);
61924     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
61925     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
61926   }
61927   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
61928   sqlite3Select(pParse, pDup, &dest);
61929   sqlite3SelectDelete(db, pDup);
61930 }
61931 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
61932
61933 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
61934 /*
61935 ** Generate an expression tree to implement the WHERE, ORDER BY,
61936 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
61937 **
61938 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
61939 **                            \__________________________/
61940 **                               pLimitWhere (pInClause)
61941 */
61942 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
61943   Parse *pParse,               /* The parser context */
61944   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
61945   Expr *pWhere,                /* The WHERE clause.  May be null */
61946   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
61947   Expr *pLimit,                /* The LIMIT clause.  May be null */
61948   Expr *pOffset,               /* The OFFSET clause.  May be null */
61949   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
61950 ){
61951   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
61952   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
61953   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
61954   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
61955   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
61956   Select *pSelect = NULL;      /* Complete SELECT tree */
61957
61958   /* Check that there isn't an ORDER BY without a LIMIT clause.
61959   */
61960   if( pOrderBy && (pLimit == 0) ) {
61961     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
61962     pParse->parseError = 1;
61963     goto limit_where_cleanup_2;
61964   }
61965
61966   /* We only need to generate a select expression if there
61967   ** is a limit/offset term to enforce.
61968   */
61969   if( pLimit == 0 ) {
61970     /* if pLimit is null, pOffset will always be null as well. */
61971     assert( pOffset == 0 );
61972     return pWhere;
61973   }
61974
61975   /* Generate a select expression tree to enforce the limit/offset 
61976   ** term for the DELETE or UPDATE statement.  For example:
61977   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
61978   ** becomes:
61979   **   DELETE FROM table_a WHERE rowid IN ( 
61980   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
61981   **   );
61982   */
61983
61984   pSelectRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
61985   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
61986   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid, 0);
61987   if( pEList == 0 ) goto limit_where_cleanup_2;
61988
61989   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
61990   ** and the SELECT subtree. */
61991   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc);
61992   if( pSelectSrc == 0 ) {
61993     sqlite3ExprListDelete(pParse->db, pEList);
61994     goto limit_where_cleanup_2;
61995   }
61996
61997   /* generate the SELECT expression tree. */
61998   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,pOrderBy,0,pLimit,pOffset);
61999   if( pSelect == 0 ) return 0;
62000
62001   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
62002   pWhereRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
62003   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
62004   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
62005   if( pInClause == 0 ) goto limit_where_cleanup_1;
62006
62007   pInClause->pSelect = pSelect;
62008   sqlite3ExprSetHeight(pParse, pInClause);
62009   return pInClause;
62010
62011   /* something went wrong. clean up anything allocated. */
62012 limit_where_cleanup_1:
62013   sqlite3SelectDelete(pParse->db, pSelect);
62014   return 0;
62015
62016 limit_where_cleanup_2:
62017   sqlite3ExprDelete(pParse->db, pWhere);
62018   sqlite3ExprListDelete(pParse->db, pOrderBy);
62019   sqlite3ExprDelete(pParse->db, pLimit);
62020   sqlite3ExprDelete(pParse->db, pOffset);
62021   return 0;
62022 }
62023 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
62024
62025 /*
62026 ** Generate code for a DELETE FROM statement.
62027 **
62028 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
62029 **                 \________/       \________________/
62030 **                  pTabList              pWhere
62031 */
62032 SQLITE_PRIVATE void sqlite3DeleteFrom(
62033   Parse *pParse,         /* The parser context */
62034   SrcList *pTabList,     /* The table from which we should delete things */
62035   Expr *pWhere           /* The WHERE clause.  May be null */
62036 ){
62037   Vdbe *v;               /* The virtual database engine */
62038   Table *pTab;           /* The table from which records will be deleted */
62039   const char *zDb;       /* Name of database holding pTab */
62040   int end, addr = 0;     /* A couple addresses of generated code */
62041   int i;                 /* Loop counter */
62042   WhereInfo *pWInfo;     /* Information about the WHERE clause */
62043   Index *pIdx;           /* For looping over indices of the table */
62044   int iCur;              /* VDBE Cursor number for pTab */
62045   sqlite3 *db;           /* Main database structure */
62046   AuthContext sContext;  /* Authorization context */
62047   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
62048   NameContext sNC;       /* Name context to resolve expressions in */
62049   int iDb;               /* Database number */
62050   int memCnt = 0;        /* Memory cell used for change counting */
62051
62052 #ifndef SQLITE_OMIT_TRIGGER
62053   int isView;                  /* True if attempting to delete from a view */
62054   int triggers_exist = 0;      /* True if any triggers exist */
62055 #endif
62056   int iBeginAfterTrigger;      /* Address of after trigger program */
62057   int iEndAfterTrigger;        /* Exit of after trigger program */
62058   int iBeginBeforeTrigger;     /* Address of before trigger program */
62059   int iEndBeforeTrigger;       /* Exit of before trigger program */
62060   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
62061
62062   sContext.pParse = 0;
62063   db = pParse->db;
62064   if( pParse->nErr || db->mallocFailed ){
62065     goto delete_from_cleanup;
62066   }
62067   assert( pTabList->nSrc==1 );
62068
62069   /* Locate the table which we want to delete.  This table has to be
62070   ** put in an SrcList structure because some of the subroutines we
62071   ** will be calling are designed to work with multiple tables and expect
62072   ** an SrcList* parameter instead of just a Table* parameter.
62073   */
62074   pTab = sqlite3SrcListLookup(pParse, pTabList);
62075   if( pTab==0 )  goto delete_from_cleanup;
62076
62077   /* Figure out if we have any triggers and if the table being
62078   ** deleted from is a view
62079   */
62080 #ifndef SQLITE_OMIT_TRIGGER
62081   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0);
62082   isView = pTab->pSelect!=0;
62083 #else
62084 # define triggers_exist 0
62085 # define isView 0
62086 #endif
62087 #ifdef SQLITE_OMIT_VIEW
62088 # undef isView
62089 # define isView 0
62090 #endif
62091
62092   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
62093     goto delete_from_cleanup;
62094   }
62095   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
62096   assert( iDb<db->nDb );
62097   zDb = db->aDb[iDb].zName;
62098   if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
62099     goto delete_from_cleanup;
62100   }
62101
62102   /* If pTab is really a view, make sure it has been initialized.
62103   */
62104   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
62105     goto delete_from_cleanup;
62106   }
62107
62108   /* Allocate a cursor used to store the old.* data for a trigger.
62109   */
62110   if( triggers_exist ){ 
62111     oldIdx = pParse->nTab++;
62112   }
62113
62114   /* Assign  cursor number to the table and all its indices.
62115   */
62116   assert( pTabList->nSrc==1 );
62117   iCur = pTabList->a[0].iCursor = pParse->nTab++;
62118   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
62119     pParse->nTab++;
62120   }
62121
62122   /* Start the view context
62123   */
62124   if( isView ){
62125     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
62126   }
62127
62128   /* Begin generating code.
62129   */
62130   v = sqlite3GetVdbe(pParse);
62131   if( v==0 ){
62132     goto delete_from_cleanup;
62133   }
62134   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
62135   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
62136
62137   if( triggers_exist ){
62138     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
62139     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
62140     addr = sqlite3VdbeMakeLabel(v);
62141
62142     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
62143     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
62144         -1, oldIdx, orconf, addr, &old_col_mask, 0);
62145     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
62146
62147     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
62148     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
62149         oldIdx, orconf, addr, &old_col_mask, 0);
62150     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
62151
62152     sqlite3VdbeJumpHere(v, iGoto);
62153   }
62154
62155   /* If we are trying to delete from a view, realize that view into
62156   ** a ephemeral table.
62157   */
62158 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
62159   if( isView ){
62160     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
62161   }
62162 #endif
62163
62164   /* Resolve the column names in the WHERE clause.
62165   */
62166   memset(&sNC, 0, sizeof(sNC));
62167   sNC.pParse = pParse;
62168   sNC.pSrcList = pTabList;
62169   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
62170     goto delete_from_cleanup;
62171   }
62172
62173   /* Initialize the counter of the number of rows deleted, if
62174   ** we are counting rows.
62175   */
62176   if( db->flags & SQLITE_CountRows ){
62177     memCnt = ++pParse->nMem;
62178     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
62179   }
62180
62181 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
62182   /* Special case: A DELETE without a WHERE clause deletes everything.
62183   ** It is easier just to erase the whole table.  Note, however, that
62184   ** this means that the row change count will be incorrect.
62185   */
62186   if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
62187     if( db->flags & SQLITE_CountRows ){
62188       /* If counting rows deleted, just count the total number of
62189       ** entries in the table. */
62190       int addr2;
62191       if( !isView ){
62192         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
62193       }
62194       sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2);
62195       addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
62196       sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2);
62197       sqlite3VdbeAddOp1(v, OP_Close, iCur);
62198     }
62199     if( !isView ){
62200       sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb);
62201       if( !pParse->nested ){
62202         sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
62203       }
62204       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
62205         assert( pIdx->pSchema==pTab->pSchema );
62206         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
62207       }
62208     }
62209   }else
62210 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
62211   /* The usual case: There is a WHERE clause so we have to scan through
62212   ** the table and pick which records to delete.
62213   */
62214   {
62215     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
62216
62217     /* Begin the database scan
62218     */
62219     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
62220     if( pWInfo==0 ) goto delete_from_cleanup;
62221
62222     /* Remember the rowid of every item to be deleted.
62223     */
62224     sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid);
62225     sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid);
62226     if( db->flags & SQLITE_CountRows ){
62227       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
62228     }
62229
62230     /* End the database scan loop.
62231     */
62232     sqlite3WhereEnd(pWInfo);
62233
62234     /* Open the pseudo-table used to store OLD if there are triggers.
62235     */
62236     if( triggers_exist ){
62237       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
62238       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
62239     }
62240
62241     /* Delete every item whose key was written to the list during the
62242     ** database scan.  We have to delete items after the scan is complete
62243     ** because deleting an item can change the scan order.
62244     */
62245     end = sqlite3VdbeMakeLabel(v);
62246
62247     if( !isView ){
62248       /* Open cursors for the table we are deleting from and 
62249       ** all its indices.
62250       */
62251       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
62252     }
62253
62254     /* This is the beginning of the delete loop. If a trigger encounters
62255     ** an IGNORE constraint, it jumps back to here.
62256     */
62257     if( triggers_exist ){
62258       sqlite3VdbeResolveLabel(v, addr);
62259     }
62260     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end);
62261
62262     if( triggers_exist ){
62263       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
62264
62265       /* If the record is no longer present in the table, jump to the
62266       ** next iteration of the loop through the contents of the fifo.
62267       */
62268       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
62269
62270       /* Populate the OLD.* pseudo-table */
62271       if( old_col_mask ){
62272         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
62273       }else{
62274         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
62275       }
62276       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
62277
62278       /* Jump back and run the BEFORE triggers */
62279       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
62280       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
62281     }
62282
62283     if( !isView ){
62284       /* Delete the row */
62285 #ifndef SQLITE_OMIT_VIRTUALTABLE
62286       if( IsVirtual(pTab) ){
62287         const char *pVtab = (const char *)pTab->pVtab;
62288         sqlite3VtabMakeWritable(pParse, pTab);
62289         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
62290       }else
62291 #endif
62292       {
62293         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
62294       }
62295     }
62296
62297     /* If there are row triggers, close all cursors then invoke
62298     ** the AFTER triggers
62299     */
62300     if( triggers_exist ){
62301       /* Jump back and run the AFTER triggers */
62302       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
62303       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
62304     }
62305
62306     /* End of the delete loop */
62307     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
62308     sqlite3VdbeResolveLabel(v, end);
62309
62310     /* Close the cursors after the loop if there are no row triggers */
62311     if( !isView  && !IsVirtual(pTab) ){
62312       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
62313         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
62314       }
62315       sqlite3VdbeAddOp1(v, OP_Close, iCur);
62316     }
62317   }
62318
62319   /*
62320   ** Return the number of rows that were deleted. If this routine is 
62321   ** generating code because of a call to sqlite3NestedParse(), do not
62322   ** invoke the callback function.
62323   */
62324   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
62325     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
62326     sqlite3VdbeSetNumCols(v, 1);
62327     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC);
62328   }
62329
62330 delete_from_cleanup:
62331   sqlite3AuthContextPop(&sContext);
62332   sqlite3SrcListDelete(db, pTabList);
62333   sqlite3ExprDelete(db, pWhere);
62334   return;
62335 }
62336
62337 /*
62338 ** This routine generates VDBE code that causes a single row of a
62339 ** single table to be deleted.
62340 **
62341 ** The VDBE must be in a particular state when this routine is called.
62342 ** These are the requirements:
62343 **
62344 **   1.  A read/write cursor pointing to pTab, the table containing the row
62345 **       to be deleted, must be opened as cursor number "base".
62346 **
62347 **   2.  Read/write cursors for all indices of pTab must be open as
62348 **       cursor number base+i for the i-th index.
62349 **
62350 **   3.  The record number of the row to be deleted must be stored in
62351 **       memory cell iRowid.
62352 **
62353 ** This routine pops the top of the stack to remove the record number
62354 ** and then generates code to remove both the table record and all index
62355 ** entries that point to that record.
62356 */
62357 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
62358   Parse *pParse,     /* Parsing context */
62359   Table *pTab,       /* Table containing the row to be deleted */
62360   int iCur,          /* Cursor number for the table */
62361   int iRowid,        /* Memory cell that contains the rowid to delete */
62362   int count          /* Increment the row change counter */
62363 ){
62364   int addr;
62365   Vdbe *v;
62366
62367   v = pParse->pVdbe;
62368   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
62369   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
62370   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
62371   if( count ){
62372     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
62373   }
62374   sqlite3VdbeJumpHere(v, addr);
62375 }
62376
62377 /*
62378 ** This routine generates VDBE code that causes the deletion of all
62379 ** index entries associated with a single row of a single table.
62380 **
62381 ** The VDBE must be in a particular state when this routine is called.
62382 ** These are the requirements:
62383 **
62384 **   1.  A read/write cursor pointing to pTab, the table containing the row
62385 **       to be deleted, must be opened as cursor number "iCur".
62386 **
62387 **   2.  Read/write cursors for all indices of pTab must be open as
62388 **       cursor number iCur+i for the i-th index.
62389 **
62390 **   3.  The "iCur" cursor must be pointing to the row that is to be
62391 **       deleted.
62392 */
62393 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
62394   Parse *pParse,     /* Parsing and code generating context */
62395   Table *pTab,       /* Table containing the row to be deleted */
62396   int iCur,          /* Cursor number for the table */
62397   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
62398 ){
62399   int i;
62400   Index *pIdx;
62401   int r1;
62402
62403   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
62404     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
62405     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
62406     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
62407   }
62408 }
62409
62410 /*
62411 ** Generate code that will assemble an index key and put it in register
62412 ** regOut.  The key with be for index pIdx which is an index on pTab.
62413 ** iCur is the index of a cursor open on the pTab table and pointing to
62414 ** the entry that needs indexing.
62415 **
62416 ** Return a register number which is the first in a block of
62417 ** registers that holds the elements of the index key.  The
62418 ** block of registers has already been deallocated by the time
62419 ** this routine returns.
62420 */
62421 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
62422   Parse *pParse,     /* Parsing context */
62423   Index *pIdx,       /* The index for which to generate a key */
62424   int iCur,          /* Cursor number for the pIdx->pTable table */
62425   int regOut,        /* Write the new index key to this register */
62426   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
62427 ){
62428   Vdbe *v = pParse->pVdbe;
62429   int j;
62430   Table *pTab = pIdx->pTable;
62431   int regBase;
62432   int nCol;
62433
62434   nCol = pIdx->nColumn;
62435   regBase = sqlite3GetTempRange(pParse, nCol+1);
62436   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
62437   for(j=0; j<nCol; j++){
62438     int idx = pIdx->aiColumn[j];
62439     if( idx==pTab->iPKey ){
62440       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
62441     }else{
62442       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
62443       sqlite3ColumnDefault(v, pTab, idx);
62444     }
62445   }
62446   if( doMakeRec ){
62447     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
62448     sqlite3IndexAffinityStr(v, pIdx);
62449     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
62450   }
62451   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
62452   return regBase;
62453 }
62454
62455 /* Make sure "isView" gets undefined in case this file becomes part of
62456 ** the amalgamation - so that subsequent files do not see isView as a
62457 ** macro. */
62458 #undef isView
62459
62460 /************** End of delete.c **********************************************/
62461 /************** Begin file func.c ********************************************/
62462 /*
62463 ** 2002 February 23
62464 **
62465 ** The author disclaims copyright to this source code.  In place of
62466 ** a legal notice, here is a blessing:
62467 **
62468 **    May you do good and not evil.
62469 **    May you find forgiveness for yourself and forgive others.
62470 **    May you share freely, never taking more than you give.
62471 **
62472 *************************************************************************
62473 ** This file contains the C functions that implement various SQL
62474 ** functions of SQLite.  
62475 **
62476 ** There is only one exported symbol in this file - the function
62477 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
62478 ** All other code has file scope.
62479 **
62480 ** $Id: func.c,v 1.203 2008/09/03 17:11:16 drh Exp $
62481 */
62482
62483 /*
62484 ** Return the collating function associated with a function.
62485 */
62486 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
62487   return context->pColl;
62488 }
62489
62490 /*
62491 ** Implementation of the non-aggregate min() and max() functions
62492 */
62493 static void minmaxFunc(
62494   sqlite3_context *context,
62495   int argc,
62496   sqlite3_value **argv
62497 ){
62498   int i;
62499   int mask;    /* 0 for min() or 0xffffffff for max() */
62500   int iBest;
62501   CollSeq *pColl;
62502
62503   if( argc==0 ) return;
62504   mask = sqlite3_user_data(context)==0 ? 0 : -1;
62505   pColl = sqlite3GetFuncCollSeq(context);
62506   assert( pColl );
62507   assert( mask==-1 || mask==0 );
62508   iBest = 0;
62509   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
62510   for(i=1; i<argc; i++){
62511     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
62512     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
62513       iBest = i;
62514     }
62515   }
62516   sqlite3_result_value(context, argv[iBest]);
62517 }
62518
62519 /*
62520 ** Return the type of the argument.
62521 */
62522 static void typeofFunc(
62523   sqlite3_context *context,
62524   int argc,
62525   sqlite3_value **argv
62526 ){
62527   const char *z = 0;
62528   switch( sqlite3_value_type(argv[0]) ){
62529     case SQLITE_NULL:    z = "null";    break;
62530     case SQLITE_INTEGER: z = "integer"; break;
62531     case SQLITE_TEXT:    z = "text";    break;
62532     case SQLITE_FLOAT:   z = "real";    break;
62533     case SQLITE_BLOB:    z = "blob";    break;
62534   }
62535   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
62536 }
62537
62538
62539 /*
62540 ** Implementation of the length() function
62541 */
62542 static void lengthFunc(
62543   sqlite3_context *context,
62544   int argc,
62545   sqlite3_value **argv
62546 ){
62547   int len;
62548
62549   assert( argc==1 );
62550   switch( sqlite3_value_type(argv[0]) ){
62551     case SQLITE_BLOB:
62552     case SQLITE_INTEGER:
62553     case SQLITE_FLOAT: {
62554       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
62555       break;
62556     }
62557     case SQLITE_TEXT: {
62558       const unsigned char *z = sqlite3_value_text(argv[0]);
62559       if( z==0 ) return;
62560       len = 0;
62561       while( *z ){
62562         len++;
62563         SQLITE_SKIP_UTF8(z);
62564       }
62565       sqlite3_result_int(context, len);
62566       break;
62567     }
62568     default: {
62569       sqlite3_result_null(context);
62570       break;
62571     }
62572   }
62573 }
62574
62575 /*
62576 ** Implementation of the abs() function
62577 */
62578 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62579   assert( argc==1 );
62580   switch( sqlite3_value_type(argv[0]) ){
62581     case SQLITE_INTEGER: {
62582       i64 iVal = sqlite3_value_int64(argv[0]);
62583       if( iVal<0 ){
62584         if( (iVal<<1)==0 ){
62585           sqlite3_result_error(context, "integer overflow", -1);
62586           return;
62587         }
62588         iVal = -iVal;
62589       } 
62590       sqlite3_result_int64(context, iVal);
62591       break;
62592     }
62593     case SQLITE_NULL: {
62594       sqlite3_result_null(context);
62595       break;
62596     }
62597     default: {
62598       double rVal = sqlite3_value_double(argv[0]);
62599       if( rVal<0 ) rVal = -rVal;
62600       sqlite3_result_double(context, rVal);
62601       break;
62602     }
62603   }
62604 }
62605
62606 /*
62607 ** Implementation of the substr() function.
62608 **
62609 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
62610 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
62611 ** of x.  If x is text, then we actually count UTF-8 characters.
62612 ** If x is a blob, then we count bytes.
62613 **
62614 ** If p1 is negative, then we begin abs(p1) from the end of x[].
62615 */
62616 static void substrFunc(
62617   sqlite3_context *context,
62618   int argc,
62619   sqlite3_value **argv
62620 ){
62621   const unsigned char *z;
62622   const unsigned char *z2;
62623   int len;
62624   int p0type;
62625   i64 p1, p2;
62626
62627   assert( argc==3 || argc==2 );
62628   p0type = sqlite3_value_type(argv[0]);
62629   if( p0type==SQLITE_BLOB ){
62630     len = sqlite3_value_bytes(argv[0]);
62631     z = sqlite3_value_blob(argv[0]);
62632     if( z==0 ) return;
62633     assert( len==sqlite3_value_bytes(argv[0]) );
62634   }else{
62635     z = sqlite3_value_text(argv[0]);
62636     if( z==0 ) return;
62637     len = 0;
62638     for(z2=z; *z2; len++){
62639       SQLITE_SKIP_UTF8(z2);
62640     }
62641   }
62642   p1 = sqlite3_value_int(argv[1]);
62643   if( argc==3 ){
62644     p2 = sqlite3_value_int(argv[2]);
62645   }else{
62646     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
62647   }
62648   if( p1<0 ){
62649     p1 += len;
62650     if( p1<0 ){
62651       p2 += p1;
62652       p1 = 0;
62653     }
62654   }else if( p1>0 ){
62655     p1--;
62656   }
62657   if( p1+p2>len ){
62658     p2 = len-p1;
62659   }
62660   if( p0type!=SQLITE_BLOB ){
62661     while( *z && p1 ){
62662       SQLITE_SKIP_UTF8(z);
62663       p1--;
62664     }
62665     for(z2=z; *z2 && p2; p2--){
62666       SQLITE_SKIP_UTF8(z2);
62667     }
62668     sqlite3_result_text(context, (char*)z, z2-z, SQLITE_TRANSIENT);
62669   }else{
62670     if( p2<0 ) p2 = 0;
62671     sqlite3_result_blob(context, (char*)&z[p1], p2, SQLITE_TRANSIENT);
62672   }
62673 }
62674
62675 /*
62676 ** Implementation of the round() function
62677 */
62678 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62679   int n = 0;
62680   double r;
62681   char zBuf[500];  /* larger than the %f representation of the largest double */
62682   assert( argc==1 || argc==2 );
62683   if( argc==2 ){
62684     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
62685     n = sqlite3_value_int(argv[1]);
62686     if( n>30 ) n = 30;
62687     if( n<0 ) n = 0;
62688   }
62689   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
62690   r = sqlite3_value_double(argv[0]);
62691   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
62692   sqlite3AtoF(zBuf, &r);
62693   sqlite3_result_double(context, r);
62694 }
62695
62696 /*
62697 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
62698 ** allocation fails, call sqlite3_result_error_nomem() to notify
62699 ** the database handle that malloc() has failed.
62700 */
62701 static void *contextMalloc(sqlite3_context *context, i64 nByte){
62702   char *z;
62703   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
62704     sqlite3_result_error_toobig(context);
62705     z = 0;
62706   }else{
62707     z = sqlite3Malloc(nByte);
62708     if( !z && nByte>0 ){
62709       sqlite3_result_error_nomem(context);
62710     }
62711   }
62712   return z;
62713 }
62714
62715 /*
62716 ** Implementation of the upper() and lower() SQL functions.
62717 */
62718 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62719   char *z1;
62720   const char *z2;
62721   int i, n;
62722   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
62723   z2 = (char*)sqlite3_value_text(argv[0]);
62724   n = sqlite3_value_bytes(argv[0]);
62725   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
62726   assert( z2==(char*)sqlite3_value_text(argv[0]) );
62727   if( z2 ){
62728     z1 = contextMalloc(context, ((i64)n)+1);
62729     if( z1 ){
62730       memcpy(z1, z2, n+1);
62731       for(i=0; z1[i]; i++){
62732         z1[i] = toupper(z1[i]);
62733       }
62734       sqlite3_result_text(context, z1, -1, sqlite3_free);
62735     }
62736   }
62737 }
62738 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
62739   char *z1;
62740   const char *z2;
62741   int i, n;
62742   if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
62743   z2 = (char*)sqlite3_value_text(argv[0]);
62744   n = sqlite3_value_bytes(argv[0]);
62745   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
62746   assert( z2==(char*)sqlite3_value_text(argv[0]) );
62747   if( z2 ){
62748     z1 = contextMalloc(context, ((i64)n)+1);
62749     if( z1 ){
62750       memcpy(z1, z2, n+1);
62751       for(i=0; z1[i]; i++){
62752         z1[i] = tolower(z1[i]);
62753       }
62754       sqlite3_result_text(context, z1, -1, sqlite3_free);
62755     }
62756   }
62757 }
62758
62759 /*
62760 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
62761 ** All three do the same thing.  They return the first non-NULL
62762 ** argument.
62763 */
62764 static void ifnullFunc(
62765   sqlite3_context *context,
62766   int argc,
62767   sqlite3_value **argv
62768 ){
62769   int i;
62770   for(i=0; i<argc; i++){
62771     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
62772       sqlite3_result_value(context, argv[i]);
62773       break;
62774     }
62775   }
62776 }
62777
62778 /*
62779 ** Implementation of random().  Return a random integer.  
62780 */
62781 static void randomFunc(
62782   sqlite3_context *context,
62783   int argc,
62784   sqlite3_value **argv
62785 ){
62786   sqlite_int64 r;
62787   sqlite3_randomness(sizeof(r), &r);
62788   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
62789                           /* can always do abs() of the result */
62790   sqlite3_result_int64(context, r);
62791 }
62792
62793 /*
62794 ** Implementation of randomblob(N).  Return a random blob
62795 ** that is N bytes long.
62796 */
62797 static void randomBlob(
62798   sqlite3_context *context,
62799   int argc,
62800   sqlite3_value **argv
62801 ){
62802   int n;
62803   unsigned char *p;
62804   assert( argc==1 );
62805   n = sqlite3_value_int(argv[0]);
62806   if( n<1 ){
62807     n = 1;
62808   }
62809   p = contextMalloc(context, n);
62810   if( p ){
62811     sqlite3_randomness(n, p);
62812     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
62813   }
62814 }
62815
62816 /*
62817 ** Implementation of the last_insert_rowid() SQL function.  The return
62818 ** value is the same as the sqlite3_last_insert_rowid() API function.
62819 */
62820 static void last_insert_rowid(
62821   sqlite3_context *context, 
62822   int arg, 
62823   sqlite3_value **argv
62824 ){
62825   sqlite3 *db = sqlite3_context_db_handle(context);
62826   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
62827 }
62828
62829 /*
62830 ** Implementation of the changes() SQL function.  The return value is the
62831 ** same as the sqlite3_changes() API function.
62832 */
62833 static void changes(
62834   sqlite3_context *context,
62835   int arg,
62836   sqlite3_value **argv
62837 ){
62838   sqlite3 *db = sqlite3_context_db_handle(context);
62839   sqlite3_result_int(context, sqlite3_changes(db));
62840 }
62841
62842 /*
62843 ** Implementation of the total_changes() SQL function.  The return value is
62844 ** the same as the sqlite3_total_changes() API function.
62845 */
62846 static void total_changes(
62847   sqlite3_context *context,
62848   int arg,
62849   sqlite3_value **argv
62850 ){
62851   sqlite3 *db = sqlite3_context_db_handle(context);
62852   sqlite3_result_int(context, sqlite3_total_changes(db));
62853 }
62854
62855 /*
62856 ** A structure defining how to do GLOB-style comparisons.
62857 */
62858 struct compareInfo {
62859   u8 matchAll;
62860   u8 matchOne;
62861   u8 matchSet;
62862   u8 noCase;
62863 };
62864
62865 /*
62866 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
62867 ** character is exactly one byte in size.  Also, all characters are
62868 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
62869 ** whereas only characters less than 0x80 do in ASCII.
62870 */
62871 #if defined(SQLITE_EBCDIC)
62872 # define sqlite3Utf8Read(A,B,C)  (*(A++))
62873 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
62874 #else
62875 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
62876 #endif
62877
62878 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
62879 /* The correct SQL-92 behavior is for the LIKE operator to ignore
62880 ** case.  Thus  'a' LIKE 'A' would be true. */
62881 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
62882 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
62883 ** is case sensitive causing 'a' LIKE 'A' to be false */
62884 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
62885
62886 /*
62887 ** Compare two UTF-8 strings for equality where the first string can
62888 ** potentially be a "glob" expression.  Return true (1) if they
62889 ** are the same and false (0) if they are different.
62890 **
62891 ** Globbing rules:
62892 **
62893 **      '*'       Matches any sequence of zero or more characters.
62894 **
62895 **      '?'       Matches exactly one character.
62896 **
62897 **     [...]      Matches one character from the enclosed list of
62898 **                characters.
62899 **
62900 **     [^...]     Matches one character not in the enclosed list.
62901 **
62902 ** With the [...] and [^...] matching, a ']' character can be included
62903 ** in the list by making it the first character after '[' or '^'.  A
62904 ** range of characters can be specified using '-'.  Example:
62905 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
62906 ** it the last character in the list.
62907 **
62908 ** This routine is usually quick, but can be N**2 in the worst case.
62909 **
62910 ** Hints: to match '*' or '?', put them in "[]".  Like this:
62911 **
62912 **         abc[*]xyz        Matches "abc*xyz" only
62913 */
62914 static int patternCompare(
62915   const u8 *zPattern,              /* The glob pattern */
62916   const u8 *zString,               /* The string to compare against the glob */
62917   const struct compareInfo *pInfo, /* Information about how to do the compare */
62918   const int esc                    /* The escape character */
62919 ){
62920   int c, c2;
62921   int invert;
62922   int seen;
62923   u8 matchOne = pInfo->matchOne;
62924   u8 matchAll = pInfo->matchAll;
62925   u8 matchSet = pInfo->matchSet;
62926   u8 noCase = pInfo->noCase; 
62927   int prevEscape = 0;     /* True if the previous character was 'escape' */
62928
62929   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
62930     if( !prevEscape && c==matchAll ){
62931       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
62932                || c == matchOne ){
62933         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
62934           return 0;
62935         }
62936       }
62937       if( c==0 ){
62938         return 1;
62939       }else if( c==esc ){
62940         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
62941         if( c==0 ){
62942           return 0;
62943         }
62944       }else if( c==matchSet ){
62945         assert( esc==0 );         /* This is GLOB, not LIKE */
62946         assert( matchSet<0x80 );  /* '[' is a single-byte character */
62947         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
62948           SQLITE_SKIP_UTF8(zString);
62949         }
62950         return *zString!=0;
62951       }
62952       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
62953         if( noCase ){
62954           GlogUpperToLower(c2);
62955           GlogUpperToLower(c);
62956           while( c2 != 0 && c2 != c ){
62957             c2 = sqlite3Utf8Read(zString, 0, &zString);
62958             GlogUpperToLower(c2);
62959           }
62960         }else{
62961           while( c2 != 0 && c2 != c ){
62962             c2 = sqlite3Utf8Read(zString, 0, &zString);
62963           }
62964         }
62965         if( c2==0 ) return 0;
62966         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
62967       }
62968       return 0;
62969     }else if( !prevEscape && c==matchOne ){
62970       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
62971         return 0;
62972       }
62973     }else if( c==matchSet ){
62974       int prior_c = 0;
62975       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
62976       seen = 0;
62977       invert = 0;
62978       c = sqlite3Utf8Read(zString, 0, &zString);
62979       if( c==0 ) return 0;
62980       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62981       if( c2=='^' ){
62982         invert = 1;
62983         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62984       }
62985       if( c2==']' ){
62986         if( c==']' ) seen = 1;
62987         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62988       }
62989       while( c2 && c2!=']' ){
62990         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
62991           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
62992           if( c>=prior_c && c<=c2 ) seen = 1;
62993           prior_c = 0;
62994         }else{
62995           if( c==c2 ){
62996             seen = 1;
62997           }
62998           prior_c = c2;
62999         }
63000         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
63001       }
63002       if( c2==0 || (seen ^ invert)==0 ){
63003         return 0;
63004       }
63005     }else if( esc==c && !prevEscape ){
63006       prevEscape = 1;
63007     }else{
63008       c2 = sqlite3Utf8Read(zString, 0, &zString);
63009       if( noCase ){
63010         GlogUpperToLower(c);
63011         GlogUpperToLower(c2);
63012       }
63013       if( c!=c2 ){
63014         return 0;
63015       }
63016       prevEscape = 0;
63017     }
63018   }
63019   return *zString==0;
63020 }
63021
63022 /*
63023 ** Count the number of times that the LIKE operator (or GLOB which is
63024 ** just a variation of LIKE) gets called.  This is used for testing
63025 ** only.
63026 */
63027 #ifdef SQLITE_TEST
63028 SQLITE_API int sqlite3_like_count = 0;
63029 #endif
63030
63031
63032 /*
63033 ** Implementation of the like() SQL function.  This function implements
63034 ** the build-in LIKE operator.  The first argument to the function is the
63035 ** pattern and the second argument is the string.  So, the SQL statements:
63036 **
63037 **       A LIKE B
63038 **
63039 ** is implemented as like(B,A).
63040 **
63041 ** This same function (with a different compareInfo structure) computes
63042 ** the GLOB operator.
63043 */
63044 static void likeFunc(
63045   sqlite3_context *context, 
63046   int argc, 
63047   sqlite3_value **argv
63048 ){
63049   const unsigned char *zA, *zB;
63050   int escape = 0;
63051   sqlite3 *db = sqlite3_context_db_handle(context);
63052
63053   zB = sqlite3_value_text(argv[0]);
63054   zA = sqlite3_value_text(argv[1]);
63055
63056   /* Limit the length of the LIKE or GLOB pattern to avoid problems
63057   ** of deep recursion and N*N behavior in patternCompare().
63058   */
63059   if( sqlite3_value_bytes(argv[0]) >
63060         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
63061     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
63062     return;
63063   }
63064   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
63065
63066   if( argc==3 ){
63067     /* The escape character string must consist of a single UTF-8 character.
63068     ** Otherwise, return an error.
63069     */
63070     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
63071     if( zEsc==0 ) return;
63072     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
63073       sqlite3_result_error(context, 
63074           "ESCAPE expression must be a single character", -1);
63075       return;
63076     }
63077     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
63078   }
63079   if( zA && zB ){
63080     struct compareInfo *pInfo = sqlite3_user_data(context);
63081 #ifdef SQLITE_TEST
63082     sqlite3_like_count++;
63083 #endif
63084     
63085     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
63086   }
63087 }
63088
63089 /*
63090 ** Implementation of the NULLIF(x,y) function.  The result is the first
63091 ** argument if the arguments are different.  The result is NULL if the
63092 ** arguments are equal to each other.
63093 */
63094 static void nullifFunc(
63095   sqlite3_context *context,
63096   int argc,
63097   sqlite3_value **argv
63098 ){
63099   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
63100   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
63101     sqlite3_result_value(context, argv[0]);
63102   }
63103 }
63104
63105 /*
63106 ** Implementation of the VERSION(*) function.  The result is the version
63107 ** of the SQLite library that is running.
63108 */
63109 static void versionFunc(
63110   sqlite3_context *context,
63111   int argc,
63112   sqlite3_value **argv
63113 ){
63114   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
63115 }
63116
63117 /* Array for converting from half-bytes (nybbles) into ASCII hex
63118 ** digits. */
63119 static const char hexdigits[] = {
63120   '0', '1', '2', '3', '4', '5', '6', '7',
63121   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
63122 };
63123
63124 /*
63125 ** EXPERIMENTAL - This is not an official function.  The interface may
63126 ** change.  This function may disappear.  Do not write code that depends
63127 ** on this function.
63128 **
63129 ** Implementation of the QUOTE() function.  This function takes a single
63130 ** argument.  If the argument is numeric, the return value is the same as
63131 ** the argument.  If the argument is NULL, the return value is the string
63132 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
63133 ** single-quote escapes.
63134 */
63135 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
63136   if( argc<1 ) return;
63137   switch( sqlite3_value_type(argv[0]) ){
63138     case SQLITE_NULL: {
63139       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
63140       break;
63141     }
63142     case SQLITE_INTEGER:
63143     case SQLITE_FLOAT: {
63144       sqlite3_result_value(context, argv[0]);
63145       break;
63146     }
63147     case SQLITE_BLOB: {
63148       char *zText = 0;
63149       char const *zBlob = sqlite3_value_blob(argv[0]);
63150       int nBlob = sqlite3_value_bytes(argv[0]);
63151       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
63152       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
63153       if( zText ){
63154         int i;
63155         for(i=0; i<nBlob; i++){
63156           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
63157           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
63158         }
63159         zText[(nBlob*2)+2] = '\'';
63160         zText[(nBlob*2)+3] = '\0';
63161         zText[0] = 'X';
63162         zText[1] = '\'';
63163         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
63164         sqlite3_free(zText);
63165       }
63166       break;
63167     }
63168     case SQLITE_TEXT: {
63169       int i,j;
63170       u64 n;
63171       const unsigned char *zArg = sqlite3_value_text(argv[0]);
63172       char *z;
63173
63174       if( zArg==0 ) return;
63175       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
63176       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
63177       if( z ){
63178         z[0] = '\'';
63179         for(i=0, j=1; zArg[i]; i++){
63180           z[j++] = zArg[i];
63181           if( zArg[i]=='\'' ){
63182             z[j++] = '\'';
63183           }
63184         }
63185         z[j++] = '\'';
63186         z[j] = 0;
63187         sqlite3_result_text(context, z, j, sqlite3_free);
63188       }
63189     }
63190   }
63191 }
63192
63193 /*
63194 ** The hex() function.  Interpret the argument as a blob.  Return
63195 ** a hexadecimal rendering as text.
63196 */
63197 static void hexFunc(
63198   sqlite3_context *context,
63199   int argc,
63200   sqlite3_value **argv
63201 ){
63202   int i, n;
63203   const unsigned char *pBlob;
63204   char *zHex, *z;
63205   assert( argc==1 );
63206   pBlob = sqlite3_value_blob(argv[0]);
63207   n = sqlite3_value_bytes(argv[0]);
63208   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
63209   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
63210   if( zHex ){
63211     for(i=0; i<n; i++, pBlob++){
63212       unsigned char c = *pBlob;
63213       *(z++) = hexdigits[(c>>4)&0xf];
63214       *(z++) = hexdigits[c&0xf];
63215     }
63216     *z = 0;
63217     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
63218   }
63219 }
63220
63221 /*
63222 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
63223 */
63224 static void zeroblobFunc(
63225   sqlite3_context *context,
63226   int argc,
63227   sqlite3_value **argv
63228 ){
63229   i64 n;
63230   assert( argc==1 );
63231   n = sqlite3_value_int64(argv[0]);
63232   if( n>SQLITE_MAX_LENGTH ){
63233     sqlite3_result_error_toobig(context);
63234   }else{
63235     sqlite3_result_zeroblob(context, n);
63236   }
63237 }
63238
63239 /*
63240 ** The replace() function.  Three arguments are all strings: call
63241 ** them A, B, and C. The result is also a string which is derived
63242 ** from A by replacing every occurance of B with C.  The match
63243 ** must be exact.  Collating sequences are not used.
63244 */
63245 static void replaceFunc(
63246   sqlite3_context *context,
63247   int argc,
63248   sqlite3_value **argv
63249 ){
63250   const unsigned char *zStr;        /* The input string A */
63251   const unsigned char *zPattern;    /* The pattern string B */
63252   const unsigned char *zRep;        /* The replacement string C */
63253   unsigned char *zOut;              /* The output */
63254   int nStr;                /* Size of zStr */
63255   int nPattern;            /* Size of zPattern */
63256   int nRep;                /* Size of zRep */
63257   i64 nOut;                /* Maximum size of zOut */
63258   int loopLimit;           /* Last zStr[] that might match zPattern[] */
63259   int i, j;                /* Loop counters */
63260
63261   assert( argc==3 );
63262   zStr = sqlite3_value_text(argv[0]);
63263   if( zStr==0 ) return;
63264   nStr = sqlite3_value_bytes(argv[0]);
63265   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
63266   zPattern = sqlite3_value_text(argv[1]);
63267   if( zPattern==0 || zPattern[0]==0 ) return;
63268   nPattern = sqlite3_value_bytes(argv[1]);
63269   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
63270   zRep = sqlite3_value_text(argv[2]);
63271   if( zRep==0 ) return;
63272   nRep = sqlite3_value_bytes(argv[2]);
63273   assert( zRep==sqlite3_value_text(argv[2]) );
63274   nOut = nStr + 1;
63275   assert( nOut<SQLITE_MAX_LENGTH );
63276   zOut = contextMalloc(context, (i64)nOut);
63277   if( zOut==0 ){
63278     return;
63279   }
63280   loopLimit = nStr - nPattern;  
63281   for(i=j=0; i<=loopLimit; i++){
63282     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
63283       zOut[j++] = zStr[i];
63284     }else{
63285       u8 *zOld;
63286       sqlite3 *db = sqlite3_context_db_handle(context);
63287       nOut += nRep - nPattern;
63288       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
63289         sqlite3_result_error_toobig(context);
63290         sqlite3DbFree(db, zOut);
63291         return;
63292       }
63293       zOld = zOut;
63294       zOut = sqlite3_realloc(zOut, (int)nOut);
63295       if( zOut==0 ){
63296         sqlite3_result_error_nomem(context);
63297         sqlite3DbFree(db, zOld);
63298         return;
63299       }
63300       memcpy(&zOut[j], zRep, nRep);
63301       j += nRep;
63302       i += nPattern-1;
63303     }
63304   }
63305   assert( j+nStr-i+1==nOut );
63306   memcpy(&zOut[j], &zStr[i], nStr-i);
63307   j += nStr - i;
63308   assert( j<=nOut );
63309   zOut[j] = 0;
63310   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
63311 }
63312
63313 /*
63314 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
63315 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
63316 */
63317 static void trimFunc(
63318   sqlite3_context *context,
63319   int argc,
63320   sqlite3_value **argv
63321 ){
63322   const unsigned char *zIn;         /* Input string */
63323   const unsigned char *zCharSet;    /* Set of characters to trim */
63324   int nIn;                          /* Number of bytes in input */
63325   int flags;                        /* 1: trimleft  2: trimright  3: trim */
63326   int i;                            /* Loop counter */
63327   unsigned char *aLen;              /* Length of each character in zCharSet */
63328   unsigned char **azChar;           /* Individual characters in zCharSet */
63329   int nChar;                        /* Number of characters in zCharSet */
63330
63331   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
63332     return;
63333   }
63334   zIn = sqlite3_value_text(argv[0]);
63335   if( zIn==0 ) return;
63336   nIn = sqlite3_value_bytes(argv[0]);
63337   assert( zIn==sqlite3_value_text(argv[0]) );
63338   if( argc==1 ){
63339     static const unsigned char lenOne[] = { 1 };
63340     static unsigned char * const azOne[] = { (u8*)" " };
63341     nChar = 1;
63342     aLen = (u8*)lenOne;
63343     azChar = (unsigned char **)azOne;
63344     zCharSet = 0;
63345   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
63346     return;
63347   }else{
63348     const unsigned char *z;
63349     for(z=zCharSet, nChar=0; *z; nChar++){
63350       SQLITE_SKIP_UTF8(z);
63351     }
63352     if( nChar>0 ){
63353       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
63354       if( azChar==0 ){
63355         return;
63356       }
63357       aLen = (unsigned char*)&azChar[nChar];
63358       for(z=zCharSet, nChar=0; *z; nChar++){
63359         azChar[nChar] = (unsigned char *)z;
63360         SQLITE_SKIP_UTF8(z);
63361         aLen[nChar] = z - azChar[nChar];
63362       }
63363     }
63364   }
63365   if( nChar>0 ){
63366     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
63367     if( flags & 1 ){
63368       while( nIn>0 ){
63369         int len;
63370         for(i=0; i<nChar; i++){
63371           len = aLen[i];
63372           if( memcmp(zIn, azChar[i], len)==0 ) break;
63373         }
63374         if( i>=nChar ) break;
63375         zIn += len;
63376         nIn -= len;
63377       }
63378     }
63379     if( flags & 2 ){
63380       while( nIn>0 ){
63381         int len;
63382         for(i=0; i<nChar; i++){
63383           len = aLen[i];
63384           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
63385         }
63386         if( i>=nChar ) break;
63387         nIn -= len;
63388       }
63389     }
63390     if( zCharSet ){
63391       sqlite3_free(azChar);
63392     }
63393   }
63394   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
63395 }
63396
63397
63398 #ifdef SQLITE_SOUNDEX
63399 /*
63400 ** Compute the soundex encoding of a word.
63401 */
63402 static void soundexFunc(
63403   sqlite3_context *context,
63404   int argc,
63405   sqlite3_value **argv
63406 ){
63407   char zResult[8];
63408   const u8 *zIn;
63409   int i, j;
63410   static const unsigned char iCode[] = {
63411     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63412     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63413     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63414     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63415     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
63416     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
63417     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
63418     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
63419   };
63420   assert( argc==1 );
63421   zIn = (u8*)sqlite3_value_text(argv[0]);
63422   if( zIn==0 ) zIn = (u8*)"";
63423   for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
63424   if( zIn[i] ){
63425     u8 prevcode = iCode[zIn[i]&0x7f];
63426     zResult[0] = toupper(zIn[i]);
63427     for(j=1; j<4 && zIn[i]; i++){
63428       int code = iCode[zIn[i]&0x7f];
63429       if( code>0 ){
63430         if( code!=prevcode ){
63431           prevcode = code;
63432           zResult[j++] = code + '0';
63433         }
63434       }else{
63435         prevcode = 0;
63436       }
63437     }
63438     while( j<4 ){
63439       zResult[j++] = '0';
63440     }
63441     zResult[j] = 0;
63442     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
63443   }else{
63444     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
63445   }
63446 }
63447 #endif
63448
63449 #ifndef SQLITE_OMIT_LOAD_EXTENSION
63450 /*
63451 ** A function that loads a shared-library extension then returns NULL.
63452 */
63453 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
63454   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
63455   const char *zProc;
63456   sqlite3 *db = sqlite3_context_db_handle(context);
63457   char *zErrMsg = 0;
63458
63459   if( argc==2 ){
63460     zProc = (const char *)sqlite3_value_text(argv[1]);
63461   }else{
63462     zProc = 0;
63463   }
63464   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
63465     sqlite3_result_error(context, zErrMsg, -1);
63466     sqlite3_free(zErrMsg);
63467   }
63468 }
63469 #endif
63470
63471
63472 /*
63473 ** An instance of the following structure holds the context of a
63474 ** sum() or avg() aggregate computation.
63475 */
63476 typedef struct SumCtx SumCtx;
63477 struct SumCtx {
63478   double rSum;      /* Floating point sum */
63479   i64 iSum;         /* Integer sum */   
63480   i64 cnt;          /* Number of elements summed */
63481   u8 overflow;      /* True if integer overflow seen */
63482   u8 approx;        /* True if non-integer value was input to the sum */
63483 };
63484
63485 /*
63486 ** Routines used to compute the sum, average, and total.
63487 **
63488 ** The SUM() function follows the (broken) SQL standard which means
63489 ** that it returns NULL if it sums over no inputs.  TOTAL returns
63490 ** 0.0 in that case.  In addition, TOTAL always returns a float where
63491 ** SUM might return an integer if it never encounters a floating point
63492 ** value.  TOTAL never fails, but SUM might through an exception if
63493 ** it overflows an integer.
63494 */
63495 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63496   SumCtx *p;
63497   int type;
63498   assert( argc==1 );
63499   p = sqlite3_aggregate_context(context, sizeof(*p));
63500   type = sqlite3_value_numeric_type(argv[0]);
63501   if( p && type!=SQLITE_NULL ){
63502     p->cnt++;
63503     if( type==SQLITE_INTEGER ){
63504       i64 v = sqlite3_value_int64(argv[0]);
63505       p->rSum += v;
63506       if( (p->approx|p->overflow)==0 ){
63507         i64 iNewSum = p->iSum + v;
63508         int s1 = p->iSum >> (sizeof(i64)*8-1);
63509         int s2 = v       >> (sizeof(i64)*8-1);
63510         int s3 = iNewSum >> (sizeof(i64)*8-1);
63511         p->overflow = (s1&s2&~s3) | (~s1&~s2&s3);
63512         p->iSum = iNewSum;
63513       }
63514     }else{
63515       p->rSum += sqlite3_value_double(argv[0]);
63516       p->approx = 1;
63517     }
63518   }
63519 }
63520 static void sumFinalize(sqlite3_context *context){
63521   SumCtx *p;
63522   p = sqlite3_aggregate_context(context, 0);
63523   if( p && p->cnt>0 ){
63524     if( p->overflow ){
63525       sqlite3_result_error(context,"integer overflow",-1);
63526     }else if( p->approx ){
63527       sqlite3_result_double(context, p->rSum);
63528     }else{
63529       sqlite3_result_int64(context, p->iSum);
63530     }
63531   }
63532 }
63533 static void avgFinalize(sqlite3_context *context){
63534   SumCtx *p;
63535   p = sqlite3_aggregate_context(context, 0);
63536   if( p && p->cnt>0 ){
63537     sqlite3_result_double(context, p->rSum/(double)p->cnt);
63538   }
63539 }
63540 static void totalFinalize(sqlite3_context *context){
63541   SumCtx *p;
63542   p = sqlite3_aggregate_context(context, 0);
63543   sqlite3_result_double(context, p ? p->rSum : 0.0);
63544 }
63545
63546 /*
63547 ** The following structure keeps track of state information for the
63548 ** count() aggregate function.
63549 */
63550 typedef struct CountCtx CountCtx;
63551 struct CountCtx {
63552   i64 n;
63553 };
63554
63555 /*
63556 ** Routines to implement the count() aggregate function.
63557 */
63558 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63559   CountCtx *p;
63560   p = sqlite3_aggregate_context(context, sizeof(*p));
63561   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
63562     p->n++;
63563   }
63564 }   
63565 static void countFinalize(sqlite3_context *context){
63566   CountCtx *p;
63567   p = sqlite3_aggregate_context(context, 0);
63568   sqlite3_result_int64(context, p ? p->n : 0);
63569 }
63570
63571 /*
63572 ** Routines to implement min() and max() aggregate functions.
63573 */
63574 static void minmaxStep(sqlite3_context *context, int argc, sqlite3_value **argv){
63575   Mem *pArg  = (Mem *)argv[0];
63576   Mem *pBest;
63577
63578   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63579   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
63580   if( !pBest ) return;
63581
63582   if( pBest->flags ){
63583     int max;
63584     int cmp;
63585     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
63586     /* This step function is used for both the min() and max() aggregates,
63587     ** the only difference between the two being that the sense of the
63588     ** comparison is inverted. For the max() aggregate, the
63589     ** sqlite3_user_data() function returns (void *)-1. For min() it
63590     ** returns (void *)db, where db is the sqlite3* database pointer.
63591     ** Therefore the next statement sets variable 'max' to 1 for the max()
63592     ** aggregate, or 0 for min().
63593     */
63594     max = sqlite3_user_data(context)!=0;
63595     cmp = sqlite3MemCompare(pBest, pArg, pColl);
63596     if( (max && cmp<0) || (!max && cmp>0) ){
63597       sqlite3VdbeMemCopy(pBest, pArg);
63598     }
63599   }else{
63600     sqlite3VdbeMemCopy(pBest, pArg);
63601   }
63602 }
63603 static void minMaxFinalize(sqlite3_context *context){
63604   sqlite3_value *pRes;
63605   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
63606   if( pRes ){
63607     if( pRes->flags ){
63608       sqlite3_result_value(context, pRes);
63609     }
63610     sqlite3VdbeMemRelease(pRes);
63611   }
63612 }
63613
63614 /*
63615 ** group_concat(EXPR, ?SEPARATOR?)
63616 */
63617 static void groupConcatStep(
63618   sqlite3_context *context,
63619   int argc,
63620   sqlite3_value **argv
63621 ){
63622   const char *zVal;
63623   StrAccum *pAccum;
63624   const char *zSep;
63625   int nVal, nSep, i;
63626   if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
63627   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
63628
63629   if( pAccum ){
63630     sqlite3 *db = sqlite3_context_db_handle(context);
63631     pAccum->useMalloc = 1;
63632     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
63633     if( pAccum->nChar ){
63634       if( argc>1 ){
63635         zSep = (char*)sqlite3_value_text(argv[argc-1]);
63636         nSep = sqlite3_value_bytes(argv[argc-1]);
63637       }else{
63638         zSep = ",";
63639         nSep = 1;
63640       }
63641       sqlite3StrAccumAppend(pAccum, zSep, nSep);
63642     }
63643     i = 0;
63644     do{
63645       zVal = (char*)sqlite3_value_text(argv[i]);
63646       nVal = sqlite3_value_bytes(argv[i]);
63647       sqlite3StrAccumAppend(pAccum, zVal, nVal);
63648       i++;
63649     }while( i<argc-1 );
63650   }
63651 }
63652 static void groupConcatFinalize(sqlite3_context *context){
63653   StrAccum *pAccum;
63654   pAccum = sqlite3_aggregate_context(context, 0);
63655   if( pAccum ){
63656     if( pAccum->tooBig ){
63657       sqlite3_result_error_toobig(context);
63658     }else if( pAccum->mallocFailed ){
63659       sqlite3_result_error_nomem(context);
63660     }else{    
63661       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
63662                           sqlite3_free);
63663     }
63664   }
63665 }
63666
63667 /*
63668 ** This function registered all of the above C functions as SQL
63669 ** functions.  This should be the only routine in this file with
63670 ** external linkage.
63671 */
63672 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
63673 #ifndef SQLITE_OMIT_ALTERTABLE
63674   sqlite3AlterFunctions(db);
63675 #endif
63676 #ifndef SQLITE_OMIT_PARSER
63677   sqlite3AttachFunctions(db);
63678 #endif
63679   if( !db->mallocFailed ){
63680     int rc = sqlite3_overload_function(db, "MATCH", 2);
63681     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
63682     if( rc==SQLITE_NOMEM ){
63683       db->mallocFailed = 1;
63684     }
63685   }
63686 #ifdef SQLITE_SSE
63687   (void)sqlite3SseFunctions(db);
63688 #endif
63689 }
63690
63691 /*
63692 ** Set the LIKEOPT flag on the 2-argument function with the given name.
63693 */
63694 static void setLikeOptFlag(sqlite3 *db, const char *zName, int flagVal){
63695   FuncDef *pDef;
63696   pDef = sqlite3FindFunction(db, zName, strlen(zName), 2, SQLITE_UTF8, 0);
63697   if( pDef ){
63698     pDef->flags = flagVal;
63699   }
63700 }
63701
63702 /*
63703 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
63704 ** parameter determines whether or not the LIKE operator is case
63705 ** sensitive.  GLOB is always case sensitive.
63706 */
63707 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
63708   struct compareInfo *pInfo;
63709   if( caseSensitive ){
63710     pInfo = (struct compareInfo*)&likeInfoAlt;
63711   }else{
63712     pInfo = (struct compareInfo*)&likeInfoNorm;
63713   }
63714   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
63715   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
63716   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
63717       (struct compareInfo*)&globInfo, likeFunc, 0,0);
63718   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
63719   setLikeOptFlag(db, "like", 
63720       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
63721 }
63722
63723 /*
63724 ** pExpr points to an expression which implements a function.  If
63725 ** it is appropriate to apply the LIKE optimization to that function
63726 ** then set aWc[0] through aWc[2] to the wildcard characters and
63727 ** return TRUE.  If the function is not a LIKE-style function then
63728 ** return FALSE.
63729 */
63730 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
63731   FuncDef *pDef;
63732   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
63733     return 0;
63734   }
63735   if( pExpr->pList->nExpr!=2 ){
63736     return 0;
63737   }
63738   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
63739                              SQLITE_UTF8, 0);
63740   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
63741     return 0;
63742   }
63743
63744   /* The memcpy() statement assumes that the wildcard characters are
63745   ** the first three statements in the compareInfo structure.  The
63746   ** asserts() that follow verify that assumption
63747   */
63748   memcpy(aWc, pDef->pUserData, 3);
63749   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
63750   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
63751   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
63752   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
63753   return 1;
63754 }
63755
63756 /*
63757 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
63758 ** to the global function hash table.  This occurs at start-time (as
63759 ** a consequence of calling sqlite3_initialize()).
63760 **
63761 ** After this routine runs
63762 */
63763 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
63764   /*
63765   ** The following array holds FuncDef structures for all of the functions
63766   ** defined in this file.
63767   **
63768   ** The array cannot be constant since changes are made to the
63769   ** FuncDef.pHash elements at start-time.  The elements of this array
63770   ** are read-only after initialization is complete.
63771   */
63772   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
63773     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
63774     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
63775     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
63776     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
63777     FUNCTION(trim,               1, 3, 0, trimFunc         ),
63778     FUNCTION(trim,               2, 3, 0, trimFunc         ),
63779     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
63780     FUNCTION(min,                0, 0, 1, 0                ),
63781     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
63782     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
63783     FUNCTION(max,                0, 1, 1, 0                ),
63784     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
63785     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
63786     FUNCTION(length,             1, 0, 0, lengthFunc       ),
63787     FUNCTION(substr,             2, 0, 0, substrFunc       ),
63788     FUNCTION(substr,             3, 0, 0, substrFunc       ),
63789     FUNCTION(abs,                1, 0, 0, absFunc          ),
63790     FUNCTION(round,              1, 0, 0, roundFunc        ),
63791     FUNCTION(round,              2, 0, 0, roundFunc        ),
63792     FUNCTION(upper,              1, 0, 0, upperFunc        ),
63793     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
63794     FUNCTION(coalesce,           1, 0, 0, 0                ),
63795     FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
63796     FUNCTION(coalesce,           0, 0, 0, 0                ),
63797     FUNCTION(hex,                1, 0, 0, hexFunc          ),
63798     FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
63799     FUNCTION(random,            -1, 0, 0, randomFunc       ),
63800     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
63801     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
63802     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
63803     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
63804     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
63805     FUNCTION(changes,            0, 0, 0, changes          ),
63806     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
63807     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
63808     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
63809   #ifdef SQLITE_SOUNDEX
63810     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
63811   #endif
63812   #ifndef SQLITE_OMIT_LOAD_EXTENSION
63813     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
63814     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
63815   #endif
63816     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
63817     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
63818     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
63819     AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
63820     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
63821     AGGREGATE(group_concat,     -1, 0, 0, groupConcatStep, groupConcatFinalize),
63822   
63823     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63824   #ifdef SQLITE_CASE_SENSITIVE_LIKE
63825     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63826     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
63827   #else
63828     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
63829     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
63830   #endif
63831   };
63832
63833   int i;
63834   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
63835   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
63836
63837   for(i=0; i<ArraySize(aBuiltinFunc); i++){
63838     sqlite3FuncDefInsert(pHash, &aFunc[i]);
63839   }
63840   sqlite3RegisterDateTimeFunctions();
63841 }
63842
63843 /************** End of func.c ************************************************/
63844 /************** Begin file insert.c ******************************************/
63845 /*
63846 ** 2001 September 15
63847 **
63848 ** The author disclaims copyright to this source code.  In place of
63849 ** a legal notice, here is a blessing:
63850 **
63851 **    May you do good and not evil.
63852 **    May you find forgiveness for yourself and forgive others.
63853 **    May you share freely, never taking more than you give.
63854 **
63855 *************************************************************************
63856 ** This file contains C code routines that are called by the parser
63857 ** to handle INSERT statements in SQLite.
63858 **
63859 ** $Id: insert.c,v 1.249 2008/08/20 16:35:10 drh Exp $
63860 */
63861
63862 /*
63863 ** Set P4 of the most recently inserted opcode to a column affinity
63864 ** string for index pIdx. A column affinity string has one character
63865 ** for each column in the table, according to the affinity of the column:
63866 **
63867 **  Character      Column affinity
63868 **  ------------------------------
63869 **  'a'            TEXT
63870 **  'b'            NONE
63871 **  'c'            NUMERIC
63872 **  'd'            INTEGER
63873 **  'e'            REAL
63874 **
63875 ** An extra 'b' is appended to the end of the string to cover the
63876 ** rowid that appears as the last column in every index.
63877 */
63878 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
63879   if( !pIdx->zColAff ){
63880     /* The first time a column affinity string for a particular index is
63881     ** required, it is allocated and populated here. It is then stored as
63882     ** a member of the Index structure for subsequent use.
63883     **
63884     ** The column affinity string will eventually be deleted by
63885     ** sqliteDeleteIndex() when the Index structure itself is cleaned
63886     ** up.
63887     */
63888     int n;
63889     Table *pTab = pIdx->pTable;
63890     sqlite3 *db = sqlite3VdbeDb(v);
63891     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
63892     if( !pIdx->zColAff ){
63893       db->mallocFailed = 1;
63894       return;
63895     }
63896     for(n=0; n<pIdx->nColumn; n++){
63897       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
63898     }
63899     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
63900     pIdx->zColAff[n] = 0;
63901   }
63902  
63903   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
63904 }
63905
63906 /*
63907 ** Set P4 of the most recently inserted opcode to a column affinity
63908 ** string for table pTab. A column affinity string has one character
63909 ** for each column indexed by the index, according to the affinity of the
63910 ** column:
63911 **
63912 **  Character      Column affinity
63913 **  ------------------------------
63914 **  'a'            TEXT
63915 **  'b'            NONE
63916 **  'c'            NUMERIC
63917 **  'd'            INTEGER
63918 **  'e'            REAL
63919 */
63920 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
63921   /* The first time a column affinity string for a particular table
63922   ** is required, it is allocated and populated here. It is then 
63923   ** stored as a member of the Table structure for subsequent use.
63924   **
63925   ** The column affinity string will eventually be deleted by
63926   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
63927   */
63928   if( !pTab->zColAff ){
63929     char *zColAff;
63930     int i;
63931     sqlite3 *db = sqlite3VdbeDb(v);
63932
63933     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
63934     if( !zColAff ){
63935       db->mallocFailed = 1;
63936       return;
63937     }
63938
63939     for(i=0; i<pTab->nCol; i++){
63940       zColAff[i] = pTab->aCol[i].affinity;
63941     }
63942     zColAff[pTab->nCol] = '\0';
63943
63944     pTab->zColAff = zColAff;
63945   }
63946
63947   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
63948 }
63949
63950 /*
63951 ** Return non-zero if the table pTab in database iDb or any of its indices
63952 ** have been opened at any point in the VDBE program beginning at location
63953 ** iStartAddr throught the end of the program.  This is used to see if 
63954 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
63955 ** run without using temporary table for the results of the SELECT. 
63956 */
63957 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
63958   int i;
63959   int iEnd = sqlite3VdbeCurrentAddr(v);
63960   for(i=iStartAddr; i<iEnd; i++){
63961     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
63962     assert( pOp!=0 );
63963     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
63964       Index *pIndex;
63965       int tnum = pOp->p2;
63966       if( tnum==pTab->tnum ){
63967         return 1;
63968       }
63969       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
63970         if( tnum==pIndex->tnum ){
63971           return 1;
63972         }
63973       }
63974     }
63975 #ifndef SQLITE_OMIT_VIRTUALTABLE
63976     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
63977       assert( pOp->p4.pVtab!=0 );
63978       assert( pOp->p4type==P4_VTAB );
63979       return 1;
63980     }
63981 #endif
63982   }
63983   return 0;
63984 }
63985
63986 #ifndef SQLITE_OMIT_AUTOINCREMENT
63987 /*
63988 ** Write out code to initialize the autoincrement logic.  This code
63989 ** looks up the current autoincrement value in the sqlite_sequence
63990 ** table and stores that value in a register.  Code generated by
63991 ** autoIncStep() will keep that register holding the largest
63992 ** rowid value.  Code generated by autoIncEnd() will write the new
63993 ** largest value of the counter back into the sqlite_sequence table.
63994 **
63995 ** This routine returns the index of the mem[] cell that contains
63996 ** the maximum rowid counter.
63997 **
63998 ** Three consecutive registers are allocated by this routine.  The
63999 ** first two hold the name of the target table and the maximum rowid 
64000 ** inserted into the target table, respectively.
64001 ** The third holds the rowid in sqlite_sequence where we will
64002 ** write back the revised maximum rowid.  This routine returns the
64003 ** index of the second of these three registers.
64004 */
64005 static int autoIncBegin(
64006   Parse *pParse,      /* Parsing context */
64007   int iDb,            /* Index of the database holding pTab */
64008   Table *pTab         /* The table we are writing to */
64009 ){
64010   int memId = 0;      /* Register holding maximum rowid */
64011   if( pTab->tabFlags & TF_Autoincrement ){
64012     Vdbe *v = pParse->pVdbe;
64013     Db *pDb = &pParse->db->aDb[iDb];
64014     int iCur = pParse->nTab;
64015     int addr;               /* Address of the top of the loop */
64016     assert( v );
64017     pParse->nMem++;         /* Holds name of table */
64018     memId = ++pParse->nMem;
64019     pParse->nMem++;
64020     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
64021     addr = sqlite3VdbeCurrentAddr(v);
64022     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
64023     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
64024     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
64025     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
64026     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
64027     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
64028     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
64029     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
64030     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
64031     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
64032     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
64033   }
64034   return memId;
64035 }
64036
64037 /*
64038 ** Update the maximum rowid for an autoincrement calculation.
64039 **
64040 ** This routine should be called when the top of the stack holds a
64041 ** new rowid that is about to be inserted.  If that new rowid is
64042 ** larger than the maximum rowid in the memId memory cell, then the
64043 ** memory cell is updated.  The stack is unchanged.
64044 */
64045 static void autoIncStep(Parse *pParse, int memId, int regRowid){
64046   if( memId>0 ){
64047     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
64048   }
64049 }
64050
64051 /*
64052 ** After doing one or more inserts, the maximum rowid is stored
64053 ** in reg[memId].  Generate code to write this value back into the
64054 ** the sqlite_sequence table.
64055 */
64056 static void autoIncEnd(
64057   Parse *pParse,     /* The parsing context */
64058   int iDb,           /* Index of the database holding pTab */
64059   Table *pTab,       /* Table we are inserting into */
64060   int memId          /* Memory cell holding the maximum rowid */
64061 ){
64062   if( pTab->tabFlags & TF_Autoincrement ){
64063     int iCur = pParse->nTab;
64064     Vdbe *v = pParse->pVdbe;
64065     Db *pDb = &pParse->db->aDb[iDb];
64066     int j1;
64067     int iRec = ++pParse->nMem;    /* Memory cell used for record */
64068
64069     assert( v );
64070     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
64071     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
64072     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
64073     sqlite3VdbeJumpHere(v, j1);
64074     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
64075     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
64076     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
64077     sqlite3VdbeAddOp1(v, OP_Close, iCur);
64078   }
64079 }
64080 #else
64081 /*
64082 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
64083 ** above are all no-ops
64084 */
64085 # define autoIncBegin(A,B,C) (0)
64086 # define autoIncStep(A,B,C)
64087 # define autoIncEnd(A,B,C,D)
64088 #endif /* SQLITE_OMIT_AUTOINCREMENT */
64089
64090
64091 /* Forward declaration */
64092 static int xferOptimization(
64093   Parse *pParse,        /* Parser context */
64094   Table *pDest,         /* The table we are inserting into */
64095   Select *pSelect,      /* A SELECT statement to use as the data source */
64096   int onError,          /* How to handle constraint errors */
64097   int iDbDest           /* The database of pDest */
64098 );
64099
64100 /*
64101 ** This routine is call to handle SQL of the following forms:
64102 **
64103 **    insert into TABLE (IDLIST) values(EXPRLIST)
64104 **    insert into TABLE (IDLIST) select
64105 **
64106 ** The IDLIST following the table name is always optional.  If omitted,
64107 ** then a list of all columns for the table is substituted.  The IDLIST
64108 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
64109 **
64110 ** The pList parameter holds EXPRLIST in the first form of the INSERT
64111 ** statement above, and pSelect is NULL.  For the second form, pList is
64112 ** NULL and pSelect is a pointer to the select statement used to generate
64113 ** data for the insert.
64114 **
64115 ** The code generated follows one of four templates.  For a simple
64116 ** select with data coming from a VALUES clause, the code executes
64117 ** once straight down through.  Pseudo-code follows (we call this
64118 ** the "1st template"):
64119 **
64120 **         open write cursor to <table> and its indices
64121 **         puts VALUES clause expressions onto the stack
64122 **         write the resulting record into <table>
64123 **         cleanup
64124 **
64125 ** The three remaining templates assume the statement is of the form
64126 **
64127 **   INSERT INTO <table> SELECT ...
64128 **
64129 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
64130 ** in other words if the SELECT pulls all columns from a single table
64131 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
64132 ** if <table2> and <table1> are distinct tables but have identical
64133 ** schemas, including all the same indices, then a special optimization
64134 ** is invoked that copies raw records from <table2> over to <table1>.
64135 ** See the xferOptimization() function for the implementation of this
64136 ** template.  This is the 2nd template.
64137 **
64138 **         open a write cursor to <table>
64139 **         open read cursor on <table2>
64140 **         transfer all records in <table2> over to <table>
64141 **         close cursors
64142 **         foreach index on <table>
64143 **           open a write cursor on the <table> index
64144 **           open a read cursor on the corresponding <table2> index
64145 **           transfer all records from the read to the write cursors
64146 **           close cursors
64147 **         end foreach
64148 **
64149 ** The 3rd template is for when the second template does not apply
64150 ** and the SELECT clause does not read from <table> at any time.
64151 ** The generated code follows this template:
64152 **
64153 **         EOF <- 0
64154 **         X <- A
64155 **         goto B
64156 **      A: setup for the SELECT
64157 **         loop over the rows in the SELECT
64158 **           load values into registers R..R+n
64159 **           yield X
64160 **         end loop
64161 **         cleanup after the SELECT
64162 **         EOF <- 1
64163 **         yield X
64164 **         goto A
64165 **      B: open write cursor to <table> and its indices
64166 **      C: yield X
64167 **         if EOF goto D
64168 **         insert the select result into <table> from R..R+n
64169 **         goto C
64170 **      D: cleanup
64171 **
64172 ** The 4th template is used if the insert statement takes its
64173 ** values from a SELECT but the data is being inserted into a table
64174 ** that is also read as part of the SELECT.  In the third form,
64175 ** we have to use a intermediate table to store the results of
64176 ** the select.  The template is like this:
64177 **
64178 **         EOF <- 0
64179 **         X <- A
64180 **         goto B
64181 **      A: setup for the SELECT
64182 **         loop over the tables in the SELECT
64183 **           load value into register R..R+n
64184 **           yield X
64185 **         end loop
64186 **         cleanup after the SELECT
64187 **         EOF <- 1
64188 **         yield X
64189 **         halt-error
64190 **      B: open temp table
64191 **      L: yield X
64192 **         if EOF goto M
64193 **         insert row from R..R+n into temp table
64194 **         goto L
64195 **      M: open write cursor to <table> and its indices
64196 **         rewind temp table
64197 **      C: loop over rows of intermediate table
64198 **           transfer values form intermediate table into <table>
64199 **         end loop
64200 **      D: cleanup
64201 */
64202 SQLITE_PRIVATE void sqlite3Insert(
64203   Parse *pParse,        /* Parser context */
64204   SrcList *pTabList,    /* Name of table into which we are inserting */
64205   ExprList *pList,      /* List of values to be inserted */
64206   Select *pSelect,      /* A SELECT statement to use as the data source */
64207   IdList *pColumn,      /* Column names corresponding to IDLIST. */
64208   int onError           /* How to handle constraint errors */
64209 ){
64210   sqlite3 *db;          /* The main database structure */
64211   Table *pTab;          /* The table to insert into.  aka TABLE */
64212   char *zTab;           /* Name of the table into which we are inserting */
64213   const char *zDb;      /* Name of the database holding this table */
64214   int i, j, idx;        /* Loop counters */
64215   Vdbe *v;              /* Generate code into this virtual machine */
64216   Index *pIdx;          /* For looping over indices of the table */
64217   int nColumn;          /* Number of columns in the data */
64218   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
64219   int baseCur = 0;      /* VDBE Cursor number for pTab */
64220   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
64221   int endOfLoop;        /* Label for the end of the insertion loop */
64222   int useTempTable = 0; /* Store SELECT results in intermediate table */
64223   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
64224   int addrInsTop = 0;   /* Jump to label "D" */
64225   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
64226   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
64227   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
64228   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
64229   int iDb;              /* Index of database holding TABLE */
64230   Db *pDb;              /* The database containing table being inserted into */
64231   int appendFlag = 0;   /* True if the insert is likely to be an append */
64232
64233   /* Register allocations */
64234   int regFromSelect;    /* Base register for data coming from SELECT */
64235   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
64236   int regRowCount = 0;  /* Memory cell used for the row counter */
64237   int regIns;           /* Block of regs holding rowid+data being inserted */
64238   int regRowid;         /* registers holding insert rowid */
64239   int regData;          /* register holding first column to insert */
64240   int regRecord;        /* Holds the assemblied row record */
64241   int regEof;           /* Register recording end of SELECT data */
64242   int *aRegIdx = 0;     /* One register allocated to each index */
64243
64244
64245 #ifndef SQLITE_OMIT_TRIGGER
64246   int isView;                 /* True if attempting to insert into a view */
64247   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
64248 #endif
64249
64250   db = pParse->db;
64251   if( pParse->nErr || db->mallocFailed ){
64252     goto insert_cleanup;
64253   }
64254
64255   /* Locate the table into which we will be inserting new information.
64256   */
64257   assert( pTabList->nSrc==1 );
64258   zTab = pTabList->a[0].zName;
64259   if( zTab==0 ) goto insert_cleanup;
64260   pTab = sqlite3SrcListLookup(pParse, pTabList);
64261   if( pTab==0 ){
64262     goto insert_cleanup;
64263   }
64264   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64265   assert( iDb<db->nDb );
64266   pDb = &db->aDb[iDb];
64267   zDb = pDb->zName;
64268   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
64269     goto insert_cleanup;
64270   }
64271
64272   /* Figure out if we have any triggers and if the table being
64273   ** inserted into is a view
64274   */
64275 #ifndef SQLITE_OMIT_TRIGGER
64276   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0);
64277   isView = pTab->pSelect!=0;
64278 #else
64279 # define triggers_exist 0
64280 # define isView 0
64281 #endif
64282 #ifdef SQLITE_OMIT_VIEW
64283 # undef isView
64284 # define isView 0
64285 #endif
64286
64287   /* Ensure that:
64288   *  (a) the table is not read-only, 
64289   *  (b) that if it is a view then ON INSERT triggers exist
64290   */
64291   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
64292     goto insert_cleanup;
64293   }
64294   assert( pTab!=0 );
64295
64296   /* If pTab is really a view, make sure it has been initialized.
64297   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
64298   ** module table).
64299   */
64300   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64301     goto insert_cleanup;
64302   }
64303
64304   /* Allocate a VDBE
64305   */
64306   v = sqlite3GetVdbe(pParse);
64307   if( v==0 ) goto insert_cleanup;
64308   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
64309   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
64310
64311   /* if there are row triggers, allocate a temp table for new.* references. */
64312   if( triggers_exist ){
64313     newIdx = pParse->nTab++;
64314   }
64315
64316 #ifndef SQLITE_OMIT_XFER_OPT
64317   /* If the statement is of the form
64318   **
64319   **       INSERT INTO <table1> SELECT * FROM <table2>;
64320   **
64321   ** Then special optimizations can be applied that make the transfer
64322   ** very fast and which reduce fragmentation of indices.
64323   **
64324   ** This is the 2nd template.
64325   */
64326   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
64327     assert( !triggers_exist );
64328     assert( pList==0 );
64329     goto insert_cleanup;
64330   }
64331 #endif /* SQLITE_OMIT_XFER_OPT */
64332
64333   /* If this is an AUTOINCREMENT table, look up the sequence number in the
64334   ** sqlite_sequence table and store it in memory cell regAutoinc.
64335   */
64336   regAutoinc = autoIncBegin(pParse, iDb, pTab);
64337
64338   /* Figure out how many columns of data are supplied.  If the data
64339   ** is coming from a SELECT statement, then generate a co-routine that
64340   ** produces a single row of the SELECT on each invocation.  The
64341   ** co-routine is the common header to the 3rd and 4th templates.
64342   */
64343   if( pSelect ){
64344     /* Data is coming from a SELECT.  Generate code to implement that SELECT
64345     ** as a co-routine.  The code is common to both the 3rd and 4th
64346     ** templates:
64347     **
64348     **         EOF <- 0
64349     **         X <- A
64350     **         goto B
64351     **      A: setup for the SELECT
64352     **         loop over the tables in the SELECT
64353     **           load value into register R..R+n
64354     **           yield X
64355     **         end loop
64356     **         cleanup after the SELECT
64357     **         EOF <- 1
64358     **         yield X
64359     **         halt-error
64360     **
64361     ** On each invocation of the co-routine, it puts a single row of the
64362     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
64363     ** (These output registers are allocated by sqlite3Select().)  When
64364     ** the SELECT completes, it sets the EOF flag stored in regEof.
64365     */
64366     int rc, j1;
64367
64368     regEof = ++pParse->nMem;
64369     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
64370     VdbeComment((v, "SELECT eof flag"));
64371     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
64372     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
64373     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
64374     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
64375     VdbeComment((v, "Jump over SELECT coroutine"));
64376
64377     /* Resolve the expressions in the SELECT statement and execute it. */
64378     rc = sqlite3Select(pParse, pSelect, &dest);
64379     if( rc || pParse->nErr || db->mallocFailed ){
64380       goto insert_cleanup;
64381     }
64382     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
64383     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
64384     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
64385     VdbeComment((v, "End of SELECT coroutine"));
64386     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
64387
64388     regFromSelect = dest.iMem;
64389     assert( pSelect->pEList );
64390     nColumn = pSelect->pEList->nExpr;
64391     assert( dest.nMem==nColumn );
64392
64393     /* Set useTempTable to TRUE if the result of the SELECT statement
64394     ** should be written into a temporary table (template 4).  Set to
64395     ** FALSE if each* row of the SELECT can be written directly into
64396     ** the destination table (template 3).
64397     **
64398     ** A temp table must be used if the table being updated is also one
64399     ** of the tables being read by the SELECT statement.  Also use a 
64400     ** temp table in the case of row triggers.
64401     */
64402     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
64403       useTempTable = 1;
64404     }
64405
64406     if( useTempTable ){
64407       /* Invoke the coroutine to extract information from the SELECT
64408       ** and add it to a transient table srcTab.  The code generated
64409       ** here is from the 4th template:
64410       **
64411       **      B: open temp table
64412       **      L: yield X
64413       **         if EOF goto M
64414       **         insert row from R..R+n into temp table
64415       **         goto L
64416       **      M: ...
64417       */
64418       int regRec;      /* Register to hold packed record */
64419       int regRowid;    /* Register to hold temp table ROWID */
64420       int addrTop;     /* Label "L" */
64421       int addrIf;      /* Address of jump to M */
64422
64423       srcTab = pParse->nTab++;
64424       regRec = sqlite3GetTempReg(pParse);
64425       regRowid = sqlite3GetTempReg(pParse);
64426       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
64427       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
64428       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
64429       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
64430       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid);
64431       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid);
64432       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
64433       sqlite3VdbeJumpHere(v, addrIf);
64434       sqlite3ReleaseTempReg(pParse, regRec);
64435       sqlite3ReleaseTempReg(pParse, regRowid);
64436     }
64437   }else{
64438     /* This is the case if the data for the INSERT is coming from a VALUES
64439     ** clause
64440     */
64441     NameContext sNC;
64442     memset(&sNC, 0, sizeof(sNC));
64443     sNC.pParse = pParse;
64444     srcTab = -1;
64445     assert( useTempTable==0 );
64446     nColumn = pList ? pList->nExpr : 0;
64447     for(i=0; i<nColumn; i++){
64448       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
64449         goto insert_cleanup;
64450       }
64451     }
64452   }
64453
64454   /* Make sure the number of columns in the source data matches the number
64455   ** of columns to be inserted into the table.
64456   */
64457   if( IsVirtual(pTab) ){
64458     for(i=0; i<pTab->nCol; i++){
64459       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
64460     }
64461   }
64462   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
64463     sqlite3ErrorMsg(pParse, 
64464        "table %S has %d columns but %d values were supplied",
64465        pTabList, 0, pTab->nCol, nColumn);
64466     goto insert_cleanup;
64467   }
64468   if( pColumn!=0 && nColumn!=pColumn->nId ){
64469     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
64470     goto insert_cleanup;
64471   }
64472
64473   /* If the INSERT statement included an IDLIST term, then make sure
64474   ** all elements of the IDLIST really are columns of the table and 
64475   ** remember the column indices.
64476   **
64477   ** If the table has an INTEGER PRIMARY KEY column and that column
64478   ** is named in the IDLIST, then record in the keyColumn variable
64479   ** the index into IDLIST of the primary key column.  keyColumn is
64480   ** the index of the primary key as it appears in IDLIST, not as
64481   ** is appears in the original table.  (The index of the primary
64482   ** key in the original table is pTab->iPKey.)
64483   */
64484   if( pColumn ){
64485     for(i=0; i<pColumn->nId; i++){
64486       pColumn->a[i].idx = -1;
64487     }
64488     for(i=0; i<pColumn->nId; i++){
64489       for(j=0; j<pTab->nCol; j++){
64490         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
64491           pColumn->a[i].idx = j;
64492           if( j==pTab->iPKey ){
64493             keyColumn = i;
64494           }
64495           break;
64496         }
64497       }
64498       if( j>=pTab->nCol ){
64499         if( sqlite3IsRowid(pColumn->a[i].zName) ){
64500           keyColumn = i;
64501         }else{
64502           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
64503               pTabList, 0, pColumn->a[i].zName);
64504           pParse->nErr++;
64505           goto insert_cleanup;
64506         }
64507       }
64508     }
64509   }
64510
64511   /* If there is no IDLIST term but the table has an integer primary
64512   ** key, the set the keyColumn variable to the primary key column index
64513   ** in the original table definition.
64514   */
64515   if( pColumn==0 && nColumn>0 ){
64516     keyColumn = pTab->iPKey;
64517   }
64518
64519   /* Open the temp table for FOR EACH ROW triggers
64520   */
64521   if( triggers_exist ){
64522     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
64523     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
64524   }
64525     
64526   /* Initialize the count of rows to be inserted
64527   */
64528   if( db->flags & SQLITE_CountRows ){
64529     regRowCount = ++pParse->nMem;
64530     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
64531   }
64532
64533   /* If this is not a view, open the table and and all indices */
64534   if( !isView ){
64535     int nIdx;
64536     int i;
64537
64538     baseCur = pParse->nTab;
64539     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
64540     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
64541     if( aRegIdx==0 ){
64542       goto insert_cleanup;
64543     }
64544     for(i=0; i<nIdx; i++){
64545       aRegIdx[i] = ++pParse->nMem;
64546     }
64547   }
64548
64549   /* This is the top of the main insertion loop */
64550   if( useTempTable ){
64551     /* This block codes the top of loop only.  The complete loop is the
64552     ** following pseudocode (template 4):
64553     **
64554     **         rewind temp table
64555     **      C: loop over rows of intermediate table
64556     **           transfer values form intermediate table into <table>
64557     **         end loop
64558     **      D: ...
64559     */
64560     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
64561     addrCont = sqlite3VdbeCurrentAddr(v);
64562   }else if( pSelect ){
64563     /* This block codes the top of loop only.  The complete loop is the
64564     ** following pseudocode (template 3):
64565     **
64566     **      C: yield X
64567     **         if EOF goto D
64568     **         insert the select result into <table> from R..R+n
64569     **         goto C
64570     **      D: ...
64571     */
64572     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
64573     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
64574   }
64575
64576   /* Allocate registers for holding the rowid of the new row,
64577   ** the content of the new row, and the assemblied row record.
64578   */
64579   regRecord = ++pParse->nMem;
64580   regRowid = regIns = pParse->nMem+1;
64581   pParse->nMem += pTab->nCol + 1;
64582   if( IsVirtual(pTab) ){
64583     regRowid++;
64584     pParse->nMem++;
64585   }
64586   regData = regRowid+1;
64587
64588   /* Run the BEFORE and INSTEAD OF triggers, if there are any
64589   */
64590   endOfLoop = sqlite3VdbeMakeLabel(v);
64591   if( triggers_exist & TRIGGER_BEFORE ){
64592     int regRowid;
64593     int regCols;
64594     int regRec;
64595
64596     /* build the NEW.* reference row.  Note that if there is an INTEGER
64597     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
64598     ** translated into a unique ID for the row.  But on a BEFORE trigger,
64599     ** we do not know what the unique ID will be (because the insert has
64600     ** not happened yet) so we substitute a rowid of -1
64601     */
64602     regRowid = sqlite3GetTempReg(pParse);
64603     if( keyColumn<0 ){
64604       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
64605     }else if( useTempTable ){
64606       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
64607     }else{
64608       int j1;
64609       assert( pSelect==0 );  /* Otherwise useTempTable is true */
64610       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
64611       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
64612       sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
64613       sqlite3VdbeJumpHere(v, j1);
64614       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
64615     }
64616
64617     /* Cannot have triggers on a virtual table. If it were possible,
64618     ** this block would have to account for hidden column.
64619     */
64620     assert(!IsVirtual(pTab));
64621
64622     /* Create the new column data
64623     */
64624     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
64625     for(i=0; i<pTab->nCol; i++){
64626       if( pColumn==0 ){
64627         j = i;
64628       }else{
64629         for(j=0; j<pColumn->nId; j++){
64630           if( pColumn->a[j].idx==i ) break;
64631         }
64632       }
64633       if( pColumn && j>=pColumn->nId ){
64634         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
64635       }else if( useTempTable ){
64636         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
64637       }else{
64638         assert( pSelect==0 ); /* Otherwise useTempTable is true */
64639         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
64640       }
64641     }
64642     regRec = sqlite3GetTempReg(pParse);
64643     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
64644
64645     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
64646     ** do not attempt any conversions before assembling the record.
64647     ** If this is a real table, attempt conversions as required by the
64648     ** table column affinities.
64649     */
64650     if( !isView ){
64651       sqlite3TableAffinityStr(v, pTab);
64652     }
64653     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
64654     sqlite3ReleaseTempReg(pParse, regRec);
64655     sqlite3ReleaseTempReg(pParse, regRowid);
64656     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
64657
64658     /* Fire BEFORE or INSTEAD OF triggers */
64659     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
64660         newIdx, -1, onError, endOfLoop, 0, 0) ){
64661       goto insert_cleanup;
64662     }
64663   }
64664
64665   /* Push the record number for the new entry onto the stack.  The
64666   ** record number is a randomly generate integer created by NewRowid
64667   ** except when the table has an INTEGER PRIMARY KEY column, in which
64668   ** case the record number is the same as that column. 
64669   */
64670   if( !isView ){
64671     if( IsVirtual(pTab) ){
64672       /* The row that the VUpdate opcode will delete: none */
64673       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
64674     }
64675     if( keyColumn>=0 ){
64676       if( useTempTable ){
64677         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
64678       }else if( pSelect ){
64679         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
64680       }else{
64681         VdbeOp *pOp;
64682         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
64683         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
64684         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
64685           appendFlag = 1;
64686           pOp->opcode = OP_NewRowid;
64687           pOp->p1 = baseCur;
64688           pOp->p2 = regRowid;
64689           pOp->p3 = regAutoinc;
64690         }
64691       }
64692       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
64693       ** to generate a unique primary key value.
64694       */
64695       if( !appendFlag ){
64696         int j1;
64697         if( !IsVirtual(pTab) ){
64698           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
64699           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
64700           sqlite3VdbeJumpHere(v, j1);
64701         }else{
64702           j1 = sqlite3VdbeCurrentAddr(v);
64703           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
64704         }
64705         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
64706       }
64707     }else if( IsVirtual(pTab) ){
64708       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
64709     }else{
64710       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
64711       appendFlag = 1;
64712     }
64713     autoIncStep(pParse, regAutoinc, regRowid);
64714
64715     /* Push onto the stack, data for all columns of the new entry, beginning
64716     ** with the first column.
64717     */
64718     nHidden = 0;
64719     for(i=0; i<pTab->nCol; i++){
64720       int iRegStore = regRowid+1+i;
64721       if( i==pTab->iPKey ){
64722         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
64723         ** Whenever this column is read, the record number will be substituted
64724         ** in its place.  So will fill this column with a NULL to avoid
64725         ** taking up data space with information that will never be used. */
64726         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
64727         continue;
64728       }
64729       if( pColumn==0 ){
64730         if( IsHiddenColumn(&pTab->aCol[i]) ){
64731           assert( IsVirtual(pTab) );
64732           j = -1;
64733           nHidden++;
64734         }else{
64735           j = i - nHidden;
64736         }
64737       }else{
64738         for(j=0; j<pColumn->nId; j++){
64739           if( pColumn->a[j].idx==i ) break;
64740         }
64741       }
64742       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
64743         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
64744       }else if( useTempTable ){
64745         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
64746       }else if( pSelect ){
64747         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
64748       }else{
64749         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
64750       }
64751     }
64752
64753     /* Generate code to check constraints and generate index keys and
64754     ** do the insertion.
64755     */
64756 #ifndef SQLITE_OMIT_VIRTUALTABLE
64757     if( IsVirtual(pTab) ){
64758       sqlite3VtabMakeWritable(pParse, pTab);
64759       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
64760                      (const char*)pTab->pVtab, P4_VTAB);
64761     }else
64762 #endif
64763     {
64764       sqlite3GenerateConstraintChecks(
64765           pParse,
64766           pTab,
64767           baseCur,
64768           regIns,
64769           aRegIdx,
64770           keyColumn>=0,
64771           0,
64772           onError,
64773           endOfLoop
64774       );
64775       sqlite3CompleteInsertion(
64776           pParse,
64777           pTab,
64778           baseCur,
64779           regIns,
64780           aRegIdx,
64781           0,
64782           0,
64783           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
64784           appendFlag
64785        );
64786     }
64787   }
64788
64789   /* Update the count of rows that are inserted
64790   */
64791   if( (db->flags & SQLITE_CountRows)!=0 ){
64792     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
64793   }
64794
64795   if( triggers_exist ){
64796     /* Code AFTER triggers */
64797     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
64798           newIdx, -1, onError, endOfLoop, 0, 0) ){
64799       goto insert_cleanup;
64800     }
64801   }
64802
64803   /* The bottom of the main insertion loop, if the data source
64804   ** is a SELECT statement.
64805   */
64806   sqlite3VdbeResolveLabel(v, endOfLoop);
64807   if( useTempTable ){
64808     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
64809     sqlite3VdbeJumpHere(v, addrInsTop);
64810     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
64811   }else if( pSelect ){
64812     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
64813     sqlite3VdbeJumpHere(v, addrInsTop);
64814   }
64815
64816   if( !IsVirtual(pTab) && !isView ){
64817     /* Close all tables opened */
64818     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
64819     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
64820       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
64821     }
64822   }
64823
64824   /* Update the sqlite_sequence table by storing the content of the
64825   ** counter value in memory regAutoinc back into the sqlite_sequence
64826   ** table.
64827   */
64828   autoIncEnd(pParse, iDb, pTab, regAutoinc);
64829
64830   /*
64831   ** Return the number of rows inserted. If this routine is 
64832   ** generating code because of a call to sqlite3NestedParse(), do not
64833   ** invoke the callback function.
64834   */
64835   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
64836     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
64837     sqlite3VdbeSetNumCols(v, 1);
64838     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC);
64839   }
64840
64841 insert_cleanup:
64842   sqlite3SrcListDelete(db, pTabList);
64843   sqlite3ExprListDelete(db, pList);
64844   sqlite3SelectDelete(db, pSelect);
64845   sqlite3IdListDelete(db, pColumn);
64846   sqlite3DbFree(db, aRegIdx);
64847 }
64848
64849 /*
64850 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
64851 **
64852 ** The input is a range of consecutive registers as follows:
64853 **
64854 **    1.  The rowid of the row to be updated before the update.  This
64855 **        value is omitted unless we are doing an UPDATE that involves a
64856 **        change to the record number or writing to a virtual table.
64857 **
64858 **    2.  The rowid of the row after the update.
64859 **
64860 **    3.  The data in the first column of the entry after the update.
64861 **
64862 **    i.  Data from middle columns...
64863 **
64864 **    N.  The data in the last column of the entry after the update.
64865 **
64866 ** The regRowid parameter is the index of the register containing (2).
64867 **
64868 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
64869 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
64870 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
64871 ** the update or insert statement.  If rowidChng is false, it means that
64872 ** the rowid is computed automatically in an insert or that the rowid value
64873 ** is not modified by the update.
64874 **
64875 ** The code generated by this routine store new index entries into
64876 ** registers identified by aRegIdx[].  No index entry is created for
64877 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
64878 ** the same as the order of indices on the linked list of indices
64879 ** attached to the table.
64880 **
64881 ** This routine also generates code to check constraints.  NOT NULL,
64882 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
64883 ** then the appropriate action is performed.  There are five possible
64884 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
64885 **
64886 **  Constraint type  Action       What Happens
64887 **  ---------------  ----------   ----------------------------------------
64888 **  any              ROLLBACK     The current transaction is rolled back and
64889 **                                sqlite3_exec() returns immediately with a
64890 **                                return code of SQLITE_CONSTRAINT.
64891 **
64892 **  any              ABORT        Back out changes from the current command
64893 **                                only (do not do a complete rollback) then
64894 **                                cause sqlite3_exec() to return immediately
64895 **                                with SQLITE_CONSTRAINT.
64896 **
64897 **  any              FAIL         Sqlite_exec() returns immediately with a
64898 **                                return code of SQLITE_CONSTRAINT.  The
64899 **                                transaction is not rolled back and any
64900 **                                prior changes are retained.
64901 **
64902 **  any              IGNORE       The record number and data is popped from
64903 **                                the stack and there is an immediate jump
64904 **                                to label ignoreDest.
64905 **
64906 **  NOT NULL         REPLACE      The NULL value is replace by the default
64907 **                                value for that column.  If the default value
64908 **                                is NULL, the action is the same as ABORT.
64909 **
64910 **  UNIQUE           REPLACE      The other row that conflicts with the row
64911 **                                being inserted is removed.
64912 **
64913 **  CHECK            REPLACE      Illegal.  The results in an exception.
64914 **
64915 ** Which action to take is determined by the overrideError parameter.
64916 ** Or if overrideError==OE_Default, then the pParse->onError parameter
64917 ** is used.  Or if pParse->onError==OE_Default then the onError value
64918 ** for the constraint is used.
64919 **
64920 ** The calling routine must open a read/write cursor for pTab with
64921 ** cursor number "baseCur".  All indices of pTab must also have open
64922 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
64923 ** Except, if there is no possibility of a REPLACE action then
64924 ** cursors do not need to be open for indices where aRegIdx[i]==0.
64925 */
64926 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
64927   Parse *pParse,      /* The parser context */
64928   Table *pTab,        /* the table into which we are inserting */
64929   int baseCur,        /* Index of a read/write cursor pointing at pTab */
64930   int regRowid,       /* Index of the range of input registers */
64931   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
64932   int rowidChng,      /* True if the rowid might collide with existing entry */
64933   int isUpdate,       /* True for UPDATE, False for INSERT */
64934   int overrideError,  /* Override onError to this if not OE_Default */
64935   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
64936 ){
64937   int i;
64938   Vdbe *v;
64939   int nCol;
64940   int onError;
64941   int j1, j2, j3;     /* Addresses of jump instructions */
64942   int regData;        /* Register containing first data column */
64943   int iCur;
64944   Index *pIdx;
64945   int seenReplace = 0;
64946   int hasTwoRowids = (isUpdate && rowidChng);
64947
64948   v = sqlite3GetVdbe(pParse);
64949   assert( v!=0 );
64950   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
64951   nCol = pTab->nCol;
64952   regData = regRowid + 1;
64953
64954
64955   /* Test all NOT NULL constraints.
64956   */
64957   for(i=0; i<nCol; i++){
64958     if( i==pTab->iPKey ){
64959       continue;
64960     }
64961     onError = pTab->aCol[i].notNull;
64962     if( onError==OE_None ) continue;
64963     if( overrideError!=OE_Default ){
64964       onError = overrideError;
64965     }else if( onError==OE_Default ){
64966       onError = OE_Abort;
64967     }
64968     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
64969       onError = OE_Abort;
64970     }
64971     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
64972     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
64973         || onError==OE_Ignore || onError==OE_Replace );
64974     switch( onError ){
64975       case OE_Rollback:
64976       case OE_Abort:
64977       case OE_Fail: {
64978         char *zMsg;
64979         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
64980         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
64981                               pTab->zName, pTab->aCol[i].zName);
64982         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
64983         break;
64984       }
64985       case OE_Ignore: {
64986         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
64987         break;
64988       }
64989       case OE_Replace: {
64990         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
64991         break;
64992       }
64993     }
64994     sqlite3VdbeJumpHere(v, j1);
64995   }
64996
64997   /* Test all CHECK constraints
64998   */
64999 #ifndef SQLITE_OMIT_CHECK
65000   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
65001     int allOk = sqlite3VdbeMakeLabel(v);
65002     pParse->ckBase = regData;
65003     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
65004     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
65005     if( onError==OE_Ignore ){
65006       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65007     }else{
65008       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
65009     }
65010     sqlite3VdbeResolveLabel(v, allOk);
65011   }
65012 #endif /* !defined(SQLITE_OMIT_CHECK) */
65013
65014   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
65015   ** of the new record does not previously exist.  Except, if this
65016   ** is an UPDATE and the primary key is not changing, that is OK.
65017   */
65018   if( rowidChng ){
65019     onError = pTab->keyConf;
65020     if( overrideError!=OE_Default ){
65021       onError = overrideError;
65022     }else if( onError==OE_Default ){
65023       onError = OE_Abort;
65024     }
65025     
65026     if( onError!=OE_Replace || pTab->pIndex ){
65027       if( isUpdate ){
65028         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
65029       }
65030       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
65031       switch( onError ){
65032         default: {
65033           onError = OE_Abort;
65034           /* Fall thru into the next case */
65035         }
65036         case OE_Rollback:
65037         case OE_Abort:
65038         case OE_Fail: {
65039           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
65040                            "PRIMARY KEY must be unique", P4_STATIC);
65041           break;
65042         }
65043         case OE_Replace: {
65044           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
65045           seenReplace = 1;
65046           break;
65047         }
65048         case OE_Ignore: {
65049           assert( seenReplace==0 );
65050           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65051           break;
65052         }
65053       }
65054       sqlite3VdbeJumpHere(v, j3);
65055       if( isUpdate ){
65056         sqlite3VdbeJumpHere(v, j2);
65057       }
65058     }
65059   }
65060
65061   /* Test all UNIQUE constraints by creating entries for each UNIQUE
65062   ** index and making sure that duplicate entries do not already exist.
65063   ** Add the new records to the indices as we go.
65064   */
65065   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
65066     int regIdx;
65067     int regR;
65068
65069     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
65070
65071     /* Create a key for accessing the index entry */
65072     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
65073     for(i=0; i<pIdx->nColumn; i++){
65074       int idx = pIdx->aiColumn[i];
65075       if( idx==pTab->iPKey ){
65076         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
65077       }else{
65078         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
65079       }
65080     }
65081     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
65082     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
65083     sqlite3IndexAffinityStr(v, pIdx);
65084     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
65085     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
65086
65087     /* Find out what action to take in case there is an indexing conflict */
65088     onError = pIdx->onError;
65089     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
65090     if( overrideError!=OE_Default ){
65091       onError = overrideError;
65092     }else if( onError==OE_Default ){
65093       onError = OE_Abort;
65094     }
65095     if( seenReplace ){
65096       if( onError==OE_Ignore ) onError = OE_Replace;
65097       else if( onError==OE_Fail ) onError = OE_Abort;
65098     }
65099     
65100
65101     /* Check to see if the new index entry will be unique */
65102     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
65103     regR = sqlite3GetTempReg(pParse);
65104     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
65105     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
65106                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
65107                            P4_INT32);
65108
65109     /* Generate code that executes if the new index entry is not unique */
65110     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
65111         || onError==OE_Ignore || onError==OE_Replace );
65112     switch( onError ){
65113       case OE_Rollback:
65114       case OE_Abort:
65115       case OE_Fail: {
65116         int j, n1, n2;
65117         char zErrMsg[200];
65118         sqlite3_snprintf(sizeof(zErrMsg), zErrMsg,
65119                          pIdx->nColumn>1 ? "columns " : "column ");
65120         n1 = strlen(zErrMsg);
65121         for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
65122           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
65123           n2 = strlen(zCol);
65124           if( j>0 ){
65125             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], ", ");
65126             n1 += 2;
65127           }
65128           if( n1+n2>sizeof(zErrMsg)-30 ){
65129             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "...");
65130             n1 += 3;
65131             break;
65132           }else{
65133             sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
65134             n1 += n2;
65135           }
65136         }
65137         sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], 
65138             pIdx->nColumn>1 ? " are not unique" : " is not unique");
65139         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
65140         break;
65141       }
65142       case OE_Ignore: {
65143         assert( seenReplace==0 );
65144         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
65145         break;
65146       }
65147       case OE_Replace: {
65148         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
65149         seenReplace = 1;
65150         break;
65151       }
65152     }
65153     sqlite3VdbeJumpHere(v, j2);
65154     sqlite3VdbeJumpHere(v, j3);
65155     sqlite3ReleaseTempReg(pParse, regR);
65156   }
65157 }
65158
65159 /*
65160 ** This routine generates code to finish the INSERT or UPDATE operation
65161 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
65162 ** A consecutive range of registers starting at regRowid contains the
65163 ** rowid and the content to be inserted.
65164 **
65165 ** The arguments to this routine should be the same as the first six
65166 ** arguments to sqlite3GenerateConstraintChecks.
65167 */
65168 SQLITE_PRIVATE void sqlite3CompleteInsertion(
65169   Parse *pParse,      /* The parser context */
65170   Table *pTab,        /* the table into which we are inserting */
65171   int baseCur,        /* Index of a read/write cursor pointing at pTab */
65172   int regRowid,       /* Range of content */
65173   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
65174   int rowidChng,      /* True if the record number will change */
65175   int isUpdate,       /* True for UPDATE, False for INSERT */
65176   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
65177   int appendBias      /* True if this is likely to be an append */
65178 ){
65179   int i;
65180   Vdbe *v;
65181   int nIdx;
65182   Index *pIdx;
65183   int pik_flags;
65184   int regData;
65185   int regRec;
65186
65187   v = sqlite3GetVdbe(pParse);
65188   assert( v!=0 );
65189   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
65190   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
65191   for(i=nIdx-1; i>=0; i--){
65192     if( aRegIdx[i]==0 ) continue;
65193     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
65194   }
65195   regData = regRowid + 1;
65196   regRec = sqlite3GetTempReg(pParse);
65197   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
65198   sqlite3TableAffinityStr(v, pTab);
65199   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
65200 #ifndef SQLITE_OMIT_TRIGGER
65201   if( newIdx>=0 ){
65202     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
65203   }
65204 #endif
65205   if( pParse->nested ){
65206     pik_flags = 0;
65207   }else{
65208     pik_flags = OPFLAG_NCHANGE;
65209     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
65210   }
65211   if( appendBias ){
65212     pik_flags |= OPFLAG_APPEND;
65213   }
65214   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
65215   if( !pParse->nested ){
65216     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
65217   }
65218   sqlite3VdbeChangeP5(v, pik_flags);
65219 }
65220
65221 /*
65222 ** Generate code that will open cursors for a table and for all
65223 ** indices of that table.  The "baseCur" parameter is the cursor number used
65224 ** for the table.  Indices are opened on subsequent cursors.
65225 **
65226 ** Return the number of indices on the table.
65227 */
65228 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
65229   Parse *pParse,   /* Parsing context */
65230   Table *pTab,     /* Table to be opened */
65231   int baseCur,        /* Cursor number assigned to the table */
65232   int op           /* OP_OpenRead or OP_OpenWrite */
65233 ){
65234   int i;
65235   int iDb;
65236   Index *pIdx;
65237   Vdbe *v;
65238
65239   if( IsVirtual(pTab) ) return 0;
65240   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65241   v = sqlite3GetVdbe(pParse);
65242   assert( v!=0 );
65243   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
65244   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
65245     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
65246     assert( pIdx->pSchema==pTab->pSchema );
65247     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
65248                       (char*)pKey, P4_KEYINFO_HANDOFF);
65249     VdbeComment((v, "%s", pIdx->zName));
65250   }
65251   if( pParse->nTab<=baseCur+i ){
65252     pParse->nTab = baseCur+i;
65253   }
65254   return i-1;
65255 }
65256
65257
65258 #ifdef SQLITE_TEST
65259 /*
65260 ** The following global variable is incremented whenever the
65261 ** transfer optimization is used.  This is used for testing
65262 ** purposes only - to make sure the transfer optimization really
65263 ** is happening when it is suppose to.
65264 */
65265 SQLITE_API int sqlite3_xferopt_count;
65266 #endif /* SQLITE_TEST */
65267
65268
65269 #ifndef SQLITE_OMIT_XFER_OPT
65270 /*
65271 ** Check to collation names to see if they are compatible.
65272 */
65273 static int xferCompatibleCollation(const char *z1, const char *z2){
65274   if( z1==0 ){
65275     return z2==0;
65276   }
65277   if( z2==0 ){
65278     return 0;
65279   }
65280   return sqlite3StrICmp(z1, z2)==0;
65281 }
65282
65283
65284 /*
65285 ** Check to see if index pSrc is compatible as a source of data
65286 ** for index pDest in an insert transfer optimization.  The rules
65287 ** for a compatible index:
65288 **
65289 **    *   The index is over the same set of columns
65290 **    *   The same DESC and ASC markings occurs on all columns
65291 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
65292 **    *   The same collating sequence on each column
65293 */
65294 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
65295   int i;
65296   assert( pDest && pSrc );
65297   assert( pDest->pTable!=pSrc->pTable );
65298   if( pDest->nColumn!=pSrc->nColumn ){
65299     return 0;   /* Different number of columns */
65300   }
65301   if( pDest->onError!=pSrc->onError ){
65302     return 0;   /* Different conflict resolution strategies */
65303   }
65304   for(i=0; i<pSrc->nColumn; i++){
65305     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
65306       return 0;   /* Different columns indexed */
65307     }
65308     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
65309       return 0;   /* Different sort orders */
65310     }
65311     if( pSrc->azColl[i]!=pDest->azColl[i] ){
65312       return 0;   /* Different collating sequences */
65313     }
65314   }
65315
65316   /* If no test above fails then the indices must be compatible */
65317   return 1;
65318 }
65319
65320 /*
65321 ** Attempt the transfer optimization on INSERTs of the form
65322 **
65323 **     INSERT INTO tab1 SELECT * FROM tab2;
65324 **
65325 ** This optimization is only attempted if
65326 **
65327 **    (1)  tab1 and tab2 have identical schemas including all the
65328 **         same indices and constraints
65329 **
65330 **    (2)  tab1 and tab2 are different tables
65331 **
65332 **    (3)  There must be no triggers on tab1
65333 **
65334 **    (4)  The result set of the SELECT statement is "*"
65335 **
65336 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
65337 **         or LIMIT clause.
65338 **
65339 **    (6)  The SELECT statement is a simple (not a compound) select that
65340 **         contains only tab2 in its FROM clause
65341 **
65342 ** This method for implementing the INSERT transfers raw records from
65343 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
65344 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
65345 ** the resulting tab1 has much less fragmentation.
65346 **
65347 ** This routine returns TRUE if the optimization is attempted.  If any
65348 ** of the conditions above fail so that the optimization should not
65349 ** be attempted, then this routine returns FALSE.
65350 */
65351 static int xferOptimization(
65352   Parse *pParse,        /* Parser context */
65353   Table *pDest,         /* The table we are inserting into */
65354   Select *pSelect,      /* A SELECT statement to use as the data source */
65355   int onError,          /* How to handle constraint errors */
65356   int iDbDest           /* The database of pDest */
65357 ){
65358   ExprList *pEList;                /* The result set of the SELECT */
65359   Table *pSrc;                     /* The table in the FROM clause of SELECT */
65360   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
65361   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
65362   int i;                           /* Loop counter */
65363   int iDbSrc;                      /* The database of pSrc */
65364   int iSrc, iDest;                 /* Cursors from source and destination */
65365   int addr1, addr2;                /* Loop addresses */
65366   int emptyDestTest;               /* Address of test for empty pDest */
65367   int emptySrcTest;                /* Address of test for empty pSrc */
65368   Vdbe *v;                         /* The VDBE we are building */
65369   KeyInfo *pKey;                   /* Key information for an index */
65370   int regAutoinc;                  /* Memory register used by AUTOINC */
65371   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
65372   int regData, regRowid;           /* Registers holding data and rowid */
65373
65374   if( pSelect==0 ){
65375     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
65376   }
65377   if( pDest->pTrigger ){
65378     return 0;   /* tab1 must not have triggers */
65379   }
65380 #ifndef SQLITE_OMIT_VIRTUALTABLE
65381   if( pDest->tabFlags & TF_Virtual ){
65382     return 0;   /* tab1 must not be a virtual table */
65383   }
65384 #endif
65385   if( onError==OE_Default ){
65386     onError = OE_Abort;
65387   }
65388   if( onError!=OE_Abort && onError!=OE_Rollback ){
65389     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
65390   }
65391   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
65392   if( pSelect->pSrc->nSrc!=1 ){
65393     return 0;   /* FROM clause must have exactly one term */
65394   }
65395   if( pSelect->pSrc->a[0].pSelect ){
65396     return 0;   /* FROM clause cannot contain a subquery */
65397   }
65398   if( pSelect->pWhere ){
65399     return 0;   /* SELECT may not have a WHERE clause */
65400   }
65401   if( pSelect->pOrderBy ){
65402     return 0;   /* SELECT may not have an ORDER BY clause */
65403   }
65404   /* Do not need to test for a HAVING clause.  If HAVING is present but
65405   ** there is no ORDER BY, we will get an error. */
65406   if( pSelect->pGroupBy ){
65407     return 0;   /* SELECT may not have a GROUP BY clause */
65408   }
65409   if( pSelect->pLimit ){
65410     return 0;   /* SELECT may not have a LIMIT clause */
65411   }
65412   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
65413   if( pSelect->pPrior ){
65414     return 0;   /* SELECT may not be a compound query */
65415   }
65416   if( pSelect->selFlags & SF_Distinct ){
65417     return 0;   /* SELECT may not be DISTINCT */
65418   }
65419   pEList = pSelect->pEList;
65420   assert( pEList!=0 );
65421   if( pEList->nExpr!=1 ){
65422     return 0;   /* The result set must have exactly one column */
65423   }
65424   assert( pEList->a[0].pExpr );
65425   if( pEList->a[0].pExpr->op!=TK_ALL ){
65426     return 0;   /* The result set must be the special operator "*" */
65427   }
65428
65429   /* At this point we have established that the statement is of the
65430   ** correct syntactic form to participate in this optimization.  Now
65431   ** we have to check the semantics.
65432   */
65433   pItem = pSelect->pSrc->a;
65434   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
65435   if( pSrc==0 ){
65436     return 0;   /* FROM clause does not contain a real table */
65437   }
65438   if( pSrc==pDest ){
65439     return 0;   /* tab1 and tab2 may not be the same table */
65440   }
65441 #ifndef SQLITE_OMIT_VIRTUALTABLE
65442   if( pSrc->tabFlags & TF_Virtual ){
65443     return 0;   /* tab2 must not be a virtual table */
65444   }
65445 #endif
65446   if( pSrc->pSelect ){
65447     return 0;   /* tab2 may not be a view */
65448   }
65449   if( pDest->nCol!=pSrc->nCol ){
65450     return 0;   /* Number of columns must be the same in tab1 and tab2 */
65451   }
65452   if( pDest->iPKey!=pSrc->iPKey ){
65453     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
65454   }
65455   for(i=0; i<pDest->nCol; i++){
65456     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
65457       return 0;    /* Affinity must be the same on all columns */
65458     }
65459     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
65460       return 0;    /* Collating sequence must be the same on all columns */
65461     }
65462     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
65463       return 0;    /* tab2 must be NOT NULL if tab1 is */
65464     }
65465   }
65466   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
65467     if( pDestIdx->onError!=OE_None ){
65468       destHasUniqueIdx = 1;
65469     }
65470     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
65471       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
65472     }
65473     if( pSrcIdx==0 ){
65474       return 0;    /* pDestIdx has no corresponding index in pSrc */
65475     }
65476   }
65477 #ifndef SQLITE_OMIT_CHECK
65478   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
65479     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
65480   }
65481 #endif
65482
65483   /* If we get this far, it means either:
65484   **
65485   **    *   We can always do the transfer if the table contains an
65486   **        an integer primary key
65487   **
65488   **    *   We can conditionally do the transfer if the destination
65489   **        table is empty.
65490   */
65491 #ifdef SQLITE_TEST
65492   sqlite3_xferopt_count++;
65493 #endif
65494   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
65495   v = sqlite3GetVdbe(pParse);
65496   sqlite3CodeVerifySchema(pParse, iDbSrc);
65497   iSrc = pParse->nTab++;
65498   iDest = pParse->nTab++;
65499   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
65500   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
65501   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
65502     /* If tables do not have an INTEGER PRIMARY KEY and there
65503     ** are indices to be copied and the destination is not empty,
65504     ** we have to disallow the transfer optimization because the
65505     ** the rowids might change which will mess up indexing.
65506     **
65507     ** Or if the destination has a UNIQUE index and is not empty,
65508     ** we also disallow the transfer optimization because we cannot
65509     ** insure that all entries in the union of DEST and SRC will be
65510     ** unique.
65511     */
65512     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
65513     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
65514     sqlite3VdbeJumpHere(v, addr1);
65515   }else{
65516     emptyDestTest = 0;
65517   }
65518   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
65519   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
65520   regData = sqlite3GetTempReg(pParse);
65521   regRowid = sqlite3GetTempReg(pParse);
65522   if( pDest->iPKey>=0 ){
65523     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
65524     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
65525     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
65526                       "PRIMARY KEY must be unique", P4_STATIC);
65527     sqlite3VdbeJumpHere(v, addr2);
65528     autoIncStep(pParse, regAutoinc, regRowid);
65529   }else if( pDest->pIndex==0 ){
65530     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
65531   }else{
65532     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
65533     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
65534   }
65535   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
65536   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
65537   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
65538   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
65539   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
65540   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
65541   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
65542     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
65543       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
65544     }
65545     assert( pSrcIdx );
65546     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
65547     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65548     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
65549     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
65550                       (char*)pKey, P4_KEYINFO_HANDOFF);
65551     VdbeComment((v, "%s", pSrcIdx->zName));
65552     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
65553     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
65554                       (char*)pKey, P4_KEYINFO_HANDOFF);
65555     VdbeComment((v, "%s", pDestIdx->zName));
65556     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
65557     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
65558     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
65559     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
65560     sqlite3VdbeJumpHere(v, addr1);
65561   }
65562   sqlite3VdbeJumpHere(v, emptySrcTest);
65563   sqlite3ReleaseTempReg(pParse, regRowid);
65564   sqlite3ReleaseTempReg(pParse, regData);
65565   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
65566   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65567   if( emptyDestTest ){
65568     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
65569     sqlite3VdbeJumpHere(v, emptyDestTest);
65570     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
65571     return 0;
65572   }else{
65573     return 1;
65574   }
65575 }
65576 #endif /* SQLITE_OMIT_XFER_OPT */
65577
65578 /* Make sure "isView" gets undefined in case this file becomes part of
65579 ** the amalgamation - so that subsequent files do not see isView as a
65580 ** macro. */
65581 #undef isView
65582
65583 /************** End of insert.c **********************************************/
65584 /************** Begin file legacy.c ******************************************/
65585 /*
65586 ** 2001 September 15
65587 **
65588 ** The author disclaims copyright to this source code.  In place of
65589 ** a legal notice, here is a blessing:
65590 **
65591 **    May you do good and not evil.
65592 **    May you find forgiveness for yourself and forgive others.
65593 **    May you share freely, never taking more than you give.
65594 **
65595 *************************************************************************
65596 ** Main file for the SQLite library.  The routines in this file
65597 ** implement the programmer interface to the library.  Routines in
65598 ** other files are for internal use by SQLite and should not be
65599 ** accessed by users of the library.
65600 **
65601 ** $Id: legacy.c,v 1.29 2008/08/02 03:50:39 drh Exp $
65602 */
65603
65604
65605 /*
65606 ** Execute SQL code.  Return one of the SQLITE_ success/failure
65607 ** codes.  Also write an error message into memory obtained from
65608 ** malloc() and make *pzErrMsg point to that message.
65609 **
65610 ** If the SQL is a query, then for each row in the query result
65611 ** the xCallback() function is called.  pArg becomes the first
65612 ** argument to xCallback().  If xCallback=NULL then no callback
65613 ** is invoked, even for queries.
65614 */
65615 SQLITE_API int sqlite3_exec(
65616   sqlite3 *db,                /* The database on which the SQL executes */
65617   const char *zSql,           /* The SQL to be executed */
65618   sqlite3_callback xCallback, /* Invoke this callback routine */
65619   void *pArg,                 /* First argument to xCallback() */
65620   char **pzErrMsg             /* Write error messages here */
65621 ){
65622   int rc = SQLITE_OK;
65623   const char *zLeftover;
65624   sqlite3_stmt *pStmt = 0;
65625   char **azCols = 0;
65626
65627   int nRetry = 0;
65628   int nCallback;
65629
65630   if( zSql==0 ) zSql = "";
65631
65632   sqlite3_mutex_enter(db->mutex);
65633   sqlite3Error(db, SQLITE_OK, 0);
65634   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
65635     int nCol;
65636     char **azVals = 0;
65637
65638     pStmt = 0;
65639     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
65640     assert( rc==SQLITE_OK || pStmt==0 );
65641     if( rc!=SQLITE_OK ){
65642       continue;
65643     }
65644     if( !pStmt ){
65645       /* this happens for a comment or white-space */
65646       zSql = zLeftover;
65647       continue;
65648     }
65649
65650     nCallback = 0;
65651     nCol = sqlite3_column_count(pStmt);
65652
65653     while( 1 ){
65654       int i;
65655       rc = sqlite3_step(pStmt);
65656
65657       /* Invoke the callback function if required */
65658       if( xCallback && (SQLITE_ROW==rc || 
65659           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
65660         if( 0==nCallback ){
65661           if( azCols==0 ){
65662             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
65663             if( azCols==0 ){
65664               goto exec_out;
65665             }
65666           }
65667           for(i=0; i<nCol; i++){
65668             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
65669             /* sqlite3VdbeSetColName() installs column names as UTF8
65670             ** strings so there is no way for sqlite3_column_name() to fail. */
65671             assert( azCols[i]!=0 );
65672           }
65673           nCallback++;
65674         }
65675         if( rc==SQLITE_ROW ){
65676           azVals = &azCols[nCol];
65677           for(i=0; i<nCol; i++){
65678             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
65679             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
65680               db->mallocFailed = 1;
65681               goto exec_out;
65682             }
65683           }
65684         }
65685         if( xCallback(pArg, nCol, azVals, azCols) ){
65686           rc = SQLITE_ABORT;
65687           sqlite3_finalize(pStmt);
65688           pStmt = 0;
65689           sqlite3Error(db, SQLITE_ABORT, 0);
65690           goto exec_out;
65691         }
65692       }
65693
65694       if( rc!=SQLITE_ROW ){
65695         rc = sqlite3_finalize(pStmt);
65696         pStmt = 0;
65697         if( rc!=SQLITE_SCHEMA ){
65698           nRetry = 0;
65699           zSql = zLeftover;
65700           while( isspace((unsigned char)zSql[0]) ) zSql++;
65701         }
65702         break;
65703       }
65704     }
65705
65706     sqlite3DbFree(db, azCols);
65707     azCols = 0;
65708   }
65709
65710 exec_out:
65711   if( pStmt ) sqlite3_finalize(pStmt);
65712   sqlite3DbFree(db, azCols);
65713
65714   rc = sqlite3ApiExit(db, rc);
65715   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
65716     int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
65717     *pzErrMsg = sqlite3Malloc(nErrMsg);
65718     if( *pzErrMsg ){
65719       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
65720     }
65721   }else if( pzErrMsg ){
65722     *pzErrMsg = 0;
65723   }
65724
65725   assert( (rc&db->errMask)==rc );
65726   sqlite3_mutex_leave(db->mutex);
65727   return rc;
65728 }
65729
65730 /************** End of legacy.c **********************************************/
65731 /************** Begin file loadext.c *****************************************/
65732 /*
65733 ** 2006 June 7
65734 **
65735 ** The author disclaims copyright to this source code.  In place of
65736 ** a legal notice, here is a blessing:
65737 **
65738 **    May you do good and not evil.
65739 **    May you find forgiveness for yourself and forgive others.
65740 **    May you share freely, never taking more than you give.
65741 **
65742 *************************************************************************
65743 ** This file contains code used to dynamically load extensions into
65744 ** the SQLite library.
65745 **
65746 ** $Id: loadext.c,v 1.56 2008/10/12 00:27:53 shane Exp $
65747 */
65748
65749 #ifndef SQLITE_CORE
65750   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
65751 #endif
65752 /************** Include sqlite3ext.h in the middle of loadext.c **************/
65753 /************** Begin file sqlite3ext.h **************************************/
65754 /*
65755 ** 2006 June 7
65756 **
65757 ** The author disclaims copyright to this source code.  In place of
65758 ** a legal notice, here is a blessing:
65759 **
65760 **    May you do good and not evil.
65761 **    May you find forgiveness for yourself and forgive others.
65762 **    May you share freely, never taking more than you give.
65763 **
65764 *************************************************************************
65765 ** This header file defines the SQLite interface for use by
65766 ** shared libraries that want to be imported as extensions into
65767 ** an SQLite instance.  Shared libraries that intend to be loaded
65768 ** as extensions by SQLite should #include this file instead of 
65769 ** sqlite3.h.
65770 **
65771 ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
65772 */
65773 #ifndef _SQLITE3EXT_H_
65774 #define _SQLITE3EXT_H_
65775
65776 typedef struct sqlite3_api_routines sqlite3_api_routines;
65777
65778 /*
65779 ** The following structure holds pointers to all of the SQLite API
65780 ** routines.
65781 **
65782 ** WARNING:  In order to maintain backwards compatibility, add new
65783 ** interfaces to the end of this structure only.  If you insert new
65784 ** interfaces in the middle of this structure, then older different
65785 ** versions of SQLite will not be able to load each others' shared
65786 ** libraries!
65787 */
65788 struct sqlite3_api_routines {
65789   void * (*aggregate_context)(sqlite3_context*,int nBytes);
65790   int  (*aggregate_count)(sqlite3_context*);
65791   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
65792   int  (*bind_double)(sqlite3_stmt*,int,double);
65793   int  (*bind_int)(sqlite3_stmt*,int,int);
65794   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
65795   int  (*bind_null)(sqlite3_stmt*,int);
65796   int  (*bind_parameter_count)(sqlite3_stmt*);
65797   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
65798   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
65799   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
65800   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
65801   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
65802   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
65803   int  (*busy_timeout)(sqlite3*,int ms);
65804   int  (*changes)(sqlite3*);
65805   int  (*close)(sqlite3*);
65806   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
65807   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
65808   const void * (*column_blob)(sqlite3_stmt*,int iCol);
65809   int  (*column_bytes)(sqlite3_stmt*,int iCol);
65810   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
65811   int  (*column_count)(sqlite3_stmt*pStmt);
65812   const char * (*column_database_name)(sqlite3_stmt*,int);
65813   const void * (*column_database_name16)(sqlite3_stmt*,int);
65814   const char * (*column_decltype)(sqlite3_stmt*,int i);
65815   const void * (*column_decltype16)(sqlite3_stmt*,int);
65816   double  (*column_double)(sqlite3_stmt*,int iCol);
65817   int  (*column_int)(sqlite3_stmt*,int iCol);
65818   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
65819   const char * (*column_name)(sqlite3_stmt*,int);
65820   const void * (*column_name16)(sqlite3_stmt*,int);
65821   const char * (*column_origin_name)(sqlite3_stmt*,int);
65822   const void * (*column_origin_name16)(sqlite3_stmt*,int);
65823   const char * (*column_table_name)(sqlite3_stmt*,int);
65824   const void * (*column_table_name16)(sqlite3_stmt*,int);
65825   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
65826   const void * (*column_text16)(sqlite3_stmt*,int iCol);
65827   int  (*column_type)(sqlite3_stmt*,int iCol);
65828   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
65829   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
65830   int  (*complete)(const char*sql);
65831   int  (*complete16)(const void*sql);
65832   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
65833   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
65834   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*));
65835   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*));
65836   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
65837   int  (*data_count)(sqlite3_stmt*pStmt);
65838   sqlite3 * (*db_handle)(sqlite3_stmt*);
65839   int (*declare_vtab)(sqlite3*,const char*);
65840   int  (*enable_shared_cache)(int);
65841   int  (*errcode)(sqlite3*db);
65842   const char * (*errmsg)(sqlite3*);
65843   const void * (*errmsg16)(sqlite3*);
65844   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
65845   int  (*expired)(sqlite3_stmt*);
65846   int  (*finalize)(sqlite3_stmt*pStmt);
65847   void  (*free)(void*);
65848   void  (*free_table)(char**result);
65849   int  (*get_autocommit)(sqlite3*);
65850   void * (*get_auxdata)(sqlite3_context*,int);
65851   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
65852   int  (*global_recover)(void);
65853   void  (*interruptx)(sqlite3*);
65854   sqlite_int64  (*last_insert_rowid)(sqlite3*);
65855   const char * (*libversion)(void);
65856   int  (*libversion_number)(void);
65857   void *(*malloc)(int);
65858   char * (*mprintf)(const char*,...);
65859   int  (*open)(const char*,sqlite3**);
65860   int  (*open16)(const void*,sqlite3**);
65861   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
65862   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
65863   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
65864   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
65865   void *(*realloc)(void*,int);
65866   int  (*reset)(sqlite3_stmt*pStmt);
65867   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
65868   void  (*result_double)(sqlite3_context*,double);
65869   void  (*result_error)(sqlite3_context*,const char*,int);
65870   void  (*result_error16)(sqlite3_context*,const void*,int);
65871   void  (*result_int)(sqlite3_context*,int);
65872   void  (*result_int64)(sqlite3_context*,sqlite_int64);
65873   void  (*result_null)(sqlite3_context*);
65874   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
65875   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
65876   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
65877   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
65878   void  (*result_value)(sqlite3_context*,sqlite3_value*);
65879   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
65880   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
65881   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
65882   char * (*snprintf)(int,char*,const char*,...);
65883   int  (*step)(sqlite3_stmt*);
65884   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
65885   void  (*thread_cleanup)(void);
65886   int  (*total_changes)(sqlite3*);
65887   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
65888   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
65889   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
65890   void * (*user_data)(sqlite3_context*);
65891   const void * (*value_blob)(sqlite3_value*);
65892   int  (*value_bytes)(sqlite3_value*);
65893   int  (*value_bytes16)(sqlite3_value*);
65894   double  (*value_double)(sqlite3_value*);
65895   int  (*value_int)(sqlite3_value*);
65896   sqlite_int64  (*value_int64)(sqlite3_value*);
65897   int  (*value_numeric_type)(sqlite3_value*);
65898   const unsigned char * (*value_text)(sqlite3_value*);
65899   const void * (*value_text16)(sqlite3_value*);
65900   const void * (*value_text16be)(sqlite3_value*);
65901   const void * (*value_text16le)(sqlite3_value*);
65902   int  (*value_type)(sqlite3_value*);
65903   char *(*vmprintf)(const char*,va_list);
65904   /* Added ??? */
65905   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
65906   /* Added by 3.3.13 */
65907   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
65908   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
65909   int (*clear_bindings)(sqlite3_stmt*);
65910   /* Added by 3.4.1 */
65911   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
65912   /* Added by 3.5.0 */
65913   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
65914   int (*blob_bytes)(sqlite3_blob*);
65915   int (*blob_close)(sqlite3_blob*);
65916   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
65917   int (*blob_read)(sqlite3_blob*,void*,int,int);
65918   int (*blob_write)(sqlite3_blob*,const void*,int,int);
65919   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
65920   int (*file_control)(sqlite3*,const char*,int,void*);
65921   sqlite3_int64 (*memory_highwater)(int);
65922   sqlite3_int64 (*memory_used)(void);
65923   sqlite3_mutex *(*mutex_alloc)(int);
65924   void (*mutex_enter)(sqlite3_mutex*);
65925   void (*mutex_free)(sqlite3_mutex*);
65926   void (*mutex_leave)(sqlite3_mutex*);
65927   int (*mutex_try)(sqlite3_mutex*);
65928   int (*open_v2)(const char*,sqlite3**,int,const char*);
65929   int (*release_memory)(int);
65930   void (*result_error_nomem)(sqlite3_context*);
65931   void (*result_error_toobig)(sqlite3_context*);
65932   int (*sleep)(int);
65933   void (*soft_heap_limit)(int);
65934   sqlite3_vfs *(*vfs_find)(const char*);
65935   int (*vfs_register)(sqlite3_vfs*,int);
65936   int (*vfs_unregister)(sqlite3_vfs*);
65937   int (*xthreadsafe)(void);
65938   void (*result_zeroblob)(sqlite3_context*,int);
65939   void (*result_error_code)(sqlite3_context*,int);
65940   int (*test_control)(int, ...);
65941   void (*randomness)(int,void*);
65942   sqlite3 *(*context_db_handle)(sqlite3_context*);
65943   int (*extended_result_codes)(sqlite3*,int);
65944   int (*limit)(sqlite3*,int,int);
65945   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
65946   const char *(*sql)(sqlite3_stmt*);
65947   int (*status)(int,int*,int*,int);
65948 };
65949
65950 /*
65951 ** The following macros redefine the API routines so that they are
65952 ** redirected throught the global sqlite3_api structure.
65953 **
65954 ** This header file is also used by the loadext.c source file
65955 ** (part of the main SQLite library - not an extension) so that
65956 ** it can get access to the sqlite3_api_routines structure
65957 ** definition.  But the main library does not want to redefine
65958 ** the API.  So the redefinition macros are only valid if the
65959 ** SQLITE_CORE macros is undefined.
65960 */
65961 #ifndef SQLITE_CORE
65962 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
65963 #ifndef SQLITE_OMIT_DEPRECATED
65964 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
65965 #endif
65966 #define sqlite3_bind_blob              sqlite3_api->bind_blob
65967 #define sqlite3_bind_double            sqlite3_api->bind_double
65968 #define sqlite3_bind_int               sqlite3_api->bind_int
65969 #define sqlite3_bind_int64             sqlite3_api->bind_int64
65970 #define sqlite3_bind_null              sqlite3_api->bind_null
65971 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
65972 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
65973 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
65974 #define sqlite3_bind_text              sqlite3_api->bind_text
65975 #define sqlite3_bind_text16            sqlite3_api->bind_text16
65976 #define sqlite3_bind_value             sqlite3_api->bind_value
65977 #define sqlite3_busy_handler           sqlite3_api->busy_handler
65978 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
65979 #define sqlite3_changes                sqlite3_api->changes
65980 #define sqlite3_close                  sqlite3_api->close
65981 #define sqlite3_collation_needed       sqlite3_api->collation_needed
65982 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
65983 #define sqlite3_column_blob            sqlite3_api->column_blob
65984 #define sqlite3_column_bytes           sqlite3_api->column_bytes
65985 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
65986 #define sqlite3_column_count           sqlite3_api->column_count
65987 #define sqlite3_column_database_name   sqlite3_api->column_database_name
65988 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
65989 #define sqlite3_column_decltype        sqlite3_api->column_decltype
65990 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
65991 #define sqlite3_column_double          sqlite3_api->column_double
65992 #define sqlite3_column_int             sqlite3_api->column_int
65993 #define sqlite3_column_int64           sqlite3_api->column_int64
65994 #define sqlite3_column_name            sqlite3_api->column_name
65995 #define sqlite3_column_name16          sqlite3_api->column_name16
65996 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
65997 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
65998 #define sqlite3_column_table_name      sqlite3_api->column_table_name
65999 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
66000 #define sqlite3_column_text            sqlite3_api->column_text
66001 #define sqlite3_column_text16          sqlite3_api->column_text16
66002 #define sqlite3_column_type            sqlite3_api->column_type
66003 #define sqlite3_column_value           sqlite3_api->column_value
66004 #define sqlite3_commit_hook            sqlite3_api->commit_hook
66005 #define sqlite3_complete               sqlite3_api->complete
66006 #define sqlite3_complete16             sqlite3_api->complete16
66007 #define sqlite3_create_collation       sqlite3_api->create_collation
66008 #define sqlite3_create_collation16     sqlite3_api->create_collation16
66009 #define sqlite3_create_function        sqlite3_api->create_function
66010 #define sqlite3_create_function16      sqlite3_api->create_function16
66011 #define sqlite3_create_module          sqlite3_api->create_module
66012 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
66013 #define sqlite3_data_count             sqlite3_api->data_count
66014 #define sqlite3_db_handle              sqlite3_api->db_handle
66015 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
66016 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
66017 #define sqlite3_errcode                sqlite3_api->errcode
66018 #define sqlite3_errmsg                 sqlite3_api->errmsg
66019 #define sqlite3_errmsg16               sqlite3_api->errmsg16
66020 #define sqlite3_exec                   sqlite3_api->exec
66021 #ifndef SQLITE_OMIT_DEPRECATED
66022 #define sqlite3_expired                sqlite3_api->expired
66023 #endif
66024 #define sqlite3_finalize               sqlite3_api->finalize
66025 #define sqlite3_free                   sqlite3_api->free
66026 #define sqlite3_free_table             sqlite3_api->free_table
66027 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
66028 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
66029 #define sqlite3_get_table              sqlite3_api->get_table
66030 #ifndef SQLITE_OMIT_DEPRECATED
66031 #define sqlite3_global_recover         sqlite3_api->global_recover
66032 #endif
66033 #define sqlite3_interrupt              sqlite3_api->interruptx
66034 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
66035 #define sqlite3_libversion             sqlite3_api->libversion
66036 #define sqlite3_libversion_number      sqlite3_api->libversion_number
66037 #define sqlite3_malloc                 sqlite3_api->malloc
66038 #define sqlite3_mprintf                sqlite3_api->mprintf
66039 #define sqlite3_open                   sqlite3_api->open
66040 #define sqlite3_open16                 sqlite3_api->open16
66041 #define sqlite3_prepare                sqlite3_api->prepare
66042 #define sqlite3_prepare16              sqlite3_api->prepare16
66043 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
66044 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
66045 #define sqlite3_profile                sqlite3_api->profile
66046 #define sqlite3_progress_handler       sqlite3_api->progress_handler
66047 #define sqlite3_realloc                sqlite3_api->realloc
66048 #define sqlite3_reset                  sqlite3_api->reset
66049 #define sqlite3_result_blob            sqlite3_api->result_blob
66050 #define sqlite3_result_double          sqlite3_api->result_double
66051 #define sqlite3_result_error           sqlite3_api->result_error
66052 #define sqlite3_result_error16         sqlite3_api->result_error16
66053 #define sqlite3_result_int             sqlite3_api->result_int
66054 #define sqlite3_result_int64           sqlite3_api->result_int64
66055 #define sqlite3_result_null            sqlite3_api->result_null
66056 #define sqlite3_result_text            sqlite3_api->result_text
66057 #define sqlite3_result_text16          sqlite3_api->result_text16
66058 #define sqlite3_result_text16be        sqlite3_api->result_text16be
66059 #define sqlite3_result_text16le        sqlite3_api->result_text16le
66060 #define sqlite3_result_value           sqlite3_api->result_value
66061 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
66062 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
66063 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
66064 #define sqlite3_snprintf               sqlite3_api->snprintf
66065 #define sqlite3_step                   sqlite3_api->step
66066 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
66067 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
66068 #define sqlite3_total_changes          sqlite3_api->total_changes
66069 #define sqlite3_trace                  sqlite3_api->trace
66070 #ifndef SQLITE_OMIT_DEPRECATED
66071 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
66072 #endif
66073 #define sqlite3_update_hook            sqlite3_api->update_hook
66074 #define sqlite3_user_data              sqlite3_api->user_data
66075 #define sqlite3_value_blob             sqlite3_api->value_blob
66076 #define sqlite3_value_bytes            sqlite3_api->value_bytes
66077 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
66078 #define sqlite3_value_double           sqlite3_api->value_double
66079 #define sqlite3_value_int              sqlite3_api->value_int
66080 #define sqlite3_value_int64            sqlite3_api->value_int64
66081 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
66082 #define sqlite3_value_text             sqlite3_api->value_text
66083 #define sqlite3_value_text16           sqlite3_api->value_text16
66084 #define sqlite3_value_text16be         sqlite3_api->value_text16be
66085 #define sqlite3_value_text16le         sqlite3_api->value_text16le
66086 #define sqlite3_value_type             sqlite3_api->value_type
66087 #define sqlite3_vmprintf               sqlite3_api->vmprintf
66088 #define sqlite3_overload_function      sqlite3_api->overload_function
66089 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
66090 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
66091 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
66092 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
66093 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
66094 #define sqlite3_blob_close             sqlite3_api->blob_close
66095 #define sqlite3_blob_open              sqlite3_api->blob_open
66096 #define sqlite3_blob_read              sqlite3_api->blob_read
66097 #define sqlite3_blob_write             sqlite3_api->blob_write
66098 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
66099 #define sqlite3_file_control           sqlite3_api->file_control
66100 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
66101 #define sqlite3_memory_used            sqlite3_api->memory_used
66102 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
66103 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
66104 #define sqlite3_mutex_free             sqlite3_api->mutex_free
66105 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
66106 #define sqlite3_mutex_try              sqlite3_api->mutex_try
66107 #define sqlite3_open_v2                sqlite3_api->open_v2
66108 #define sqlite3_release_memory         sqlite3_api->release_memory
66109 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
66110 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
66111 #define sqlite3_sleep                  sqlite3_api->sleep
66112 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
66113 #define sqlite3_vfs_find               sqlite3_api->vfs_find
66114 #define sqlite3_vfs_register           sqlite3_api->vfs_register
66115 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
66116 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
66117 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
66118 #define sqlite3_result_error_code      sqlite3_api->result_error_code
66119 #define sqlite3_test_control           sqlite3_api->test_control
66120 #define sqlite3_randomness             sqlite3_api->randomness
66121 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
66122 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
66123 #define sqlite3_limit                  sqlite3_api->limit
66124 #define sqlite3_next_stmt              sqlite3_api->next_stmt
66125 #define sqlite3_sql                    sqlite3_api->sql
66126 #define sqlite3_status                 sqlite3_api->status
66127 #endif /* SQLITE_CORE */
66128
66129 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
66130 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
66131
66132 #endif /* _SQLITE3EXT_H_ */
66133
66134 /************** End of sqlite3ext.h ******************************************/
66135 /************** Continuing where we left off in loadext.c ********************/
66136
66137 #ifndef SQLITE_OMIT_LOAD_EXTENSION
66138
66139 /*
66140 ** Some API routines are omitted when various features are
66141 ** excluded from a build of SQLite.  Substitute a NULL pointer
66142 ** for any missing APIs.
66143 */
66144 #ifndef SQLITE_ENABLE_COLUMN_METADATA
66145 # define sqlite3_column_database_name   0
66146 # define sqlite3_column_database_name16 0
66147 # define sqlite3_column_table_name      0
66148 # define sqlite3_column_table_name16    0
66149 # define sqlite3_column_origin_name     0
66150 # define sqlite3_column_origin_name16   0
66151 # define sqlite3_table_column_metadata  0
66152 #endif
66153
66154 #ifdef SQLITE_OMIT_AUTHORIZATION
66155 # define sqlite3_set_authorizer         0
66156 #endif
66157
66158 #ifdef SQLITE_OMIT_UTF16
66159 # define sqlite3_bind_text16            0
66160 # define sqlite3_collation_needed16     0
66161 # define sqlite3_column_decltype16      0
66162 # define sqlite3_column_name16          0
66163 # define sqlite3_column_text16          0
66164 # define sqlite3_complete16             0
66165 # define sqlite3_create_collation16     0
66166 # define sqlite3_create_function16      0
66167 # define sqlite3_errmsg16               0
66168 # define sqlite3_open16                 0
66169 # define sqlite3_prepare16              0
66170 # define sqlite3_prepare16_v2           0
66171 # define sqlite3_result_error16         0
66172 # define sqlite3_result_text16          0
66173 # define sqlite3_result_text16be        0
66174 # define sqlite3_result_text16le        0
66175 # define sqlite3_value_text16           0
66176 # define sqlite3_value_text16be         0
66177 # define sqlite3_value_text16le         0
66178 # define sqlite3_column_database_name16 0
66179 # define sqlite3_column_table_name16    0
66180 # define sqlite3_column_origin_name16   0
66181 #endif
66182
66183 #ifdef SQLITE_OMIT_COMPLETE
66184 # define sqlite3_complete 0
66185 # define sqlite3_complete16 0
66186 #endif
66187
66188 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
66189 # define sqlite3_progress_handler 0
66190 #endif
66191
66192 #ifdef SQLITE_OMIT_VIRTUALTABLE
66193 # define sqlite3_create_module 0
66194 # define sqlite3_create_module_v2 0
66195 # define sqlite3_declare_vtab 0
66196 #endif
66197
66198 #ifdef SQLITE_OMIT_SHARED_CACHE
66199 # define sqlite3_enable_shared_cache 0
66200 #endif
66201
66202 #ifdef SQLITE_OMIT_TRACE
66203 # define sqlite3_profile       0
66204 # define sqlite3_trace         0
66205 #endif
66206
66207 #ifdef SQLITE_OMIT_GET_TABLE
66208 # define sqlite3_free_table    0
66209 # define sqlite3_get_table     0
66210 #endif
66211
66212 #ifdef SQLITE_OMIT_INCRBLOB
66213 #define sqlite3_bind_zeroblob  0
66214 #define sqlite3_blob_bytes     0
66215 #define sqlite3_blob_close     0
66216 #define sqlite3_blob_open      0
66217 #define sqlite3_blob_read      0
66218 #define sqlite3_blob_write     0
66219 #endif
66220
66221 /*
66222 ** The following structure contains pointers to all SQLite API routines.
66223 ** A pointer to this structure is passed into extensions when they are
66224 ** loaded so that the extension can make calls back into the SQLite
66225 ** library.
66226 **
66227 ** When adding new APIs, add them to the bottom of this structure
66228 ** in order to preserve backwards compatibility.
66229 **
66230 ** Extensions that use newer APIs should first call the
66231 ** sqlite3_libversion_number() to make sure that the API they
66232 ** intend to use is supported by the library.  Extensions should
66233 ** also check to make sure that the pointer to the function is
66234 ** not NULL before calling it.
66235 */
66236 static const sqlite3_api_routines sqlite3Apis = {
66237   sqlite3_aggregate_context,
66238 #ifndef SQLITE_OMIT_DEPRECATED
66239   sqlite3_aggregate_count,
66240 #else
66241   0,
66242 #endif
66243   sqlite3_bind_blob,
66244   sqlite3_bind_double,
66245   sqlite3_bind_int,
66246   sqlite3_bind_int64,
66247   sqlite3_bind_null,
66248   sqlite3_bind_parameter_count,
66249   sqlite3_bind_parameter_index,
66250   sqlite3_bind_parameter_name,
66251   sqlite3_bind_text,
66252   sqlite3_bind_text16,
66253   sqlite3_bind_value,
66254   sqlite3_busy_handler,
66255   sqlite3_busy_timeout,
66256   sqlite3_changes,
66257   sqlite3_close,
66258   sqlite3_collation_needed,
66259   sqlite3_collation_needed16,
66260   sqlite3_column_blob,
66261   sqlite3_column_bytes,
66262   sqlite3_column_bytes16,
66263   sqlite3_column_count,
66264   sqlite3_column_database_name,
66265   sqlite3_column_database_name16,
66266   sqlite3_column_decltype,
66267   sqlite3_column_decltype16,
66268   sqlite3_column_double,
66269   sqlite3_column_int,
66270   sqlite3_column_int64,
66271   sqlite3_column_name,
66272   sqlite3_column_name16,
66273   sqlite3_column_origin_name,
66274   sqlite3_column_origin_name16,
66275   sqlite3_column_table_name,
66276   sqlite3_column_table_name16,
66277   sqlite3_column_text,
66278   sqlite3_column_text16,
66279   sqlite3_column_type,
66280   sqlite3_column_value,
66281   sqlite3_commit_hook,
66282   sqlite3_complete,
66283   sqlite3_complete16,
66284   sqlite3_create_collation,
66285   sqlite3_create_collation16,
66286   sqlite3_create_function,
66287   sqlite3_create_function16,
66288   sqlite3_create_module,
66289   sqlite3_data_count,
66290   sqlite3_db_handle,
66291   sqlite3_declare_vtab,
66292   sqlite3_enable_shared_cache,
66293   sqlite3_errcode,
66294   sqlite3_errmsg,
66295   sqlite3_errmsg16,
66296   sqlite3_exec,
66297 #ifndef SQLITE_OMIT_DEPRECATED
66298   sqlite3_expired,
66299 #else
66300   0,
66301 #endif
66302   sqlite3_finalize,
66303   sqlite3_free,
66304   sqlite3_free_table,
66305   sqlite3_get_autocommit,
66306   sqlite3_get_auxdata,
66307   sqlite3_get_table,
66308   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
66309   sqlite3_interrupt,
66310   sqlite3_last_insert_rowid,
66311   sqlite3_libversion,
66312   sqlite3_libversion_number,
66313   sqlite3_malloc,
66314   sqlite3_mprintf,
66315   sqlite3_open,
66316   sqlite3_open16,
66317   sqlite3_prepare,
66318   sqlite3_prepare16,
66319   sqlite3_profile,
66320   sqlite3_progress_handler,
66321   sqlite3_realloc,
66322   sqlite3_reset,
66323   sqlite3_result_blob,
66324   sqlite3_result_double,
66325   sqlite3_result_error,
66326   sqlite3_result_error16,
66327   sqlite3_result_int,
66328   sqlite3_result_int64,
66329   sqlite3_result_null,
66330   sqlite3_result_text,
66331   sqlite3_result_text16,
66332   sqlite3_result_text16be,
66333   sqlite3_result_text16le,
66334   sqlite3_result_value,
66335   sqlite3_rollback_hook,
66336   sqlite3_set_authorizer,
66337   sqlite3_set_auxdata,
66338   sqlite3_snprintf,
66339   sqlite3_step,
66340   sqlite3_table_column_metadata,
66341 #ifndef SQLITE_OMIT_DEPRECATED
66342   sqlite3_thread_cleanup,
66343 #else
66344   0,
66345 #endif
66346   sqlite3_total_changes,
66347   sqlite3_trace,
66348 #ifndef SQLITE_OMIT_DEPRECATED
66349   sqlite3_transfer_bindings,
66350 #else
66351   0,
66352 #endif
66353   sqlite3_update_hook,
66354   sqlite3_user_data,
66355   sqlite3_value_blob,
66356   sqlite3_value_bytes,
66357   sqlite3_value_bytes16,
66358   sqlite3_value_double,
66359   sqlite3_value_int,
66360   sqlite3_value_int64,
66361   sqlite3_value_numeric_type,
66362   sqlite3_value_text,
66363   sqlite3_value_text16,
66364   sqlite3_value_text16be,
66365   sqlite3_value_text16le,
66366   sqlite3_value_type,
66367   sqlite3_vmprintf,
66368   /*
66369   ** The original API set ends here.  All extensions can call any
66370   ** of the APIs above provided that the pointer is not NULL.  But
66371   ** before calling APIs that follow, extension should check the
66372   ** sqlite3_libversion_number() to make sure they are dealing with
66373   ** a library that is new enough to support that API.
66374   *************************************************************************
66375   */
66376   sqlite3_overload_function,
66377
66378   /*
66379   ** Added after 3.3.13
66380   */
66381   sqlite3_prepare_v2,
66382   sqlite3_prepare16_v2,
66383   sqlite3_clear_bindings,
66384
66385   /*
66386   ** Added for 3.4.1
66387   */
66388   sqlite3_create_module_v2,
66389
66390   /*
66391   ** Added for 3.5.0
66392   */
66393   sqlite3_bind_zeroblob,
66394   sqlite3_blob_bytes,
66395   sqlite3_blob_close,
66396   sqlite3_blob_open,
66397   sqlite3_blob_read,
66398   sqlite3_blob_write,
66399   sqlite3_create_collation_v2,
66400   sqlite3_file_control,
66401   sqlite3_memory_highwater,
66402   sqlite3_memory_used,
66403 #ifdef SQLITE_MUTEX_OMIT
66404   0, 
66405   0, 
66406   0,
66407   0,
66408   0,
66409 #else
66410   sqlite3_mutex_alloc,
66411   sqlite3_mutex_enter,
66412   sqlite3_mutex_free,
66413   sqlite3_mutex_leave,
66414   sqlite3_mutex_try,
66415 #endif
66416   sqlite3_open_v2,
66417   sqlite3_release_memory,
66418   sqlite3_result_error_nomem,
66419   sqlite3_result_error_toobig,
66420   sqlite3_sleep,
66421   sqlite3_soft_heap_limit,
66422   sqlite3_vfs_find,
66423   sqlite3_vfs_register,
66424   sqlite3_vfs_unregister,
66425
66426   /*
66427   ** Added for 3.5.8
66428   */
66429   sqlite3_threadsafe,
66430   sqlite3_result_zeroblob,
66431   sqlite3_result_error_code,
66432   sqlite3_test_control,
66433   sqlite3_randomness,
66434   sqlite3_context_db_handle,
66435
66436   /*
66437   ** Added for 3.6.0
66438   */
66439   sqlite3_extended_result_codes,
66440   sqlite3_limit,
66441   sqlite3_next_stmt,
66442   sqlite3_sql,
66443   sqlite3_status,
66444 };
66445
66446 /*
66447 ** Attempt to load an SQLite extension library contained in the file
66448 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
66449 ** default entry point name (sqlite3_extension_init) is used.  Use
66450 ** of the default name is recommended.
66451 **
66452 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
66453 **
66454 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
66455 ** error message text.  The calling function should free this memory
66456 ** by calling sqlite3DbFree(db, ).
66457 */
66458 static int sqlite3LoadExtension(
66459   sqlite3 *db,          /* Load the extension into this database connection */
66460   const char *zFile,    /* Name of the shared library containing extension */
66461   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
66462   char **pzErrMsg       /* Put error message here if not 0 */
66463 ){
66464   sqlite3_vfs *pVfs = db->pVfs;
66465   void *handle;
66466   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
66467   char *zErrmsg = 0;
66468   void **aHandle;
66469
66470   /* Ticket #1863.  To avoid a creating security problems for older
66471   ** applications that relink against newer versions of SQLite, the
66472   ** ability to run load_extension is turned off by default.  One
66473   ** must call sqlite3_enable_load_extension() to turn on extension
66474   ** loading.  Otherwise you get the following error.
66475   */
66476   if( (db->flags & SQLITE_LoadExtension)==0 ){
66477     if( pzErrMsg ){
66478       *pzErrMsg = sqlite3_mprintf("not authorized");
66479     }
66480     return SQLITE_ERROR;
66481   }
66482
66483   if( zProc==0 ){
66484     zProc = "sqlite3_extension_init";
66485   }
66486
66487   handle = sqlite3OsDlOpen(pVfs, zFile);
66488   if( handle==0 ){
66489     if( pzErrMsg ){
66490       char zErr[256];
66491       zErr[sizeof(zErr)-1] = '\0';
66492       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
66493           "unable to open shared library [%s]", zFile);
66494       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
66495       *pzErrMsg = sqlite3DbStrDup(0, zErr);
66496     }
66497     return SQLITE_ERROR;
66498   }
66499   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
66500                    sqlite3OsDlSym(pVfs, handle, zProc);
66501   if( xInit==0 ){
66502     if( pzErrMsg ){
66503       char zErr[256];
66504       zErr[sizeof(zErr)-1] = '\0';
66505       sqlite3_snprintf(sizeof(zErr)-1, zErr,
66506           "no entry point [%s] in shared library [%s]", zProc,zFile);
66507       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
66508       *pzErrMsg = sqlite3DbStrDup(0, zErr);
66509       sqlite3OsDlClose(pVfs, handle);
66510     }
66511     return SQLITE_ERROR;
66512   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
66513     if( pzErrMsg ){
66514       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
66515     }
66516     sqlite3_free(zErrmsg);
66517     sqlite3OsDlClose(pVfs, handle);
66518     return SQLITE_ERROR;
66519   }
66520
66521   /* Append the new shared library handle to the db->aExtension array. */
66522   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
66523   if( aHandle==0 ){
66524     return SQLITE_NOMEM;
66525   }
66526   if( db->nExtension>0 ){
66527     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
66528   }
66529   sqlite3DbFree(db, db->aExtension);
66530   db->aExtension = aHandle;
66531
66532   db->aExtension[db->nExtension++] = handle;
66533   return SQLITE_OK;
66534 }
66535 SQLITE_API int sqlite3_load_extension(
66536   sqlite3 *db,          /* Load the extension into this database connection */
66537   const char *zFile,    /* Name of the shared library containing extension */
66538   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
66539   char **pzErrMsg       /* Put error message here if not 0 */
66540 ){
66541   int rc;
66542   sqlite3_mutex_enter(db->mutex);
66543   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
66544   sqlite3_mutex_leave(db->mutex);
66545   return rc;
66546 }
66547
66548 /*
66549 ** Call this routine when the database connection is closing in order
66550 ** to clean up loaded extensions
66551 */
66552 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
66553   int i;
66554   assert( sqlite3_mutex_held(db->mutex) );
66555   for(i=0; i<db->nExtension; i++){
66556     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
66557   }
66558   sqlite3DbFree(db, db->aExtension);
66559 }
66560
66561 /*
66562 ** Enable or disable extension loading.  Extension loading is disabled by
66563 ** default so as not to open security holes in older applications.
66564 */
66565 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
66566   sqlite3_mutex_enter(db->mutex);
66567   if( onoff ){
66568     db->flags |= SQLITE_LoadExtension;
66569   }else{
66570     db->flags &= ~SQLITE_LoadExtension;
66571   }
66572   sqlite3_mutex_leave(db->mutex);
66573   return SQLITE_OK;
66574 }
66575
66576 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
66577
66578 /*
66579 ** The auto-extension code added regardless of whether or not extension
66580 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
66581 ** code if regular extension loading is not available.  This is that
66582 ** dummy pointer.
66583 */
66584 #ifdef SQLITE_OMIT_LOAD_EXTENSION
66585 static const sqlite3_api_routines sqlite3Apis = { 0 };
66586 #endif
66587
66588
66589 /*
66590 ** The following object holds the list of automatically loaded
66591 ** extensions.
66592 **
66593 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
66594 ** mutex must be held while accessing this list.
66595 */
66596 typedef struct sqlite3ExtType sqlite3ExtType;
66597 static SQLITE_WSD struct sqlite3ExtType {
66598   int nExt;        /* Number of entries in aExt[] */          
66599   void **aExt;     /* Pointers to the extension init functions */
66600 } sqlite3Autoext = { 0, 0 };
66601
66602 /* The "wsdAutoext" macro will resolve to the autoextension
66603 ** state vector.  If writable static data is unsupported on the target,
66604 ** we have to locate the state vector at run-time.  In the more common
66605 ** case where writable static data is supported, wsdStat can refer directly
66606 ** to the "sqlite3Autoext" state vector declared above.
66607 */
66608 #ifdef SQLITE_OMIT_WSD
66609 # define wsdAutoextInit \
66610   sqlite3ExtType *x = &GLOBAL(sqlite3ExtType,sqlite3Autoext)
66611 # define wsdAutoext x[0]
66612 #else
66613 # define wsdAutoextInit
66614 # define wsdAutoext sqlite3Autoext
66615 #endif
66616
66617
66618 /*
66619 ** Register a statically linked extension that is automatically
66620 ** loaded by every new database connection.
66621 */
66622 SQLITE_API int sqlite3_auto_extension(void *xInit){
66623   int rc = SQLITE_OK;
66624 #ifndef SQLITE_OMIT_AUTOINIT
66625   rc = sqlite3_initialize();
66626   if( rc ){
66627     return rc;
66628   }else
66629 #endif
66630   {
66631     int i;
66632 #if SQLITE_THREADSAFE
66633     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66634 #endif
66635     wsdAutoextInit;
66636     sqlite3_mutex_enter(mutex);
66637     for(i=0; i<wsdAutoext.nExt; i++){
66638       if( wsdAutoext.aExt[i]==xInit ) break;
66639     }
66640     if( i==wsdAutoext.nExt ){
66641       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
66642       void **aNew;
66643       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
66644       if( aNew==0 ){
66645         rc = SQLITE_NOMEM;
66646       }else{
66647         wsdAutoext.aExt = aNew;
66648         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
66649         wsdAutoext.nExt++;
66650       }
66651     }
66652     sqlite3_mutex_leave(mutex);
66653     assert( (rc&0xff)==rc );
66654     return rc;
66655   }
66656 }
66657
66658 /*
66659 ** Reset the automatic extension loading mechanism.
66660 */
66661 SQLITE_API void sqlite3_reset_auto_extension(void){
66662 #ifndef SQLITE_OMIT_AUTOINIT
66663   if( sqlite3_initialize()==SQLITE_OK )
66664 #endif
66665   {
66666 #if SQLITE_THREADSAFE
66667     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66668 #endif
66669     wsdAutoextInit;
66670     sqlite3_mutex_enter(mutex);
66671     sqlite3_free(wsdAutoext.aExt);
66672     wsdAutoext.aExt = 0;
66673     wsdAutoext.nExt = 0;
66674     sqlite3_mutex_leave(mutex);
66675   }
66676 }
66677
66678 /*
66679 ** Load all automatic extensions.
66680 */
66681 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
66682   int i;
66683   int go = 1;
66684   int rc = SQLITE_OK;
66685   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
66686
66687   wsdAutoextInit;
66688   if( wsdAutoext.nExt==0 ){
66689     /* Common case: early out without every having to acquire a mutex */
66690     return SQLITE_OK;
66691   }
66692   for(i=0; go; i++){
66693     char *zErrmsg = 0;
66694 #if SQLITE_THREADSAFE
66695     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
66696 #endif
66697     sqlite3_mutex_enter(mutex);
66698     if( i>=wsdAutoext.nExt ){
66699       xInit = 0;
66700       go = 0;
66701     }else{
66702       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
66703               wsdAutoext.aExt[i];
66704     }
66705     sqlite3_mutex_leave(mutex);
66706     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
66707       sqlite3Error(db, SQLITE_ERROR,
66708             "automatic extension loading failed: %s", zErrmsg);
66709       go = 0;
66710       rc = SQLITE_ERROR;
66711       sqlite3_free(zErrmsg);
66712     }
66713   }
66714   return rc;
66715 }
66716
66717 /************** End of loadext.c *********************************************/
66718 /************** Begin file pragma.c ******************************************/
66719 /*
66720 ** 2003 April 6
66721 **
66722 ** The author disclaims copyright to this source code.  In place of
66723 ** a legal notice, here is a blessing:
66724 **
66725 **    May you do good and not evil.
66726 **    May you find forgiveness for yourself and forgive others.
66727 **    May you share freely, never taking more than you give.
66728 **
66729 *************************************************************************
66730 ** This file contains code used to implement the PRAGMA command.
66731 **
66732 ** $Id: pragma.c,v 1.189 2008/10/10 17:47:21 danielk1977 Exp $
66733 */
66734
66735 /* Ignore this whole file if pragmas are disabled
66736 */
66737 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
66738
66739 /*
66740 ** Interpret the given string as a safety level.  Return 0 for OFF,
66741 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
66742 ** unrecognized string argument.
66743 **
66744 ** Note that the values returned are one less that the values that
66745 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
66746 ** to support legacy SQL code.  The safety level used to be boolean
66747 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
66748 */
66749 static int getSafetyLevel(const char *z){
66750                              /* 123456789 123456789 */
66751   static const char zText[] = "onoffalseyestruefull";
66752   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
66753   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
66754   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
66755   int i, n;
66756   if( isdigit(*z) ){
66757     return atoi(z);
66758   }
66759   n = strlen(z);
66760   for(i=0; i<sizeof(iLength); i++){
66761     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
66762       return iValue[i];
66763     }
66764   }
66765   return 1;
66766 }
66767
66768 /*
66769 ** Interpret the given string as a boolean value.
66770 */
66771 static int getBoolean(const char *z){
66772   return getSafetyLevel(z)&1;
66773 }
66774
66775 /*
66776 ** Interpret the given string as a locking mode value.
66777 */
66778 static int getLockingMode(const char *z){
66779   if( z ){
66780     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
66781     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
66782   }
66783   return PAGER_LOCKINGMODE_QUERY;
66784 }
66785
66786 #ifndef SQLITE_OMIT_AUTOVACUUM
66787 /*
66788 ** Interpret the given string as an auto-vacuum mode value.
66789 **
66790 ** The following strings, "none", "full" and "incremental" are 
66791 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
66792 */
66793 static int getAutoVacuum(const char *z){
66794   int i;
66795   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
66796   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
66797   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
66798   i = atoi(z);
66799   return ((i>=0&&i<=2)?i:0);
66800 }
66801 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
66802
66803 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66804 /*
66805 ** Interpret the given string as a temp db location. Return 1 for file
66806 ** backed temporary databases, 2 for the Red-Black tree in memory database
66807 ** and 0 to use the compile-time default.
66808 */
66809 static int getTempStore(const char *z){
66810   if( z[0]>='0' && z[0]<='2' ){
66811     return z[0] - '0';
66812   }else if( sqlite3StrICmp(z, "file")==0 ){
66813     return 1;
66814   }else if( sqlite3StrICmp(z, "memory")==0 ){
66815     return 2;
66816   }else{
66817     return 0;
66818   }
66819 }
66820 #endif /* SQLITE_PAGER_PRAGMAS */
66821
66822 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66823 /*
66824 ** Invalidate temp storage, either when the temp storage is changed
66825 ** from default, or when 'file' and the temp_store_directory has changed
66826 */
66827 static int invalidateTempStorage(Parse *pParse){
66828   sqlite3 *db = pParse->db;
66829   if( db->aDb[1].pBt!=0 ){
66830     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
66831       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
66832         "from within a transaction");
66833       return SQLITE_ERROR;
66834     }
66835     sqlite3BtreeClose(db->aDb[1].pBt);
66836     db->aDb[1].pBt = 0;
66837     sqlite3ResetInternalSchema(db, 0);
66838   }
66839   return SQLITE_OK;
66840 }
66841 #endif /* SQLITE_PAGER_PRAGMAS */
66842
66843 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
66844 /*
66845 ** If the TEMP database is open, close it and mark the database schema
66846 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
66847 ** or DEFAULT_TEMP_STORE pragmas.
66848 */
66849 static int changeTempStorage(Parse *pParse, const char *zStorageType){
66850   int ts = getTempStore(zStorageType);
66851   sqlite3 *db = pParse->db;
66852   if( db->temp_store==ts ) return SQLITE_OK;
66853   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
66854     return SQLITE_ERROR;
66855   }
66856   db->temp_store = ts;
66857   return SQLITE_OK;
66858 }
66859 #endif /* SQLITE_PAGER_PRAGMAS */
66860
66861 /*
66862 ** Generate code to return a single integer value.
66863 */
66864 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
66865   Vdbe *v = sqlite3GetVdbe(pParse);
66866   int mem = ++pParse->nMem;
66867   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
66868   if( pParse->explain==0 ){
66869     sqlite3VdbeSetNumCols(v, 1);
66870     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC);
66871   }
66872   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
66873 }
66874
66875 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
66876 /*
66877 ** Check to see if zRight and zLeft refer to a pragma that queries
66878 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
66879 ** Also, implement the pragma.
66880 */
66881 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
66882   static const struct sPragmaType {
66883     const char *zName;  /* Name of the pragma */
66884     int mask;           /* Mask for the db->flags value */
66885   } aPragma[] = {
66886     { "full_column_names",        SQLITE_FullColNames  },
66887     { "short_column_names",       SQLITE_ShortColNames },
66888     { "count_changes",            SQLITE_CountRows     },
66889     { "empty_result_callbacks",   SQLITE_NullCallback  },
66890     { "legacy_file_format",       SQLITE_LegacyFileFmt },
66891     { "fullfsync",                SQLITE_FullFSync     },
66892 #ifdef SQLITE_DEBUG
66893     { "sql_trace",                SQLITE_SqlTrace      },
66894     { "vdbe_listing",             SQLITE_VdbeListing   },
66895     { "vdbe_trace",               SQLITE_VdbeTrace     },
66896 #endif
66897 #ifndef SQLITE_OMIT_CHECK
66898     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
66899 #endif
66900     /* The following is VERY experimental */
66901     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
66902     { "omit_readlock",            SQLITE_NoReadlock    },
66903
66904     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
66905     ** flag if there are any active statements. */
66906     { "read_uncommitted",         SQLITE_ReadUncommitted },
66907   };
66908   int i;
66909   const struct sPragmaType *p;
66910   for(i=0, p=aPragma; i<sizeof(aPragma)/sizeof(aPragma[0]); i++, p++){
66911     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
66912       sqlite3 *db = pParse->db;
66913       Vdbe *v;
66914       v = sqlite3GetVdbe(pParse);
66915       if( v ){
66916         if( zRight==0 ){
66917           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
66918         }else{
66919           if( getBoolean(zRight) ){
66920             db->flags |= p->mask;
66921           }else{
66922             db->flags &= ~p->mask;
66923           }
66924
66925           /* Many of the flag-pragmas modify the code generated by the SQL 
66926           ** compiler (eg. count_changes). So add an opcode to expire all
66927           ** compiled SQL statements after modifying a pragma value.
66928           */
66929           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
66930         }
66931       }
66932
66933       return 1;
66934     }
66935   }
66936   return 0;
66937 }
66938 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
66939
66940 static const char *actionName(u8 action){
66941   switch( action ){
66942     case OE_SetNull:  return "SET NULL";
66943     case OE_SetDflt:  return "SET DEFAULT";
66944     case OE_Restrict: return "RESTRICT";
66945     case OE_Cascade:  return "CASCADE";
66946   }
66947   return "";
66948 }
66949
66950 /*
66951 ** Process a pragma statement.  
66952 **
66953 ** Pragmas are of this form:
66954 **
66955 **      PRAGMA [database.]id [= value]
66956 **
66957 ** The identifier might also be a string.  The value is a string, and
66958 ** identifier, or a number.  If minusFlag is true, then the value is
66959 ** a number that was preceded by a minus sign.
66960 **
66961 ** If the left side is "database.id" then pId1 is the database name
66962 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
66963 ** id and pId2 is any empty string.
66964 */
66965 SQLITE_PRIVATE void sqlite3Pragma(
66966   Parse *pParse, 
66967   Token *pId1,        /* First part of [database.]id field */
66968   Token *pId2,        /* Second part of [database.]id field, or NULL */
66969   Token *pValue,      /* Token for <value>, or NULL */
66970   int minusFlag       /* True if a '-' sign preceded <value> */
66971 ){
66972   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
66973   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
66974   const char *zDb = 0;   /* The database name */
66975   Token *pId;            /* Pointer to <id> token */
66976   int iDb;               /* Database index for <database> */
66977   sqlite3 *db = pParse->db;
66978   Db *pDb;
66979   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
66980   if( v==0 ) return;
66981   pParse->nMem = 2;
66982
66983   /* Interpret the [database.] part of the pragma statement. iDb is the
66984   ** index of the database this pragma is being applied to in db.aDb[]. */
66985   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
66986   if( iDb<0 ) return;
66987   pDb = &db->aDb[iDb];
66988
66989   /* If the temp database has been explicitly named as part of the 
66990   ** pragma, make sure it is open. 
66991   */
66992   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
66993     return;
66994   }
66995
66996   zLeft = sqlite3NameFromToken(db, pId);
66997   if( !zLeft ) return;
66998   if( minusFlag ){
66999     zRight = sqlite3MPrintf(db, "-%T", pValue);
67000   }else{
67001     zRight = sqlite3NameFromToken(db, pValue);
67002   }
67003
67004   zDb = ((pId2 && pId2->n>0)?pDb->zName:0);
67005   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
67006     goto pragma_out;
67007   }
67008  
67009 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67010   /*
67011   **  PRAGMA [database.]default_cache_size
67012   **  PRAGMA [database.]default_cache_size=N
67013   **
67014   ** The first form reports the current persistent setting for the
67015   ** page cache size.  The value returned is the maximum number of
67016   ** pages in the page cache.  The second form sets both the current
67017   ** page cache size value and the persistent page cache size value
67018   ** stored in the database file.
67019   **
67020   ** The default cache size is stored in meta-value 2 of page 1 of the
67021   ** database file.  The cache size is actually the absolute value of
67022   ** this memory location.  The sign of meta-value 2 determines the
67023   ** synchronous setting.  A negative value means synchronous is off
67024   ** and a positive value means synchronous is on.
67025   */
67026   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
67027     static const VdbeOpList getCacheSize[] = {
67028       { OP_ReadCookie,  0, 1,        2},  /* 0 */
67029       { OP_IfPos,       1, 6,        0},
67030       { OP_Integer,     0, 2,        0},
67031       { OP_Subtract,    1, 2,        1},
67032       { OP_IfPos,       1, 6,        0},
67033       { OP_Integer,     0, 1,        0},  /* 5 */
67034       { OP_ResultRow,   1, 1,        0},
67035     };
67036     int addr;
67037     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67038     sqlite3VdbeUsesBtree(v, iDb);
67039     if( !zRight ){
67040       sqlite3VdbeSetNumCols(v, 1);
67041       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC);
67042       pParse->nMem += 2;
67043       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
67044       sqlite3VdbeChangeP1(v, addr, iDb);
67045       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
67046     }else{
67047       int size = atoi(zRight);
67048       if( size<0 ) size = -size;
67049       sqlite3BeginWriteOperation(pParse, 0, iDb);
67050       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
67051       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
67052       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
67053       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
67054       sqlite3VdbeJumpHere(v, addr);
67055       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
67056       pDb->pSchema->cache_size = size;
67057       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
67058     }
67059   }else
67060
67061   /*
67062   **  PRAGMA [database.]page_size
67063   **  PRAGMA [database.]page_size=N
67064   **
67065   ** The first form reports the current setting for the
67066   ** database page size in bytes.  The second form sets the
67067   ** database page size value.  The value can only be set if
67068   ** the database has not yet been created.
67069   */
67070   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
67071     Btree *pBt = pDb->pBt;
67072     if( !zRight ){
67073       int size = pBt ? sqlite3BtreeGetPageSize(pBt) : 0;
67074       returnSingleInt(pParse, "page_size", size);
67075     }else{
67076       /* Malloc may fail when setting the page-size, as there is an internal
67077       ** buffer that the pager module resizes using sqlite3_realloc().
67078       */
67079       db->nextPagesize = atoi(zRight);
67080       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
67081         db->mallocFailed = 1;
67082       }
67083     }
67084   }else
67085
67086   /*
67087   **  PRAGMA [database.]max_page_count
67088   **  PRAGMA [database.]max_page_count=N
67089   **
67090   ** The first form reports the current setting for the
67091   ** maximum number of pages in the database file.  The 
67092   ** second form attempts to change this setting.  Both
67093   ** forms return the current setting.
67094   */
67095   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
67096     Btree *pBt = pDb->pBt;
67097     int newMax = 0;
67098     if( zRight ){
67099       newMax = atoi(zRight);
67100     }
67101     if( pBt ){
67102       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
67103     }
67104     returnSingleInt(pParse, "max_page_count", newMax);
67105   }else
67106
67107   /*
67108   **  PRAGMA [database.]page_count
67109   **
67110   ** Return the number of pages in the specified database.
67111   */
67112   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
67113     Vdbe *v;
67114     int iReg;
67115     v = sqlite3GetVdbe(pParse);
67116     if( !v || sqlite3ReadSchema(pParse) ) goto pragma_out;
67117     sqlite3CodeVerifySchema(pParse, iDb);
67118     iReg = ++pParse->nMem;
67119     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
67120     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
67121     sqlite3VdbeSetNumCols(v, 1);
67122     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", P4_STATIC);
67123   }else
67124
67125   /*
67126   **  PRAGMA [database.]locking_mode
67127   **  PRAGMA [database.]locking_mode = (normal|exclusive)
67128   */
67129   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
67130     const char *zRet = "normal";
67131     int eMode = getLockingMode(zRight);
67132
67133     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
67134       /* Simple "PRAGMA locking_mode;" statement. This is a query for
67135       ** the current default locking mode (which may be different to
67136       ** the locking-mode of the main database).
67137       */
67138       eMode = db->dfltLockMode;
67139     }else{
67140       Pager *pPager;
67141       if( pId2->n==0 ){
67142         /* This indicates that no database name was specified as part
67143         ** of the PRAGMA command. In this case the locking-mode must be
67144         ** set on all attached databases, as well as the main db file.
67145         **
67146         ** Also, the sqlite3.dfltLockMode variable is set so that
67147         ** any subsequently attached databases also use the specified
67148         ** locking mode.
67149         */
67150         int ii;
67151         assert(pDb==&db->aDb[0]);
67152         for(ii=2; ii<db->nDb; ii++){
67153           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
67154           sqlite3PagerLockingMode(pPager, eMode);
67155         }
67156         db->dfltLockMode = eMode;
67157       }
67158       pPager = sqlite3BtreePager(pDb->pBt);
67159       eMode = sqlite3PagerLockingMode(pPager, eMode);
67160     }
67161
67162     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
67163     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
67164       zRet = "exclusive";
67165     }
67166     sqlite3VdbeSetNumCols(v, 1);
67167     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC);
67168     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
67169     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67170   }else
67171
67172   /*
67173   **  PRAGMA [database.]journal_mode
67174   **  PRAGMA [database.]journal_mode = (delete|persist|off)
67175   */
67176   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
67177     int eMode;
67178     static char * const azModeName[] = {"delete", "persist", "off", "truncate"};
67179
67180     if( zRight==0 ){
67181       eMode = PAGER_JOURNALMODE_QUERY;
67182     }else{
67183       int n = strlen(zRight);
67184       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
67185       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
67186         eMode--;
67187       }
67188     }
67189     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
67190       /* Simple "PRAGMA journal_mode;" statement. This is a query for
67191       ** the current default journal mode (which may be different to
67192       ** the journal-mode of the main database).
67193       */
67194       eMode = db->dfltJournalMode;
67195     }else{
67196       Pager *pPager;
67197       if( pId2->n==0 ){
67198         /* This indicates that no database name was specified as part
67199         ** of the PRAGMA command. In this case the journal-mode must be
67200         ** set on all attached databases, as well as the main db file.
67201         **
67202         ** Also, the sqlite3.dfltJournalMode variable is set so that
67203         ** any subsequently attached databases also use the specified
67204         ** journal mode.
67205         */
67206         int ii;
67207         assert(pDb==&db->aDb[0]);
67208         for(ii=1; ii<db->nDb; ii++){
67209           if( db->aDb[ii].pBt ){
67210             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
67211             sqlite3PagerJournalMode(pPager, eMode);
67212           }
67213         }
67214         db->dfltJournalMode = eMode;
67215       }
67216       pPager = sqlite3BtreePager(pDb->pBt);
67217       eMode = sqlite3PagerJournalMode(pPager, eMode);
67218     }
67219     assert( eMode==PAGER_JOURNALMODE_DELETE
67220               || eMode==PAGER_JOURNALMODE_TRUNCATE
67221               || eMode==PAGER_JOURNALMODE_PERSIST
67222               || eMode==PAGER_JOURNALMODE_OFF );
67223     sqlite3VdbeSetNumCols(v, 1);
67224     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", P4_STATIC);
67225     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
67226            azModeName[eMode], P4_STATIC);
67227     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67228   }else
67229
67230   /*
67231   **  PRAGMA [database.]journal_size_limit
67232   **  PRAGMA [database.]journal_size_limit=N
67233   **
67234   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
67235   */
67236   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
67237     Pager *pPager = sqlite3BtreePager(pDb->pBt);
67238     i64 iLimit = -2;
67239     if( zRight ){
67240       int iLimit32 = atoi(zRight);
67241       if( iLimit32<-1 ){
67242         iLimit32 = -1;
67243       }
67244       iLimit = iLimit32;
67245     }
67246     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
67247     returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
67248   }else
67249
67250 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
67251
67252   /*
67253   **  PRAGMA [database.]auto_vacuum
67254   **  PRAGMA [database.]auto_vacuum=N
67255   **
67256   ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
67257   */
67258 #ifndef SQLITE_OMIT_AUTOVACUUM
67259   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
67260     Btree *pBt = pDb->pBt;
67261     if( sqlite3ReadSchema(pParse) ){
67262       goto pragma_out;
67263     }
67264     if( !zRight ){
67265       int auto_vacuum = 
67266           pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
67267       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
67268     }else{
67269       int eAuto = getAutoVacuum(zRight);
67270       db->nextAutovac = eAuto;
67271       if( eAuto>=0 ){
67272         /* Call SetAutoVacuum() to set initialize the internal auto and
67273         ** incr-vacuum flags. This is required in case this connection
67274         ** creates the database file. It is important that it is created
67275         ** as an auto-vacuum capable db.
67276         */
67277         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
67278         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
67279           /* When setting the auto_vacuum mode to either "full" or 
67280           ** "incremental", write the value of meta[6] in the database
67281           ** file. Before writing to meta[6], check that meta[3] indicates
67282           ** that this really is an auto-vacuum capable database.
67283           */
67284           static const VdbeOpList setMeta6[] = {
67285             { OP_Transaction,    0,               1,        0},    /* 0 */
67286             { OP_ReadCookie,     0,               1,        3},    /* 1 */
67287             { OP_If,             1,               0,        0},    /* 2 */
67288             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
67289             { OP_Integer,        0,               1,        0},    /* 4 */
67290             { OP_SetCookie,      0,               6,        1},    /* 5 */
67291           };
67292           int iAddr;
67293           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
67294           sqlite3VdbeChangeP1(v, iAddr, iDb);
67295           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
67296           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
67297           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
67298           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
67299           sqlite3VdbeUsesBtree(v, iDb);
67300         }
67301       }
67302     }
67303   }else
67304 #endif
67305
67306   /*
67307   **  PRAGMA [database.]incremental_vacuum(N)
67308   **
67309   ** Do N steps of incremental vacuuming on a database.
67310   */
67311 #ifndef SQLITE_OMIT_AUTOVACUUM
67312   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
67313     int iLimit, addr;
67314     if( sqlite3ReadSchema(pParse) ){
67315       goto pragma_out;
67316     }
67317     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
67318       iLimit = 0x7fffffff;
67319     }
67320     sqlite3BeginWriteOperation(pParse, 0, iDb);
67321     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
67322     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
67323     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
67324     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
67325     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
67326     sqlite3VdbeJumpHere(v, addr);
67327   }else
67328 #endif
67329
67330 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
67331   /*
67332   **  PRAGMA [database.]cache_size
67333   **  PRAGMA [database.]cache_size=N
67334   **
67335   ** The first form reports the current local setting for the
67336   ** page cache size.  The local setting can be different from
67337   ** the persistent cache size value that is stored in the database
67338   ** file itself.  The value returned is the maximum number of
67339   ** pages in the page cache.  The second form sets the local
67340   ** page cache size value.  It does not change the persistent
67341   ** cache size stored on the disk so the cache size will revert
67342   ** to its default value when the database is closed and reopened.
67343   ** N should be a positive integer.
67344   */
67345   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
67346     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67347     if( !zRight ){
67348       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
67349     }else{
67350       int size = atoi(zRight);
67351       if( size<0 ) size = -size;
67352       pDb->pSchema->cache_size = size;
67353       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
67354     }
67355   }else
67356
67357   /*
67358   **   PRAGMA temp_store
67359   **   PRAGMA temp_store = "default"|"memory"|"file"
67360   **
67361   ** Return or set the local value of the temp_store flag.  Changing
67362   ** the local value does not make changes to the disk file and the default
67363   ** value will be restored the next time the database is opened.
67364   **
67365   ** Note that it is possible for the library compile-time options to
67366   ** override this setting
67367   */
67368   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
67369     if( !zRight ){
67370       returnSingleInt(pParse, "temp_store", db->temp_store);
67371     }else{
67372       changeTempStorage(pParse, zRight);
67373     }
67374   }else
67375
67376   /*
67377   **   PRAGMA temp_store_directory
67378   **   PRAGMA temp_store_directory = ""|"directory_name"
67379   **
67380   ** Return or set the local value of the temp_store_directory flag.  Changing
67381   ** the value sets a specific directory to be used for temporary files.
67382   ** Setting to a null string reverts to the default temporary directory search.
67383   ** If temporary directory is changed, then invalidateTempStorage.
67384   **
67385   */
67386   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
67387     if( !zRight ){
67388       if( sqlite3_temp_directory ){
67389         sqlite3VdbeSetNumCols(v, 1);
67390         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
67391             "temp_store_directory", P4_STATIC);
67392         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
67393         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67394       }
67395     }else{
67396 #ifndef SQLITE_OMIT_WSD
67397       if( zRight[0] ){
67398         int rc;
67399         int res;
67400         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
67401         if( rc!=SQLITE_OK || res==0 ){
67402           sqlite3ErrorMsg(pParse, "not a writable directory");
67403           goto pragma_out;
67404         }
67405       }
67406       if( SQLITE_TEMP_STORE==0
67407        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
67408        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
67409       ){
67410         invalidateTempStorage(pParse);
67411       }
67412       sqlite3_free(sqlite3_temp_directory);
67413       if( zRight[0] ){
67414         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
67415       }else{
67416         sqlite3_temp_directory = 0;
67417       }
67418 #endif /* SQLITE_OMIT_WSD */
67419     }
67420   }else
67421
67422   /*
67423   **   PRAGMA [database.]synchronous
67424   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
67425   **
67426   ** Return or set the local value of the synchronous flag.  Changing
67427   ** the local value does not make changes to the disk file and the
67428   ** default value will be restored the next time the database is
67429   ** opened.
67430   */
67431   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
67432     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67433     if( !zRight ){
67434       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
67435     }else{
67436       if( !db->autoCommit ){
67437         sqlite3ErrorMsg(pParse, 
67438             "Safety level may not be changed inside a transaction");
67439       }else{
67440         pDb->safety_level = getSafetyLevel(zRight)+1;
67441       }
67442     }
67443   }else
67444 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
67445
67446 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
67447   if( flagPragma(pParse, zLeft, zRight) ){
67448     /* The flagPragma() subroutine also generates any necessary code
67449     ** there is nothing more to do here */
67450   }else
67451 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
67452
67453 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
67454   /*
67455   **   PRAGMA table_info(<table>)
67456   **
67457   ** Return a single row for each column of the named table. The columns of
67458   ** the returned data set are:
67459   **
67460   ** cid:        Column id (numbered from left to right, starting at 0)
67461   ** name:       Column name
67462   ** type:       Column declaration type.
67463   ** notnull:    True if 'NOT NULL' is part of column declaration
67464   ** dflt_value: The default value for the column, if any.
67465   */
67466   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
67467     Table *pTab;
67468     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67469     pTab = sqlite3FindTable(db, zRight, zDb);
67470     if( pTab ){
67471       int i;
67472       int nHidden = 0;
67473       Column *pCol;
67474       sqlite3VdbeSetNumCols(v, 6);
67475       pParse->nMem = 6;
67476       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC);
67477       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67478       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC);
67479       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC);
67480       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC);
67481       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC);
67482       sqlite3ViewGetColumnNames(pParse, pTab);
67483       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
67484         const Token *pDflt;
67485         if( IsHiddenColumn(pCol) ){
67486           nHidden++;
67487           continue;
67488         }
67489         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
67490         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
67491         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67492            pCol->zType ? pCol->zType : "", 0);
67493         sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4);
67494         if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
67495           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
67496         }else{
67497           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
67498         }
67499         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
67500         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
67501       }
67502     }
67503   }else
67504
67505   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
67506     Index *pIdx;
67507     Table *pTab;
67508     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67509     pIdx = sqlite3FindIndex(db, zRight, zDb);
67510     if( pIdx ){
67511       int i;
67512       pTab = pIdx->pTable;
67513       sqlite3VdbeSetNumCols(v, 3);
67514       pParse->nMem = 3;
67515       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC);
67516       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC);
67517       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC);
67518       for(i=0; i<pIdx->nColumn; i++){
67519         int cnum = pIdx->aiColumn[i];
67520         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67521         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
67522         assert( pTab->nCol>cnum );
67523         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
67524         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67525       }
67526     }
67527   }else
67528
67529   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
67530     Index *pIdx;
67531     Table *pTab;
67532     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67533     pTab = sqlite3FindTable(db, zRight, zDb);
67534     if( pTab ){
67535       v = sqlite3GetVdbe(pParse);
67536       pIdx = pTab->pIndex;
67537       if( pIdx ){
67538         int i = 0; 
67539         sqlite3VdbeSetNumCols(v, 3);
67540         pParse->nMem = 3;
67541         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67542         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67543         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC);
67544         while(pIdx){
67545           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67546           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
67547           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
67548           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67549           ++i;
67550           pIdx = pIdx->pNext;
67551         }
67552       }
67553     }
67554   }else
67555
67556   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
67557     int i;
67558     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67559     sqlite3VdbeSetNumCols(v, 3);
67560     pParse->nMem = 3;
67561     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67562     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67563     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC);
67564     for(i=0; i<db->nDb; i++){
67565       if( db->aDb[i].pBt==0 ) continue;
67566       assert( db->aDb[i].zName!=0 );
67567       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67568       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
67569       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67570            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
67571       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
67572     }
67573   }else
67574
67575   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
67576     int i = 0;
67577     HashElem *p;
67578     sqlite3VdbeSetNumCols(v, 2);
67579     pParse->nMem = 2;
67580     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC);
67581     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC);
67582     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
67583       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
67584       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
67585       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
67586       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
67587     }
67588   }else
67589 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
67590
67591 #ifndef SQLITE_OMIT_FOREIGN_KEY
67592   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
67593     FKey *pFK;
67594     Table *pTab;
67595     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67596     pTab = sqlite3FindTable(db, zRight, zDb);
67597     if( pTab ){
67598       v = sqlite3GetVdbe(pParse);
67599       pFK = pTab->pFKey;
67600       if( pFK ){
67601         int i = 0; 
67602         sqlite3VdbeSetNumCols(v, 8);
67603         pParse->nMem = 8;
67604         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC);
67605         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC);
67606         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC);
67607         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC);
67608         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC);
67609         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", P4_STATIC);
67610         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", P4_STATIC);
67611         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", P4_STATIC);
67612         while(pFK){
67613           int j;
67614           for(j=0; j<pFK->nCol; j++){
67615             char *zCol = pFK->aCol[j].zCol;
67616             char *zOnUpdate = (char *)actionName(pFK->updateConf);
67617             char *zOnDelete = (char *)actionName(pFK->deleteConf);
67618             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
67619             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
67620             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
67621             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
67622                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
67623             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
67624             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
67625             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
67626             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
67627             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
67628           }
67629           ++i;
67630           pFK = pFK->pNextFrom;
67631         }
67632       }
67633     }
67634   }else
67635 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
67636
67637 #ifndef NDEBUG
67638   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
67639     if( zRight ){
67640       if( getBoolean(zRight) ){
67641         sqlite3ParserTrace(stderr, "parser: ");
67642       }else{
67643         sqlite3ParserTrace(0, 0);
67644       }
67645     }
67646   }else
67647 #endif
67648
67649   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
67650   ** used will be case sensitive or not depending on the RHS.
67651   */
67652   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
67653     if( zRight ){
67654       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
67655     }
67656   }else
67657
67658 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
67659 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
67660 #endif
67661
67662 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67663   /* Pragma "quick_check" is an experimental reduced version of 
67664   ** integrity_check designed to detect most database corruption
67665   ** without most of the overhead of a full integrity-check.
67666   */
67667   if( sqlite3StrICmp(zLeft, "integrity_check")==0
67668    || sqlite3StrICmp(zLeft, "quick_check")==0 
67669   ){
67670     int i, j, addr, mxErr;
67671
67672     /* Code that appears at the end of the integrity check.  If no error
67673     ** messages have been generated, output OK.  Otherwise output the
67674     ** error message
67675     */
67676     static const VdbeOpList endCode[] = {
67677       { OP_AddImm,      1, 0,        0},    /* 0 */
67678       { OP_IfNeg,       1, 0,        0},    /* 1 */
67679       { OP_String8,     0, 3,        0},    /* 2 */
67680       { OP_ResultRow,   3, 1,        0},
67681     };
67682
67683     int isQuick = (zLeft[0]=='q');
67684
67685     /* Initialize the VDBE program */
67686     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67687     pParse->nMem = 6;
67688     sqlite3VdbeSetNumCols(v, 1);
67689     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC);
67690
67691     /* Set the maximum error count */
67692     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
67693     if( zRight ){
67694       mxErr = atoi(zRight);
67695       if( mxErr<=0 ){
67696         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
67697       }
67698     }
67699     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
67700
67701     /* Do an integrity check on each database file */
67702     for(i=0; i<db->nDb; i++){
67703       HashElem *x;
67704       Hash *pTbls;
67705       int cnt = 0;
67706
67707       if( OMIT_TEMPDB && i==1 ) continue;
67708
67709       sqlite3CodeVerifySchema(pParse, i);
67710       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
67711       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67712       sqlite3VdbeJumpHere(v, addr);
67713
67714       /* Do an integrity check of the B-Tree
67715       **
67716       ** Begin by filling registers 2, 3, ... with the root pages numbers
67717       ** for all tables and indices in the database.
67718       */
67719       pTbls = &db->aDb[i].pSchema->tblHash;
67720       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
67721         Table *pTab = sqliteHashData(x);
67722         Index *pIdx;
67723         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
67724         cnt++;
67725         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
67726           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
67727           cnt++;
67728         }
67729       }
67730       if( cnt==0 ) continue;
67731
67732       /* Make sure sufficient number of registers have been allocated */
67733       if( pParse->nMem < cnt+4 ){
67734         pParse->nMem = cnt+4;
67735       }
67736
67737       /* Do the b-tree integrity checks */
67738       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
67739       sqlite3VdbeChangeP5(v, i);
67740       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
67741       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
67742          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
67743          P4_DYNAMIC);
67744       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
67745       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
67746       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
67747       sqlite3VdbeJumpHere(v, addr);
67748
67749       /* Make sure all the indices are constructed correctly.
67750       */
67751       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
67752         Table *pTab = sqliteHashData(x);
67753         Index *pIdx;
67754         int loopTop;
67755
67756         if( pTab->pIndex==0 ) continue;
67757         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
67758         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67759         sqlite3VdbeJumpHere(v, addr);
67760         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
67761         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
67762         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
67763         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
67764         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
67765           int jmp2;
67766           static const VdbeOpList idxErr[] = {
67767             { OP_AddImm,      1, -1,  0},
67768             { OP_String8,     0,  3,  0},    /* 1 */
67769             { OP_Rowid,       1,  4,  0},
67770             { OP_String8,     0,  5,  0},    /* 3 */
67771             { OP_String8,     0,  6,  0},    /* 4 */
67772             { OP_Concat,      4,  3,  3},
67773             { OP_Concat,      5,  3,  3},
67774             { OP_Concat,      6,  3,  3},
67775             { OP_ResultRow,   3,  1,  0},
67776             { OP_IfPos,       1,  0,  0},    /* 9 */
67777             { OP_Halt,        0,  0,  0},
67778           };
67779           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
67780           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
67781           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
67782           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
67783           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
67784           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
67785           sqlite3VdbeJumpHere(v, addr+9);
67786           sqlite3VdbeJumpHere(v, jmp2);
67787         }
67788         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
67789         sqlite3VdbeJumpHere(v, loopTop);
67790         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
67791           static const VdbeOpList cntIdx[] = {
67792              { OP_Integer,      0,  3,  0},
67793              { OP_Rewind,       0,  0,  0},  /* 1 */
67794              { OP_AddImm,       3,  1,  0},
67795              { OP_Next,         0,  0,  0},  /* 3 */
67796              { OP_Eq,           2,  0,  3},  /* 4 */
67797              { OP_AddImm,       1, -1,  0},
67798              { OP_String8,      0,  2,  0},  /* 6 */
67799              { OP_String8,      0,  3,  0},  /* 7 */
67800              { OP_Concat,       3,  2,  2},
67801              { OP_ResultRow,    2,  1,  0},
67802           };
67803           if( pIdx->tnum==0 ) continue;
67804           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
67805           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
67806           sqlite3VdbeJumpHere(v, addr);
67807           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
67808           sqlite3VdbeChangeP1(v, addr+1, j+2);
67809           sqlite3VdbeChangeP2(v, addr+1, addr+4);
67810           sqlite3VdbeChangeP1(v, addr+3, j+2);
67811           sqlite3VdbeChangeP2(v, addr+3, addr+2);
67812           sqlite3VdbeJumpHere(v, addr+4);
67813           sqlite3VdbeChangeP4(v, addr+6, 
67814                      "wrong # of entries in index ", P4_STATIC);
67815           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
67816         }
67817       } 
67818     }
67819     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
67820     sqlite3VdbeChangeP2(v, addr, -mxErr);
67821     sqlite3VdbeJumpHere(v, addr+1);
67822     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
67823   }else
67824 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67825
67826 #ifndef SQLITE_OMIT_UTF16
67827   /*
67828   **   PRAGMA encoding
67829   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
67830   **
67831   ** In its first form, this pragma returns the encoding of the main
67832   ** database. If the database is not initialized, it is initialized now.
67833   **
67834   ** The second form of this pragma is a no-op if the main database file
67835   ** has not already been initialized. In this case it sets the default
67836   ** encoding that will be used for the main database file if a new file
67837   ** is created. If an existing main database file is opened, then the
67838   ** default text encoding for the existing database is used.
67839   ** 
67840   ** In all cases new databases created using the ATTACH command are
67841   ** created to use the same default text encoding as the main database. If
67842   ** the main database has not been initialized and/or created when ATTACH
67843   ** is executed, this is done before the ATTACH operation.
67844   **
67845   ** In the second form this pragma sets the text encoding to be used in
67846   ** new database files created using this database handle. It is only
67847   ** useful if invoked immediately after the main database i
67848   */
67849   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
67850     static const struct EncName {
67851       char *zName;
67852       u8 enc;
67853     } encnames[] = {
67854       { "UTF-8",    SQLITE_UTF8        },
67855       { "UTF8",     SQLITE_UTF8        },
67856       { "UTF-16le", SQLITE_UTF16LE     },
67857       { "UTF16le",  SQLITE_UTF16LE     },
67858       { "UTF-16be", SQLITE_UTF16BE     },
67859       { "UTF16be",  SQLITE_UTF16BE     },
67860       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
67861       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
67862       { 0, 0 }
67863     };
67864     const struct EncName *pEnc;
67865     if( !zRight ){    /* "PRAGMA encoding" */
67866       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
67867       sqlite3VdbeSetNumCols(v, 1);
67868       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC);
67869       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
67870       for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
67871         if( pEnc->enc==ENC(pParse->db) ){
67872           sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC);
67873           break;
67874         }
67875       }
67876       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
67877     }else{                        /* "PRAGMA encoding = XXX" */
67878       /* Only change the value of sqlite.enc if the database handle is not
67879       ** initialized. If the main database exists, the new sqlite.enc value
67880       ** will be overwritten when the schema is next loaded. If it does not
67881       ** already exists, it will be created to use the new encoding value.
67882       */
67883       if( 
67884         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
67885         DbHasProperty(db, 0, DB_Empty) 
67886       ){
67887         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
67888           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
67889             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
67890             break;
67891           }
67892         }
67893         if( !pEnc->zName ){
67894           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
67895         }
67896       }
67897     }
67898   }else
67899 #endif /* SQLITE_OMIT_UTF16 */
67900
67901 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
67902   /*
67903   **   PRAGMA [database.]schema_version
67904   **   PRAGMA [database.]schema_version = <integer>
67905   **
67906   **   PRAGMA [database.]user_version
67907   **   PRAGMA [database.]user_version = <integer>
67908   **
67909   ** The pragma's schema_version and user_version are used to set or get
67910   ** the value of the schema-version and user-version, respectively. Both
67911   ** the schema-version and the user-version are 32-bit signed integers
67912   ** stored in the database header.
67913   **
67914   ** The schema-cookie is usually only manipulated internally by SQLite. It
67915   ** is incremented by SQLite whenever the database schema is modified (by
67916   ** creating or dropping a table or index). The schema version is used by
67917   ** SQLite each time a query is executed to ensure that the internal cache
67918   ** of the schema used when compiling the SQL query matches the schema of
67919   ** the database against which the compiled query is actually executed.
67920   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
67921   ** the schema-version is potentially dangerous and may lead to program
67922   ** crashes or database corruption. Use with caution!
67923   **
67924   ** The user-version is not used internally by SQLite. It may be used by
67925   ** applications for any purpose.
67926   */
67927   if( sqlite3StrICmp(zLeft, "schema_version")==0 
67928    || sqlite3StrICmp(zLeft, "user_version")==0 
67929    || sqlite3StrICmp(zLeft, "freelist_count")==0 
67930   ){
67931     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
67932     sqlite3VdbeUsesBtree(v, iDb);
67933     switch( zLeft[0] ){
67934       case 's': case 'S':
67935         iCookie = 0;
67936         break;
67937       case 'f': case 'F':
67938         iCookie = 1;
67939         iDb = (-1*(iDb+1));
67940         assert(iDb<=0);
67941         break;
67942       default:
67943         iCookie = 5;
67944         break;
67945     }
67946
67947     if( zRight && iDb>=0 ){
67948       /* Write the specified cookie value */
67949       static const VdbeOpList setCookie[] = {
67950         { OP_Transaction,    0,  1,  0},    /* 0 */
67951         { OP_Integer,        0,  1,  0},    /* 1 */
67952         { OP_SetCookie,      0,  0,  1},    /* 2 */
67953       };
67954       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
67955       sqlite3VdbeChangeP1(v, addr, iDb);
67956       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
67957       sqlite3VdbeChangeP1(v, addr+2, iDb);
67958       sqlite3VdbeChangeP2(v, addr+2, iCookie);
67959     }else{
67960       /* Read the specified cookie value */
67961       static const VdbeOpList readCookie[] = {
67962         { OP_ReadCookie,      0,  1,  0},    /* 0 */
67963         { OP_ResultRow,       1,  1,  0}
67964       };
67965       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
67966       sqlite3VdbeChangeP1(v, addr, iDb);
67967       sqlite3VdbeChangeP3(v, addr, iCookie);
67968       sqlite3VdbeSetNumCols(v, 1);
67969       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT);
67970     }
67971   }else
67972 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
67973
67974 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
67975   /*
67976   ** Report the current state of file logs for all databases
67977   */
67978   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
67979     static const char *const azLockName[] = {
67980       "unlocked", "shared", "reserved", "pending", "exclusive"
67981     };
67982     int i;
67983     Vdbe *v = sqlite3GetVdbe(pParse);
67984     sqlite3VdbeSetNumCols(v, 2);
67985     pParse->nMem = 2;
67986     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC);
67987     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC);
67988     for(i=0; i<db->nDb; i++){
67989       Btree *pBt;
67990       Pager *pPager;
67991       const char *zState = "unknown";
67992       int j;
67993       if( db->aDb[i].zName==0 ) continue;
67994       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
67995       pBt = db->aDb[i].pBt;
67996       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
67997         zState = "closed";
67998       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
67999                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
68000          zState = azLockName[j];
68001       }
68002       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
68003       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
68004     }
68005
68006   }else
68007 #endif
68008
68009 #ifdef SQLITE_SSE
68010   /*
68011   ** Check to see if the sqlite_statements table exists.  Create it
68012   ** if it does not.
68013   */
68014   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
68015     extern int sqlite3CreateStatementsTable(Parse*);
68016     sqlite3CreateStatementsTable(pParse);
68017   }else
68018 #endif
68019
68020 #if SQLITE_HAS_CODEC
68021   if( sqlite3StrICmp(zLeft, "key")==0 ){
68022     sqlite3_key(db, zRight, strlen(zRight));
68023   }else
68024 #endif
68025 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
68026   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
68027 #if SQLITE_HAS_CODEC
68028     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
68029       extern void sqlite3_activate_see(const char*);
68030       sqlite3_activate_see(&zRight[4]);
68031     }
68032 #endif
68033 #ifdef SQLITE_ENABLE_CEROD
68034     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
68035       extern void sqlite3_activate_cerod(const char*);
68036       sqlite3_activate_cerod(&zRight[6]);
68037     }
68038 #endif
68039   }
68040 #endif
68041
68042   {}
68043
68044   if( v ){
68045     /* Code an OP_Expire at the end of each PRAGMA program to cause
68046     ** the VDBE implementing the pragma to expire. Most (all?) pragmas
68047     ** are only valid for a single execution.
68048     */
68049     sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
68050
68051     /*
68052     ** Reset the safety level, in case the fullfsync flag or synchronous
68053     ** setting changed.
68054     */
68055 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
68056     if( db->autoCommit ){
68057       sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
68058                  (db->flags&SQLITE_FullFSync)!=0);
68059     }
68060 #endif
68061   }
68062 pragma_out:
68063   sqlite3DbFree(db, zLeft);
68064   sqlite3DbFree(db, zRight);
68065 }
68066
68067 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
68068
68069 /************** End of pragma.c **********************************************/
68070 /************** Begin file prepare.c *****************************************/
68071 /*
68072 ** 2005 May 25
68073 **
68074 ** The author disclaims copyright to this source code.  In place of
68075 ** a legal notice, here is a blessing:
68076 **
68077 **    May you do good and not evil.
68078 **    May you find forgiveness for yourself and forgive others.
68079 **    May you share freely, never taking more than you give.
68080 **
68081 *************************************************************************
68082 ** This file contains the implementation of the sqlite3_prepare()
68083 ** interface, and routines that contribute to loading the database schema
68084 ** from disk.
68085 **
68086 ** $Id: prepare.c,v 1.97 2008/09/08 09:06:19 danielk1977 Exp $
68087 */
68088
68089 /*
68090 ** Fill the InitData structure with an error message that indicates
68091 ** that the database is corrupt.
68092 */
68093 static void corruptSchema(
68094   InitData *pData,     /* Initialization context */
68095   const char *zObj,    /* Object being parsed at the point of error */
68096   const char *zExtra   /* Error information */
68097 ){
68098   sqlite3 *db = pData->db;
68099   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
68100     if( zObj==0 ) zObj = "?";
68101     sqlite3SetString(pData->pzErrMsg, pData->db,
68102        "malformed database schema (%s)", zObj);
68103     if( zExtra && zExtra[0] ){
68104       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
68105                                   *pData->pzErrMsg, zExtra);
68106     }
68107   }
68108   pData->rc = SQLITE_CORRUPT;
68109 }
68110
68111 /*
68112 ** This is the callback routine for the code that initializes the
68113 ** database.  See sqlite3Init() below for additional information.
68114 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
68115 **
68116 ** Each callback contains the following information:
68117 **
68118 **     argv[0] = name of thing being created
68119 **     argv[1] = root page number for table or index. 0 for trigger or view.
68120 **     argv[2] = SQL text for the CREATE statement.
68121 **
68122 */
68123 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
68124   InitData *pData = (InitData*)pInit;
68125   sqlite3 *db = pData->db;
68126   int iDb = pData->iDb;
68127
68128   assert( sqlite3_mutex_held(db->mutex) );
68129   DbClearProperty(db, iDb, DB_Empty);
68130   if( db->mallocFailed ){
68131     corruptSchema(pData, argv[0], 0);
68132     return SQLITE_NOMEM;
68133   }
68134
68135   assert( argc==3 );
68136   assert( iDb>=0 && iDb<db->nDb );
68137   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
68138   if( argv[1]==0 ){
68139     corruptSchema(pData, argv[0], 0);
68140   }else if( argv[2] && argv[2][0] ){
68141     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
68142     ** But because db->init.busy is set to 1, no VDBE code is generated
68143     ** or executed.  All the parser does is build the internal data
68144     ** structures that describe the table, index, or view.
68145     */
68146     char *zErr;
68147     int rc;
68148     u8 lookasideEnabled;
68149     assert( db->init.busy );
68150     db->init.iDb = iDb;
68151     db->init.newTnum = atoi(argv[1]);
68152     lookasideEnabled = db->lookaside.bEnabled;
68153     db->lookaside.bEnabled = 0;
68154     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
68155     db->init.iDb = 0;
68156     db->lookaside.bEnabled = lookasideEnabled;
68157     assert( rc!=SQLITE_OK || zErr==0 );
68158     if( SQLITE_OK!=rc ){
68159       pData->rc = rc;
68160       if( rc==SQLITE_NOMEM ){
68161         db->mallocFailed = 1;
68162       }else if( rc!=SQLITE_INTERRUPT ){
68163         corruptSchema(pData, argv[0], zErr);
68164       }
68165       sqlite3DbFree(db, zErr);
68166     }
68167   }else if( argv[0]==0 ){
68168     corruptSchema(pData, 0, 0);
68169   }else{
68170     /* If the SQL column is blank it means this is an index that
68171     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
68172     ** constraint for a CREATE TABLE.  The index should have already
68173     ** been created when we processed the CREATE TABLE.  All we have
68174     ** to do here is record the root page number for that index.
68175     */
68176     Index *pIndex;
68177     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
68178     if( pIndex==0 || pIndex->tnum!=0 ){
68179       /* This can occur if there exists an index on a TEMP table which
68180       ** has the same name as another index on a permanent index.  Since
68181       ** the permanent table is hidden by the TEMP table, we can also
68182       ** safely ignore the index on the permanent table.
68183       */
68184       /* Do Nothing */;
68185     }else{
68186       pIndex->tnum = atoi(argv[1]);
68187     }
68188   }
68189   return 0;
68190 }
68191
68192 /*
68193 ** Attempt to read the database schema and initialize internal
68194 ** data structures for a single database file.  The index of the
68195 ** database file is given by iDb.  iDb==0 is used for the main
68196 ** database.  iDb==1 should never be used.  iDb>=2 is used for
68197 ** auxiliary databases.  Return one of the SQLITE_ error codes to
68198 ** indicate success or failure.
68199 */
68200 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
68201   int rc;
68202   BtCursor *curMain;
68203   int size;
68204   Table *pTab;
68205   Db *pDb;
68206   char const *azArg[4];
68207   int meta[10];
68208   InitData initData;
68209   char const *zMasterSchema;
68210   char const *zMasterName = SCHEMA_TABLE(iDb);
68211
68212   /*
68213   ** The master database table has a structure like this
68214   */
68215   static const char master_schema[] = 
68216      "CREATE TABLE sqlite_master(\n"
68217      "  type text,\n"
68218      "  name text,\n"
68219      "  tbl_name text,\n"
68220      "  rootpage integer,\n"
68221      "  sql text\n"
68222      ")"
68223   ;
68224 #ifndef SQLITE_OMIT_TEMPDB
68225   static const char temp_master_schema[] = 
68226      "CREATE TEMP TABLE sqlite_temp_master(\n"
68227      "  type text,\n"
68228      "  name text,\n"
68229      "  tbl_name text,\n"
68230      "  rootpage integer,\n"
68231      "  sql text\n"
68232      ")"
68233   ;
68234 #else
68235   #define temp_master_schema 0
68236 #endif
68237
68238   assert( iDb>=0 && iDb<db->nDb );
68239   assert( db->aDb[iDb].pSchema );
68240   assert( sqlite3_mutex_held(db->mutex) );
68241   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
68242
68243   /* zMasterSchema and zInitScript are set to point at the master schema
68244   ** and initialisation script appropriate for the database being
68245   ** initialised. zMasterName is the name of the master table.
68246   */
68247   if( !OMIT_TEMPDB && iDb==1 ){
68248     zMasterSchema = temp_master_schema;
68249   }else{
68250     zMasterSchema = master_schema;
68251   }
68252   zMasterName = SCHEMA_TABLE(iDb);
68253
68254   /* Construct the schema tables.  */
68255   azArg[0] = zMasterName;
68256   azArg[1] = "1";
68257   azArg[2] = zMasterSchema;
68258   azArg[3] = 0;
68259   initData.db = db;
68260   initData.iDb = iDb;
68261   initData.rc = SQLITE_OK;
68262   initData.pzErrMsg = pzErrMsg;
68263   (void)sqlite3SafetyOff(db);
68264   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
68265   (void)sqlite3SafetyOn(db);
68266   if( initData.rc ){
68267     rc = initData.rc;
68268     goto error_out;
68269   }
68270   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
68271   if( pTab ){
68272     pTab->tabFlags |= TF_Readonly;
68273   }
68274
68275   /* Create a cursor to hold the database open
68276   */
68277   pDb = &db->aDb[iDb];
68278   if( pDb->pBt==0 ){
68279     if( !OMIT_TEMPDB && iDb==1 ){
68280       DbSetProperty(db, 1, DB_SchemaLoaded);
68281     }
68282     return SQLITE_OK;
68283   }
68284   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
68285   if( !curMain ){
68286     rc = SQLITE_NOMEM;
68287     goto error_out;
68288   }
68289   sqlite3BtreeEnter(pDb->pBt);
68290   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
68291   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
68292     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
68293     goto initone_error_out;
68294   }
68295
68296   /* Get the database meta information.
68297   **
68298   ** Meta values are as follows:
68299   **    meta[0]   Schema cookie.  Changes with each schema change.
68300   **    meta[1]   File format of schema layer.
68301   **    meta[2]   Size of the page cache.
68302   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
68303   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
68304   **    meta[5]   The user cookie. Used by the application.
68305   **    meta[6]   Incremental-vacuum flag.
68306   **    meta[7]
68307   **    meta[8]
68308   **    meta[9]
68309   **
68310   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
68311   ** the possible values of meta[4].
68312   */
68313   if( rc==SQLITE_OK ){
68314     int i;
68315     for(i=0; i<sizeof(meta)/sizeof(meta[0]); i++){
68316       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
68317       if( rc ){
68318         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
68319         goto initone_error_out;
68320       }
68321     }
68322   }else{
68323     memset(meta, 0, sizeof(meta));
68324   }
68325   pDb->pSchema->schema_cookie = meta[0];
68326
68327   /* If opening a non-empty database, check the text encoding. For the
68328   ** main database, set sqlite3.enc to the encoding of the main database.
68329   ** For an attached db, it is an error if the encoding is not the same
68330   ** as sqlite3.enc.
68331   */
68332   if( meta[4] ){  /* text encoding */
68333     if( iDb==0 ){
68334       /* If opening the main database, set ENC(db). */
68335       ENC(db) = (u8)meta[4];
68336       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
68337     }else{
68338       /* If opening an attached database, the encoding much match ENC(db) */
68339       if( meta[4]!=ENC(db) ){
68340         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
68341             " text encoding as main database");
68342         rc = SQLITE_ERROR;
68343         goto initone_error_out;
68344       }
68345     }
68346   }else{
68347     DbSetProperty(db, iDb, DB_Empty);
68348   }
68349   pDb->pSchema->enc = ENC(db);
68350
68351   if( pDb->pSchema->cache_size==0 ){
68352     size = meta[2];
68353     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
68354     if( size<0 ) size = -size;
68355     pDb->pSchema->cache_size = size;
68356     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
68357   }
68358
68359   /*
68360   ** file_format==1    Version 3.0.0.
68361   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
68362   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
68363   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
68364   */
68365   pDb->pSchema->file_format = meta[1];
68366   if( pDb->pSchema->file_format==0 ){
68367     pDb->pSchema->file_format = 1;
68368   }
68369   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
68370     sqlite3SetString(pzErrMsg, db, "unsupported file format");
68371     rc = SQLITE_ERROR;
68372     goto initone_error_out;
68373   }
68374
68375   /* Ticket #2804:  When we open a database in the newer file format,
68376   ** clear the legacy_file_format pragma flag so that a VACUUM will
68377   ** not downgrade the database and thus invalidate any descending
68378   ** indices that the user might have created.
68379   */
68380   if( iDb==0 && meta[1]>=4 ){
68381     db->flags &= ~SQLITE_LegacyFileFmt;
68382   }
68383
68384   /* Read the schema information out of the schema tables
68385   */
68386   assert( db->init.busy );
68387   if( rc==SQLITE_EMPTY ){
68388     /* For an empty database, there is nothing to read */
68389     rc = SQLITE_OK;
68390   }else{
68391     char *zSql;
68392     zSql = sqlite3MPrintf(db, 
68393         "SELECT name, rootpage, sql FROM '%q'.%s",
68394         db->aDb[iDb].zName, zMasterName);
68395     (void)sqlite3SafetyOff(db);
68396 #ifndef SQLITE_OMIT_AUTHORIZATION
68397     {
68398       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
68399       xAuth = db->xAuth;
68400       db->xAuth = 0;
68401 #endif
68402       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
68403 #ifndef SQLITE_OMIT_AUTHORIZATION
68404       db->xAuth = xAuth;
68405     }
68406 #endif
68407     if( rc==SQLITE_OK ) rc = initData.rc;
68408     (void)sqlite3SafetyOn(db);
68409     sqlite3DbFree(db, zSql);
68410 #ifndef SQLITE_OMIT_ANALYZE
68411     if( rc==SQLITE_OK ){
68412       sqlite3AnalysisLoad(db, iDb);
68413     }
68414 #endif
68415   }
68416   if( db->mallocFailed ){
68417     rc = SQLITE_NOMEM;
68418     sqlite3ResetInternalSchema(db, 0);
68419   }
68420   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
68421     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
68422     ** the schema loaded, even if errors occured. In this situation the 
68423     ** current sqlite3_prepare() operation will fail, but the following one
68424     ** will attempt to compile the supplied statement against whatever subset
68425     ** of the schema was loaded before the error occured. The primary
68426     ** purpose of this is to allow access to the sqlite_master table
68427     ** even when its contents have been corrupted.
68428     */
68429     DbSetProperty(db, iDb, DB_SchemaLoaded);
68430     rc = SQLITE_OK;
68431   }
68432
68433   /* Jump here for an error that occurs after successfully allocating
68434   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
68435   ** before that point, jump to error_out.
68436   */
68437 initone_error_out:
68438   sqlite3BtreeCloseCursor(curMain);
68439   sqlite3_free(curMain);
68440   sqlite3BtreeLeave(pDb->pBt);
68441
68442 error_out:
68443   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
68444     db->mallocFailed = 1;
68445   }
68446   return rc;
68447 }
68448
68449 /*
68450 ** Initialize all database files - the main database file, the file
68451 ** used to store temporary tables, and any additional database files
68452 ** created using ATTACH statements.  Return a success code.  If an
68453 ** error occurs, write an error message into *pzErrMsg.
68454 **
68455 ** After a database is initialized, the DB_SchemaLoaded bit is set
68456 ** bit is set in the flags field of the Db structure. If the database
68457 ** file was of zero-length, then the DB_Empty flag is also set.
68458 */
68459 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
68460   int i, rc;
68461   int commit_internal = !(db->flags&SQLITE_InternChanges);
68462   
68463   assert( sqlite3_mutex_held(db->mutex) );
68464   if( db->init.busy ) return SQLITE_OK;
68465   rc = SQLITE_OK;
68466   db->init.busy = 1;
68467   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
68468     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
68469     rc = sqlite3InitOne(db, i, pzErrMsg);
68470     if( rc ){
68471       sqlite3ResetInternalSchema(db, i);
68472     }
68473   }
68474
68475   /* Once all the other databases have been initialised, load the schema
68476   ** for the TEMP database. This is loaded last, as the TEMP database
68477   ** schema may contain references to objects in other databases.
68478   */
68479 #ifndef SQLITE_OMIT_TEMPDB
68480   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
68481     rc = sqlite3InitOne(db, 1, pzErrMsg);
68482     if( rc ){
68483       sqlite3ResetInternalSchema(db, 1);
68484     }
68485   }
68486 #endif
68487
68488   db->init.busy = 0;
68489   if( rc==SQLITE_OK && commit_internal ){
68490     sqlite3CommitInternalChanges(db);
68491   }
68492
68493   return rc; 
68494 }
68495
68496 /*
68497 ** This routine is a no-op if the database schema is already initialised.
68498 ** Otherwise, the schema is loaded. An error code is returned.
68499 */
68500 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
68501   int rc = SQLITE_OK;
68502   sqlite3 *db = pParse->db;
68503   assert( sqlite3_mutex_held(db->mutex) );
68504   if( !db->init.busy ){
68505     rc = sqlite3Init(db, &pParse->zErrMsg);
68506   }
68507   if( rc!=SQLITE_OK ){
68508     pParse->rc = rc;
68509     pParse->nErr++;
68510   }
68511   return rc;
68512 }
68513
68514
68515 /*
68516 ** Check schema cookies in all databases.  If any cookie is out
68517 ** of date, return 0.  If all schema cookies are current, return 1.
68518 */
68519 static int schemaIsValid(sqlite3 *db){
68520   int iDb;
68521   int rc;
68522   BtCursor *curTemp;
68523   int cookie;
68524   int allOk = 1;
68525
68526   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
68527   if( curTemp ){
68528     assert( sqlite3_mutex_held(db->mutex) );
68529     for(iDb=0; allOk && iDb<db->nDb; iDb++){
68530       Btree *pBt;
68531       pBt = db->aDb[iDb].pBt;
68532       if( pBt==0 ) continue;
68533       memset(curTemp, 0, sqlite3BtreeCursorSize());
68534       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
68535       if( rc==SQLITE_OK ){
68536         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
68537         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
68538           allOk = 0;
68539         }
68540         sqlite3BtreeCloseCursor(curTemp);
68541       }
68542       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
68543         db->mallocFailed = 1;
68544       }
68545     }
68546     sqlite3_free(curTemp);
68547   }else{
68548     allOk = 0;
68549     db->mallocFailed = 1;
68550   }
68551
68552   return allOk;
68553 }
68554
68555 /*
68556 ** Convert a schema pointer into the iDb index that indicates
68557 ** which database file in db->aDb[] the schema refers to.
68558 **
68559 ** If the same database is attached more than once, the first
68560 ** attached database is returned.
68561 */
68562 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
68563   int i = -1000000;
68564
68565   /* If pSchema is NULL, then return -1000000. This happens when code in 
68566   ** expr.c is trying to resolve a reference to a transient table (i.e. one
68567   ** created by a sub-select). In this case the return value of this 
68568   ** function should never be used.
68569   **
68570   ** We return -1000000 instead of the more usual -1 simply because using
68571   ** -1000000 as incorrectly using -1000000 index into db->aDb[] is much 
68572   ** more likely to cause a segfault than -1 (of course there are assert()
68573   ** statements too, but it never hurts to play the odds).
68574   */
68575   assert( sqlite3_mutex_held(db->mutex) );
68576   if( pSchema ){
68577     for(i=0; i<db->nDb; i++){
68578       if( db->aDb[i].pSchema==pSchema ){
68579         break;
68580       }
68581     }
68582     assert( i>=0 &&i>=0 &&  i<db->nDb );
68583   }
68584   return i;
68585 }
68586
68587 /*
68588 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
68589 */
68590 static int sqlite3Prepare(
68591   sqlite3 *db,              /* Database handle. */
68592   const char *zSql,         /* UTF-8 encoded SQL statement. */
68593   int nBytes,               /* Length of zSql in bytes. */
68594   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
68595   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68596   const char **pzTail       /* OUT: End of parsed string */
68597 ){
68598   Parse sParse;
68599   char *zErrMsg = 0;
68600   int rc = SQLITE_OK;
68601   int i;
68602
68603   assert( ppStmt );
68604   *ppStmt = 0;
68605   if( sqlite3SafetyOn(db) ){
68606     return SQLITE_MISUSE;
68607   }
68608   assert( !db->mallocFailed );
68609   assert( sqlite3_mutex_held(db->mutex) );
68610
68611   /* If any attached database schemas are locked, do not proceed with
68612   ** compilation. Instead return SQLITE_LOCKED immediately.
68613   */
68614   for(i=0; i<db->nDb; i++) {
68615     Btree *pBt = db->aDb[i].pBt;
68616     if( pBt ){
68617       int rc;
68618       rc = sqlite3BtreeSchemaLocked(pBt);
68619       if( rc ){
68620         const char *zDb = db->aDb[i].zName;
68621         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
68622         (void)sqlite3SafetyOff(db);
68623         return sqlite3ApiExit(db, SQLITE_LOCKED);
68624       }
68625     }
68626   }
68627   
68628   memset(&sParse, 0, sizeof(sParse));
68629   sParse.db = db;
68630   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
68631     char *zSqlCopy;
68632     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
68633     if( nBytes>mxLen ){
68634       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
68635       (void)sqlite3SafetyOff(db);
68636       return sqlite3ApiExit(db, SQLITE_TOOBIG);
68637     }
68638     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
68639     if( zSqlCopy ){
68640       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
68641       sqlite3DbFree(db, zSqlCopy);
68642       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
68643     }else{
68644       sParse.zTail = &zSql[nBytes];
68645     }
68646   }else{
68647     sqlite3RunParser(&sParse, zSql, &zErrMsg);
68648   }
68649
68650   if( db->mallocFailed ){
68651     sParse.rc = SQLITE_NOMEM;
68652   }
68653   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
68654   if( sParse.checkSchema && !schemaIsValid(db) ){
68655     sParse.rc = SQLITE_SCHEMA;
68656   }
68657   if( sParse.rc==SQLITE_SCHEMA ){
68658     sqlite3ResetInternalSchema(db, 0);
68659   }
68660   if( db->mallocFailed ){
68661     sParse.rc = SQLITE_NOMEM;
68662   }
68663   if( pzTail ){
68664     *pzTail = sParse.zTail;
68665   }
68666   rc = sParse.rc;
68667
68668 #ifndef SQLITE_OMIT_EXPLAIN
68669   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
68670     if( sParse.explain==2 ){
68671       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
68672       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC);
68673       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC);
68674       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC);
68675     }else{
68676       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
68677       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC);
68678       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC);
68679       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC);
68680       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC);
68681       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC);
68682       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC);
68683       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC);
68684       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC);
68685     }
68686   }
68687 #endif
68688
68689   if( sqlite3SafetyOff(db) ){
68690     rc = SQLITE_MISUSE;
68691   }
68692
68693   if( saveSqlFlag ){
68694     sqlite3VdbeSetSql(sParse.pVdbe, zSql, sParse.zTail - zSql);
68695   }
68696   if( rc!=SQLITE_OK || db->mallocFailed ){
68697     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
68698     assert(!(*ppStmt));
68699   }else{
68700     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
68701   }
68702
68703   if( zErrMsg ){
68704     sqlite3Error(db, rc, "%s", zErrMsg);
68705     sqlite3DbFree(db, zErrMsg);
68706   }else{
68707     sqlite3Error(db, rc, 0);
68708   }
68709
68710   rc = sqlite3ApiExit(db, rc);
68711   assert( (rc&db->errMask)==rc );
68712   return rc;
68713 }
68714 static int sqlite3LockAndPrepare(
68715   sqlite3 *db,              /* Database handle. */
68716   const char *zSql,         /* UTF-8 encoded SQL statement. */
68717   int nBytes,               /* Length of zSql in bytes. */
68718   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
68719   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68720   const char **pzTail       /* OUT: End of parsed string */
68721 ){
68722   int rc;
68723   if( !sqlite3SafetyCheckOk(db) ){
68724     return SQLITE_MISUSE;
68725   }
68726   sqlite3_mutex_enter(db->mutex);
68727   sqlite3BtreeEnterAll(db);
68728   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
68729   sqlite3BtreeLeaveAll(db);
68730   sqlite3_mutex_leave(db->mutex);
68731   return rc;
68732 }
68733
68734 /*
68735 ** Rerun the compilation of a statement after a schema change.
68736 ** Return true if the statement was recompiled successfully.
68737 ** Return false if there is an error of some kind.
68738 */
68739 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
68740   int rc;
68741   sqlite3_stmt *pNew;
68742   const char *zSql;
68743   sqlite3 *db;
68744
68745   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
68746   zSql = sqlite3_sql((sqlite3_stmt *)p);
68747   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
68748   db = sqlite3VdbeDb(p);
68749   assert( sqlite3_mutex_held(db->mutex) );
68750   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
68751   if( rc ){
68752     if( rc==SQLITE_NOMEM ){
68753       db->mallocFailed = 1;
68754     }
68755     assert( pNew==0 );
68756     return 0;
68757   }else{
68758     assert( pNew!=0 );
68759   }
68760   sqlite3VdbeSwap((Vdbe*)pNew, p);
68761   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
68762   sqlite3VdbeResetStepResult((Vdbe*)pNew);
68763   sqlite3VdbeFinalize((Vdbe*)pNew);
68764   return 1;
68765 }
68766
68767
68768 /*
68769 ** Two versions of the official API.  Legacy and new use.  In the legacy
68770 ** version, the original SQL text is not saved in the prepared statement
68771 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
68772 ** sqlite3_step().  In the new version, the original SQL text is retained
68773 ** and the statement is automatically recompiled if an schema change
68774 ** occurs.
68775 */
68776 SQLITE_API int sqlite3_prepare(
68777   sqlite3 *db,              /* Database handle. */
68778   const char *zSql,         /* UTF-8 encoded SQL statement. */
68779   int nBytes,               /* Length of zSql in bytes. */
68780   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68781   const char **pzTail       /* OUT: End of parsed string */
68782 ){
68783   int rc;
68784   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
68785   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68786   return rc;
68787 }
68788 SQLITE_API int sqlite3_prepare_v2(
68789   sqlite3 *db,              /* Database handle. */
68790   const char *zSql,         /* UTF-8 encoded SQL statement. */
68791   int nBytes,               /* Length of zSql in bytes. */
68792   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68793   const char **pzTail       /* OUT: End of parsed string */
68794 ){
68795   int rc;
68796   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
68797   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68798   return rc;
68799 }
68800
68801
68802 #ifndef SQLITE_OMIT_UTF16
68803 /*
68804 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
68805 */
68806 static int sqlite3Prepare16(
68807   sqlite3 *db,              /* Database handle. */ 
68808   const void *zSql,         /* UTF-8 encoded SQL statement. */
68809   int nBytes,               /* Length of zSql in bytes. */
68810   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
68811   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68812   const void **pzTail       /* OUT: End of parsed string */
68813 ){
68814   /* This function currently works by first transforming the UTF-16
68815   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
68816   ** tricky bit is figuring out the pointer to return in *pzTail.
68817   */
68818   char *zSql8;
68819   const char *zTail8 = 0;
68820   int rc = SQLITE_OK;
68821
68822   if( !sqlite3SafetyCheckOk(db) ){
68823     return SQLITE_MISUSE;
68824   }
68825   sqlite3_mutex_enter(db->mutex);
68826   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
68827   if( zSql8 ){
68828     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
68829   }
68830
68831   if( zTail8 && pzTail ){
68832     /* If sqlite3_prepare returns a tail pointer, we calculate the
68833     ** equivalent pointer into the UTF-16 string by counting the unicode
68834     ** characters between zSql8 and zTail8, and then returning a pointer
68835     ** the same number of characters into the UTF-16 string.
68836     */
68837     int chars_parsed = sqlite3Utf8CharLen(zSql8, zTail8-zSql8);
68838     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
68839   }
68840   sqlite3DbFree(db, zSql8); 
68841   rc = sqlite3ApiExit(db, rc);
68842   sqlite3_mutex_leave(db->mutex);
68843   return rc;
68844 }
68845
68846 /*
68847 ** Two versions of the official API.  Legacy and new use.  In the legacy
68848 ** version, the original SQL text is not saved in the prepared statement
68849 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
68850 ** sqlite3_step().  In the new version, the original SQL text is retained
68851 ** and the statement is automatically recompiled if an schema change
68852 ** occurs.
68853 */
68854 SQLITE_API int sqlite3_prepare16(
68855   sqlite3 *db,              /* Database handle. */ 
68856   const void *zSql,         /* UTF-8 encoded SQL statement. */
68857   int nBytes,               /* Length of zSql in bytes. */
68858   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68859   const void **pzTail       /* OUT: End of parsed string */
68860 ){
68861   int rc;
68862   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
68863   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68864   return rc;
68865 }
68866 SQLITE_API int sqlite3_prepare16_v2(
68867   sqlite3 *db,              /* Database handle. */ 
68868   const void *zSql,         /* UTF-8 encoded SQL statement. */
68869   int nBytes,               /* Length of zSql in bytes. */
68870   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
68871   const void **pzTail       /* OUT: End of parsed string */
68872 ){
68873   int rc;
68874   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
68875   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
68876   return rc;
68877 }
68878
68879 #endif /* SQLITE_OMIT_UTF16 */
68880
68881 /************** End of prepare.c *********************************************/
68882 /************** Begin file select.c ******************************************/
68883 /*
68884 ** 2001 September 15
68885 **
68886 ** The author disclaims copyright to this source code.  In place of
68887 ** a legal notice, here is a blessing:
68888 **
68889 **    May you do good and not evil.
68890 **    May you find forgiveness for yourself and forgive others.
68891 **    May you share freely, never taking more than you give.
68892 **
68893 *************************************************************************
68894 ** This file contains C code routines that are called by the parser
68895 ** to handle SELECT statements in SQLite.
68896 **
68897 ** $Id: select.c,v 1.480 2008/10/07 19:53:14 drh Exp $
68898 */
68899
68900
68901 /*
68902 ** Delete all the content of a Select structure but do not deallocate
68903 ** the select structure itself.
68904 */
68905 static void clearSelect(sqlite3 *db, Select *p){
68906   sqlite3ExprListDelete(db, p->pEList);
68907   sqlite3SrcListDelete(db, p->pSrc);
68908   sqlite3ExprDelete(db, p->pWhere);
68909   sqlite3ExprListDelete(db, p->pGroupBy);
68910   sqlite3ExprDelete(db, p->pHaving);
68911   sqlite3ExprListDelete(db, p->pOrderBy);
68912   sqlite3SelectDelete(db, p->pPrior);
68913   sqlite3ExprDelete(db, p->pLimit);
68914   sqlite3ExprDelete(db, p->pOffset);
68915 }
68916
68917 /*
68918 ** Initialize a SelectDest structure.
68919 */
68920 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
68921   pDest->eDest = eDest;
68922   pDest->iParm = iParm;
68923   pDest->affinity = 0;
68924   pDest->iMem = 0;
68925   pDest->nMem = 0;
68926 }
68927
68928
68929 /*
68930 ** Allocate a new Select structure and return a pointer to that
68931 ** structure.
68932 */
68933 SQLITE_PRIVATE Select *sqlite3SelectNew(
68934   Parse *pParse,        /* Parsing context */
68935   ExprList *pEList,     /* which columns to include in the result */
68936   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
68937   Expr *pWhere,         /* the WHERE clause */
68938   ExprList *pGroupBy,   /* the GROUP BY clause */
68939   Expr *pHaving,        /* the HAVING clause */
68940   ExprList *pOrderBy,   /* the ORDER BY clause */
68941   int isDistinct,       /* true if the DISTINCT keyword is present */
68942   Expr *pLimit,         /* LIMIT value.  NULL means not used */
68943   Expr *pOffset         /* OFFSET value.  NULL means no offset */
68944 ){
68945   Select *pNew;
68946   Select standin;
68947   sqlite3 *db = pParse->db;
68948   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
68949   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
68950   if( pNew==0 ){
68951     pNew = &standin;
68952     memset(pNew, 0, sizeof(*pNew));
68953   }
68954   if( pEList==0 ){
68955     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
68956   }
68957   pNew->pEList = pEList;
68958   pNew->pSrc = pSrc;
68959   pNew->pWhere = pWhere;
68960   pNew->pGroupBy = pGroupBy;
68961   pNew->pHaving = pHaving;
68962   pNew->pOrderBy = pOrderBy;
68963   pNew->selFlags = isDistinct ? SF_Distinct : 0;
68964   pNew->op = TK_SELECT;
68965   pNew->pLimit = pLimit;
68966   pNew->pOffset = pOffset;
68967   pNew->addrOpenEphm[0] = -1;
68968   pNew->addrOpenEphm[1] = -1;
68969   pNew->addrOpenEphm[2] = -1;
68970   if( db->mallocFailed ) {
68971     clearSelect(db, pNew);
68972     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
68973     pNew = 0;
68974   }
68975   return pNew;
68976 }
68977
68978 /*
68979 ** Delete the given Select structure and all of its substructures.
68980 */
68981 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
68982   if( p ){
68983     clearSelect(db, p);
68984     sqlite3DbFree(db, p);
68985   }
68986 }
68987
68988 /*
68989 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
68990 ** type of join.  Return an integer constant that expresses that type
68991 ** in terms of the following bit values:
68992 **
68993 **     JT_INNER
68994 **     JT_CROSS
68995 **     JT_OUTER
68996 **     JT_NATURAL
68997 **     JT_LEFT
68998 **     JT_RIGHT
68999 **
69000 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
69001 **
69002 ** If an illegal or unsupported join type is seen, then still return
69003 ** a join type, but put an error in the pParse structure.
69004 */
69005 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
69006   int jointype = 0;
69007   Token *apAll[3];
69008   Token *p;
69009   static const struct {
69010     const char zKeyword[8];
69011     u8 nChar;
69012     u8 code;
69013   } keywords[] = {
69014     { "natural", 7, JT_NATURAL },
69015     { "left",    4, JT_LEFT|JT_OUTER },
69016     { "right",   5, JT_RIGHT|JT_OUTER },
69017     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
69018     { "outer",   5, JT_OUTER },
69019     { "inner",   5, JT_INNER },
69020     { "cross",   5, JT_INNER|JT_CROSS },
69021   };
69022   int i, j;
69023   apAll[0] = pA;
69024   apAll[1] = pB;
69025   apAll[2] = pC;
69026   for(i=0; i<3 && apAll[i]; i++){
69027     p = apAll[i];
69028     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
69029       if( p->n==keywords[j].nChar 
69030           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
69031         jointype |= keywords[j].code;
69032         break;
69033       }
69034     }
69035     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
69036       jointype |= JT_ERROR;
69037       break;
69038     }
69039   }
69040   if(
69041      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
69042      (jointype & JT_ERROR)!=0
69043   ){
69044     const char *zSp = " ";
69045     assert( pB!=0 );
69046     if( pC==0 ){ zSp++; }
69047     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
69048        "%T %T%s%T", pA, pB, zSp, pC);
69049     jointype = JT_INNER;
69050   }else if( jointype & JT_RIGHT ){
69051     sqlite3ErrorMsg(pParse, 
69052       "RIGHT and FULL OUTER JOINs are not currently supported");
69053     jointype = JT_INNER;
69054   }
69055   return jointype;
69056 }
69057
69058 /*
69059 ** Return the index of a column in a table.  Return -1 if the column
69060 ** is not contained in the table.
69061 */
69062 static int columnIndex(Table *pTab, const char *zCol){
69063   int i;
69064   for(i=0; i<pTab->nCol; i++){
69065     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
69066   }
69067   return -1;
69068 }
69069
69070 /*
69071 ** Set the value of a token to a '\000'-terminated string.
69072 */
69073 static void setToken(Token *p, const char *z){
69074   p->z = (u8*)z;
69075   p->n = z ? strlen(z) : 0;
69076   p->dyn = 0;
69077 }
69078
69079 /*
69080 ** Set the token to the double-quoted and escaped version of the string pointed
69081 ** to by z. For example;
69082 **
69083 **    {a"bc}  ->  {"a""bc"}
69084 */
69085 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
69086
69087   /* Check if the string appears to be quoted using "..." or `...`
69088   ** or [...] or '...' or if the string contains any " characters.  
69089   ** If it does, then record a version of the string with the special
69090   ** characters escaped.
69091   */
69092   const char *z2 = z;
69093   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
69094     while( *z2 ){
69095       if( *z2=='"' ) break;
69096       z2++;
69097     }
69098   }
69099
69100   if( *z2 ){
69101     /* String contains " characters - copy and quote the string. */
69102     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
69103     if( p->z ){
69104       p->n = strlen((char *)p->z);
69105       p->dyn = 1;
69106     }
69107   }else{
69108     /* String contains no " characters - copy the pointer. */
69109     p->z = (u8*)z;
69110     p->n = (z2 - z);
69111     p->dyn = 0;
69112   }
69113 }
69114
69115 /*
69116 ** Create an expression node for an identifier with the name of zName
69117 */
69118 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
69119   Token dummy;
69120   setToken(&dummy, zName);
69121   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
69122 }
69123
69124 /*
69125 ** Add a term to the WHERE expression in *ppExpr that requires the
69126 ** zCol column to be equal in the two tables pTab1 and pTab2.
69127 */
69128 static void addWhereTerm(
69129   Parse *pParse,           /* Parsing context */
69130   const char *zCol,        /* Name of the column */
69131   const Table *pTab1,      /* First table */
69132   const char *zAlias1,     /* Alias for first table.  May be NULL */
69133   const Table *pTab2,      /* Second table */
69134   const char *zAlias2,     /* Alias for second table.  May be NULL */
69135   int iRightJoinTable,     /* VDBE cursor for the right table */
69136   Expr **ppExpr,           /* Add the equality term to this expression */
69137   int isOuterJoin          /* True if dealing with an OUTER join */
69138 ){
69139   Expr *pE1a, *pE1b, *pE1c;
69140   Expr *pE2a, *pE2b, *pE2c;
69141   Expr *pE;
69142
69143   pE1a = sqlite3CreateIdExpr(pParse, zCol);
69144   pE2a = sqlite3CreateIdExpr(pParse, zCol);
69145   if( zAlias1==0 ){
69146     zAlias1 = pTab1->zName;
69147   }
69148   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
69149   if( zAlias2==0 ){
69150     zAlias2 = pTab2->zName;
69151   }
69152   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
69153   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
69154   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
69155   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
69156   if( pE && isOuterJoin ){
69157     ExprSetProperty(pE, EP_FromJoin);
69158     pE->iRightJoinTable = iRightJoinTable;
69159   }
69160   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
69161 }
69162
69163 /*
69164 ** Set the EP_FromJoin property on all terms of the given expression.
69165 ** And set the Expr.iRightJoinTable to iTable for every term in the
69166 ** expression.
69167 **
69168 ** The EP_FromJoin property is used on terms of an expression to tell
69169 ** the LEFT OUTER JOIN processing logic that this term is part of the
69170 ** join restriction specified in the ON or USING clause and not a part
69171 ** of the more general WHERE clause.  These terms are moved over to the
69172 ** WHERE clause during join processing but we need to remember that they
69173 ** originated in the ON or USING clause.
69174 **
69175 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
69176 ** expression depends on table iRightJoinTable even if that table is not
69177 ** explicitly mentioned in the expression.  That information is needed
69178 ** for cases like this:
69179 **
69180 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
69181 **
69182 ** The where clause needs to defer the handling of the t1.x=5
69183 ** term until after the t2 loop of the join.  In that way, a
69184 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
69185 ** defer the handling of t1.x=5, it will be processed immediately
69186 ** after the t1 loop and rows with t1.x!=5 will never appear in
69187 ** the output, which is incorrect.
69188 */
69189 static void setJoinExpr(Expr *p, int iTable){
69190   while( p ){
69191     ExprSetProperty(p, EP_FromJoin);
69192     p->iRightJoinTable = iTable;
69193     setJoinExpr(p->pLeft, iTable);
69194     p = p->pRight;
69195   } 
69196 }
69197
69198 /*
69199 ** This routine processes the join information for a SELECT statement.
69200 ** ON and USING clauses are converted into extra terms of the WHERE clause.
69201 ** NATURAL joins also create extra WHERE clause terms.
69202 **
69203 ** The terms of a FROM clause are contained in the Select.pSrc structure.
69204 ** The left most table is the first entry in Select.pSrc.  The right-most
69205 ** table is the last entry.  The join operator is held in the entry to
69206 ** the left.  Thus entry 0 contains the join operator for the join between
69207 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
69208 ** also attached to the left entry.
69209 **
69210 ** This routine returns the number of errors encountered.
69211 */
69212 static int sqliteProcessJoin(Parse *pParse, Select *p){
69213   SrcList *pSrc;                  /* All tables in the FROM clause */
69214   int i, j;                       /* Loop counters */
69215   struct SrcList_item *pLeft;     /* Left table being joined */
69216   struct SrcList_item *pRight;    /* Right table being joined */
69217
69218   pSrc = p->pSrc;
69219   pLeft = &pSrc->a[0];
69220   pRight = &pLeft[1];
69221   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
69222     Table *pLeftTab = pLeft->pTab;
69223     Table *pRightTab = pRight->pTab;
69224     int isOuter;
69225
69226     if( pLeftTab==0 || pRightTab==0 ) continue;
69227     isOuter = (pRight->jointype & JT_OUTER)!=0;
69228
69229     /* When the NATURAL keyword is present, add WHERE clause terms for
69230     ** every column that the two tables have in common.
69231     */
69232     if( pRight->jointype & JT_NATURAL ){
69233       if( pRight->pOn || pRight->pUsing ){
69234         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
69235            "an ON or USING clause", 0);
69236         return 1;
69237       }
69238       for(j=0; j<pLeftTab->nCol; j++){
69239         char *zName = pLeftTab->aCol[j].zName;
69240         if( columnIndex(pRightTab, zName)>=0 ){
69241           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
69242                               pRightTab, pRight->zAlias,
69243                               pRight->iCursor, &p->pWhere, isOuter);
69244           
69245         }
69246       }
69247     }
69248
69249     /* Disallow both ON and USING clauses in the same join
69250     */
69251     if( pRight->pOn && pRight->pUsing ){
69252       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
69253         "clauses in the same join");
69254       return 1;
69255     }
69256
69257     /* Add the ON clause to the end of the WHERE clause, connected by
69258     ** an AND operator.
69259     */
69260     if( pRight->pOn ){
69261       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
69262       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
69263       pRight->pOn = 0;
69264     }
69265
69266     /* Create extra terms on the WHERE clause for each column named
69267     ** in the USING clause.  Example: If the two tables to be joined are 
69268     ** A and B and the USING clause names X, Y, and Z, then add this
69269     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
69270     ** Report an error if any column mentioned in the USING clause is
69271     ** not contained in both tables to be joined.
69272     */
69273     if( pRight->pUsing ){
69274       IdList *pList = pRight->pUsing;
69275       for(j=0; j<pList->nId; j++){
69276         char *zName = pList->a[j].zName;
69277         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
69278           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
69279             "not present in both tables", zName);
69280           return 1;
69281         }
69282         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
69283                             pRightTab, pRight->zAlias,
69284                             pRight->iCursor, &p->pWhere, isOuter);
69285       }
69286     }
69287   }
69288   return 0;
69289 }
69290
69291 /*
69292 ** Insert code into "v" that will push the record on the top of the
69293 ** stack into the sorter.
69294 */
69295 static void pushOntoSorter(
69296   Parse *pParse,         /* Parser context */
69297   ExprList *pOrderBy,    /* The ORDER BY clause */
69298   Select *pSelect,       /* The whole SELECT statement */
69299   int regData            /* Register holding data to be sorted */
69300 ){
69301   Vdbe *v = pParse->pVdbe;
69302   int nExpr = pOrderBy->nExpr;
69303   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
69304   int regRecord = sqlite3GetTempReg(pParse);
69305   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
69306   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
69307   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
69308   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
69309   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
69310   sqlite3ReleaseTempReg(pParse, regRecord);
69311   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
69312   if( pSelect->iLimit ){
69313     int addr1, addr2;
69314     int iLimit;
69315     if( pSelect->iOffset ){
69316       iLimit = pSelect->iOffset+1;
69317     }else{
69318       iLimit = pSelect->iLimit;
69319     }
69320     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
69321     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
69322     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
69323     sqlite3VdbeJumpHere(v, addr1);
69324     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
69325     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
69326     sqlite3VdbeJumpHere(v, addr2);
69327     pSelect->iLimit = 0;
69328   }
69329 }
69330
69331 /*
69332 ** Add code to implement the OFFSET
69333 */
69334 static void codeOffset(
69335   Vdbe *v,          /* Generate code into this VM */
69336   Select *p,        /* The SELECT statement being coded */
69337   int iContinue     /* Jump here to skip the current record */
69338 ){
69339   if( p->iOffset && iContinue!=0 ){
69340     int addr;
69341     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
69342     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
69343     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
69344     VdbeComment((v, "skip OFFSET records"));
69345     sqlite3VdbeJumpHere(v, addr);
69346   }
69347 }
69348
69349 /*
69350 ** Add code that will check to make sure the N registers starting at iMem
69351 ** form a distinct entry.  iTab is a sorting index that holds previously
69352 ** seen combinations of the N values.  A new entry is made in iTab
69353 ** if the current N values are new.
69354 **
69355 ** A jump to addrRepeat is made and the N+1 values are popped from the
69356 ** stack if the top N elements are not distinct.
69357 */
69358 static void codeDistinct(
69359   Parse *pParse,     /* Parsing and code generating context */
69360   int iTab,          /* A sorting index used to test for distinctness */
69361   int addrRepeat,    /* Jump to here if not distinct */
69362   int N,             /* Number of elements */
69363   int iMem           /* First element */
69364 ){
69365   Vdbe *v;
69366   int r1;
69367
69368   v = pParse->pVdbe;
69369   r1 = sqlite3GetTempReg(pParse);
69370   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
69371   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
69372   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
69373   sqlite3ReleaseTempReg(pParse, r1);
69374 }
69375
69376 /*
69377 ** Generate an error message when a SELECT is used within a subexpression
69378 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
69379 ** column.  We do this in a subroutine because the error occurs in multiple
69380 ** places.
69381 */
69382 static int checkForMultiColumnSelectError(
69383   Parse *pParse,       /* Parse context. */
69384   SelectDest *pDest,   /* Destination of SELECT results */
69385   int nExpr            /* Number of result columns returned by SELECT */
69386 ){
69387   int eDest = pDest->eDest;
69388   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
69389     sqlite3ErrorMsg(pParse, "only a single result allowed for "
69390        "a SELECT that is part of an expression");
69391     return 1;
69392   }else{
69393     return 0;
69394   }
69395 }
69396
69397 /*
69398 ** This routine generates the code for the inside of the inner loop
69399 ** of a SELECT.
69400 **
69401 ** If srcTab and nColumn are both zero, then the pEList expressions
69402 ** are evaluated in order to get the data for this row.  If nColumn>0
69403 ** then data is pulled from srcTab and pEList is used only to get the
69404 ** datatypes for each column.
69405 */
69406 static void selectInnerLoop(
69407   Parse *pParse,          /* The parser context */
69408   Select *p,              /* The complete select statement being coded */
69409   ExprList *pEList,       /* List of values being extracted */
69410   int srcTab,             /* Pull data from this table */
69411   int nColumn,            /* Number of columns in the source table */
69412   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
69413   int distinct,           /* If >=0, make sure results are distinct */
69414   SelectDest *pDest,      /* How to dispose of the results */
69415   int iContinue,          /* Jump here to continue with next row */
69416   int iBreak              /* Jump here to break out of the inner loop */
69417 ){
69418   Vdbe *v = pParse->pVdbe;
69419   int i;
69420   int hasDistinct;        /* True if the DISTINCT keyword is present */
69421   int regResult;              /* Start of memory holding result set */
69422   int eDest = pDest->eDest;   /* How to dispose of results */
69423   int iParm = pDest->iParm;   /* First argument to disposal method */
69424   int nResultCol;             /* Number of result columns */
69425
69426   if( v==0 ) return;
69427   assert( pEList!=0 );
69428   hasDistinct = distinct>=0;
69429   if( pOrderBy==0 && !hasDistinct ){
69430     codeOffset(v, p, iContinue);
69431   }
69432
69433   /* Pull the requested columns.
69434   */
69435   if( nColumn>0 ){
69436     nResultCol = nColumn;
69437   }else{
69438     nResultCol = pEList->nExpr;
69439   }
69440   if( pDest->iMem==0 ){
69441     pDest->iMem = pParse->nMem+1;
69442     pDest->nMem = nResultCol;
69443     pParse->nMem += nResultCol;
69444   }else if( pDest->nMem!=nResultCol ){
69445     /* This happens when two SELECTs of a compound SELECT have differing
69446     ** numbers of result columns.  The error message will be generated by
69447     ** a higher-level routine. */
69448     return;
69449   }
69450   regResult = pDest->iMem;
69451   if( nColumn>0 ){
69452     for(i=0; i<nColumn; i++){
69453       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
69454     }
69455   }else if( eDest!=SRT_Exists ){
69456     /* If the destination is an EXISTS(...) expression, the actual
69457     ** values returned by the SELECT are not required.
69458     */
69459     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
69460   }
69461   nColumn = nResultCol;
69462
69463   /* If the DISTINCT keyword was present on the SELECT statement
69464   ** and this row has been seen before, then do not make this row
69465   ** part of the result.
69466   */
69467   if( hasDistinct ){
69468     assert( pEList!=0 );
69469     assert( pEList->nExpr==nColumn );
69470     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
69471     if( pOrderBy==0 ){
69472       codeOffset(v, p, iContinue);
69473     }
69474   }
69475
69476   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
69477     return;
69478   }
69479
69480   switch( eDest ){
69481     /* In this mode, write each query result to the key of the temporary
69482     ** table iParm.
69483     */
69484 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69485     case SRT_Union: {
69486       int r1;
69487       r1 = sqlite3GetTempReg(pParse);
69488       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69489       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
69490       sqlite3ReleaseTempReg(pParse, r1);
69491       break;
69492     }
69493
69494     /* Construct a record from the query result, but instead of
69495     ** saving that record, use it as a key to delete elements from
69496     ** the temporary table iParm.
69497     */
69498     case SRT_Except: {
69499       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
69500       break;
69501     }
69502 #endif
69503
69504     /* Store the result as data using a unique key.
69505     */
69506     case SRT_Table:
69507     case SRT_EphemTab: {
69508       int r1 = sqlite3GetTempReg(pParse);
69509       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69510       if( pOrderBy ){
69511         pushOntoSorter(pParse, pOrderBy, p, r1);
69512       }else{
69513         int r2 = sqlite3GetTempReg(pParse);
69514         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
69515         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
69516         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69517         sqlite3ReleaseTempReg(pParse, r2);
69518       }
69519       sqlite3ReleaseTempReg(pParse, r1);
69520       break;
69521     }
69522
69523 #ifndef SQLITE_OMIT_SUBQUERY
69524     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
69525     ** then there should be a single item on the stack.  Write this
69526     ** item into the set table with bogus data.
69527     */
69528     case SRT_Set: {
69529       assert( nColumn==1 );
69530       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
69531       if( pOrderBy ){
69532         /* At first glance you would think we could optimize out the
69533         ** ORDER BY in this case since the order of entries in the set
69534         ** does not matter.  But there might be a LIMIT clause, in which
69535         ** case the order does matter */
69536         pushOntoSorter(pParse, pOrderBy, p, regResult);
69537       }else{
69538         int r1 = sqlite3GetTempReg(pParse);
69539         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
69540         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
69541         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
69542         sqlite3ReleaseTempReg(pParse, r1);
69543       }
69544       break;
69545     }
69546
69547     /* If any row exist in the result set, record that fact and abort.
69548     */
69549     case SRT_Exists: {
69550       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
69551       /* The LIMIT clause will terminate the loop for us */
69552       break;
69553     }
69554
69555     /* If this is a scalar select that is part of an expression, then
69556     ** store the results in the appropriate memory cell and break out
69557     ** of the scan loop.
69558     */
69559     case SRT_Mem: {
69560       assert( nColumn==1 );
69561       if( pOrderBy ){
69562         pushOntoSorter(pParse, pOrderBy, p, regResult);
69563       }else{
69564         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
69565         /* The LIMIT clause will jump out of the loop for us */
69566       }
69567       break;
69568     }
69569 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
69570
69571     /* Send the data to the callback function or to a subroutine.  In the
69572     ** case of a subroutine, the subroutine itself is responsible for
69573     ** popping the data from the stack.
69574     */
69575     case SRT_Coroutine:
69576     case SRT_Output: {
69577       if( pOrderBy ){
69578         int r1 = sqlite3GetTempReg(pParse);
69579         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
69580         pushOntoSorter(pParse, pOrderBy, p, r1);
69581         sqlite3ReleaseTempReg(pParse, r1);
69582       }else if( eDest==SRT_Coroutine ){
69583         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
69584       }else{
69585         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
69586         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
69587       }
69588       break;
69589     }
69590
69591 #if !defined(SQLITE_OMIT_TRIGGER)
69592     /* Discard the results.  This is used for SELECT statements inside
69593     ** the body of a TRIGGER.  The purpose of such selects is to call
69594     ** user-defined functions that have side effects.  We do not care
69595     ** about the actual results of the select.
69596     */
69597     default: {
69598       assert( eDest==SRT_Discard );
69599       break;
69600     }
69601 #endif
69602   }
69603
69604   /* Jump to the end of the loop if the LIMIT is reached.
69605   */
69606   if( p->iLimit ){
69607     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
69608                             ** pushOntoSorter() would have cleared p->iLimit */
69609     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
69610     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
69611   }
69612 }
69613
69614 /*
69615 ** Given an expression list, generate a KeyInfo structure that records
69616 ** the collating sequence for each expression in that expression list.
69617 **
69618 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
69619 ** KeyInfo structure is appropriate for initializing a virtual index to
69620 ** implement that clause.  If the ExprList is the result set of a SELECT
69621 ** then the KeyInfo structure is appropriate for initializing a virtual
69622 ** index to implement a DISTINCT test.
69623 **
69624 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
69625 ** function is responsible for seeing that this structure is eventually
69626 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
69627 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
69628 */
69629 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
69630   sqlite3 *db = pParse->db;
69631   int nExpr;
69632   KeyInfo *pInfo;
69633   struct ExprList_item *pItem;
69634   int i;
69635
69636   nExpr = pList->nExpr;
69637   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
69638   if( pInfo ){
69639     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
69640     pInfo->nField = nExpr;
69641     pInfo->enc = ENC(db);
69642     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
69643       CollSeq *pColl;
69644       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
69645       if( !pColl ){
69646         pColl = db->pDfltColl;
69647       }
69648       pInfo->aColl[i] = pColl;
69649       pInfo->aSortOrder[i] = pItem->sortOrder;
69650     }
69651   }
69652   return pInfo;
69653 }
69654
69655
69656 /*
69657 ** If the inner loop was generated using a non-null pOrderBy argument,
69658 ** then the results were placed in a sorter.  After the loop is terminated
69659 ** we need to run the sorter and output the results.  The following
69660 ** routine generates the code needed to do that.
69661 */
69662 static void generateSortTail(
69663   Parse *pParse,    /* Parsing context */
69664   Select *p,        /* The SELECT statement */
69665   Vdbe *v,          /* Generate code into this VDBE */
69666   int nColumn,      /* Number of columns of data */
69667   SelectDest *pDest /* Write the sorted results here */
69668 ){
69669   int brk = sqlite3VdbeMakeLabel(v);
69670   int cont = sqlite3VdbeMakeLabel(v);
69671   int addr;
69672   int iTab;
69673   int pseudoTab = 0;
69674   ExprList *pOrderBy = p->pOrderBy;
69675
69676   int eDest = pDest->eDest;
69677   int iParm = pDest->iParm;
69678
69679   int regRow;
69680   int regRowid;
69681
69682   iTab = pOrderBy->iECursor;
69683   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
69684     pseudoTab = pParse->nTab++;
69685     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
69686     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
69687   }
69688   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
69689   codeOffset(v, p, cont);
69690   regRow = sqlite3GetTempReg(pParse);
69691   regRowid = sqlite3GetTempReg(pParse);
69692   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
69693   switch( eDest ){
69694     case SRT_Table:
69695     case SRT_EphemTab: {
69696       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
69697       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
69698       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69699       break;
69700     }
69701 #ifndef SQLITE_OMIT_SUBQUERY
69702     case SRT_Set: {
69703       assert( nColumn==1 );
69704       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
69705       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
69706       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
69707       break;
69708     }
69709     case SRT_Mem: {
69710       assert( nColumn==1 );
69711       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
69712       /* The LIMIT clause will terminate the loop for us */
69713       break;
69714     }
69715 #endif
69716     case SRT_Output:
69717     case SRT_Coroutine: {
69718       int i;
69719       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
69720       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
69721       for(i=0; i<nColumn; i++){
69722         assert( regRow!=pDest->iMem+i );
69723         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
69724       }
69725       if( eDest==SRT_Output ){
69726         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
69727         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
69728       }else{
69729         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
69730       }
69731       break;
69732     }
69733     default: {
69734       /* Do nothing */
69735       break;
69736     }
69737   }
69738   sqlite3ReleaseTempReg(pParse, regRow);
69739   sqlite3ReleaseTempReg(pParse, regRowid);
69740
69741   /* LIMIT has been implemented by the pushOntoSorter() routine.
69742   */
69743   assert( p->iLimit==0 );
69744
69745   /* The bottom of the loop
69746   */
69747   sqlite3VdbeResolveLabel(v, cont);
69748   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
69749   sqlite3VdbeResolveLabel(v, brk);
69750   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
69751     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
69752   }
69753
69754 }
69755
69756 /*
69757 ** Return a pointer to a string containing the 'declaration type' of the
69758 ** expression pExpr. The string may be treated as static by the caller.
69759 **
69760 ** The declaration type is the exact datatype definition extracted from the
69761 ** original CREATE TABLE statement if the expression is a column. The
69762 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
69763 ** is considered a column can be complex in the presence of subqueries. The
69764 ** result-set expression in all of the following SELECT statements is 
69765 ** considered a column by this function.
69766 **
69767 **   SELECT col FROM tbl;
69768 **   SELECT (SELECT col FROM tbl;
69769 **   SELECT (SELECT col FROM tbl);
69770 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
69771 ** 
69772 ** The declaration type for any expression other than a column is NULL.
69773 */
69774 static const char *columnType(
69775   NameContext *pNC, 
69776   Expr *pExpr,
69777   const char **pzOriginDb,
69778   const char **pzOriginTab,
69779   const char **pzOriginCol
69780 ){
69781   char const *zType = 0;
69782   char const *zOriginDb = 0;
69783   char const *zOriginTab = 0;
69784   char const *zOriginCol = 0;
69785   int j;
69786   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
69787
69788   switch( pExpr->op ){
69789     case TK_AGG_COLUMN:
69790     case TK_COLUMN: {
69791       /* The expression is a column. Locate the table the column is being
69792       ** extracted from in NameContext.pSrcList. This table may be real
69793       ** database table or a subquery.
69794       */
69795       Table *pTab = 0;            /* Table structure column is extracted from */
69796       Select *pS = 0;             /* Select the column is extracted from */
69797       int iCol = pExpr->iColumn;  /* Index of column in pTab */
69798       while( pNC && !pTab ){
69799         SrcList *pTabList = pNC->pSrcList;
69800         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
69801         if( j<pTabList->nSrc ){
69802           pTab = pTabList->a[j].pTab;
69803           pS = pTabList->a[j].pSelect;
69804         }else{
69805           pNC = pNC->pNext;
69806         }
69807       }
69808
69809       if( pTab==0 ){
69810         /* FIX ME:
69811         ** This can occurs if you have something like "SELECT new.x;" inside
69812         ** a trigger.  In other words, if you reference the special "new"
69813         ** table in the result set of a select.  We do not have a good way
69814         ** to find the actual table type, so call it "TEXT".  This is really
69815         ** something of a bug, but I do not know how to fix it.
69816         **
69817         ** This code does not produce the correct answer - it just prevents
69818         ** a segfault.  See ticket #1229.
69819         */
69820         zType = "TEXT";
69821         break;
69822       }
69823
69824       assert( pTab );
69825       if( pS ){
69826         /* The "table" is actually a sub-select or a view in the FROM clause
69827         ** of the SELECT statement. Return the declaration type and origin
69828         ** data for the result-set column of the sub-select.
69829         */
69830         if( iCol>=0 && iCol<pS->pEList->nExpr ){
69831           /* If iCol is less than zero, then the expression requests the
69832           ** rowid of the sub-select or view. This expression is legal (see 
69833           ** test case misc2.2.2) - it always evaluates to NULL.
69834           */
69835           NameContext sNC;
69836           Expr *p = pS->pEList->a[iCol].pExpr;
69837           sNC.pSrcList = pS->pSrc;
69838           sNC.pNext = 0;
69839           sNC.pParse = pNC->pParse;
69840           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
69841         }
69842       }else if( pTab->pSchema ){
69843         /* A real table */
69844         assert( !pS );
69845         if( iCol<0 ) iCol = pTab->iPKey;
69846         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
69847         if( iCol<0 ){
69848           zType = "INTEGER";
69849           zOriginCol = "rowid";
69850         }else{
69851           zType = pTab->aCol[iCol].zType;
69852           zOriginCol = pTab->aCol[iCol].zName;
69853         }
69854         zOriginTab = pTab->zName;
69855         if( pNC->pParse ){
69856           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
69857           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
69858         }
69859       }
69860       break;
69861     }
69862 #ifndef SQLITE_OMIT_SUBQUERY
69863     case TK_SELECT: {
69864       /* The expression is a sub-select. Return the declaration type and
69865       ** origin info for the single column in the result set of the SELECT
69866       ** statement.
69867       */
69868       NameContext sNC;
69869       Select *pS = pExpr->pSelect;
69870       Expr *p = pS->pEList->a[0].pExpr;
69871       sNC.pSrcList = pS->pSrc;
69872       sNC.pNext = pNC;
69873       sNC.pParse = pNC->pParse;
69874       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
69875       break;
69876     }
69877 #endif
69878   }
69879   
69880   if( pzOriginDb ){
69881     assert( pzOriginTab && pzOriginCol );
69882     *pzOriginDb = zOriginDb;
69883     *pzOriginTab = zOriginTab;
69884     *pzOriginCol = zOriginCol;
69885   }
69886   return zType;
69887 }
69888
69889 /*
69890 ** Generate code that will tell the VDBE the declaration types of columns
69891 ** in the result set.
69892 */
69893 static void generateColumnTypes(
69894   Parse *pParse,      /* Parser context */
69895   SrcList *pTabList,  /* List of tables */
69896   ExprList *pEList    /* Expressions defining the result set */
69897 ){
69898 #ifndef SQLITE_OMIT_DECLTYPE
69899   Vdbe *v = pParse->pVdbe;
69900   int i;
69901   NameContext sNC;
69902   sNC.pSrcList = pTabList;
69903   sNC.pParse = pParse;
69904   for(i=0; i<pEList->nExpr; i++){
69905     Expr *p = pEList->a[i].pExpr;
69906     const char *zType;
69907 #ifdef SQLITE_ENABLE_COLUMN_METADATA
69908     const char *zOrigDb = 0;
69909     const char *zOrigTab = 0;
69910     const char *zOrigCol = 0;
69911     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
69912
69913     /* The vdbe must make its own copy of the column-type and other 
69914     ** column specific strings, in case the schema is reset before this
69915     ** virtual machine is deleted.
69916     */
69917     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
69918     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
69919     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
69920 #else
69921     zType = columnType(&sNC, p, 0, 0, 0);
69922 #endif
69923     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
69924   }
69925 #endif /* SQLITE_OMIT_DECLTYPE */
69926 }
69927
69928 /*
69929 ** Generate code that will tell the VDBE the names of columns
69930 ** in the result set.  This information is used to provide the
69931 ** azCol[] values in the callback.
69932 */
69933 static void generateColumnNames(
69934   Parse *pParse,      /* Parser context */
69935   SrcList *pTabList,  /* List of tables */
69936   ExprList *pEList    /* Expressions defining the result set */
69937 ){
69938   Vdbe *v = pParse->pVdbe;
69939   int i, j;
69940   sqlite3 *db = pParse->db;
69941   int fullNames, shortNames;
69942
69943 #ifndef SQLITE_OMIT_EXPLAIN
69944   /* If this is an EXPLAIN, skip this step */
69945   if( pParse->explain ){
69946     return;
69947   }
69948 #endif
69949
69950   assert( v!=0 );
69951   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
69952   pParse->colNamesSet = 1;
69953   fullNames = (db->flags & SQLITE_FullColNames)!=0;
69954   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
69955   sqlite3VdbeSetNumCols(v, pEList->nExpr);
69956   for(i=0; i<pEList->nExpr; i++){
69957     Expr *p;
69958     p = pEList->a[i].pExpr;
69959     if( p==0 ) continue;
69960     if( pEList->a[i].zName ){
69961       char *zName = pEList->a[i].zName;
69962       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
69963     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
69964       Table *pTab;
69965       char *zCol;
69966       int iCol = p->iColumn;
69967       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
69968       assert( j<pTabList->nSrc );
69969       pTab = pTabList->a[j].pTab;
69970       if( iCol<0 ) iCol = pTab->iPKey;
69971       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
69972       if( iCol<0 ){
69973         zCol = "rowid";
69974       }else{
69975         zCol = pTab->aCol[iCol].zName;
69976       }
69977       if( !shortNames && !fullNames ){
69978         sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
69979       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
69980         char *zName = 0;
69981         char *zTab;
69982  
69983         zTab = pTabList->a[j].zAlias;
69984         if( fullNames || zTab==0 ) zTab = pTab->zName;
69985         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
69986         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
69987       }else{
69988         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
69989       }
69990     }else{
69991       sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
69992     }
69993   }
69994   generateColumnTypes(pParse, pTabList, pEList);
69995 }
69996
69997 #ifndef SQLITE_OMIT_COMPOUND_SELECT
69998 /*
69999 ** Name of the connection operator, used for error messages.
70000 */
70001 static const char *selectOpName(int id){
70002   char *z;
70003   switch( id ){
70004     case TK_ALL:       z = "UNION ALL";   break;
70005     case TK_INTERSECT: z = "INTERSECT";   break;
70006     case TK_EXCEPT:    z = "EXCEPT";      break;
70007     default:           z = "UNION";       break;
70008   }
70009   return z;
70010 }
70011 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
70012
70013 /*
70014 ** Given a an expression list (which is really the list of expressions
70015 ** that form the result set of a SELECT statement) compute appropriate
70016 ** column names for a table that would hold the expression list.
70017 **
70018 ** All column names will be unique.
70019 **
70020 ** Only the column names are computed.  Column.zType, Column.zColl,
70021 ** and other fields of Column are zeroed.
70022 **
70023 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
70024 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
70025 */
70026 static int selectColumnsFromExprList(
70027   Parse *pParse,          /* Parsing context */
70028   ExprList *pEList,       /* Expr list from which to derive column names */
70029   int *pnCol,             /* Write the number of columns here */
70030   Column **paCol          /* Write the new column list here */
70031 ){
70032   sqlite3 *db = pParse->db;
70033   int i, j, cnt;
70034   Column *aCol, *pCol;
70035   int nCol;
70036   Expr *p;
70037   char *zName;
70038   int nName;
70039
70040   *pnCol = nCol = pEList->nExpr;
70041   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
70042   if( aCol==0 ) return SQLITE_NOMEM;
70043   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
70044     /* Get an appropriate name for the column
70045     */
70046     p = pEList->a[i].pExpr;
70047     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
70048     if( (zName = pEList->a[i].zName)!=0 ){
70049       /* If the column contains an "AS <name>" phrase, use <name> as the name */
70050       zName = sqlite3DbStrDup(db, zName);
70051     }else{
70052       Expr *pCol = p;
70053       Table *pTab;
70054       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
70055       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
70056         /* For columns use the column name name */
70057         int iCol = pCol->iColumn;
70058         if( iCol<0 ) iCol = pTab->iPKey;
70059         zName = sqlite3MPrintf(db, "%s",
70060                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
70061       }else{
70062         /* Use the original text of the column expression as its name */
70063         zName = sqlite3MPrintf(db, "%T", &pCol->span);
70064       }
70065     }
70066     if( db->mallocFailed ){
70067       sqlite3DbFree(db, zName);
70068       break;
70069     }
70070     sqlite3Dequote(zName);
70071
70072     /* Make sure the column name is unique.  If the name is not unique,
70073     ** append a integer to the name so that it becomes unique.
70074     */
70075     nName = strlen(zName);
70076     for(j=cnt=0; j<i; j++){
70077       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
70078         char *zNewName;
70079         zName[nName] = 0;
70080         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
70081         sqlite3DbFree(db, zName);
70082         zName = zNewName;
70083         j = -1;
70084         if( zName==0 ) break;
70085       }
70086     }
70087     pCol->zName = zName;
70088   }
70089   if( db->mallocFailed ){
70090     int j;
70091     for(j=0; j<i; j++){
70092       sqlite3DbFree(db, aCol[j].zName);
70093     }
70094     sqlite3DbFree(db, aCol);
70095     *paCol = 0;
70096     *pnCol = 0;
70097     return SQLITE_NOMEM;
70098   }
70099   return SQLITE_OK;
70100 }
70101
70102 /*
70103 ** Add type and collation information to a column list based on
70104 ** a SELECT statement.
70105 ** 
70106 ** The column list presumably came from selectColumnNamesFromExprList().
70107 ** The column list has only names, not types or collations.  This
70108 ** routine goes through and adds the types and collations.
70109 **
70110 ** This routine requires that all indentifiers in the SELECT
70111 ** statement be resolved.
70112 */
70113 static void selectAddColumnTypeAndCollation(
70114   Parse *pParse,        /* Parsing contexts */
70115   int nCol,             /* Number of columns */
70116   Column *aCol,         /* List of columns */
70117   Select *pSelect       /* SELECT used to determine types and collations */
70118 ){
70119   sqlite3 *db = pParse->db;
70120   NameContext sNC;
70121   Column *pCol;
70122   CollSeq *pColl;
70123   int i;
70124   Expr *p;
70125   struct ExprList_item *a;
70126
70127   assert( pSelect!=0 );
70128   assert( (pSelect->selFlags & SF_Resolved)!=0 );
70129   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
70130   if( db->mallocFailed ) return;
70131   memset(&sNC, 0, sizeof(sNC));
70132   sNC.pSrcList = pSelect->pSrc;
70133   a = pSelect->pEList->a;
70134   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
70135     p = a[i].pExpr;
70136     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
70137     pCol->affinity = sqlite3ExprAffinity(p);
70138     pColl = sqlite3ExprCollSeq(pParse, p);
70139     if( pColl ){
70140       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
70141     }
70142   }
70143 }
70144
70145 /*
70146 ** Given a SELECT statement, generate a Table structure that describes
70147 ** the result set of that SELECT.
70148 */
70149 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
70150   Table *pTab;
70151   sqlite3 *db = pParse->db;
70152   int savedFlags;
70153
70154   savedFlags = db->flags;
70155   db->flags &= ~SQLITE_FullColNames;
70156   db->flags |= SQLITE_ShortColNames;
70157   sqlite3SelectPrep(pParse, pSelect, 0);
70158   if( pParse->nErr ) return 0;
70159   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
70160   db->flags = savedFlags;
70161   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
70162   if( pTab==0 ){
70163     return 0;
70164   }
70165   pTab->db = db;
70166   pTab->nRef = 1;
70167   pTab->zName = 0;
70168   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
70169   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
70170   pTab->iPKey = -1;
70171   if( db->mallocFailed ){
70172     sqlite3DeleteTable(pTab);
70173     return 0;
70174   }
70175   return pTab;
70176 }
70177
70178 /*
70179 ** Get a VDBE for the given parser context.  Create a new one if necessary.
70180 ** If an error occurs, return NULL and leave a message in pParse.
70181 */
70182 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
70183   Vdbe *v = pParse->pVdbe;
70184   if( v==0 ){
70185     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
70186 #ifndef SQLITE_OMIT_TRACE
70187     if( v ){
70188       sqlite3VdbeAddOp0(v, OP_Trace);
70189     }
70190 #endif
70191   }
70192   return v;
70193 }
70194
70195
70196 /*
70197 ** Compute the iLimit and iOffset fields of the SELECT based on the
70198 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
70199 ** that appear in the original SQL statement after the LIMIT and OFFSET
70200 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
70201 ** are the integer memory register numbers for counters used to compute 
70202 ** the limit and offset.  If there is no limit and/or offset, then 
70203 ** iLimit and iOffset are negative.
70204 **
70205 ** This routine changes the values of iLimit and iOffset only if
70206 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
70207 ** iOffset should have been preset to appropriate default values
70208 ** (usually but not always -1) prior to calling this routine.
70209 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
70210 ** redefined.  The UNION ALL operator uses this property to force
70211 ** the reuse of the same limit and offset registers across multiple
70212 ** SELECT statements.
70213 */
70214 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
70215   Vdbe *v = 0;
70216   int iLimit = 0;
70217   int iOffset;
70218   int addr1;
70219   if( p->iLimit ) return;
70220
70221   /* 
70222   ** "LIMIT -1" always shows all rows.  There is some
70223   ** contraversy about what the correct behavior should be.
70224   ** The current implementation interprets "LIMIT 0" to mean
70225   ** no rows.
70226   */
70227   if( p->pLimit ){
70228     p->iLimit = iLimit = ++pParse->nMem;
70229     v = sqlite3GetVdbe(pParse);
70230     if( v==0 ) return;
70231     sqlite3ExprCode(pParse, p->pLimit, iLimit);
70232     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
70233     VdbeComment((v, "LIMIT counter"));
70234     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
70235   }
70236   if( p->pOffset ){
70237     p->iOffset = iOffset = ++pParse->nMem;
70238     if( p->pLimit ){
70239       pParse->nMem++;   /* Allocate an extra register for limit+offset */
70240     }
70241     v = sqlite3GetVdbe(pParse);
70242     if( v==0 ) return;
70243     sqlite3ExprCode(pParse, p->pOffset, iOffset);
70244     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
70245     VdbeComment((v, "OFFSET counter"));
70246     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
70247     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
70248     sqlite3VdbeJumpHere(v, addr1);
70249     if( p->pLimit ){
70250       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
70251       VdbeComment((v, "LIMIT+OFFSET"));
70252       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
70253       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
70254       sqlite3VdbeJumpHere(v, addr1);
70255     }
70256   }
70257 }
70258
70259 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70260 /*
70261 ** Return the appropriate collating sequence for the iCol-th column of
70262 ** the result set for the compound-select statement "p".  Return NULL if
70263 ** the column has no default collating sequence.
70264 **
70265 ** The collating sequence for the compound select is taken from the
70266 ** left-most term of the select that has a collating sequence.
70267 */
70268 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
70269   CollSeq *pRet;
70270   if( p->pPrior ){
70271     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
70272   }else{
70273     pRet = 0;
70274   }
70275   if( pRet==0 ){
70276     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
70277   }
70278   return pRet;
70279 }
70280 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
70281
70282 /* Forward reference */
70283 static int multiSelectOrderBy(
70284   Parse *pParse,        /* Parsing context */
70285   Select *p,            /* The right-most of SELECTs to be coded */
70286   SelectDest *pDest     /* What to do with query results */
70287 );
70288
70289
70290 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70291 /*
70292 ** This routine is called to process a compound query form from
70293 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
70294 ** INTERSECT
70295 **
70296 ** "p" points to the right-most of the two queries.  the query on the
70297 ** left is p->pPrior.  The left query could also be a compound query
70298 ** in which case this routine will be called recursively. 
70299 **
70300 ** The results of the total query are to be written into a destination
70301 ** of type eDest with parameter iParm.
70302 **
70303 ** Example 1:  Consider a three-way compound SQL statement.
70304 **
70305 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
70306 **
70307 ** This statement is parsed up as follows:
70308 **
70309 **     SELECT c FROM t3
70310 **      |
70311 **      `----->  SELECT b FROM t2
70312 **                |
70313 **                `------>  SELECT a FROM t1
70314 **
70315 ** The arrows in the diagram above represent the Select.pPrior pointer.
70316 ** So if this routine is called with p equal to the t3 query, then
70317 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
70318 **
70319 ** Notice that because of the way SQLite parses compound SELECTs, the
70320 ** individual selects always group from left to right.
70321 */
70322 static int multiSelect(
70323   Parse *pParse,        /* Parsing context */
70324   Select *p,            /* The right-most of SELECTs to be coded */
70325   SelectDest *pDest     /* What to do with query results */
70326 ){
70327   int rc = SQLITE_OK;   /* Success code from a subroutine */
70328   Select *pPrior;       /* Another SELECT immediately to our left */
70329   Vdbe *v;              /* Generate code to this VDBE */
70330   SelectDest dest;      /* Alternative data destination */
70331   Select *pDelete = 0;  /* Chain of simple selects to delete */
70332   sqlite3 *db;          /* Database connection */
70333
70334   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
70335   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
70336   */
70337   assert( p && p->pPrior );  /* Calling function guarantees this much */
70338   db = pParse->db;
70339   pPrior = p->pPrior;
70340   assert( pPrior->pRightmost!=pPrior );
70341   assert( pPrior->pRightmost==p->pRightmost );
70342   dest = *pDest;
70343   if( pPrior->pOrderBy ){
70344     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
70345       selectOpName(p->op));
70346     rc = 1;
70347     goto multi_select_end;
70348   }
70349   if( pPrior->pLimit ){
70350     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
70351       selectOpName(p->op));
70352     rc = 1;
70353     goto multi_select_end;
70354   }
70355
70356   v = sqlite3GetVdbe(pParse);
70357   assert( v!=0 );  /* The VDBE already created by calling function */
70358
70359   /* Create the destination temporary table if necessary
70360   */
70361   if( dest.eDest==SRT_EphemTab ){
70362     assert( p->pEList );
70363     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
70364     dest.eDest = SRT_Table;
70365   }
70366
70367   /* Make sure all SELECTs in the statement have the same number of elements
70368   ** in their result sets.
70369   */
70370   assert( p->pEList && pPrior->pEList );
70371   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
70372     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
70373       " do not have the same number of result columns", selectOpName(p->op));
70374     rc = 1;
70375     goto multi_select_end;
70376   }
70377
70378   /* Compound SELECTs that have an ORDER BY clause are handled separately.
70379   */
70380   if( p->pOrderBy ){
70381     return multiSelectOrderBy(pParse, p, pDest);
70382   }
70383
70384   /* Generate code for the left and right SELECT statements.
70385   */
70386   switch( p->op ){
70387     case TK_ALL: {
70388       int addr = 0;
70389       assert( !pPrior->pLimit );
70390       pPrior->pLimit = p->pLimit;
70391       pPrior->pOffset = p->pOffset;
70392       rc = sqlite3Select(pParse, pPrior, &dest);
70393       p->pLimit = 0;
70394       p->pOffset = 0;
70395       if( rc ){
70396         goto multi_select_end;
70397       }
70398       p->pPrior = 0;
70399       p->iLimit = pPrior->iLimit;
70400       p->iOffset = pPrior->iOffset;
70401       if( p->iLimit ){
70402         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
70403         VdbeComment((v, "Jump ahead if LIMIT reached"));
70404       }
70405       rc = sqlite3Select(pParse, p, &dest);
70406       pDelete = p->pPrior;
70407       p->pPrior = pPrior;
70408       if( rc ){
70409         goto multi_select_end;
70410       }
70411       if( addr ){
70412         sqlite3VdbeJumpHere(v, addr);
70413       }
70414       break;
70415     }
70416     case TK_EXCEPT:
70417     case TK_UNION: {
70418       int unionTab;    /* Cursor number of the temporary table holding result */
70419       int op = 0;      /* One of the SRT_ operations to apply to self */
70420       int priorOp;     /* The SRT_ operation to apply to prior selects */
70421       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
70422       int addr;
70423       SelectDest uniondest;
70424
70425       priorOp = SRT_Union;
70426       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
70427         /* We can reuse a temporary table generated by a SELECT to our
70428         ** right.
70429         */
70430         unionTab = dest.iParm;
70431       }else{
70432         /* We will need to create our own temporary table to hold the
70433         ** intermediate results.
70434         */
70435         unionTab = pParse->nTab++;
70436         assert( p->pOrderBy==0 );
70437         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
70438         assert( p->addrOpenEphm[0] == -1 );
70439         p->addrOpenEphm[0] = addr;
70440         p->pRightmost->selFlags |= SF_UsesEphemeral;
70441         assert( p->pEList );
70442       }
70443
70444       /* Code the SELECT statements to our left
70445       */
70446       assert( !pPrior->pOrderBy );
70447       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
70448       rc = sqlite3Select(pParse, pPrior, &uniondest);
70449       if( rc ){
70450         goto multi_select_end;
70451       }
70452
70453       /* Code the current SELECT statement
70454       */
70455       if( p->op==TK_EXCEPT ){
70456         op = SRT_Except;
70457       }else{
70458         assert( p->op==TK_UNION );
70459         op = SRT_Union;
70460       }
70461       p->pPrior = 0;
70462       pLimit = p->pLimit;
70463       p->pLimit = 0;
70464       pOffset = p->pOffset;
70465       p->pOffset = 0;
70466       uniondest.eDest = op;
70467       rc = sqlite3Select(pParse, p, &uniondest);
70468       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
70469       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
70470       sqlite3ExprListDelete(db, p->pOrderBy);
70471       pDelete = p->pPrior;
70472       p->pPrior = pPrior;
70473       p->pOrderBy = 0;
70474       sqlite3ExprDelete(db, p->pLimit);
70475       p->pLimit = pLimit;
70476       p->pOffset = pOffset;
70477       p->iLimit = 0;
70478       p->iOffset = 0;
70479       if( rc ){
70480         goto multi_select_end;
70481       }
70482
70483
70484       /* Convert the data in the temporary table into whatever form
70485       ** it is that we currently need.
70486       */      
70487       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
70488         int iCont, iBreak, iStart;
70489         assert( p->pEList );
70490         if( dest.eDest==SRT_Output ){
70491           Select *pFirst = p;
70492           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
70493           generateColumnNames(pParse, 0, pFirst->pEList);
70494         }
70495         iBreak = sqlite3VdbeMakeLabel(v);
70496         iCont = sqlite3VdbeMakeLabel(v);
70497         computeLimitRegisters(pParse, p, iBreak);
70498         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
70499         iStart = sqlite3VdbeCurrentAddr(v);
70500         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
70501                         0, -1, &dest, iCont, iBreak);
70502         sqlite3VdbeResolveLabel(v, iCont);
70503         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
70504         sqlite3VdbeResolveLabel(v, iBreak);
70505         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
70506       }
70507       break;
70508     }
70509     case TK_INTERSECT: {
70510       int tab1, tab2;
70511       int iCont, iBreak, iStart;
70512       Expr *pLimit, *pOffset;
70513       int addr;
70514       SelectDest intersectdest;
70515       int r1;
70516
70517       /* INTERSECT is different from the others since it requires
70518       ** two temporary tables.  Hence it has its own case.  Begin
70519       ** by allocating the tables we will need.
70520       */
70521       tab1 = pParse->nTab++;
70522       tab2 = pParse->nTab++;
70523       assert( p->pOrderBy==0 );
70524
70525       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
70526       assert( p->addrOpenEphm[0] == -1 );
70527       p->addrOpenEphm[0] = addr;
70528       p->pRightmost->selFlags |= SF_UsesEphemeral;
70529       assert( p->pEList );
70530
70531       /* Code the SELECTs to our left into temporary table "tab1".
70532       */
70533       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
70534       rc = sqlite3Select(pParse, pPrior, &intersectdest);
70535       if( rc ){
70536         goto multi_select_end;
70537       }
70538
70539       /* Code the current SELECT into temporary table "tab2"
70540       */
70541       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
70542       assert( p->addrOpenEphm[1] == -1 );
70543       p->addrOpenEphm[1] = addr;
70544       p->pPrior = 0;
70545       pLimit = p->pLimit;
70546       p->pLimit = 0;
70547       pOffset = p->pOffset;
70548       p->pOffset = 0;
70549       intersectdest.iParm = tab2;
70550       rc = sqlite3Select(pParse, p, &intersectdest);
70551       pDelete = p->pPrior;
70552       p->pPrior = pPrior;
70553       sqlite3ExprDelete(db, p->pLimit);
70554       p->pLimit = pLimit;
70555       p->pOffset = pOffset;
70556       if( rc ){
70557         goto multi_select_end;
70558       }
70559
70560       /* Generate code to take the intersection of the two temporary
70561       ** tables.
70562       */
70563       assert( p->pEList );
70564       if( dest.eDest==SRT_Output ){
70565         Select *pFirst = p;
70566         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
70567         generateColumnNames(pParse, 0, pFirst->pEList);
70568       }
70569       iBreak = sqlite3VdbeMakeLabel(v);
70570       iCont = sqlite3VdbeMakeLabel(v);
70571       computeLimitRegisters(pParse, p, iBreak);
70572       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
70573       r1 = sqlite3GetTempReg(pParse);
70574       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
70575       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
70576       sqlite3ReleaseTempReg(pParse, r1);
70577       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
70578                       0, -1, &dest, iCont, iBreak);
70579       sqlite3VdbeResolveLabel(v, iCont);
70580       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
70581       sqlite3VdbeResolveLabel(v, iBreak);
70582       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
70583       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
70584       break;
70585     }
70586   }
70587
70588   /* Compute collating sequences used by 
70589   ** temporary tables needed to implement the compound select.
70590   ** Attach the KeyInfo structure to all temporary tables.
70591   **
70592   ** This section is run by the right-most SELECT statement only.
70593   ** SELECT statements to the left always skip this part.  The right-most
70594   ** SELECT might also skip this part if it has no ORDER BY clause and
70595   ** no temp tables are required.
70596   */
70597   if( p->selFlags & SF_UsesEphemeral ){
70598     int i;                        /* Loop counter */
70599     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
70600     Select *pLoop;                /* For looping through SELECT statements */
70601     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
70602     int nCol;                     /* Number of columns in result set */
70603
70604     assert( p->pRightmost==p );
70605     nCol = p->pEList->nExpr;
70606     pKeyInfo = sqlite3DbMallocZero(db,
70607                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
70608     if( !pKeyInfo ){
70609       rc = SQLITE_NOMEM;
70610       goto multi_select_end;
70611     }
70612
70613     pKeyInfo->enc = ENC(db);
70614     pKeyInfo->nField = nCol;
70615
70616     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
70617       *apColl = multiSelectCollSeq(pParse, p, i);
70618       if( 0==*apColl ){
70619         *apColl = db->pDfltColl;
70620       }
70621     }
70622
70623     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
70624       for(i=0; i<2; i++){
70625         int addr = pLoop->addrOpenEphm[i];
70626         if( addr<0 ){
70627           /* If [0] is unused then [1] is also unused.  So we can
70628           ** always safely abort as soon as the first unused slot is found */
70629           assert( pLoop->addrOpenEphm[1]<0 );
70630           break;
70631         }
70632         sqlite3VdbeChangeP2(v, addr, nCol);
70633         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
70634         pLoop->addrOpenEphm[i] = -1;
70635       }
70636     }
70637     sqlite3DbFree(db, pKeyInfo);
70638   }
70639
70640 multi_select_end:
70641   pDest->iMem = dest.iMem;
70642   pDest->nMem = dest.nMem;
70643   sqlite3SelectDelete(db, pDelete);
70644   return rc;
70645 }
70646 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
70647
70648 /*
70649 ** Code an output subroutine for a coroutine implementation of a
70650 ** SELECT statment.
70651 **
70652 ** The data to be output is contained in pIn->iMem.  There are
70653 ** pIn->nMem columns to be output.  pDest is where the output should
70654 ** be sent.
70655 **
70656 ** regReturn is the number of the register holding the subroutine
70657 ** return address.
70658 **
70659 ** If regPrev>0 then it is a the first register in a vector that
70660 ** records the previous output.  mem[regPrev] is a flag that is false
70661 ** if there has been no previous output.  If regPrev>0 then code is
70662 ** generated to suppress duplicates.  pKeyInfo is used for comparing
70663 ** keys.
70664 **
70665 ** If the LIMIT found in p->iLimit is reached, jump immediately to
70666 ** iBreak.
70667 */
70668 static int generateOutputSubroutine(
70669   Parse *pParse,          /* Parsing context */
70670   Select *p,              /* The SELECT statement */
70671   SelectDest *pIn,        /* Coroutine supplying data */
70672   SelectDest *pDest,      /* Where to send the data */
70673   int regReturn,          /* The return address register */
70674   int regPrev,            /* Previous result register.  No uniqueness if 0 */
70675   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
70676   int p4type,             /* The p4 type for pKeyInfo */
70677   int iBreak              /* Jump here if we hit the LIMIT */
70678 ){
70679   Vdbe *v = pParse->pVdbe;
70680   int iContinue;
70681   int addr;
70682
70683   addr = sqlite3VdbeCurrentAddr(v);
70684   iContinue = sqlite3VdbeMakeLabel(v);
70685
70686   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
70687   */
70688   if( regPrev ){
70689     int j1, j2;
70690     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
70691     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
70692                               (char*)pKeyInfo, p4type);
70693     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
70694     sqlite3VdbeJumpHere(v, j1);
70695     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
70696     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
70697   }
70698   if( pParse->db->mallocFailed ) return 0;
70699
70700   /* Suppress the the first OFFSET entries if there is an OFFSET clause
70701   */
70702   codeOffset(v, p, iContinue);
70703
70704   switch( pDest->eDest ){
70705     /* Store the result as data using a unique key.
70706     */
70707     case SRT_Table:
70708     case SRT_EphemTab: {
70709       int r1 = sqlite3GetTempReg(pParse);
70710       int r2 = sqlite3GetTempReg(pParse);
70711       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
70712       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
70713       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
70714       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
70715       sqlite3ReleaseTempReg(pParse, r2);
70716       sqlite3ReleaseTempReg(pParse, r1);
70717       break;
70718     }
70719
70720 #ifndef SQLITE_OMIT_SUBQUERY
70721     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
70722     ** then there should be a single item on the stack.  Write this
70723     ** item into the set table with bogus data.
70724     */
70725     case SRT_Set: {
70726       int r1;
70727       assert( pIn->nMem==1 );
70728       p->affinity = 
70729          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
70730       r1 = sqlite3GetTempReg(pParse);
70731       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
70732       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
70733       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
70734       sqlite3ReleaseTempReg(pParse, r1);
70735       break;
70736     }
70737
70738 #if 0  /* Never occurs on an ORDER BY query */
70739     /* If any row exist in the result set, record that fact and abort.
70740     */
70741     case SRT_Exists: {
70742       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
70743       /* The LIMIT clause will terminate the loop for us */
70744       break;
70745     }
70746 #endif
70747
70748     /* If this is a scalar select that is part of an expression, then
70749     ** store the results in the appropriate memory cell and break out
70750     ** of the scan loop.
70751     */
70752     case SRT_Mem: {
70753       assert( pIn->nMem==1 );
70754       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
70755       /* The LIMIT clause will jump out of the loop for us */
70756       break;
70757     }
70758 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
70759
70760     /* The results are stored in a sequence of registers
70761     ** starting at pDest->iMem.  Then the co-routine yields.
70762     */
70763     case SRT_Coroutine: {
70764       if( pDest->iMem==0 ){
70765         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
70766         pDest->nMem = pIn->nMem;
70767       }
70768       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
70769       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
70770       break;
70771     }
70772
70773     /* Results are stored in a sequence of registers.  Then the
70774     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
70775     ** the next row of result.
70776     */
70777     case SRT_Output: {
70778       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
70779       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
70780       break;
70781     }
70782
70783 #if !defined(SQLITE_OMIT_TRIGGER)
70784     /* Discard the results.  This is used for SELECT statements inside
70785     ** the body of a TRIGGER.  The purpose of such selects is to call
70786     ** user-defined functions that have side effects.  We do not care
70787     ** about the actual results of the select.
70788     */
70789     default: {
70790       break;
70791     }
70792 #endif
70793   }
70794
70795   /* Jump to the end of the loop if the LIMIT is reached.
70796   */
70797   if( p->iLimit ){
70798     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
70799     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
70800   }
70801
70802   /* Generate the subroutine return
70803   */
70804   sqlite3VdbeResolveLabel(v, iContinue);
70805   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
70806
70807   return addr;
70808 }
70809
70810 /*
70811 ** Alternative compound select code generator for cases when there
70812 ** is an ORDER BY clause.
70813 **
70814 ** We assume a query of the following form:
70815 **
70816 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
70817 **
70818 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
70819 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
70820 ** co-routines.  Then run the co-routines in parallel and merge the results
70821 ** into the output.  In addition to the two coroutines (called selectA and
70822 ** selectB) there are 7 subroutines:
70823 **
70824 **    outA:    Move the output of the selectA coroutine into the output
70825 **             of the compound query.
70826 **
70827 **    outB:    Move the output of the selectB coroutine into the output
70828 **             of the compound query.  (Only generated for UNION and
70829 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
70830 **             appears only in B.)
70831 **
70832 **    AltB:    Called when there is data from both coroutines and A<B.
70833 **
70834 **    AeqB:    Called when there is data from both coroutines and A==B.
70835 **
70836 **    AgtB:    Called when there is data from both coroutines and A>B.
70837 **
70838 **    EofA:    Called when data is exhausted from selectA.
70839 **
70840 **    EofB:    Called when data is exhausted from selectB.
70841 **
70842 ** The implementation of the latter five subroutines depend on which 
70843 ** <operator> is used:
70844 **
70845 **
70846 **             UNION ALL         UNION            EXCEPT          INTERSECT
70847 **          -------------  -----------------  --------------  -----------------
70848 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
70849 **
70850 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
70851 **
70852 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
70853 **
70854 **   EofA:   outB, nextB      outB, nextB          halt             halt
70855 **
70856 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
70857 **
70858 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
70859 ** causes an immediate jump to EofA and an EOF on B following nextB causes
70860 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
70861 ** following nextX causes a jump to the end of the select processing.
70862 **
70863 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
70864 ** within the output subroutine.  The regPrev register set holds the previously
70865 ** output value.  A comparison is made against this value and the output
70866 ** is skipped if the next results would be the same as the previous.
70867 **
70868 ** The implementation plan is to implement the two coroutines and seven
70869 ** subroutines first, then put the control logic at the bottom.  Like this:
70870 **
70871 **          goto Init
70872 **     coA: coroutine for left query (A)
70873 **     coB: coroutine for right query (B)
70874 **    outA: output one row of A
70875 **    outB: output one row of B (UNION and UNION ALL only)
70876 **    EofA: ...
70877 **    EofB: ...
70878 **    AltB: ...
70879 **    AeqB: ...
70880 **    AgtB: ...
70881 **    Init: initialize coroutine registers
70882 **          yield coA
70883 **          if eof(A) goto EofA
70884 **          yield coB
70885 **          if eof(B) goto EofB
70886 **    Cmpr: Compare A, B
70887 **          Jump AltB, AeqB, AgtB
70888 **     End: ...
70889 **
70890 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
70891 ** actually called using Gosub and they do not Return.  EofA and EofB loop
70892 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
70893 ** and AgtB jump to either L2 or to one of EofA or EofB.
70894 */
70895 #ifndef SQLITE_OMIT_COMPOUND_SELECT
70896 static int multiSelectOrderBy(
70897   Parse *pParse,        /* Parsing context */
70898   Select *p,            /* The right-most of SELECTs to be coded */
70899   SelectDest *pDest     /* What to do with query results */
70900 ){
70901   int i, j;             /* Loop counters */
70902   Select *pPrior;       /* Another SELECT immediately to our left */
70903   Vdbe *v;              /* Generate code to this VDBE */
70904   SelectDest destA;     /* Destination for coroutine A */
70905   SelectDest destB;     /* Destination for coroutine B */
70906   int regAddrA;         /* Address register for select-A coroutine */
70907   int regEofA;          /* Flag to indicate when select-A is complete */
70908   int regAddrB;         /* Address register for select-B coroutine */
70909   int regEofB;          /* Flag to indicate when select-B is complete */
70910   int addrSelectA;      /* Address of the select-A coroutine */
70911   int addrSelectB;      /* Address of the select-B coroutine */
70912   int regOutA;          /* Address register for the output-A subroutine */
70913   int regOutB;          /* Address register for the output-B subroutine */
70914   int addrOutA;         /* Address of the output-A subroutine */
70915   int addrOutB;         /* Address of the output-B subroutine */
70916   int addrEofA;         /* Address of the select-A-exhausted subroutine */
70917   int addrEofB;         /* Address of the select-B-exhausted subroutine */
70918   int addrAltB;         /* Address of the A<B subroutine */
70919   int addrAeqB;         /* Address of the A==B subroutine */
70920   int addrAgtB;         /* Address of the A>B subroutine */
70921   int regLimitA;        /* Limit register for select-A */
70922   int regLimitB;        /* Limit register for select-A */
70923   int regPrev;          /* A range of registers to hold previous output */
70924   int savedLimit;       /* Saved value of p->iLimit */
70925   int savedOffset;      /* Saved value of p->iOffset */
70926   int labelCmpr;        /* Label for the start of the merge algorithm */
70927   int labelEnd;         /* Label for the end of the overall SELECT stmt */
70928   int j1;               /* Jump instructions that get retargetted */
70929   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
70930   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
70931   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
70932   sqlite3 *db;          /* Database connection */
70933   ExprList *pOrderBy;   /* The ORDER BY clause */
70934   int nOrderBy;         /* Number of terms in the ORDER BY clause */
70935   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
70936
70937   assert( p->pOrderBy!=0 );
70938   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
70939   db = pParse->db;
70940   v = pParse->pVdbe;
70941   if( v==0 ) return SQLITE_NOMEM;
70942   labelEnd = sqlite3VdbeMakeLabel(v);
70943   labelCmpr = sqlite3VdbeMakeLabel(v);
70944
70945
70946   /* Patch up the ORDER BY clause
70947   */
70948   op = p->op;  
70949   pPrior = p->pPrior;
70950   assert( pPrior->pOrderBy==0 );
70951   pOrderBy = p->pOrderBy;
70952   assert( pOrderBy );
70953   nOrderBy = pOrderBy->nExpr;
70954
70955   /* For operators other than UNION ALL we have to make sure that
70956   ** the ORDER BY clause covers every term of the result set.  Add
70957   ** terms to the ORDER BY clause as necessary.
70958   */
70959   if( op!=TK_ALL ){
70960     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
70961       struct ExprList_item *pItem;
70962       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
70963         assert( pItem->iCol>0 );
70964         if( pItem->iCol==i ) break;
70965       }
70966       if( j==nOrderBy ){
70967         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
70968         if( pNew==0 ) return SQLITE_NOMEM;
70969         pNew->flags |= EP_IntValue;
70970         pNew->iTable = i;
70971         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
70972         pOrderBy->a[nOrderBy++].iCol = i;
70973       }
70974     }
70975   }
70976
70977   /* Compute the comparison permutation and keyinfo that is used with
70978   ** the permutation in order to comparisons to determine if the next
70979   ** row of results comes from selectA or selectB.  Also add explicit
70980   ** collations to the ORDER BY clause terms so that when the subqueries
70981   ** to the right and the left are evaluated, they use the correct
70982   ** collation.
70983   */
70984   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
70985   if( aPermute ){
70986     struct ExprList_item *pItem;
70987     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
70988       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
70989       aPermute[i] = pItem->iCol - 1;
70990     }
70991     pKeyMerge =
70992       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
70993     if( pKeyMerge ){
70994       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
70995       pKeyMerge->nField = nOrderBy;
70996       pKeyMerge->enc = ENC(db);
70997       for(i=0; i<nOrderBy; i++){
70998         CollSeq *pColl;
70999         Expr *pTerm = pOrderBy->a[i].pExpr;
71000         if( pTerm->flags & EP_ExpCollate ){
71001           pColl = pTerm->pColl;
71002         }else{
71003           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
71004           pTerm->flags |= EP_ExpCollate;
71005           pTerm->pColl = pColl;
71006         }
71007         pKeyMerge->aColl[i] = pColl;
71008         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
71009       }
71010     }
71011   }else{
71012     pKeyMerge = 0;
71013   }
71014
71015   /* Reattach the ORDER BY clause to the query.
71016   */
71017   p->pOrderBy = pOrderBy;
71018   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
71019
71020   /* Allocate a range of temporary registers and the KeyInfo needed
71021   ** for the logic that removes duplicate result rows when the
71022   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
71023   */
71024   if( op==TK_ALL ){
71025     regPrev = 0;
71026   }else{
71027     int nExpr = p->pEList->nExpr;
71028     assert( nOrderBy>=nExpr );
71029     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
71030     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
71031     pKeyDup = sqlite3DbMallocZero(db,
71032                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
71033     if( pKeyDup ){
71034       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
71035       pKeyDup->nField = nExpr;
71036       pKeyDup->enc = ENC(db);
71037       for(i=0; i<nExpr; i++){
71038         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
71039         pKeyDup->aSortOrder[i] = 0;
71040       }
71041     }
71042   }
71043  
71044   /* Separate the left and the right query from one another
71045   */
71046   p->pPrior = 0;
71047   pPrior->pRightmost = 0;
71048   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
71049   if( pPrior->pPrior==0 ){
71050     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
71051   }
71052
71053   /* Compute the limit registers */
71054   computeLimitRegisters(pParse, p, labelEnd);
71055   if( p->iLimit && op==TK_ALL ){
71056     regLimitA = ++pParse->nMem;
71057     regLimitB = ++pParse->nMem;
71058     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
71059                                   regLimitA);
71060     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
71061   }else{
71062     regLimitA = regLimitB = 0;
71063   }
71064   sqlite3ExprDelete(db, p->pLimit);
71065   p->pLimit = 0;
71066   sqlite3ExprDelete(db, p->pOffset);
71067   p->pOffset = 0;
71068
71069   regAddrA = ++pParse->nMem;
71070   regEofA = ++pParse->nMem;
71071   regAddrB = ++pParse->nMem;
71072   regEofB = ++pParse->nMem;
71073   regOutA = ++pParse->nMem;
71074   regOutB = ++pParse->nMem;
71075   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
71076   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
71077
71078   /* Jump past the various subroutines and coroutines to the main
71079   ** merge loop
71080   */
71081   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
71082   addrSelectA = sqlite3VdbeCurrentAddr(v);
71083
71084
71085   /* Generate a coroutine to evaluate the SELECT statement to the
71086   ** left of the compound operator - the "A" select.
71087   */
71088   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
71089   pPrior->iLimit = regLimitA;
71090   sqlite3Select(pParse, pPrior, &destA);
71091   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
71092   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71093   VdbeNoopComment((v, "End coroutine for left SELECT"));
71094
71095   /* Generate a coroutine to evaluate the SELECT statement on 
71096   ** the right - the "B" select
71097   */
71098   addrSelectB = sqlite3VdbeCurrentAddr(v);
71099   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
71100   savedLimit = p->iLimit;
71101   savedOffset = p->iOffset;
71102   p->iLimit = regLimitB;
71103   p->iOffset = 0;  
71104   sqlite3Select(pParse, p, &destB);
71105   p->iLimit = savedLimit;
71106   p->iOffset = savedOffset;
71107   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
71108   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
71109   VdbeNoopComment((v, "End coroutine for right SELECT"));
71110
71111   /* Generate a subroutine that outputs the current row of the A
71112   ** select as the next output row of the compound select.
71113   */
71114   VdbeNoopComment((v, "Output routine for A"));
71115   addrOutA = generateOutputSubroutine(pParse,
71116                  p, &destA, pDest, regOutA,
71117                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
71118   
71119   /* Generate a subroutine that outputs the current row of the B
71120   ** select as the next output row of the compound select.
71121   */
71122   if( op==TK_ALL || op==TK_UNION ){
71123     VdbeNoopComment((v, "Output routine for B"));
71124     addrOutB = generateOutputSubroutine(pParse,
71125                  p, &destB, pDest, regOutB,
71126                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
71127   }
71128
71129   /* Generate a subroutine to run when the results from select A
71130   ** are exhausted and only data in select B remains.
71131   */
71132   VdbeNoopComment((v, "eof-A subroutine"));
71133   if( op==TK_EXCEPT || op==TK_INTERSECT ){
71134     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
71135   }else{  
71136     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
71137     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
71138     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
71139     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
71140   }
71141
71142   /* Generate a subroutine to run when the results from select B
71143   ** are exhausted and only data in select A remains.
71144   */
71145   if( op==TK_INTERSECT ){
71146     addrEofB = addrEofA;
71147   }else{  
71148     VdbeNoopComment((v, "eof-B subroutine"));
71149     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
71150     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
71151     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71152     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
71153   }
71154
71155   /* Generate code to handle the case of A<B
71156   */
71157   VdbeNoopComment((v, "A-lt-B subroutine"));
71158   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
71159   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71160   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
71161   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
71162
71163   /* Generate code to handle the case of A==B
71164   */
71165   if( op==TK_ALL ){
71166     addrAeqB = addrAltB;
71167   }else if( op==TK_INTERSECT ){
71168     addrAeqB = addrAltB;
71169     addrAltB++;
71170   }else{
71171     VdbeNoopComment((v, "A-eq-B subroutine"));
71172     addrAeqB =
71173     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
71174     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
71175     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
71176   }
71177
71178   /* Generate code to handle the case of A>B
71179   */
71180   VdbeNoopComment((v, "A-gt-B subroutine"));
71181   addrAgtB = sqlite3VdbeCurrentAddr(v);
71182   if( op==TK_ALL || op==TK_UNION ){
71183     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
71184   }
71185   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
71186   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
71187   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
71188
71189   /* This code runs once to initialize everything.
71190   */
71191   sqlite3VdbeJumpHere(v, j1);
71192   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
71193   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
71194   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
71195   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
71196   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
71197   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
71198
71199   /* Implement the main merge loop
71200   */
71201   sqlite3VdbeResolveLabel(v, labelCmpr);
71202   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
71203   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
71204                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
71205   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
71206
71207   /* Release temporary registers
71208   */
71209   if( regPrev ){
71210     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
71211   }
71212
71213   /* Jump to the this point in order to terminate the query.
71214   */
71215   sqlite3VdbeResolveLabel(v, labelEnd);
71216
71217   /* Set the number of output columns
71218   */
71219   if( pDest->eDest==SRT_Output ){
71220     Select *pFirst = pPrior;
71221     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
71222     generateColumnNames(pParse, 0, pFirst->pEList);
71223   }
71224
71225   /* Reassembly the compound query so that it will be freed correctly
71226   ** by the calling function */
71227   if( p->pPrior ){
71228     sqlite3SelectDelete(db, p->pPrior);
71229   }
71230   p->pPrior = pPrior;
71231
71232   /*** TBD:  Insert subroutine calls to close cursors on incomplete
71233   **** subqueries ****/
71234   return SQLITE_OK;
71235 }
71236 #endif
71237
71238 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
71239 /* Forward Declarations */
71240 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
71241 static void substSelect(sqlite3*, Select *, int, ExprList *);
71242
71243 /*
71244 ** Scan through the expression pExpr.  Replace every reference to
71245 ** a column in table number iTable with a copy of the iColumn-th
71246 ** entry in pEList.  (But leave references to the ROWID column 
71247 ** unchanged.)
71248 **
71249 ** This routine is part of the flattening procedure.  A subquery
71250 ** whose result set is defined by pEList appears as entry in the
71251 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
71252 ** FORM clause entry is iTable.  This routine make the necessary 
71253 ** changes to pExpr so that it refers directly to the source table
71254 ** of the subquery rather the result set of the subquery.
71255 */
71256 static void substExpr(
71257   sqlite3 *db,        /* Report malloc errors to this connection */
71258   Expr *pExpr,        /* Expr in which substitution occurs */
71259   int iTable,         /* Table to be substituted */
71260   ExprList *pEList    /* Substitute expressions */
71261 ){
71262   if( pExpr==0 ) return;
71263   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
71264     if( pExpr->iColumn<0 ){
71265       pExpr->op = TK_NULL;
71266     }else{
71267       Expr *pNew;
71268       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
71269       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
71270       pNew = pEList->a[pExpr->iColumn].pExpr;
71271       assert( pNew!=0 );
71272       pExpr->op = pNew->op;
71273       assert( pExpr->pLeft==0 );
71274       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
71275       assert( pExpr->pRight==0 );
71276       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
71277       assert( pExpr->pList==0 );
71278       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
71279       pExpr->iTable = pNew->iTable;
71280       pExpr->pTab = pNew->pTab;
71281       pExpr->iColumn = pNew->iColumn;
71282       pExpr->iAgg = pNew->iAgg;
71283       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
71284       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
71285       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
71286       pExpr->flags = pNew->flags;
71287     }
71288   }else{
71289     substExpr(db, pExpr->pLeft, iTable, pEList);
71290     substExpr(db, pExpr->pRight, iTable, pEList);
71291     substSelect(db, pExpr->pSelect, iTable, pEList);
71292     substExprList(db, pExpr->pList, iTable, pEList);
71293   }
71294 }
71295 static void substExprList(
71296   sqlite3 *db,         /* Report malloc errors here */
71297   ExprList *pList,     /* List to scan and in which to make substitutes */
71298   int iTable,          /* Table to be substituted */
71299   ExprList *pEList     /* Substitute values */
71300 ){
71301   int i;
71302   if( pList==0 ) return;
71303   for(i=0; i<pList->nExpr; i++){
71304     substExpr(db, pList->a[i].pExpr, iTable, pEList);
71305   }
71306 }
71307 static void substSelect(
71308   sqlite3 *db,         /* Report malloc errors here */
71309   Select *p,           /* SELECT statement in which to make substitutions */
71310   int iTable,          /* Table to be replaced */
71311   ExprList *pEList     /* Substitute values */
71312 ){
71313   SrcList *pSrc;
71314   struct SrcList_item *pItem;
71315   int i;
71316   if( !p ) return;
71317   substExprList(db, p->pEList, iTable, pEList);
71318   substExprList(db, p->pGroupBy, iTable, pEList);
71319   substExprList(db, p->pOrderBy, iTable, pEList);
71320   substExpr(db, p->pHaving, iTable, pEList);
71321   substExpr(db, p->pWhere, iTable, pEList);
71322   substSelect(db, p->pPrior, iTable, pEList);
71323   pSrc = p->pSrc;
71324   if( pSrc ){
71325     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
71326       substSelect(db, pItem->pSelect, iTable, pEList);
71327     }
71328   }
71329 }
71330 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
71331
71332 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
71333 /*
71334 ** This routine attempts to flatten subqueries in order to speed
71335 ** execution.  It returns 1 if it makes changes and 0 if no flattening
71336 ** occurs.
71337 **
71338 ** To understand the concept of flattening, consider the following
71339 ** query:
71340 **
71341 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
71342 **
71343 ** The default way of implementing this query is to execute the
71344 ** subquery first and store the results in a temporary table, then
71345 ** run the outer query on that temporary table.  This requires two
71346 ** passes over the data.  Furthermore, because the temporary table
71347 ** has no indices, the WHERE clause on the outer query cannot be
71348 ** optimized.
71349 **
71350 ** This routine attempts to rewrite queries such as the above into
71351 ** a single flat select, like this:
71352 **
71353 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
71354 **
71355 ** The code generated for this simpification gives the same result
71356 ** but only has to scan the data once.  And because indices might 
71357 ** exist on the table t1, a complete scan of the data might be
71358 ** avoided.
71359 **
71360 ** Flattening is only attempted if all of the following are true:
71361 **
71362 **   (1)  The subquery and the outer query do not both use aggregates.
71363 **
71364 **   (2)  The subquery is not an aggregate or the outer query is not a join.
71365 **
71366 **   (3)  The subquery is not the right operand of a left outer join
71367 **        (Originally ticket #306.  Strenghtened by ticket #3300)
71368 **
71369 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
71370 **
71371 **   (5)  The subquery is not DISTINCT or the outer query does not use
71372 **        aggregates.
71373 **
71374 **   (6)  The subquery does not use aggregates or the outer query is not
71375 **        DISTINCT.
71376 **
71377 **   (7)  The subquery has a FROM clause.
71378 **
71379 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
71380 **
71381 **   (9)  The subquery does not use LIMIT or the outer query does not use
71382 **        aggregates.
71383 **
71384 **  (10)  The subquery does not use aggregates or the outer query does not
71385 **        use LIMIT.
71386 **
71387 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
71388 **
71389 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
71390 **        a separate restriction deriving from ticket #350.
71391 **
71392 **  (13)  The subquery and outer query do not both use LIMIT
71393 **
71394 **  (14)  The subquery does not use OFFSET
71395 **
71396 **  (15)  The outer query is not part of a compound select or the
71397 **        subquery does not have both an ORDER BY and a LIMIT clause.
71398 **        (See ticket #2339)
71399 **
71400 **  (16)  The outer query is not an aggregate or the subquery does
71401 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
71402 **        until we introduced the group_concat() function.  
71403 **
71404 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
71405 **        compound clause made up entirely of non-aggregate queries, and 
71406 **        the parent query:
71407 **
71408 **          * is not itself part of a compound select,
71409 **          * is not an aggregate or DISTINCT query, and
71410 **          * has no other tables or sub-selects in the FROM clause.
71411 **
71412 **        The parent and sub-query may contain WHERE clauses. Subject to
71413 **        rules (11), (13) and (14), they may also contain ORDER BY,
71414 **        LIMIT and OFFSET clauses.
71415 **
71416 **  (18)  If the sub-query is a compound select, then all terms of the
71417 **        ORDER by clause of the parent must be simple references to 
71418 **        columns of the sub-query.
71419 **
71420 **  (19)  The subquery does not use LIMIT or the outer query does not
71421 **        have a WHERE clause.
71422 **
71423 ** In this routine, the "p" parameter is a pointer to the outer query.
71424 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
71425 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
71426 **
71427 ** If flattening is not attempted, this routine is a no-op and returns 0.
71428 ** If flattening is attempted this routine returns 1.
71429 **
71430 ** All of the expression analysis must occur on both the outer query and
71431 ** the subquery before this routine runs.
71432 */
71433 static int flattenSubquery(
71434   Parse *pParse,       /* Parsing context */
71435   Select *p,           /* The parent or outer SELECT statement */
71436   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
71437   int isAgg,           /* True if outer SELECT uses aggregate functions */
71438   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
71439 ){
71440   const char *zSavedAuthContext = pParse->zAuthContext;
71441   Select *pParent;
71442   Select *pSub;       /* The inner query or "subquery" */
71443   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
71444   SrcList *pSrc;      /* The FROM clause of the outer query */
71445   SrcList *pSubSrc;   /* The FROM clause of the subquery */
71446   ExprList *pList;    /* The result set of the outer query */
71447   int iParent;        /* VDBE cursor number of the pSub result set temp table */
71448   int i;              /* Loop counter */
71449   Expr *pWhere;                    /* The WHERE clause */
71450   struct SrcList_item *pSubitem;   /* The subquery */
71451   sqlite3 *db = pParse->db;
71452
71453   /* Check to see if flattening is permitted.  Return 0 if not.
71454   */
71455   if( p==0 ) return 0;
71456   pSrc = p->pSrc;
71457   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
71458   pSubitem = &pSrc->a[iFrom];
71459   iParent = pSubitem->iCursor;
71460   pSub = pSubitem->pSelect;
71461   assert( pSub!=0 );
71462   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
71463   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
71464   pSubSrc = pSub->pSrc;
71465   assert( pSubSrc );
71466   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
71467   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
71468   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
71469   ** became arbitrary expressions, we were forced to add restrictions (13)
71470   ** and (14). */
71471   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
71472   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
71473   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
71474     return 0;                                            /* Restriction (15) */
71475   }
71476   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
71477   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
71478          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
71479      return 0;       
71480   }
71481   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
71482      return 0;         /* Restriction (6)  */
71483   }
71484   if( p->pOrderBy && pSub->pOrderBy ){
71485      return 0;                                           /* Restriction (11) */
71486   }
71487   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
71488   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
71489
71490   /* OBSOLETE COMMENT 1:
71491   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
71492   ** not used as the right operand of an outer join.  Examples of why this
71493   ** is not allowed:
71494   **
71495   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
71496   **
71497   ** If we flatten the above, we would get
71498   **
71499   **         (t1 LEFT OUTER JOIN t2) JOIN t3
71500   **
71501   ** which is not at all the same thing.
71502   **
71503   ** OBSOLETE COMMENT 2:
71504   ** Restriction 12:  If the subquery is the right operand of a left outer
71505   ** join, make sure the subquery has no WHERE clause.
71506   ** An examples of why this is not allowed:
71507   **
71508   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
71509   **
71510   ** If we flatten the above, we would get
71511   **
71512   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
71513   **
71514   ** But the t2.x>0 test will always fail on a NULL row of t2, which
71515   ** effectively converts the OUTER JOIN into an INNER JOIN.
71516   **
71517   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
71518   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
71519   ** is fraught with danger.  Best to avoid the whole thing.  If the
71520   ** subquery is the right term of a LEFT JOIN, then do not flatten.
71521   */
71522   if( (pSubitem->jointype & JT_OUTER)!=0 ){
71523     return 0;
71524   }
71525
71526   /* Restriction 17: If the sub-query is a compound SELECT, then it must
71527   ** use only the UNION ALL operator. And none of the simple select queries
71528   ** that make up the compound SELECT are allowed to be aggregate or distinct
71529   ** queries.
71530   */
71531   if( pSub->pPrior ){
71532     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
71533       return 0;
71534     }
71535     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
71536       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
71537        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
71538        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
71539       ){
71540         return 0;
71541       }
71542     }
71543
71544     /* Restriction 18. */
71545     if( p->pOrderBy ){
71546       int ii;
71547       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
71548         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
71549       }
71550     }
71551   }
71552
71553   /***** If we reach this point, flattening is permitted. *****/
71554
71555   /* Authorize the subquery */
71556   pParse->zAuthContext = pSubitem->zName;
71557   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
71558   pParse->zAuthContext = zSavedAuthContext;
71559
71560   /* If the sub-query is a compound SELECT statement, then (by restrictions
71561   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
71562   ** be of the form:
71563   **
71564   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
71565   **
71566   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
71567   ** creates N copies of the parent query without any ORDER BY, LIMIT or 
71568   ** OFFSET clauses and joins them to the left-hand-side of the original
71569   ** using UNION ALL operators. In this case N is the number of simple
71570   ** select statements in the compound sub-query.
71571   */
71572   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
71573     Select *pNew;
71574     ExprList *pOrderBy = p->pOrderBy;
71575     Expr *pLimit = p->pLimit;
71576     Expr *pOffset = p->pOffset;
71577     Select *pPrior = p->pPrior;
71578     p->pOrderBy = 0;
71579     p->pSrc = 0;
71580     p->pPrior = 0;
71581     p->pLimit = 0;
71582     pNew = sqlite3SelectDup(db, p);
71583     pNew->pPrior = pPrior;
71584     p->pPrior = pNew;
71585     p->pOrderBy = pOrderBy;
71586     p->op = TK_ALL;
71587     p->pSrc = pSrc;
71588     p->pLimit = pLimit;
71589     p->pOffset = pOffset;
71590     p->pRightmost = 0;
71591     pNew->pRightmost = 0;
71592   }
71593
71594   /* Begin flattening the iFrom-th entry of the FROM clause 
71595   ** in the outer query.
71596   */
71597   pSub = pSub1 = pSubitem->pSelect;
71598   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
71599     int nSubSrc = pSubSrc->nSrc;
71600     int jointype = 0;
71601     pSubSrc = pSub->pSrc;
71602     pSrc = pParent->pSrc;
71603
71604     /* Move all of the FROM elements of the subquery into the
71605     ** the FROM clause of the outer query.  Before doing this, remember
71606     ** the cursor number for the original outer query FROM element in
71607     ** iParent.  The iParent cursor will never be used.  Subsequent code
71608     ** will scan expressions looking for iParent references and replace
71609     ** those references with expressions that resolve to the subquery FROM
71610     ** elements we are now copying in.
71611     */
71612     if( pSrc ){
71613       Table *pTabToDel;
71614       pSubitem = &pSrc->a[iFrom];
71615       nSubSrc = pSubSrc->nSrc;
71616       jointype = pSubitem->jointype;
71617       sqlite3DbFree(db, pSubitem->zDatabase);
71618       sqlite3DbFree(db, pSubitem->zName);
71619       sqlite3DbFree(db, pSubitem->zAlias);
71620       pSubitem->zDatabase = 0;
71621       pSubitem->zName = 0;
71622       pSubitem->zAlias = 0;
71623
71624       /* If the FROM element is a subquery, defer deleting the Table
71625       ** object associated with that subquery until code generation is
71626       ** complete, since there may still exist Expr.pTab entires that
71627       ** refer to the subquery even after flattening.  Ticket #3346.
71628       */
71629       if( (pTabToDel = pSubitem->pTab)!=0 ){
71630         if( pTabToDel->nRef==1 ){
71631           pTabToDel->pNextZombie = pParse->pZombieTab;
71632           pParse->pZombieTab = pTabToDel;
71633         }else{
71634           pTabToDel->nRef--;
71635         }
71636       }
71637       pSubitem->pTab = 0;
71638     }
71639     if( nSubSrc!=1 || !pSrc ){
71640       int extra = nSubSrc - 1;
71641       for(i=(pSrc?1:0); i<nSubSrc; i++){
71642         pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
71643         if( pSrc==0 ){
71644           pParent->pSrc = 0;
71645           return 1;
71646         }
71647       }
71648       pParent->pSrc = pSrc;
71649       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
71650         pSrc->a[i] = pSrc->a[i-extra];
71651       }
71652     }
71653     for(i=0; i<nSubSrc; i++){
71654       pSrc->a[i+iFrom] = pSubSrc->a[i];
71655       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
71656     }
71657     pSrc->a[iFrom].jointype = jointype;
71658   
71659     /* Now begin substituting subquery result set expressions for 
71660     ** references to the iParent in the outer query.
71661     ** 
71662     ** Example:
71663     **
71664     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
71665     **   \                     \_____________ subquery __________/          /
71666     **    \_____________________ outer query ______________________________/
71667     **
71668     ** We look at every expression in the outer query and every place we see
71669     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
71670     */
71671     pList = pParent->pEList;
71672     for(i=0; i<pList->nExpr; i++){
71673       Expr *pExpr;
71674       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
71675         pList->a[i].zName = 
71676                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
71677       }
71678     }
71679     substExprList(db, pParent->pEList, iParent, pSub->pEList);
71680     if( isAgg ){
71681       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
71682       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
71683     }
71684     if( pSub->pOrderBy ){
71685       assert( pParent->pOrderBy==0 );
71686       pParent->pOrderBy = pSub->pOrderBy;
71687       pSub->pOrderBy = 0;
71688     }else if( pParent->pOrderBy ){
71689       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
71690     }
71691     if( pSub->pWhere ){
71692       pWhere = sqlite3ExprDup(db, pSub->pWhere);
71693     }else{
71694       pWhere = 0;
71695     }
71696     if( subqueryIsAgg ){
71697       assert( pParent->pHaving==0 );
71698       pParent->pHaving = pParent->pWhere;
71699       pParent->pWhere = pWhere;
71700       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
71701       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
71702                                   sqlite3ExprDup(db, pSub->pHaving));
71703       assert( pParent->pGroupBy==0 );
71704       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
71705     }else{
71706       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
71707       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
71708     }
71709   
71710     /* The flattened query is distinct if either the inner or the
71711     ** outer query is distinct. 
71712     */
71713     pParent->selFlags |= pSub->selFlags & SF_Distinct;
71714   
71715     /*
71716     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
71717     **
71718     ** One is tempted to try to add a and b to combine the limits.  But this
71719     ** does not work if either limit is negative.
71720     */
71721     if( pSub->pLimit ){
71722       pParent->pLimit = pSub->pLimit;
71723       pSub->pLimit = 0;
71724     }
71725   }
71726
71727   /* Finially, delete what is left of the subquery and return
71728   ** success.
71729   */
71730   sqlite3SelectDelete(db, pSub1);
71731
71732   return 1;
71733 }
71734 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
71735
71736 /*
71737 ** Analyze the SELECT statement passed as an argument to see if it
71738 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
71739 ** it is, or 0 otherwise. At present, a query is considered to be
71740 ** a min()/max() query if:
71741 **
71742 **   1. There is a single object in the FROM clause.
71743 **
71744 **   2. There is a single expression in the result set, and it is
71745 **      either min(x) or max(x), where x is a column reference.
71746 */
71747 static int minMaxQuery(Parse *pParse, Select *p){
71748   Expr *pExpr;
71749   ExprList *pEList = p->pEList;
71750
71751   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
71752   pExpr = pEList->a[0].pExpr;
71753   pEList = pExpr->pList;
71754   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
71755   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
71756   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
71757   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
71758     return WHERE_ORDERBY_MIN;
71759   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
71760     return WHERE_ORDERBY_MAX;
71761   }
71762   return WHERE_ORDERBY_NORMAL;
71763 }
71764
71765 /*
71766 ** If the source-list item passed as an argument was augmented with an
71767 ** INDEXED BY clause, then try to locate the specified index. If there
71768 ** was such a clause and the named index cannot be found, return 
71769 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
71770 ** pFrom->pIndex and return SQLITE_OK.
71771 */
71772 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
71773   if( pFrom->pTab && pFrom->zIndex ){
71774     Table *pTab = pFrom->pTab;
71775     char *zIndex = pFrom->zIndex;
71776     Index *pIdx;
71777     for(pIdx=pTab->pIndex; 
71778         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
71779         pIdx=pIdx->pNext
71780     );
71781     if( !pIdx ){
71782       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
71783       return SQLITE_ERROR;
71784     }
71785     pFrom->pIndex = pIdx;
71786   }
71787   return SQLITE_OK;
71788 }
71789
71790 /*
71791 ** This routine is a Walker callback for "expanding" a SELECT statement.
71792 ** "Expanding" means to do the following:
71793 **
71794 **    (1)  Make sure VDBE cursor numbers have been assigned to every
71795 **         element of the FROM clause.
71796 **
71797 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
71798 **         defines FROM clause.  When views appear in the FROM clause,
71799 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
71800 **         that implements the view.  A copy is made of the view's SELECT
71801 **         statement so that we can freely modify or delete that statement
71802 **         without worrying about messing up the presistent representation
71803 **         of the view.
71804 **
71805 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
71806 **         on joins and the ON and USING clause of joins.
71807 **
71808 **    (4)  Scan the list of columns in the result set (pEList) looking
71809 **         for instances of the "*" operator or the TABLE.* operator.
71810 **         If found, expand each "*" to be every column in every table
71811 **         and TABLE.* to be every column in TABLE.
71812 **
71813 */
71814 static int selectExpander(Walker *pWalker, Select *p){
71815   Parse *pParse = pWalker->pParse;
71816   int i, j, k;
71817   SrcList *pTabList;
71818   ExprList *pEList;
71819   struct SrcList_item *pFrom;
71820   sqlite3 *db = pParse->db;
71821
71822   if( db->mallocFailed  ){
71823     return WRC_Abort;
71824   }
71825   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
71826     return WRC_Prune;
71827   }
71828   p->selFlags |= SF_Expanded;
71829   pTabList = p->pSrc;
71830   pEList = p->pEList;
71831
71832   /* Make sure cursor numbers have been assigned to all entries in
71833   ** the FROM clause of the SELECT statement.
71834   */
71835   sqlite3SrcListAssignCursors(pParse, pTabList);
71836
71837   /* Look up every table named in the FROM clause of the select.  If
71838   ** an entry of the FROM clause is a subquery instead of a table or view,
71839   ** then create a transient table structure to describe the subquery.
71840   */
71841   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
71842     Table *pTab;
71843     if( pFrom->pTab!=0 ){
71844       /* This statement has already been prepared.  There is no need
71845       ** to go further. */
71846       assert( i==0 );
71847       return WRC_Prune;
71848     }
71849     if( pFrom->zName==0 ){
71850 #ifndef SQLITE_OMIT_SUBQUERY
71851       Select *pSel = pFrom->pSelect;
71852       /* A sub-query in the FROM clause of a SELECT */
71853       assert( pSel!=0 );
71854       assert( pFrom->pTab==0 );
71855       sqlite3WalkSelect(pWalker, pSel);
71856       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
71857       if( pTab==0 ) return WRC_Abort;
71858       pTab->db = db;
71859       pTab->nRef = 1;
71860       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
71861       while( pSel->pPrior ){ pSel = pSel->pPrior; }
71862       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
71863       pTab->iPKey = -1;
71864       pTab->tabFlags |= TF_Ephemeral;
71865 #endif
71866     }else{
71867       /* An ordinary table or view name in the FROM clause */
71868       assert( pFrom->pTab==0 );
71869       pFrom->pTab = pTab = 
71870         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
71871       if( pTab==0 ) return WRC_Abort;
71872       pTab->nRef++;
71873 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
71874       if( pTab->pSelect || IsVirtual(pTab) ){
71875         /* We reach here if the named table is a really a view */
71876         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
71877
71878         /* If pFrom->pSelect!=0 it means we are dealing with a
71879         ** view within a view.  The SELECT structure has already been
71880         ** copied by the outer view so we can skip the copy step here
71881         ** in the inner view.
71882         */
71883         if( pFrom->pSelect==0 ){
71884           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
71885           sqlite3WalkSelect(pWalker, pFrom->pSelect);
71886         }
71887       }
71888 #endif
71889     }
71890
71891     /* Locate the index named by the INDEXED BY clause, if any. */
71892     if( sqlite3IndexedByLookup(pParse, pFrom) ){
71893       return WRC_Abort;
71894     }
71895   }
71896
71897   /* Process NATURAL keywords, and ON and USING clauses of joins.
71898   */
71899   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
71900     return WRC_Abort;
71901   }
71902
71903   /* For every "*" that occurs in the column list, insert the names of
71904   ** all columns in all tables.  And for every TABLE.* insert the names
71905   ** of all columns in TABLE.  The parser inserted a special expression
71906   ** with the TK_ALL operator for each "*" that it found in the column list.
71907   ** The following code just has to locate the TK_ALL expressions and expand
71908   ** each one to the list of all columns in all tables.
71909   **
71910   ** The first loop just checks to see if there are any "*" operators
71911   ** that need expanding.
71912   */
71913   for(k=0; k<pEList->nExpr; k++){
71914     Expr *pE = pEList->a[k].pExpr;
71915     if( pE->op==TK_ALL ) break;
71916     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
71917          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
71918   }
71919   if( k<pEList->nExpr ){
71920     /*
71921     ** If we get here it means the result set contains one or more "*"
71922     ** operators that need to be expanded.  Loop through each expression
71923     ** in the result set and expand them one by one.
71924     */
71925     struct ExprList_item *a = pEList->a;
71926     ExprList *pNew = 0;
71927     int flags = pParse->db->flags;
71928     int longNames = (flags & SQLITE_FullColNames)!=0
71929                       && (flags & SQLITE_ShortColNames)==0;
71930
71931     for(k=0; k<pEList->nExpr; k++){
71932       Expr *pE = a[k].pExpr;
71933       if( pE->op!=TK_ALL &&
71934            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
71935         /* This particular expression does not need to be expanded.
71936         */
71937         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
71938         if( pNew ){
71939           pNew->a[pNew->nExpr-1].zName = a[k].zName;
71940         }
71941         a[k].pExpr = 0;
71942         a[k].zName = 0;
71943       }else{
71944         /* This expression is a "*" or a "TABLE.*" and needs to be
71945         ** expanded. */
71946         int tableSeen = 0;      /* Set to 1 when TABLE matches */
71947         char *zTName;            /* text of name of TABLE */
71948         if( pE->op==TK_DOT && pE->pLeft ){
71949           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
71950         }else{
71951           zTName = 0;
71952         }
71953         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
71954           Table *pTab = pFrom->pTab;
71955           char *zTabName = pFrom->zAlias;
71956           if( zTabName==0 || zTabName[0]==0 ){ 
71957             zTabName = pTab->zName;
71958           }
71959           if( db->mallocFailed ) break;
71960           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
71961             continue;
71962           }
71963           tableSeen = 1;
71964           for(j=0; j<pTab->nCol; j++){
71965             Expr *pExpr, *pRight;
71966             char *zName = pTab->aCol[j].zName;
71967
71968             /* If a column is marked as 'hidden' (currently only possible
71969             ** for virtual tables), do not include it in the expanded
71970             ** result-set list.
71971             */
71972             if( IsHiddenColumn(&pTab->aCol[j]) ){
71973               assert(IsVirtual(pTab));
71974               continue;
71975             }
71976
71977             if( i>0 ){
71978               struct SrcList_item *pLeft = &pTabList->a[i-1];
71979               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
71980                         columnIndex(pLeft->pTab, zName)>=0 ){
71981                 /* In a NATURAL join, omit the join columns from the 
71982                 ** table on the right */
71983                 continue;
71984               }
71985               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
71986                 /* In a join with a USING clause, omit columns in the
71987                 ** using clause from the table on the right. */
71988                 continue;
71989               }
71990             }
71991             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
71992             if( pRight==0 ) break;
71993             setQuotedToken(pParse, &pRight->token, zName);
71994             if( longNames || pTabList->nSrc>1 ){
71995               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
71996               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
71997               if( pExpr==0 ) break;
71998               setQuotedToken(pParse, &pLeft->token, zTabName);
71999               setToken(&pExpr->span, 
72000                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
72001               pExpr->span.dyn = 1;
72002               pExpr->token.z = 0;
72003               pExpr->token.n = 0;
72004               pExpr->token.dyn = 0;
72005             }else{
72006               pExpr = pRight;
72007               pExpr->span = pExpr->token;
72008               pExpr->span.dyn = 0;
72009             }
72010             if( longNames ){
72011               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
72012             }else{
72013               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
72014             }
72015           }
72016         }
72017         if( !tableSeen ){
72018           if( zTName ){
72019             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
72020           }else{
72021             sqlite3ErrorMsg(pParse, "no tables specified");
72022           }
72023         }
72024         sqlite3DbFree(db, zTName);
72025       }
72026     }
72027     sqlite3ExprListDelete(db, pEList);
72028     p->pEList = pNew;
72029   }
72030 #if SQLITE_MAX_COLUMN
72031   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72032     sqlite3ErrorMsg(pParse, "too many columns in result set");
72033   }
72034 #endif
72035   return WRC_Continue;
72036 }
72037
72038 /*
72039 ** No-op routine for the parse-tree walker.
72040 **
72041 ** When this routine is the Walker.xExprCallback then expression trees
72042 ** are walked without any actions being taken at each node.  Presumably,
72043 ** when this routine is used for Walker.xExprCallback then 
72044 ** Walker.xSelectCallback is set to do something useful for every 
72045 ** subquery in the parser tree.
72046 */
72047 static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
72048   return WRC_Continue;
72049 }
72050
72051 /*
72052 ** This routine "expands" a SELECT statement and all of its subqueries.
72053 ** For additional information on what it means to "expand" a SELECT
72054 ** statement, see the comment on the selectExpand worker callback above.
72055 **
72056 ** Expanding a SELECT statement is the first step in processing a
72057 ** SELECT statement.  The SELECT statement must be expanded before
72058 ** name resolution is performed.
72059 **
72060 ** If anything goes wrong, an error message is written into pParse.
72061 ** The calling function can detect the problem by looking at pParse->nErr
72062 ** and/or pParse->db->mallocFailed.
72063 */
72064 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
72065   Walker w;
72066   w.xSelectCallback = selectExpander;
72067   w.xExprCallback = exprWalkNoop;
72068   w.pParse = pParse;
72069   sqlite3WalkSelect(&w, pSelect);
72070 }
72071
72072
72073 #ifndef SQLITE_OMIT_SUBQUERY
72074 /*
72075 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
72076 ** interface.
72077 **
72078 ** For each FROM-clause subquery, add Column.zType and Column.zColl
72079 ** information to the Table structure that represents the result set
72080 ** of that subquery.
72081 **
72082 ** The Table structure that represents the result set was constructed
72083 ** by selectExpander() but the type and collation information was omitted
72084 ** at that point because identifiers had not yet been resolved.  This
72085 ** routine is called after identifier resolution.
72086 */
72087 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
72088   Parse *pParse;
72089   int i;
72090   SrcList *pTabList;
72091   struct SrcList_item *pFrom;
72092
72093   assert( p->selFlags & SF_Resolved );
72094   if( (p->selFlags & SF_HasTypeInfo)==0 ){
72095     p->selFlags |= SF_HasTypeInfo;
72096     pParse = pWalker->pParse;
72097     pTabList = p->pSrc;
72098     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
72099       Table *pTab = pFrom->pTab;
72100       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
72101         /* A sub-query in the FROM clause of a SELECT */
72102         Select *pSel = pFrom->pSelect;
72103         assert( pSel );
72104         while( pSel->pPrior ) pSel = pSel->pPrior;
72105         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
72106       }
72107     }
72108   }
72109   return WRC_Continue;
72110 }
72111 #endif
72112
72113
72114 /*
72115 ** This routine adds datatype and collating sequence information to
72116 ** the Table structures of all FROM-clause subqueries in a
72117 ** SELECT statement.
72118 **
72119 ** Use this routine after name resolution.
72120 */
72121 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
72122 #ifndef SQLITE_OMIT_SUBQUERY
72123   Walker w;
72124   w.xSelectCallback = selectAddSubqueryTypeInfo;
72125   w.xExprCallback = exprWalkNoop;
72126   w.pParse = pParse;
72127   sqlite3WalkSelect(&w, pSelect);
72128 #endif
72129 }
72130
72131
72132 /*
72133 ** This routine sets of a SELECT statement for processing.  The
72134 ** following is accomplished:
72135 **
72136 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
72137 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
72138 **     *  ON and USING clauses are shifted into WHERE statements
72139 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
72140 **     *  Identifiers in expression are matched to tables.
72141 **
72142 ** This routine acts recursively on all subqueries within the SELECT.
72143 */
72144 SQLITE_PRIVATE void sqlite3SelectPrep(
72145   Parse *pParse,         /* The parser context */
72146   Select *p,             /* The SELECT statement being coded. */
72147   NameContext *pOuterNC  /* Name context for container */
72148 ){
72149   sqlite3 *db;
72150   if( p==0 ) return;
72151   db = pParse->db;
72152   if( p->selFlags & SF_HasTypeInfo ) return;
72153   if( pParse->nErr || db->mallocFailed ) return;
72154   sqlite3SelectExpand(pParse, p);
72155   if( pParse->nErr || db->mallocFailed ) return;
72156   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
72157   if( pParse->nErr || db->mallocFailed ) return;
72158   sqlite3SelectAddTypeInfo(pParse, p);
72159 }
72160
72161 /*
72162 ** Reset the aggregate accumulator.
72163 **
72164 ** The aggregate accumulator is a set of memory cells that hold
72165 ** intermediate results while calculating an aggregate.  This
72166 ** routine simply stores NULLs in all of those memory cells.
72167 */
72168 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
72169   Vdbe *v = pParse->pVdbe;
72170   int i;
72171   struct AggInfo_func *pFunc;
72172   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
72173     return;
72174   }
72175   for(i=0; i<pAggInfo->nColumn; i++){
72176     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
72177   }
72178   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
72179     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
72180     if( pFunc->iDistinct>=0 ){
72181       Expr *pE = pFunc->pExpr;
72182       if( pE->pList==0 || pE->pList->nExpr!=1 ){
72183         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
72184            "by an expression");
72185         pFunc->iDistinct = -1;
72186       }else{
72187         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
72188         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
72189                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72190       }
72191     }
72192   }
72193 }
72194
72195 /*
72196 ** Invoke the OP_AggFinalize opcode for every aggregate function
72197 ** in the AggInfo structure.
72198 */
72199 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
72200   Vdbe *v = pParse->pVdbe;
72201   int i;
72202   struct AggInfo_func *pF;
72203   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
72204     ExprList *pList = pF->pExpr->pList;
72205     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
72206                       (void*)pF->pFunc, P4_FUNCDEF);
72207   }
72208 }
72209
72210 /*
72211 ** Update the accumulator memory cells for an aggregate based on
72212 ** the current cursor position.
72213 */
72214 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
72215   Vdbe *v = pParse->pVdbe;
72216   int i;
72217   struct AggInfo_func *pF;
72218   struct AggInfo_col *pC;
72219
72220   pAggInfo->directMode = 1;
72221   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
72222     int nArg;
72223     int addrNext = 0;
72224     int regAgg;
72225     ExprList *pList = pF->pExpr->pList;
72226     if( pList ){
72227       nArg = pList->nExpr;
72228       regAgg = sqlite3GetTempRange(pParse, nArg);
72229       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
72230     }else{
72231       nArg = 0;
72232       regAgg = 0;
72233     }
72234     if( pF->iDistinct>=0 ){
72235       addrNext = sqlite3VdbeMakeLabel(v);
72236       assert( nArg==1 );
72237       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
72238     }
72239     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
72240       CollSeq *pColl = 0;
72241       struct ExprList_item *pItem;
72242       int j;
72243       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
72244       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
72245         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
72246       }
72247       if( !pColl ){
72248         pColl = pParse->db->pDfltColl;
72249       }
72250       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
72251     }
72252     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
72253                       (void*)pF->pFunc, P4_FUNCDEF);
72254     sqlite3VdbeChangeP5(v, nArg);
72255     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
72256     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
72257     if( addrNext ){
72258       sqlite3VdbeResolveLabel(v, addrNext);
72259     }
72260   }
72261   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
72262     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
72263   }
72264   pAggInfo->directMode = 0;
72265 }
72266
72267 /*
72268 ** Generate code for the SELECT statement given in the p argument.  
72269 **
72270 ** The results are distributed in various ways depending on the
72271 ** contents of the SelectDest structure pointed to by argument pDest
72272 ** as follows:
72273 **
72274 **     pDest->eDest    Result
72275 **     ------------    -------------------------------------------
72276 **     SRT_Output      Generate a row of output (using the OP_ResultRow
72277 **                     opcode) for each row in the result set.
72278 **
72279 **     SRT_Mem         Only valid if the result is a single column.
72280 **                     Store the first column of the first result row
72281 **                     in register pDest->iParm then abandon the rest
72282 **                     of the query.  This destination implies "LIMIT 1".
72283 **
72284 **     SRT_Set         The result must be a single column.  Store each
72285 **                     row of result as the key in table pDest->iParm. 
72286 **                     Apply the affinity pDest->affinity before storing
72287 **                     results.  Used to implement "IN (SELECT ...)".
72288 **
72289 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
72290 **
72291 **     SRT_Except      Remove results from the temporary table pDest->iParm.
72292 **
72293 **     SRT_Table       Store results in temporary table pDest->iParm.
72294 **                     This is like SRT_EphemTab except that the table
72295 **                     is assumed to already be open.
72296 **
72297 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
72298 **                     the result there. The cursor is left open after
72299 **                     returning.  This is like SRT_Table except that
72300 **                     this destination uses OP_OpenEphemeral to create
72301 **                     the table first.
72302 **
72303 **     SRT_Coroutine   Generate a co-routine that returns a new row of
72304 **                     results each time it is invoked.  The entry point
72305 **                     of the co-routine is stored in register pDest->iParm.
72306 **
72307 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
72308 **                     set is not empty.
72309 **
72310 **     SRT_Discard     Throw the results away.  This is used by SELECT
72311 **                     statements within triggers whose only purpose is
72312 **                     the side-effects of functions.
72313 **
72314 ** This routine returns the number of errors.  If any errors are
72315 ** encountered, then an appropriate error message is left in
72316 ** pParse->zErrMsg.
72317 **
72318 ** This routine does NOT free the Select structure passed in.  The
72319 ** calling function needs to do that.
72320 */
72321 SQLITE_PRIVATE int sqlite3Select(
72322   Parse *pParse,         /* The parser context */
72323   Select *p,             /* The SELECT statement being coded. */
72324   SelectDest *pDest      /* What to do with the query results */
72325 ){
72326   int i, j;              /* Loop counters */
72327   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
72328   Vdbe *v;               /* The virtual machine under construction */
72329   int isAgg;             /* True for select lists like "count(*)" */
72330   ExprList *pEList;      /* List of columns to extract. */
72331   SrcList *pTabList;     /* List of tables to select from */
72332   Expr *pWhere;          /* The WHERE clause.  May be NULL */
72333   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
72334   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
72335   Expr *pHaving;         /* The HAVING clause.  May be NULL */
72336   int isDistinct;        /* True if the DISTINCT keyword is present */
72337   int distinct;          /* Table to use for the distinct set */
72338   int rc = 1;            /* Value to return from this function */
72339   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
72340   AggInfo sAggInfo;      /* Information used by aggregate queries */
72341   int iEnd;              /* Address of the end of the query */
72342   sqlite3 *db;           /* The database connection */
72343
72344   db = pParse->db;
72345   if( p==0 || db->mallocFailed || pParse->nErr ){
72346     return 1;
72347   }
72348   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
72349   memset(&sAggInfo, 0, sizeof(sAggInfo));
72350
72351   pOrderBy = p->pOrderBy;
72352   if( IgnorableOrderby(pDest) ){
72353     p->pOrderBy = 0;
72354
72355     /* In these cases the DISTINCT operator makes no difference to the
72356     ** results, so remove it if it were specified.
72357     */
72358     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
72359            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
72360     p->selFlags &= ~SF_Distinct;
72361   }
72362   sqlite3SelectPrep(pParse, p, 0);
72363   if( pParse->nErr ){
72364     goto select_end;
72365   }
72366   p->pOrderBy = pOrderBy;
72367
72368
72369   /* Make local copies of the parameters for this query.
72370   */
72371   pTabList = p->pSrc;
72372   isAgg = (p->selFlags & SF_Aggregate)!=0;
72373   pEList = p->pEList;
72374   if( pEList==0 ) goto select_end;
72375
72376   /* 
72377   ** Do not even attempt to generate any code if we have already seen
72378   ** errors before this routine starts.
72379   */
72380   if( pParse->nErr>0 ) goto select_end;
72381
72382   /* ORDER BY is ignored for some destinations.
72383   */
72384   if( IgnorableOrderby(pDest) ){
72385     pOrderBy = 0;
72386   }
72387
72388   /* Begin generating code.
72389   */
72390   v = sqlite3GetVdbe(pParse);
72391   if( v==0 ) goto select_end;
72392
72393   /* Generate code for all sub-queries in the FROM clause
72394   */
72395 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
72396   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
72397     struct SrcList_item *pItem = &pTabList->a[i];
72398     SelectDest dest;
72399     Select *pSub = pItem->pSelect;
72400     int isAggSub;
72401
72402     if( pSub==0 || pItem->isPopulated ) continue;
72403
72404     /* Increment Parse.nHeight by the height of the largest expression
72405     ** tree refered to by this, the parent select. The child select
72406     ** may contain expression trees of at most
72407     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
72408     ** more conservative than necessary, but much easier than enforcing
72409     ** an exact limit.
72410     */
72411     pParse->nHeight += sqlite3SelectExprHeight(p);
72412
72413     /* Check to see if the subquery can be absorbed into the parent. */
72414     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
72415     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
72416       if( isAggSub ){
72417         isAgg = 1;
72418         p->selFlags |= SF_Aggregate;
72419       }
72420       i = -1;
72421     }else{
72422       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
72423       assert( pItem->isPopulated==0 );
72424       sqlite3Select(pParse, pSub, &dest);
72425       pItem->isPopulated = 1;
72426     }
72427     if( pParse->nErr || db->mallocFailed ){
72428       goto select_end;
72429     }
72430     pParse->nHeight -= sqlite3SelectExprHeight(p);
72431     pTabList = p->pSrc;
72432     if( !IgnorableOrderby(pDest) ){
72433       pOrderBy = p->pOrderBy;
72434     }
72435   }
72436   pEList = p->pEList;
72437 #endif
72438   pWhere = p->pWhere;
72439   pGroupBy = p->pGroupBy;
72440   pHaving = p->pHaving;
72441   isDistinct = (p->selFlags & SF_Distinct)!=0;
72442
72443 #ifndef SQLITE_OMIT_COMPOUND_SELECT
72444   /* If there is are a sequence of queries, do the earlier ones first.
72445   */
72446   if( p->pPrior ){
72447     if( p->pRightmost==0 ){
72448       Select *pLoop, *pRight = 0;
72449       int cnt = 0;
72450       int mxSelect;
72451       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
72452         pLoop->pRightmost = p;
72453         pLoop->pNext = pRight;
72454         pRight = pLoop;
72455       }
72456       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
72457       if( mxSelect && cnt>mxSelect ){
72458         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
72459         return 1;
72460       }
72461     }
72462     return multiSelect(pParse, p, pDest);
72463   }
72464 #endif
72465
72466   /* If writing to memory or generating a set
72467   ** only a single column may be output.
72468   */
72469 #ifndef SQLITE_OMIT_SUBQUERY
72470   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
72471     goto select_end;
72472   }
72473 #endif
72474
72475   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
72476   ** GROUP BY might use an index, DISTINCT never does.
72477   */
72478   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
72479     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
72480     pGroupBy = p->pGroupBy;
72481     p->selFlags &= ~SF_Distinct;
72482     isDistinct = 0;
72483   }
72484
72485   /* If there is an ORDER BY clause, then this sorting
72486   ** index might end up being unused if the data can be 
72487   ** extracted in pre-sorted order.  If that is the case, then the
72488   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
72489   ** we figure out that the sorting index is not needed.  The addrSortIndex
72490   ** variable is used to facilitate that change.
72491   */
72492   if( pOrderBy ){
72493     KeyInfo *pKeyInfo;
72494     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
72495     pOrderBy->iECursor = pParse->nTab++;
72496     p->addrOpenEphm[2] = addrSortIndex =
72497       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
72498                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
72499                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72500   }else{
72501     addrSortIndex = -1;
72502   }
72503
72504   /* If the output is destined for a temporary table, open that table.
72505   */
72506   if( pDest->eDest==SRT_EphemTab ){
72507     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
72508   }
72509
72510   /* Set the limiter.
72511   */
72512   iEnd = sqlite3VdbeMakeLabel(v);
72513   computeLimitRegisters(pParse, p, iEnd);
72514
72515   /* Open a virtual index to use for the distinct set.
72516   */
72517   if( isDistinct ){
72518     KeyInfo *pKeyInfo;
72519     assert( isAgg || pGroupBy );
72520     distinct = pParse->nTab++;
72521     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
72522     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
72523                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72524   }else{
72525     distinct = -1;
72526   }
72527
72528   /* Aggregate and non-aggregate queries are handled differently */
72529   if( !isAgg && pGroupBy==0 ){
72530     /* This case is for non-aggregate queries
72531     ** Begin the database scan
72532     */
72533     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
72534     if( pWInfo==0 ) goto select_end;
72535
72536     /* If sorting index that was created by a prior OP_OpenEphemeral 
72537     ** instruction ended up not being needed, then change the OP_OpenEphemeral
72538     ** into an OP_Noop.
72539     */
72540     if( addrSortIndex>=0 && pOrderBy==0 ){
72541       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
72542       p->addrOpenEphm[2] = -1;
72543     }
72544
72545     /* Use the standard inner loop
72546     */
72547     assert(!isDistinct);
72548     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
72549                     pWInfo->iContinue, pWInfo->iBreak);
72550
72551     /* End the database scan loop.
72552     */
72553     sqlite3WhereEnd(pWInfo);
72554   }else{
72555     /* This is the processing for aggregate queries */
72556     NameContext sNC;    /* Name context for processing aggregate information */
72557     int iAMem;          /* First Mem address for storing current GROUP BY */
72558     int iBMem;          /* First Mem address for previous GROUP BY */
72559     int iUseFlag;       /* Mem address holding flag indicating that at least
72560                         ** one row of the input to the aggregator has been
72561                         ** processed */
72562     int iAbortFlag;     /* Mem address which causes query abort if positive */
72563     int groupBySort;    /* Rows come from source in GROUP BY order */
72564     int addrEnd;        /* End of processing for this SELECT */
72565
72566     /* Remove any and all aliases between the result set and the
72567     ** GROUP BY clause.
72568     */
72569     if( pGroupBy ){
72570       int i;                        /* Loop counter */
72571       struct ExprList_item *pItem;  /* For looping over expression in a list */
72572
72573       for(i=p->pEList->nExpr, pItem=p->pEList->a; i>0; i--, pItem++){
72574         pItem->iAlias = 0;
72575       }
72576       for(i=pGroupBy->nExpr, pItem=pGroupBy->a; i>0; i--, pItem++){
72577         pItem->iAlias = 0;
72578       }
72579     }
72580
72581  
72582     /* Create a label to jump to when we want to abort the query */
72583     addrEnd = sqlite3VdbeMakeLabel(v);
72584
72585     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
72586     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
72587     ** SELECT statement.
72588     */
72589     memset(&sNC, 0, sizeof(sNC));
72590     sNC.pParse = pParse;
72591     sNC.pSrcList = pTabList;
72592     sNC.pAggInfo = &sAggInfo;
72593     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
72594     sAggInfo.pGroupBy = pGroupBy;
72595     sqlite3ExprAnalyzeAggList(&sNC, pEList);
72596     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
72597     if( pHaving ){
72598       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
72599     }
72600     sAggInfo.nAccumulator = sAggInfo.nColumn;
72601     for(i=0; i<sAggInfo.nFunc; i++){
72602       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
72603     }
72604     if( db->mallocFailed ) goto select_end;
72605
72606     /* Processing for aggregates with GROUP BY is very different and
72607     ** much more complex than aggregates without a GROUP BY.
72608     */
72609     if( pGroupBy ){
72610       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
72611       int j1;             /* A-vs-B comparision jump */
72612       int addrOutputRow;  /* Start of subroutine that outputs a result row */
72613       int regOutputRow;   /* Return address register for output subroutine */
72614       int addrSetAbort;   /* Set the abort flag and return */
72615       int addrTopOfLoop;  /* Top of the input loop */
72616       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
72617       int addrReset;      /* Subroutine for resetting the accumulator */
72618       int regReset;       /* Return address register for reset subroutine */
72619
72620       /* If there is a GROUP BY clause we might need a sorting index to
72621       ** implement it.  Allocate that sorting index now.  If it turns out
72622       ** that we do not need it after all, the OpenEphemeral instruction
72623       ** will be converted into a Noop.  
72624       */
72625       sAggInfo.sortingIdx = pParse->nTab++;
72626       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
72627       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
72628           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
72629           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
72630
72631       /* Initialize memory locations used by GROUP BY aggregate processing
72632       */
72633       iUseFlag = ++pParse->nMem;
72634       iAbortFlag = ++pParse->nMem;
72635       regOutputRow = ++pParse->nMem;
72636       addrOutputRow = sqlite3VdbeMakeLabel(v);
72637       regReset = ++pParse->nMem;
72638       addrReset = sqlite3VdbeMakeLabel(v);
72639       iAMem = pParse->nMem + 1;
72640       pParse->nMem += pGroupBy->nExpr;
72641       iBMem = pParse->nMem + 1;
72642       pParse->nMem += pGroupBy->nExpr;
72643       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
72644       VdbeComment((v, "clear abort flag"));
72645       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
72646       VdbeComment((v, "indicate accumulator empty"));
72647
72648       /* Begin a loop that will extract all source rows in GROUP BY order.
72649       ** This might involve two separate loops with an OP_Sort in between, or
72650       ** it might be a single loop that uses an index to extract information
72651       ** in the right order to begin with.
72652       */
72653       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
72654       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
72655       if( pWInfo==0 ) goto select_end;
72656       if( pGroupBy==0 ){
72657         /* The optimizer is able to deliver rows in group by order so
72658         ** we do not have to sort.  The OP_OpenEphemeral table will be
72659         ** cancelled later because we still need to use the pKeyInfo
72660         */
72661         pGroupBy = p->pGroupBy;
72662         groupBySort = 0;
72663       }else{
72664         /* Rows are coming out in undetermined order.  We have to push
72665         ** each row into a sorting index, terminate the first loop,
72666         ** then loop over the sorting index in order to get the output
72667         ** in sorted order
72668         */
72669         int regBase;
72670         int regRecord;
72671         int nCol;
72672         int nGroupBy;
72673
72674         groupBySort = 1;
72675         nGroupBy = pGroupBy->nExpr;
72676         nCol = nGroupBy + 1;
72677         j = nGroupBy+1;
72678         for(i=0; i<sAggInfo.nColumn; i++){
72679           if( sAggInfo.aCol[i].iSorterColumn>=j ){
72680             nCol++;
72681             j++;
72682           }
72683         }
72684         regBase = sqlite3GetTempRange(pParse, nCol);
72685         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
72686         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
72687         j = nGroupBy+1;
72688         for(i=0; i<sAggInfo.nColumn; i++){
72689           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
72690           if( pCol->iSorterColumn>=j ){
72691             int r1 = j + regBase;
72692             int r2;
72693
72694             r2 = sqlite3ExprCodeGetColumn(pParse, 
72695                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
72696             if( r1!=r2 ){
72697               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
72698             }
72699             j++;
72700           }
72701         }
72702         regRecord = sqlite3GetTempReg(pParse);
72703         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
72704         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
72705         sqlite3ReleaseTempReg(pParse, regRecord);
72706         sqlite3ReleaseTempRange(pParse, regBase, nCol);
72707         sqlite3WhereEnd(pWInfo);
72708         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
72709         VdbeComment((v, "GROUP BY sort"));
72710         sAggInfo.useSortingIdx = 1;
72711       }
72712
72713       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
72714       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
72715       ** Then compare the current GROUP BY terms against the GROUP BY terms
72716       ** from the previous row currently stored in a0, a1, a2...
72717       */
72718       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
72719       for(j=0; j<pGroupBy->nExpr; j++){
72720         if( groupBySort ){
72721           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
72722         }else{
72723           sAggInfo.directMode = 1;
72724           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
72725         }
72726       }
72727       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
72728                           (char*)pKeyInfo, P4_KEYINFO);
72729       j1 = sqlite3VdbeCurrentAddr(v);
72730       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
72731
72732       /* Generate code that runs whenever the GROUP BY changes.
72733       ** Changes in the GROUP BY are detected by the previous code
72734       ** block.  If there were no changes, this block is skipped.
72735       **
72736       ** This code copies current group by terms in b0,b1,b2,...
72737       ** over to a0,a1,a2.  It then calls the output subroutine
72738       ** and resets the aggregate accumulator registers in preparation
72739       ** for the next GROUP BY batch.
72740       */
72741       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
72742       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
72743       VdbeComment((v, "output one row"));
72744       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
72745       VdbeComment((v, "check abort flag"));
72746       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
72747       VdbeComment((v, "reset accumulator"));
72748
72749       /* Update the aggregate accumulators based on the content of
72750       ** the current row
72751       */
72752       sqlite3VdbeJumpHere(v, j1);
72753       updateAccumulator(pParse, &sAggInfo);
72754       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
72755       VdbeComment((v, "indicate data in accumulator"));
72756
72757       /* End of the loop
72758       */
72759       if( groupBySort ){
72760         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
72761       }else{
72762         sqlite3WhereEnd(pWInfo);
72763         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
72764       }
72765
72766       /* Output the final row of result
72767       */
72768       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
72769       VdbeComment((v, "output final row"));
72770
72771       /* Jump over the subroutines
72772       */
72773       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
72774
72775       /* Generate a subroutine that outputs a single row of the result
72776       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
72777       ** is less than or equal to zero, the subroutine is a no-op.  If
72778       ** the processing calls for the query to abort, this subroutine
72779       ** increments the iAbortFlag memory location before returning in
72780       ** order to signal the caller to abort.
72781       */
72782       addrSetAbort = sqlite3VdbeCurrentAddr(v);
72783       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
72784       VdbeComment((v, "set abort flag"));
72785       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72786       sqlite3VdbeResolveLabel(v, addrOutputRow);
72787       addrOutputRow = sqlite3VdbeCurrentAddr(v);
72788       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
72789       VdbeComment((v, "Groupby result generator entry point"));
72790       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72791       finalizeAggFunctions(pParse, &sAggInfo);
72792       if( pHaving ){
72793         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
72794       }
72795       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
72796                       distinct, pDest,
72797                       addrOutputRow+1, addrSetAbort);
72798       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
72799       VdbeComment((v, "end groupby result generator"));
72800
72801       /* Generate a subroutine that will reset the group-by accumulator
72802       */
72803       sqlite3VdbeResolveLabel(v, addrReset);
72804       resetAccumulator(pParse, &sAggInfo);
72805       sqlite3VdbeAddOp1(v, OP_Return, regReset);
72806      
72807     } /* endif pGroupBy */
72808     else {
72809       ExprList *pMinMax = 0;
72810       ExprList *pDel = 0;
72811       u8 flag;
72812
72813       /* Check if the query is of one of the following forms:
72814       **
72815       **   SELECT min(x) FROM ...
72816       **   SELECT max(x) FROM ...
72817       **
72818       ** If it is, then ask the code in where.c to attempt to sort results
72819       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
72820       ** If where.c is able to produce results sorted in this order, then
72821       ** add vdbe code to break out of the processing loop after the 
72822       ** first iteration (since the first iteration of the loop is 
72823       ** guaranteed to operate on the row with the minimum or maximum 
72824       ** value of x, the only row required).
72825       **
72826       ** A special flag must be passed to sqlite3WhereBegin() to slightly
72827       ** modify behaviour as follows:
72828       **
72829       **   + If the query is a "SELECT min(x)", then the loop coded by
72830       **     where.c should not iterate over any values with a NULL value
72831       **     for x.
72832       **
72833       **   + The optimizer code in where.c (the thing that decides which
72834       **     index or indices to use) should place a different priority on 
72835       **     satisfying the 'ORDER BY' clause than it does in other cases.
72836       **     Refer to code and comments in where.c for details.
72837       */
72838       flag = minMaxQuery(pParse, p);
72839       if( flag ){
72840         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
72841         if( pMinMax && !db->mallocFailed ){
72842           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
72843           pMinMax->a[0].pExpr->op = TK_COLUMN;
72844         }
72845       }
72846
72847       /* This case runs if the aggregate has no GROUP BY clause.  The
72848       ** processing is much simpler since there is only a single row
72849       ** of output.
72850       */
72851       resetAccumulator(pParse, &sAggInfo);
72852       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
72853       if( pWInfo==0 ){
72854         sqlite3ExprListDelete(db, pDel);
72855         goto select_end;
72856       }
72857       updateAccumulator(pParse, &sAggInfo);
72858       if( !pMinMax && flag ){
72859         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
72860         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
72861       }
72862       sqlite3WhereEnd(pWInfo);
72863       finalizeAggFunctions(pParse, &sAggInfo);
72864       pOrderBy = 0;
72865       if( pHaving ){
72866         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
72867       }
72868       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
72869                       pDest, addrEnd, addrEnd);
72870
72871       sqlite3ExprListDelete(db, pDel);
72872     }
72873     sqlite3VdbeResolveLabel(v, addrEnd);
72874     
72875   } /* endif aggregate query */
72876
72877   /* If there is an ORDER BY clause, then we need to sort the results
72878   ** and send them to the callback one by one.
72879   */
72880   if( pOrderBy ){
72881     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
72882   }
72883
72884   /* Jump here to skip this query
72885   */
72886   sqlite3VdbeResolveLabel(v, iEnd);
72887
72888   /* The SELECT was successfully coded.   Set the return code to 0
72889   ** to indicate no errors.
72890   */
72891   rc = 0;
72892
72893   /* Control jumps to here if an error is encountered above, or upon
72894   ** successful coding of the SELECT.
72895   */
72896 select_end:
72897
72898   /* Identify column names if results of the SELECT are to be output.
72899   */
72900   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
72901     generateColumnNames(pParse, pTabList, pEList);
72902   }
72903
72904   sqlite3DbFree(db, sAggInfo.aCol);
72905   sqlite3DbFree(db, sAggInfo.aFunc);
72906   return rc;
72907 }
72908
72909 #if defined(SQLITE_DEBUG)
72910 /*
72911 *******************************************************************************
72912 ** The following code is used for testing and debugging only.  The code
72913 ** that follows does not appear in normal builds.
72914 **
72915 ** These routines are used to print out the content of all or part of a 
72916 ** parse structures such as Select or Expr.  Such printouts are useful
72917 ** for helping to understand what is happening inside the code generator
72918 ** during the execution of complex SELECT statements.
72919 **
72920 ** These routine are not called anywhere from within the normal
72921 ** code base.  Then are intended to be called from within the debugger
72922 ** or from temporary "printf" statements inserted for debugging.
72923 */
72924 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
72925   if( p->token.z && p->token.n>0 ){
72926     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
72927   }else{
72928     sqlite3DebugPrintf("(%d", p->op);
72929   }
72930   if( p->pLeft ){
72931     sqlite3DebugPrintf(" ");
72932     sqlite3PrintExpr(p->pLeft);
72933   }
72934   if( p->pRight ){
72935     sqlite3DebugPrintf(" ");
72936     sqlite3PrintExpr(p->pRight);
72937   }
72938   sqlite3DebugPrintf(")");
72939 }
72940 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
72941   int i;
72942   for(i=0; i<pList->nExpr; i++){
72943     sqlite3PrintExpr(pList->a[i].pExpr);
72944     if( i<pList->nExpr-1 ){
72945       sqlite3DebugPrintf(", ");
72946     }
72947   }
72948 }
72949 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
72950   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
72951   sqlite3PrintExprList(p->pEList);
72952   sqlite3DebugPrintf("\n");
72953   if( p->pSrc ){
72954     char *zPrefix;
72955     int i;
72956     zPrefix = "FROM";
72957     for(i=0; i<p->pSrc->nSrc; i++){
72958       struct SrcList_item *pItem = &p->pSrc->a[i];
72959       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
72960       zPrefix = "";
72961       if( pItem->pSelect ){
72962         sqlite3DebugPrintf("(\n");
72963         sqlite3PrintSelect(pItem->pSelect, indent+10);
72964         sqlite3DebugPrintf("%*s)", indent+8, "");
72965       }else if( pItem->zName ){
72966         sqlite3DebugPrintf("%s", pItem->zName);
72967       }
72968       if( pItem->pTab ){
72969         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
72970       }
72971       if( pItem->zAlias ){
72972         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
72973       }
72974       if( i<p->pSrc->nSrc-1 ){
72975         sqlite3DebugPrintf(",");
72976       }
72977       sqlite3DebugPrintf("\n");
72978     }
72979   }
72980   if( p->pWhere ){
72981     sqlite3DebugPrintf("%*s WHERE ", indent, "");
72982     sqlite3PrintExpr(p->pWhere);
72983     sqlite3DebugPrintf("\n");
72984   }
72985   if( p->pGroupBy ){
72986     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
72987     sqlite3PrintExprList(p->pGroupBy);
72988     sqlite3DebugPrintf("\n");
72989   }
72990   if( p->pHaving ){
72991     sqlite3DebugPrintf("%*s HAVING ", indent, "");
72992     sqlite3PrintExpr(p->pHaving);
72993     sqlite3DebugPrintf("\n");
72994   }
72995   if( p->pOrderBy ){
72996     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
72997     sqlite3PrintExprList(p->pOrderBy);
72998     sqlite3DebugPrintf("\n");
72999   }
73000 }
73001 /* End of the structure debug printing code
73002 *****************************************************************************/
73003 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
73004
73005 /************** End of select.c **********************************************/
73006 /************** Begin file table.c *******************************************/
73007 /*
73008 ** 2001 September 15
73009 **
73010 ** The author disclaims copyright to this source code.  In place of
73011 ** a legal notice, here is a blessing:
73012 **
73013 **    May you do good and not evil.
73014 **    May you find forgiveness for yourself and forgive others.
73015 **    May you share freely, never taking more than you give.
73016 **
73017 *************************************************************************
73018 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
73019 ** interface routines.  These are just wrappers around the main
73020 ** interface routine of sqlite3_exec().
73021 **
73022 ** These routines are in a separate files so that they will not be linked
73023 ** if they are not used.
73024 **
73025 ** $Id: table.c,v 1.36 2008/07/08 22:28:49 shane Exp $
73026 */
73027
73028 #ifndef SQLITE_OMIT_GET_TABLE
73029
73030 /*
73031 ** This structure is used to pass data from sqlite3_get_table() through
73032 ** to the callback function is uses to build the result.
73033 */
73034 typedef struct TabResult {
73035   char **azResult;
73036   char *zErrMsg;
73037   int nResult;
73038   int nAlloc;
73039   int nRow;
73040   int nColumn;
73041   int nData;
73042   int rc;
73043 } TabResult;
73044
73045 /*
73046 ** This routine is called once for each row in the result table.  Its job
73047 ** is to fill in the TabResult structure appropriately, allocating new
73048 ** memory as necessary.
73049 */
73050 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
73051   TabResult *p = (TabResult*)pArg;
73052   int need;
73053   int i;
73054   char *z;
73055
73056   /* Make sure there is enough space in p->azResult to hold everything
73057   ** we need to remember from this invocation of the callback.
73058   */
73059   if( p->nRow==0 && argv!=0 ){
73060     need = nCol*2;
73061   }else{
73062     need = nCol;
73063   }
73064   if( p->nData + need >= p->nAlloc ){
73065     char **azNew;
73066     p->nAlloc = p->nAlloc*2 + need + 1;
73067     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
73068     if( azNew==0 ) goto malloc_failed;
73069     p->azResult = azNew;
73070   }
73071
73072   /* If this is the first row, then generate an extra row containing
73073   ** the names of all columns.
73074   */
73075   if( p->nRow==0 ){
73076     p->nColumn = nCol;
73077     for(i=0; i<nCol; i++){
73078       z = sqlite3_mprintf("%s", colv[i]);
73079       if( z==0 ) goto malloc_failed;
73080       p->azResult[p->nData++] = z;
73081     }
73082   }else if( p->nColumn!=nCol ){
73083     sqlite3_free(p->zErrMsg);
73084     p->zErrMsg = sqlite3_mprintf(
73085        "sqlite3_get_table() called with two or more incompatible queries"
73086     );
73087     p->rc = SQLITE_ERROR;
73088     return 1;
73089   }
73090
73091   /* Copy over the row data
73092   */
73093   if( argv!=0 ){
73094     for(i=0; i<nCol; i++){
73095       if( argv[i]==0 ){
73096         z = 0;
73097       }else{
73098         int n = strlen(argv[i])+1;
73099         z = sqlite3_malloc( n );
73100         if( z==0 ) goto malloc_failed;
73101         memcpy(z, argv[i], n);
73102       }
73103       p->azResult[p->nData++] = z;
73104     }
73105     p->nRow++;
73106   }
73107   return 0;
73108
73109 malloc_failed:
73110   p->rc = SQLITE_NOMEM;
73111   return 1;
73112 }
73113
73114 /*
73115 ** Query the database.  But instead of invoking a callback for each row,
73116 ** malloc() for space to hold the result and return the entire results
73117 ** at the conclusion of the call.
73118 **
73119 ** The result that is written to ***pazResult is held in memory obtained
73120 ** from malloc().  But the caller cannot free this memory directly.  
73121 ** Instead, the entire table should be passed to sqlite3_free_table() when
73122 ** the calling procedure is finished using it.
73123 */
73124 SQLITE_API int sqlite3_get_table(
73125   sqlite3 *db,                /* The database on which the SQL executes */
73126   const char *zSql,           /* The SQL to be executed */
73127   char ***pazResult,          /* Write the result table here */
73128   int *pnRow,                 /* Write the number of rows in the result here */
73129   int *pnColumn,              /* Write the number of columns of result here */
73130   char **pzErrMsg             /* Write error messages here */
73131 ){
73132   int rc;
73133   TabResult res;
73134
73135   *pazResult = 0;
73136   if( pnColumn ) *pnColumn = 0;
73137   if( pnRow ) *pnRow = 0;
73138   res.zErrMsg = 0;
73139   res.nResult = 0;
73140   res.nRow = 0;
73141   res.nColumn = 0;
73142   res.nData = 1;
73143   res.nAlloc = 20;
73144   res.rc = SQLITE_OK;
73145   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
73146   if( res.azResult==0 ){
73147      db->errCode = SQLITE_NOMEM;
73148      return SQLITE_NOMEM;
73149   }
73150   res.azResult[0] = 0;
73151   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
73152   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
73153   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
73154   if( (rc&0xff)==SQLITE_ABORT ){
73155     sqlite3_free_table(&res.azResult[1]);
73156     if( res.zErrMsg ){
73157       if( pzErrMsg ){
73158         sqlite3_free(*pzErrMsg);
73159         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
73160       }
73161       sqlite3_free(res.zErrMsg);
73162     }
73163     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
73164     return res.rc;
73165   }
73166   sqlite3_free(res.zErrMsg);
73167   if( rc!=SQLITE_OK ){
73168     sqlite3_free_table(&res.azResult[1]);
73169     return rc;
73170   }
73171   if( res.nAlloc>res.nData ){
73172     char **azNew;
73173     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
73174     if( azNew==0 ){
73175       sqlite3_free_table(&res.azResult[1]);
73176       db->errCode = SQLITE_NOMEM;
73177       return SQLITE_NOMEM;
73178     }
73179     res.nAlloc = res.nData+1;
73180     res.azResult = azNew;
73181   }
73182   *pazResult = &res.azResult[1];
73183   if( pnColumn ) *pnColumn = res.nColumn;
73184   if( pnRow ) *pnRow = res.nRow;
73185   return rc;
73186 }
73187
73188 /*
73189 ** This routine frees the space the sqlite3_get_table() malloced.
73190 */
73191 SQLITE_API void sqlite3_free_table(
73192   char **azResult            /* Result returned from from sqlite3_get_table() */
73193 ){
73194   if( azResult ){
73195     int i, n;
73196     azResult--;
73197     assert( azResult!=0 );
73198     n = SQLITE_PTR_TO_INT(azResult[0]);
73199     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
73200     sqlite3_free(azResult);
73201   }
73202 }
73203
73204 #endif /* SQLITE_OMIT_GET_TABLE */
73205
73206 /************** End of table.c ***********************************************/
73207 /************** Begin file trigger.c *****************************************/
73208 /*
73209 **
73210 ** The author disclaims copyright to this source code.  In place of
73211 ** a legal notice, here is a blessing:
73212 **
73213 **    May you do good and not evil.
73214 **    May you find forgiveness for yourself and forgive others.
73215 **    May you share freely, never taking more than you give.
73216 **
73217 *************************************************************************
73218 **
73219 **
73220 ** $Id: trigger.c,v 1.129 2008/08/20 16:35:10 drh Exp $
73221 */
73222
73223 #ifndef SQLITE_OMIT_TRIGGER
73224 /*
73225 ** Delete a linked list of TriggerStep structures.
73226 */
73227 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
73228   while( pTriggerStep ){
73229     TriggerStep * pTmp = pTriggerStep;
73230     pTriggerStep = pTriggerStep->pNext;
73231
73232     if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
73233     sqlite3ExprDelete(db, pTmp->pWhere);
73234     sqlite3ExprListDelete(db, pTmp->pExprList);
73235     sqlite3SelectDelete(db, pTmp->pSelect);
73236     sqlite3IdListDelete(db, pTmp->pIdList);
73237
73238     sqlite3DbFree(db, pTmp);
73239   }
73240 }
73241
73242 /*
73243 ** This is called by the parser when it sees a CREATE TRIGGER statement
73244 ** up to the point of the BEGIN before the trigger actions.  A Trigger
73245 ** structure is generated based on the information available and stored
73246 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
73247 ** sqlite3FinishTrigger() function is called to complete the trigger
73248 ** construction process.
73249 */
73250 SQLITE_PRIVATE void sqlite3BeginTrigger(
73251   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
73252   Token *pName1,      /* The name of the trigger */
73253   Token *pName2,      /* The name of the trigger */
73254   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
73255   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
73256   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
73257   SrcList *pTableName,/* The name of the table/view the trigger applies to */
73258   Expr *pWhen,        /* WHEN clause */
73259   int isTemp,         /* True if the TEMPORARY keyword is present */
73260   int noErr           /* Suppress errors if the trigger already exists */
73261 ){
73262   Trigger *pTrigger = 0;
73263   Table *pTab;
73264   char *zName = 0;        /* Name of the trigger */
73265   sqlite3 *db = pParse->db;
73266   int iDb;                /* The database to store the trigger in */
73267   Token *pName;           /* The unqualified db name */
73268   DbFixer sFix;
73269   int iTabDb;
73270
73271   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
73272   assert( pName2!=0 );
73273   if( isTemp ){
73274     /* If TEMP was specified, then the trigger name may not be qualified. */
73275     if( pName2->n>0 ){
73276       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
73277       goto trigger_cleanup;
73278     }
73279     iDb = 1;
73280     pName = pName1;
73281   }else{
73282     /* Figure out the db that the the trigger will be created in */
73283     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
73284     if( iDb<0 ){
73285       goto trigger_cleanup;
73286     }
73287   }
73288
73289   /* If the trigger name was unqualified, and the table is a temp table,
73290   ** then set iDb to 1 to create the trigger in the temporary database.
73291   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
73292   ** exist, the error is caught by the block below.
73293   */
73294   if( !pTableName || db->mallocFailed ){
73295     goto trigger_cleanup;
73296   }
73297   pTab = sqlite3SrcListLookup(pParse, pTableName);
73298   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
73299     iDb = 1;
73300   }
73301
73302   /* Ensure the table name matches database name and that the table exists */
73303   if( db->mallocFailed ) goto trigger_cleanup;
73304   assert( pTableName->nSrc==1 );
73305   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
73306       sqlite3FixSrcList(&sFix, pTableName) ){
73307     goto trigger_cleanup;
73308   }
73309   pTab = sqlite3SrcListLookup(pParse, pTableName);
73310   if( !pTab ){
73311     /* The table does not exist. */
73312     goto trigger_cleanup;
73313   }
73314   if( IsVirtual(pTab) ){
73315     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
73316     goto trigger_cleanup;
73317   }
73318
73319   /* Check that the trigger name is not reserved and that no trigger of the
73320   ** specified name exists */
73321   zName = sqlite3NameFromToken(db, pName);
73322   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
73323     goto trigger_cleanup;
73324   }
73325   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash), zName,strlen(zName)) ){
73326     if( !noErr ){
73327       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
73328     }
73329     goto trigger_cleanup;
73330   }
73331
73332   /* Do not create a trigger on a system table */
73333   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
73334     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
73335     pParse->nErr++;
73336     goto trigger_cleanup;
73337   }
73338
73339   /* INSTEAD of triggers are only for views and views only support INSTEAD
73340   ** of triggers.
73341   */
73342   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
73343     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
73344         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
73345     goto trigger_cleanup;
73346   }
73347   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
73348     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
73349         " trigger on table: %S", pTableName, 0);
73350     goto trigger_cleanup;
73351   }
73352   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73353
73354 #ifndef SQLITE_OMIT_AUTHORIZATION
73355   {
73356     int code = SQLITE_CREATE_TRIGGER;
73357     const char *zDb = db->aDb[iTabDb].zName;
73358     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
73359     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
73360     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
73361       goto trigger_cleanup;
73362     }
73363     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
73364       goto trigger_cleanup;
73365     }
73366   }
73367 #endif
73368
73369   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
73370   ** cannot appear on views.  So we might as well translate every
73371   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
73372   ** elsewhere.
73373   */
73374   if (tr_tm == TK_INSTEAD){
73375     tr_tm = TK_BEFORE;
73376   }
73377
73378   /* Build the Trigger object */
73379   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
73380   if( pTrigger==0 ) goto trigger_cleanup;
73381   pTrigger->name = zName;
73382   zName = 0;
73383   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
73384   pTrigger->pSchema = db->aDb[iDb].pSchema;
73385   pTrigger->pTabSchema = pTab->pSchema;
73386   pTrigger->op = op;
73387   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
73388   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
73389   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
73390   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
73391   assert( pParse->pNewTrigger==0 );
73392   pParse->pNewTrigger = pTrigger;
73393
73394 trigger_cleanup:
73395   sqlite3DbFree(db, zName);
73396   sqlite3SrcListDelete(db, pTableName);
73397   sqlite3IdListDelete(db, pColumns);
73398   sqlite3ExprDelete(db, pWhen);
73399   if( !pParse->pNewTrigger ){
73400     sqlite3DeleteTrigger(db, pTrigger);
73401   }else{
73402     assert( pParse->pNewTrigger==pTrigger );
73403   }
73404 }
73405
73406 /*
73407 ** This routine is called after all of the trigger actions have been parsed
73408 ** in order to complete the process of building the trigger.
73409 */
73410 SQLITE_PRIVATE void sqlite3FinishTrigger(
73411   Parse *pParse,          /* Parser context */
73412   TriggerStep *pStepList, /* The triggered program */
73413   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
73414 ){
73415   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
73416   sqlite3 *db = pParse->db;  /* The database */
73417   DbFixer sFix;
73418   int iDb;                   /* Database containing the trigger */
73419
73420   pTrig = pParse->pNewTrigger;
73421   pParse->pNewTrigger = 0;
73422   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
73423   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
73424   pTrig->step_list = pStepList;
73425   while( pStepList ){
73426     pStepList->pTrig = pTrig;
73427     pStepList = pStepList->pNext;
73428   }
73429   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
73430           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
73431     goto triggerfinish_cleanup;
73432   }
73433
73434   /* if we are not initializing, and this trigger is not on a TEMP table, 
73435   ** build the sqlite_master entry
73436   */
73437   if( !db->init.busy ){
73438     Vdbe *v;
73439     char *z;
73440
73441     /* Make an entry in the sqlite_master table */
73442     v = sqlite3GetVdbe(pParse);
73443     if( v==0 ) goto triggerfinish_cleanup;
73444     sqlite3BeginWriteOperation(pParse, 0, iDb);
73445     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
73446     sqlite3NestedParse(pParse,
73447        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
73448        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
73449        pTrig->table, z);
73450     sqlite3DbFree(db, z);
73451     sqlite3ChangeCookie(pParse, iDb);
73452     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
73453         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
73454     );
73455   }
73456
73457   if( db->init.busy ){
73458     int n;
73459     Table *pTab;
73460     Trigger *pDel;
73461     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
73462                      pTrig->name, strlen(pTrig->name), pTrig);
73463     if( pDel ){
73464       assert( pDel==pTrig );
73465       db->mallocFailed = 1;
73466       goto triggerfinish_cleanup;
73467     }
73468     n = strlen(pTrig->table) + 1;
73469     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
73470     assert( pTab!=0 );
73471     pTrig->pNext = pTab->pTrigger;
73472     pTab->pTrigger = pTrig;
73473     pTrig = 0;
73474   }
73475
73476 triggerfinish_cleanup:
73477   sqlite3DeleteTrigger(db, pTrig);
73478   assert( !pParse->pNewTrigger );
73479   sqlite3DeleteTriggerStep(db, pStepList);
73480 }
73481
73482 /*
73483 ** Make a copy of all components of the given trigger step.  This has
73484 ** the effect of copying all Expr.token.z values into memory obtained
73485 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
73486 ** all point to the input string that was fed to the parser.  But that
73487 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
73488 ** call that started the parser exits.  This routine makes a persistent
73489 ** copy of all the Expr.token.z strings so that the TriggerStep structure
73490 ** will be valid even after the sqlite3_exec() call returns.
73491 */
73492 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
73493   if( p->target.z ){
73494     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
73495     p->target.dyn = 1;
73496   }
73497   if( p->pSelect ){
73498     Select *pNew = sqlite3SelectDup(db, p->pSelect);
73499     sqlite3SelectDelete(db, p->pSelect);
73500     p->pSelect = pNew;
73501   }
73502   if( p->pWhere ){
73503     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
73504     sqlite3ExprDelete(db, p->pWhere);
73505     p->pWhere = pNew;
73506   }
73507   if( p->pExprList ){
73508     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
73509     sqlite3ExprListDelete(db, p->pExprList);
73510     p->pExprList = pNew;
73511   }
73512   if( p->pIdList ){
73513     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
73514     sqlite3IdListDelete(db, p->pIdList);
73515     p->pIdList = pNew;
73516   }
73517 }
73518
73519 /*
73520 ** Turn a SELECT statement (that the pSelect parameter points to) into
73521 ** a trigger step.  Return a pointer to a TriggerStep structure.
73522 **
73523 ** The parser calls this routine when it finds a SELECT statement in
73524 ** body of a TRIGGER.  
73525 */
73526 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
73527   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73528   if( pTriggerStep==0 ) {
73529     sqlite3SelectDelete(db, pSelect);
73530     return 0;
73531   }
73532
73533   pTriggerStep->op = TK_SELECT;
73534   pTriggerStep->pSelect = pSelect;
73535   pTriggerStep->orconf = OE_Default;
73536   sqlitePersistTriggerStep(db, pTriggerStep);
73537
73538   return pTriggerStep;
73539 }
73540
73541 /*
73542 ** Build a trigger step out of an INSERT statement.  Return a pointer
73543 ** to the new trigger step.
73544 **
73545 ** The parser calls this routine when it sees an INSERT inside the
73546 ** body of a trigger.
73547 */
73548 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
73549   sqlite3 *db,        /* The database connection */
73550   Token *pTableName,  /* Name of the table into which we insert */
73551   IdList *pColumn,    /* List of columns in pTableName to insert into */
73552   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
73553   Select *pSelect,    /* A SELECT statement that supplies values */
73554   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
73555 ){
73556   TriggerStep *pTriggerStep;
73557
73558   assert(pEList == 0 || pSelect == 0);
73559   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
73560
73561   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73562   if( pTriggerStep ){
73563     pTriggerStep->op = TK_INSERT;
73564     pTriggerStep->pSelect = pSelect;
73565     pTriggerStep->target  = *pTableName;
73566     pTriggerStep->pIdList = pColumn;
73567     pTriggerStep->pExprList = pEList;
73568     pTriggerStep->orconf = orconf;
73569     sqlitePersistTriggerStep(db, pTriggerStep);
73570   }else{
73571     sqlite3IdListDelete(db, pColumn);
73572     sqlite3ExprListDelete(db, pEList);
73573     sqlite3SelectDelete(db, pSelect);
73574   }
73575
73576   return pTriggerStep;
73577 }
73578
73579 /*
73580 ** Construct a trigger step that implements an UPDATE statement and return
73581 ** a pointer to that trigger step.  The parser calls this routine when it
73582 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
73583 */
73584 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
73585   sqlite3 *db,         /* The database connection */
73586   Token *pTableName,   /* Name of the table to be updated */
73587   ExprList *pEList,    /* The SET clause: list of column and new values */
73588   Expr *pWhere,        /* The WHERE clause */
73589   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
73590 ){
73591   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73592   if( pTriggerStep==0 ){
73593      sqlite3ExprListDelete(db, pEList);
73594      sqlite3ExprDelete(db, pWhere);
73595      return 0;
73596   }
73597
73598   pTriggerStep->op = TK_UPDATE;
73599   pTriggerStep->target  = *pTableName;
73600   pTriggerStep->pExprList = pEList;
73601   pTriggerStep->pWhere = pWhere;
73602   pTriggerStep->orconf = orconf;
73603   sqlitePersistTriggerStep(db, pTriggerStep);
73604
73605   return pTriggerStep;
73606 }
73607
73608 /*
73609 ** Construct a trigger step that implements a DELETE statement and return
73610 ** a pointer to that trigger step.  The parser calls this routine when it
73611 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
73612 */
73613 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
73614   sqlite3 *db,            /* Database connection */
73615   Token *pTableName,      /* The table from which rows are deleted */
73616   Expr *pWhere            /* The WHERE clause */
73617 ){
73618   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
73619   if( pTriggerStep==0 ){
73620     sqlite3ExprDelete(db, pWhere);
73621     return 0;
73622   }
73623
73624   pTriggerStep->op = TK_DELETE;
73625   pTriggerStep->target  = *pTableName;
73626   pTriggerStep->pWhere = pWhere;
73627   pTriggerStep->orconf = OE_Default;
73628   sqlitePersistTriggerStep(db, pTriggerStep);
73629
73630   return pTriggerStep;
73631 }
73632
73633 /* 
73634 ** Recursively delete a Trigger structure
73635 */
73636 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
73637   if( pTrigger==0 ) return;
73638   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
73639   sqlite3DbFree(db, pTrigger->name);
73640   sqlite3DbFree(db, pTrigger->table);
73641   sqlite3ExprDelete(db, pTrigger->pWhen);
73642   sqlite3IdListDelete(db, pTrigger->pColumns);
73643   if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
73644   sqlite3DbFree(db, pTrigger);
73645 }
73646
73647 /*
73648 ** This function is called to drop a trigger from the database schema. 
73649 **
73650 ** This may be called directly from the parser and therefore identifies
73651 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
73652 ** same job as this routine except it takes a pointer to the trigger
73653 ** instead of the trigger name.
73654 **/
73655 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
73656   Trigger *pTrigger = 0;
73657   int i;
73658   const char *zDb;
73659   const char *zName;
73660   int nName;
73661   sqlite3 *db = pParse->db;
73662
73663   if( db->mallocFailed ) goto drop_trigger_cleanup;
73664   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73665     goto drop_trigger_cleanup;
73666   }
73667
73668   assert( pName->nSrc==1 );
73669   zDb = pName->a[0].zDatabase;
73670   zName = pName->a[0].zName;
73671   nName = strlen(zName);
73672   for(i=OMIT_TEMPDB; i<db->nDb; i++){
73673     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
73674     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
73675     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
73676     if( pTrigger ) break;
73677   }
73678   if( !pTrigger ){
73679     if( !noErr ){
73680       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
73681     }
73682     goto drop_trigger_cleanup;
73683   }
73684   sqlite3DropTriggerPtr(pParse, pTrigger);
73685
73686 drop_trigger_cleanup:
73687   sqlite3SrcListDelete(db, pName);
73688 }
73689
73690 /*
73691 ** Return a pointer to the Table structure for the table that a trigger
73692 ** is set on.
73693 */
73694 static Table *tableOfTrigger(Trigger *pTrigger){
73695   int n = strlen(pTrigger->table) + 1;
73696   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
73697 }
73698
73699
73700 /*
73701 ** Drop a trigger given a pointer to that trigger. 
73702 */
73703 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
73704   Table   *pTable;
73705   Vdbe *v;
73706   sqlite3 *db = pParse->db;
73707   int iDb;
73708
73709   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
73710   assert( iDb>=0 && iDb<db->nDb );
73711   pTable = tableOfTrigger(pTrigger);
73712   assert( pTable );
73713   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
73714 #ifndef SQLITE_OMIT_AUTHORIZATION
73715   {
73716     int code = SQLITE_DROP_TRIGGER;
73717     const char *zDb = db->aDb[iDb].zName;
73718     const char *zTab = SCHEMA_TABLE(iDb);
73719     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
73720     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
73721       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
73722       return;
73723     }
73724   }
73725 #endif
73726
73727   /* Generate code to destroy the database record of the trigger.
73728   */
73729   assert( pTable!=0 );
73730   if( (v = sqlite3GetVdbe(pParse))!=0 ){
73731     int base;
73732     static const VdbeOpList dropTrigger[] = {
73733       { OP_Rewind,     0, ADDR(9),  0},
73734       { OP_String8,    0, 1,        0}, /* 1 */
73735       { OP_Column,     0, 1,        2},
73736       { OP_Ne,         2, ADDR(8),  1},
73737       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
73738       { OP_Column,     0, 0,        2},
73739       { OP_Ne,         2, ADDR(8),  1},
73740       { OP_Delete,     0, 0,        0},
73741       { OP_Next,       0, ADDR(1),  0}, /* 8 */
73742     };
73743
73744     sqlite3BeginWriteOperation(pParse, 0, iDb);
73745     sqlite3OpenMasterTable(pParse, iDb);
73746     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
73747     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
73748     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
73749     sqlite3ChangeCookie(pParse, iDb);
73750     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
73751     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
73752   }
73753 }
73754
73755 /*
73756 ** Remove a trigger from the hash tables of the sqlite* pointer.
73757 */
73758 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
73759   Trigger *pTrigger;
73760   int nName = strlen(zName);
73761   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
73762                                zName, nName, 0);
73763   if( pTrigger ){
73764     Table *pTable = tableOfTrigger(pTrigger);
73765     assert( pTable!=0 );
73766     if( pTable->pTrigger == pTrigger ){
73767       pTable->pTrigger = pTrigger->pNext;
73768     }else{
73769       Trigger *cc = pTable->pTrigger;
73770       while( cc ){ 
73771         if( cc->pNext == pTrigger ){
73772           cc->pNext = cc->pNext->pNext;
73773           break;
73774         }
73775         cc = cc->pNext;
73776       }
73777       assert(cc);
73778     }
73779     sqlite3DeleteTrigger(db, pTrigger);
73780     db->flags |= SQLITE_InternChanges;
73781   }
73782 }
73783
73784 /*
73785 ** pEList is the SET clause of an UPDATE statement.  Each entry
73786 ** in pEList is of the format <id>=<expr>.  If any of the entries
73787 ** in pEList have an <id> which matches an identifier in pIdList,
73788 ** then return TRUE.  If pIdList==NULL, then it is considered a
73789 ** wildcard that matches anything.  Likewise if pEList==NULL then
73790 ** it matches anything so always return true.  Return false only
73791 ** if there is no match.
73792 */
73793 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
73794   int e;
73795   if( !pIdList || !pEList ) return 1;
73796   for(e=0; e<pEList->nExpr; e++){
73797     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
73798   }
73799   return 0; 
73800 }
73801
73802 /*
73803 ** Return a bit vector to indicate what kind of triggers exist for operation
73804 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
73805 ** that are being updated.  Triggers only match if the ON clause of the
73806 ** trigger definition overlaps the set of columns being updated.
73807 **
73808 ** The returned bit vector is some combination of TRIGGER_BEFORE and
73809 ** TRIGGER_AFTER.
73810 */
73811 SQLITE_PRIVATE int sqlite3TriggersExist(
73812   Parse *pParse,          /* Used to check for recursive triggers */
73813   Table *pTab,            /* The table the contains the triggers */
73814   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
73815   ExprList *pChanges      /* Columns that change in an UPDATE statement */
73816 ){
73817   Trigger *pTrigger;
73818   int mask = 0;
73819
73820   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
73821   while( pTrigger ){
73822     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
73823       mask |= pTrigger->tr_tm;
73824     }
73825     pTrigger = pTrigger->pNext;
73826   }
73827   return mask;
73828 }
73829
73830 /*
73831 ** Convert the pStep->target token into a SrcList and return a pointer
73832 ** to that SrcList.
73833 **
73834 ** This routine adds a specific database name, if needed, to the target when
73835 ** forming the SrcList.  This prevents a trigger in one database from
73836 ** referring to a target in another database.  An exception is when the
73837 ** trigger is in TEMP in which case it can refer to any other database it
73838 ** wants.
73839 */
73840 static SrcList *targetSrcList(
73841   Parse *pParse,       /* The parsing context */
73842   TriggerStep *pStep   /* The trigger containing the target token */
73843 ){
73844   Token sDb;           /* Dummy database name token */
73845   int iDb;             /* Index of the database to use */
73846   SrcList *pSrc;       /* SrcList to be returned */
73847
73848   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
73849   if( iDb==0 || iDb>=2 ){
73850     assert( iDb<pParse->db->nDb );
73851     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
73852     sDb.n = strlen((char*)sDb.z);
73853     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
73854   } else {
73855     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
73856   }
73857   return pSrc;
73858 }
73859
73860 /*
73861 ** Generate VDBE code for zero or more statements inside the body of a
73862 ** trigger.  
73863 */
73864 static int codeTriggerProgram(
73865   Parse *pParse,            /* The parser context */
73866   TriggerStep *pStepList,   /* List of statements inside the trigger body */
73867   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
73868 ){
73869   TriggerStep * pTriggerStep = pStepList;
73870   int orconf;
73871   Vdbe *v = pParse->pVdbe;
73872   sqlite3 *db = pParse->db;
73873
73874   assert( pTriggerStep!=0 );
73875   assert( v!=0 );
73876   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
73877   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
73878   while( pTriggerStep ){
73879     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
73880     pParse->trigStack->orconf = orconf;
73881     switch( pTriggerStep->op ){
73882       case TK_SELECT: {
73883         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
73884         if( ss ){
73885           SelectDest dest;
73886
73887           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
73888           sqlite3Select(pParse, ss, &dest);
73889           sqlite3SelectDelete(db, ss);
73890         }
73891         break;
73892       }
73893       case TK_UPDATE: {
73894         SrcList *pSrc;
73895         pSrc = targetSrcList(pParse, pTriggerStep);
73896         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73897         sqlite3Update(pParse, pSrc,
73898                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
73899                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
73900         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73901         break;
73902       }
73903       case TK_INSERT: {
73904         SrcList *pSrc;
73905         pSrc = targetSrcList(pParse, pTriggerStep);
73906         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73907         sqlite3Insert(pParse, pSrc,
73908           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
73909           sqlite3SelectDup(db, pTriggerStep->pSelect), 
73910           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
73911         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73912         break;
73913       }
73914       case TK_DELETE: {
73915         SrcList *pSrc;
73916         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
73917         pSrc = targetSrcList(pParse, pTriggerStep);
73918         sqlite3DeleteFrom(pParse, pSrc, 
73919                           sqlite3ExprDup(db, pTriggerStep->pWhere));
73920         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
73921         break;
73922       }
73923       default:
73924         assert(0);
73925     } 
73926     pTriggerStep = pTriggerStep->pNext;
73927   }
73928   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
73929   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
73930
73931   return 0;
73932 }
73933
73934 /*
73935 ** This is called to code FOR EACH ROW triggers.
73936 **
73937 ** When the code that this function generates is executed, the following 
73938 ** must be true:
73939 **
73940 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
73941 **    can be indices of cursors in temporary tables.  See below.)
73942 **
73943 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
73944 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
73945 **    a row containing values to be substituted for new.* expressions in the
73946 **    trigger program(s).
73947 **
73948 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
73949 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
73950 **    a row containing values to be substituted for old.* expressions in the
73951 **    trigger program(s).
73952 **
73953 ** If they are not NULL, the piOldColMask and piNewColMask output variables
73954 ** are set to values that describe the columns used by the trigger program
73955 ** in the OLD.* and NEW.* tables respectively. If column N of the 
73956 ** pseudo-table is read at least once, the corresponding bit of the output
73957 ** mask is set. If a column with an index greater than 32 is read, the
73958 ** output mask is set to the special value 0xffffffff.
73959 **
73960 */
73961 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
73962   Parse *pParse,       /* Parse context */
73963   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
73964   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
73965   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
73966   Table *pTab,         /* The table to code triggers from */
73967   int newIdx,          /* The indice of the "new" row to access */
73968   int oldIdx,          /* The indice of the "old" row to access */
73969   int orconf,          /* ON CONFLICT policy */
73970   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
73971   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
73972   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
73973 ){
73974   Trigger *p;
73975   sqlite3 *db = pParse->db;
73976   TriggerStack trigStackEntry;
73977
73978   trigStackEntry.oldColMask = 0;
73979   trigStackEntry.newColMask = 0;
73980
73981   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
73982   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
73983
73984   assert(newIdx != -1 || oldIdx != -1);
73985
73986   for(p=pTab->pTrigger; p; p=p->pNext){
73987     int fire_this = 0;
73988
73989     /* Determine whether we should code this trigger */
73990     if( 
73991       p->op==op && 
73992       p->tr_tm==tr_tm && 
73993       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
73994       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
73995     ){
73996       TriggerStack *pS;      /* Pointer to trigger-stack entry */
73997       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
73998       if( !pS ){
73999         fire_this = 1;
74000       }
74001 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
74002       else{
74003         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
74004             p->name);
74005         return SQLITE_ERROR;
74006       }
74007 #endif
74008     }
74009  
74010     if( fire_this ){
74011       int endTrigger;
74012       Expr * whenExpr;
74013       AuthContext sContext;
74014       NameContext sNC;
74015
74016 #ifndef SQLITE_OMIT_TRACE
74017       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
74018                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
74019                         P4_DYNAMIC);
74020 #endif
74021       memset(&sNC, 0, sizeof(sNC));
74022       sNC.pParse = pParse;
74023
74024       /* Push an entry on to the trigger stack */
74025       trigStackEntry.pTrigger = p;
74026       trigStackEntry.newIdx = newIdx;
74027       trigStackEntry.oldIdx = oldIdx;
74028       trigStackEntry.pTab = pTab;
74029       trigStackEntry.pNext = pParse->trigStack;
74030       trigStackEntry.ignoreJump = ignoreJump;
74031       pParse->trigStack = &trigStackEntry;
74032       sqlite3AuthContextPush(pParse, &sContext, p->name);
74033
74034       /* code the WHEN clause */
74035       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
74036       whenExpr = sqlite3ExprDup(db, p->pWhen);
74037       if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
74038         pParse->trigStack = trigStackEntry.pNext;
74039         sqlite3ExprDelete(db, whenExpr);
74040         return 1;
74041       }
74042       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
74043       sqlite3ExprDelete(db, whenExpr);
74044
74045       codeTriggerProgram(pParse, p->step_list, orconf); 
74046
74047       /* Pop the entry off the trigger stack */
74048       pParse->trigStack = trigStackEntry.pNext;
74049       sqlite3AuthContextPop(&sContext);
74050
74051       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
74052     }
74053   }
74054   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
74055   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
74056   return 0;
74057 }
74058 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74059
74060 /************** End of trigger.c *********************************************/
74061 /************** Begin file update.c ******************************************/
74062 /*
74063 ** 2001 September 15
74064 **
74065 ** The author disclaims copyright to this source code.  In place of
74066 ** a legal notice, here is a blessing:
74067 **
74068 **    May you do good and not evil.
74069 **    May you find forgiveness for yourself and forgive others.
74070 **    May you share freely, never taking more than you give.
74071 **
74072 *************************************************************************
74073 ** This file contains C code routines that are called by the parser
74074 ** to handle UPDATE statements.
74075 **
74076 ** $Id: update.c,v 1.185 2008/10/09 18:48:31 danielk1977 Exp $
74077 */
74078
74079 #ifndef SQLITE_OMIT_VIRTUALTABLE
74080 /* Forward declaration */
74081 static void updateVirtualTable(
74082   Parse *pParse,       /* The parsing context */
74083   SrcList *pSrc,       /* The virtual table to be modified */
74084   Table *pTab,         /* The virtual table */
74085   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
74086   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
74087   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
74088   Expr *pWhere         /* WHERE clause of the UPDATE statement */
74089 );
74090 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74091
74092 /*
74093 ** The most recently coded instruction was an OP_Column to retrieve the
74094 ** i-th column of table pTab. This routine sets the P4 parameter of the 
74095 ** OP_Column to the default value, if any.
74096 **
74097 ** The default value of a column is specified by a DEFAULT clause in the 
74098 ** column definition. This was either supplied by the user when the table
74099 ** was created, or added later to the table definition by an ALTER TABLE
74100 ** command. If the latter, then the row-records in the table btree on disk
74101 ** may not contain a value for the column and the default value, taken
74102 ** from the P4 parameter of the OP_Column instruction, is returned instead.
74103 ** If the former, then all row-records are guaranteed to include a value
74104 ** for the column and the P4 value is not required.
74105 **
74106 ** Column definitions created by an ALTER TABLE command may only have 
74107 ** literal default values specified: a number, null or a string. (If a more
74108 ** complicated default expression value was provided, it is evaluated 
74109 ** when the ALTER TABLE is executed and one of the literal values written
74110 ** into the sqlite_master table.)
74111 **
74112 ** Therefore, the P4 parameter is only required if the default value for
74113 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
74114 ** function is capable of transforming these types of expressions into
74115 ** sqlite3_value objects.
74116 */
74117 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
74118   if( pTab && !pTab->pSelect ){
74119     sqlite3_value *pValue;
74120     u8 enc = ENC(sqlite3VdbeDb(v));
74121     Column *pCol = &pTab->aCol[i];
74122     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
74123     assert( i<pTab->nCol );
74124     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
74125                          pCol->affinity, &pValue);
74126     if( pValue ){
74127       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
74128     }
74129   }
74130 }
74131
74132 /*
74133 ** Process an UPDATE statement.
74134 **
74135 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
74136 **          \_______/ \________/     \______/       \________________/
74137 *            onError   pTabList      pChanges             pWhere
74138 */
74139 SQLITE_PRIVATE void sqlite3Update(
74140   Parse *pParse,         /* The parser context */
74141   SrcList *pTabList,     /* The table in which we should change things */
74142   ExprList *pChanges,    /* Things to be changed */
74143   Expr *pWhere,          /* The WHERE clause.  May be null */
74144   int onError            /* How to handle constraint errors */
74145 ){
74146   int i, j;              /* Loop counters */
74147   Table *pTab;           /* The table to be updated */
74148   int addr = 0;          /* VDBE instruction address of the start of the loop */
74149   WhereInfo *pWInfo;     /* Information about the WHERE clause */
74150   Vdbe *v;               /* The virtual database engine */
74151   Index *pIdx;           /* For looping over indices */
74152   int nIdx;              /* Number of indices that need updating */
74153   int iCur;              /* VDBE Cursor number of pTab */
74154   sqlite3 *db;           /* The database structure */
74155   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
74156   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
74157                          ** an expression for the i-th column of the table.
74158                          ** aXRef[i]==-1 if the i-th column is not changed. */
74159   int chngRowid;         /* True if the record number is being changed */
74160   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
74161   int openAll = 0;       /* True if all indices need to be opened */
74162   AuthContext sContext;  /* The authorization context */
74163   NameContext sNC;       /* The name-context to resolve expressions in */
74164   int iDb;               /* Database containing the table being updated */
74165   int j1;                /* Addresses of jump instructions */
74166   int okOnePass;         /* True for one-pass algorithm without the FIFO */
74167
74168 #ifndef SQLITE_OMIT_TRIGGER
74169   int isView;                  /* Trying to update a view */
74170   int triggers_exist = 0;      /* True if any row triggers exist */
74171 #endif
74172   int iBeginAfterTrigger;      /* Address of after trigger program */
74173   int iEndAfterTrigger;        /* Exit of after trigger program */
74174   int iBeginBeforeTrigger;     /* Address of before trigger program */
74175   int iEndBeforeTrigger;       /* Exit of before trigger program */
74176   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
74177   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
74178
74179   int newIdx      = -1;  /* index of trigger "new" temp table       */
74180   int oldIdx      = -1;  /* index of trigger "old" temp table       */
74181
74182   /* Register Allocations */
74183   int regRowCount = 0;   /* A count of rows changed */
74184   int regOldRowid;       /* The old rowid */
74185   int regNewRowid;       /* The new rowid */
74186   int regData;           /* New data for the row */
74187
74188   sContext.pParse = 0;
74189   db = pParse->db;
74190   if( pParse->nErr || db->mallocFailed ){
74191     goto update_cleanup;
74192   }
74193   assert( pTabList->nSrc==1 );
74194
74195   /* Locate the table which we want to update. 
74196   */
74197   pTab = sqlite3SrcListLookup(pParse, pTabList);
74198   if( pTab==0 ) goto update_cleanup;
74199   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
74200
74201   /* Figure out if we have any triggers and if the table being
74202   ** updated is a view
74203   */
74204 #ifndef SQLITE_OMIT_TRIGGER
74205   triggers_exist = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges);
74206   isView = pTab->pSelect!=0;
74207 #else
74208 # define triggers_exist 0
74209 # define isView 0
74210 #endif
74211 #ifdef SQLITE_OMIT_VIEW
74212 # undef isView
74213 # define isView 0
74214 #endif
74215
74216   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
74217     goto update_cleanup;
74218   }
74219   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74220     goto update_cleanup;
74221   }
74222   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
74223   if( aXRef==0 ) goto update_cleanup;
74224   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
74225
74226   /* If there are FOR EACH ROW triggers, allocate cursors for the
74227   ** special OLD and NEW tables
74228   */
74229   if( triggers_exist ){
74230     newIdx = pParse->nTab++;
74231     oldIdx = pParse->nTab++;
74232   }
74233
74234   /* Allocate a cursors for the main database table and for all indices.
74235   ** The index cursors might not be used, but if they are used they
74236   ** need to occur right after the database cursor.  So go ahead and
74237   ** allocate enough space, just in case.
74238   */
74239   pTabList->a[0].iCursor = iCur = pParse->nTab++;
74240   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74241     pParse->nTab++;
74242   }
74243
74244   /* Initialize the name-context */
74245   memset(&sNC, 0, sizeof(sNC));
74246   sNC.pParse = pParse;
74247   sNC.pSrcList = pTabList;
74248
74249   /* Resolve the column names in all the expressions of the
74250   ** of the UPDATE statement.  Also find the column index
74251   ** for each column to be updated in the pChanges array.  For each
74252   ** column to be updated, make sure we have authorization to change
74253   ** that column.
74254   */
74255   chngRowid = 0;
74256   for(i=0; i<pChanges->nExpr; i++){
74257     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
74258       goto update_cleanup;
74259     }
74260     for(j=0; j<pTab->nCol; j++){
74261       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
74262         if( j==pTab->iPKey ){
74263           chngRowid = 1;
74264           pRowidExpr = pChanges->a[i].pExpr;
74265         }
74266         aXRef[j] = i;
74267         break;
74268       }
74269     }
74270     if( j>=pTab->nCol ){
74271       if( sqlite3IsRowid(pChanges->a[i].zName) ){
74272         chngRowid = 1;
74273         pRowidExpr = pChanges->a[i].pExpr;
74274       }else{
74275         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
74276         goto update_cleanup;
74277       }
74278     }
74279 #ifndef SQLITE_OMIT_AUTHORIZATION
74280     {
74281       int rc;
74282       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
74283                            pTab->aCol[j].zName, db->aDb[iDb].zName);
74284       if( rc==SQLITE_DENY ){
74285         goto update_cleanup;
74286       }else if( rc==SQLITE_IGNORE ){
74287         aXRef[j] = -1;
74288       }
74289     }
74290 #endif
74291   }
74292
74293   /* Allocate memory for the array aRegIdx[].  There is one entry in the
74294   ** array for each index associated with table being updated.  Fill in
74295   ** the value with a register number for indices that are to be used
74296   ** and with zero for unused indices.
74297   */
74298   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
74299   if( nIdx>0 ){
74300     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
74301     if( aRegIdx==0 ) goto update_cleanup;
74302   }
74303   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
74304     int reg;
74305     if( chngRowid ){
74306       reg = ++pParse->nMem;
74307     }else{
74308       reg = 0;
74309       for(i=0; i<pIdx->nColumn; i++){
74310         if( aXRef[pIdx->aiColumn[i]]>=0 ){
74311           reg = ++pParse->nMem;
74312           break;
74313         }
74314       }
74315     }
74316     aRegIdx[j] = reg;
74317   }
74318
74319   /* Allocate a block of register used to store the change record
74320   ** sent to sqlite3GenerateConstraintChecks().  There are either
74321   ** one or two registers for holding the rowid.  One rowid register
74322   ** is used if chngRowid is false and two are used if chngRowid is
74323   ** true.  Following these are pTab->nCol register holding column
74324   ** data.
74325   */
74326   regOldRowid = regNewRowid = pParse->nMem + 1;
74327   pParse->nMem += pTab->nCol + 1;
74328   if( chngRowid ){
74329     regNewRowid++;
74330     pParse->nMem++;
74331   }
74332   regData = regNewRowid+1;
74333  
74334
74335   /* Begin generating code.
74336   */
74337   v = sqlite3GetVdbe(pParse);
74338   if( v==0 ) goto update_cleanup;
74339   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74340   sqlite3BeginWriteOperation(pParse, 1, iDb);
74341
74342 #ifndef SQLITE_OMIT_VIRTUALTABLE
74343   /* Virtual tables must be handled separately */
74344   if( IsVirtual(pTab) ){
74345     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
74346                        pWhere);
74347     pWhere = 0;
74348     pTabList = 0;
74349     goto update_cleanup;
74350   }
74351 #endif
74352
74353   /* Start the view context
74354   */
74355   if( isView ){
74356     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
74357   }
74358
74359   /* Generate the code for triggers.
74360   */
74361   if( triggers_exist ){
74362     int iGoto;
74363
74364     /* Create pseudo-tables for NEW and OLD
74365     */
74366     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
74367     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
74368     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
74369     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
74370
74371     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74372     addr = sqlite3VdbeMakeLabel(v);
74373     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
74374     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
74375           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
74376       goto update_cleanup;
74377     }
74378     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74379     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
74380     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
74381           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
74382       goto update_cleanup;
74383     }
74384     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74385     sqlite3VdbeJumpHere(v, iGoto);
74386   }
74387
74388   /* If we are trying to update a view, realize that view into
74389   ** a ephemeral table.
74390   */
74391 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
74392   if( isView ){
74393     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
74394   }
74395 #endif
74396
74397   /* Resolve the column names in all the expressions in the
74398   ** WHERE clause.
74399   */
74400   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
74401     goto update_cleanup;
74402   }
74403
74404   /* Begin the database scan
74405   */
74406   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
74407   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
74408                              WHERE_ONEPASS_DESIRED);
74409   if( pWInfo==0 ) goto update_cleanup;
74410   okOnePass = pWInfo->okOnePass;
74411
74412   /* Remember the rowid of every item to be updated.
74413   */
74414   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
74415   if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0);
74416
74417   /* End the database scan loop.
74418   */
74419   sqlite3WhereEnd(pWInfo);
74420
74421   /* Initialize the count of updated rows
74422   */
74423   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
74424     regRowCount = ++pParse->nMem;
74425     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74426   }
74427
74428   if( !isView && !IsVirtual(pTab) ){
74429     /* 
74430     ** Open every index that needs updating.  Note that if any
74431     ** index could potentially invoke a REPLACE conflict resolution 
74432     ** action, then we need to open all indices because we might need
74433     ** to be deleting some records.
74434     */
74435     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
74436     if( onError==OE_Replace ){
74437       openAll = 1;
74438     }else{
74439       openAll = 0;
74440       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74441         if( pIdx->onError==OE_Replace ){
74442           openAll = 1;
74443           break;
74444         }
74445       }
74446     }
74447     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
74448       if( openAll || aRegIdx[i]>0 ){
74449         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
74450         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
74451                        (char*)pKey, P4_KEYINFO_HANDOFF);
74452         assert( pParse->nTab>iCur+i+1 );
74453       }
74454     }
74455   }
74456   
74457   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
74458   if( triggers_exist ){
74459     sqlite3VdbeResolveLabel(v, addr);
74460   }
74461
74462   /* Top of the update loop */
74463   if( okOnePass ){
74464     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
74465     addr = sqlite3VdbeAddOp0(v, OP_Goto);
74466     sqlite3VdbeJumpHere(v, a1);
74467   }else{
74468     addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0);
74469   }
74470
74471   if( triggers_exist ){
74472     int regRowid;
74473     int regRow;
74474     int regCols;
74475
74476     /* Make cursor iCur point to the record that is being updated.
74477     */
74478     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
74479
74480     /* Generate the OLD table
74481     */
74482     regRowid = sqlite3GetTempReg(pParse);
74483     regRow = sqlite3GetTempReg(pParse);
74484     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
74485     if( !old_col_mask ){
74486       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
74487     }else{
74488       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
74489     }
74490     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
74491
74492     /* Generate the NEW table
74493     */
74494     if( chngRowid ){
74495       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
74496       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74497     }else{
74498       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
74499     }
74500     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
74501     for(i=0; i<pTab->nCol; i++){
74502       if( i==pTab->iPKey ){
74503         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
74504         continue;
74505       }
74506       j = aXRef[i];
74507       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
74508         if( j<0 ){
74509           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
74510           sqlite3ColumnDefault(v, pTab, i);
74511         }else{
74512           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
74513         }
74514       }else{
74515         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
74516       }
74517     }
74518     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
74519     if( !isView ){
74520       sqlite3TableAffinityStr(v, pTab);
74521       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
74522     }
74523     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
74524     /* if( pParse->nErr ) goto update_cleanup; */
74525     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
74526     sqlite3ReleaseTempReg(pParse, regRowid);
74527     sqlite3ReleaseTempReg(pParse, regRow);
74528
74529     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
74530     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
74531   }
74532
74533   if( !isView && !IsVirtual(pTab) ){
74534     /* Loop over every record that needs updating.  We have to load
74535     ** the old data for each record to be updated because some columns
74536     ** might not change and we will need to copy the old value.
74537     ** Also, the old data is needed to delete the old index entries.
74538     ** So make the cursor point at the old record.
74539     */
74540     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
74541
74542     /* If the record number will change, push the record number as it
74543     ** will be after the update. (The old record number is currently
74544     ** on top of the stack.)
74545     */
74546     if( chngRowid ){
74547       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
74548       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
74549     }
74550
74551     /* Compute new data for this record.  
74552     */
74553     for(i=0; i<pTab->nCol; i++){
74554       if( i==pTab->iPKey ){
74555         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
74556         continue;
74557       }
74558       j = aXRef[i];
74559       if( j<0 ){
74560         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
74561         sqlite3ColumnDefault(v, pTab, i);
74562       }else{
74563         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
74564       }
74565     }
74566
74567     /* Do constraint checks
74568     */
74569     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
74570                                     aRegIdx, chngRowid, 1,
74571                                     onError, addr);
74572
74573     /* Delete the old indices for the current record.
74574     */
74575     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
74576     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
74577
74578     /* If changing the record number, delete the old record.
74579     */
74580     if( chngRowid ){
74581       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
74582     }
74583     sqlite3VdbeJumpHere(v, j1);
74584
74585     /* Create the new index entries and the new record.
74586     */
74587     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
74588                              aRegIdx, chngRowid, 1, -1, 0);
74589   }
74590
74591   /* Increment the row counter 
74592   */
74593   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
74594     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74595   }
74596
74597   /* If there are triggers, close all the cursors after each iteration
74598   ** through the loop.  The fire the after triggers.
74599   */
74600   if( triggers_exist ){
74601     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
74602     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
74603   }
74604
74605   /* Repeat the above with the next record to be updated, until
74606   ** all record selected by the WHERE clause have been updated.
74607   */
74608   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
74609   sqlite3VdbeJumpHere(v, addr);
74610
74611   /* Close all tables */
74612   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
74613     if( openAll || aRegIdx[i]>0 ){
74614       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
74615     }
74616   }
74617   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
74618   if( triggers_exist ){
74619     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
74620     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
74621   }
74622
74623   /*
74624   ** Return the number of rows that were changed. If this routine is 
74625   ** generating code because of a call to sqlite3NestedParse(), do not
74626   ** invoke the callback function.
74627   */
74628   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
74629     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
74630     sqlite3VdbeSetNumCols(v, 1);
74631     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC);
74632   }
74633
74634 update_cleanup:
74635   sqlite3AuthContextPop(&sContext);
74636   sqlite3DbFree(db, aRegIdx);
74637   sqlite3DbFree(db, aXRef);
74638   sqlite3SrcListDelete(db, pTabList);
74639   sqlite3ExprListDelete(db, pChanges);
74640   sqlite3ExprDelete(db, pWhere);
74641   return;
74642 }
74643
74644 #ifndef SQLITE_OMIT_VIRTUALTABLE
74645 /*
74646 ** Generate code for an UPDATE of a virtual table.
74647 **
74648 ** The strategy is that we create an ephemerial table that contains
74649 ** for each row to be changed:
74650 **
74651 **   (A)  The original rowid of that row.
74652 **   (B)  The revised rowid for the row. (note1)
74653 **   (C)  The content of every column in the row.
74654 **
74655 ** Then we loop over this ephemeral table and for each row in
74656 ** the ephermeral table call VUpdate.
74657 **
74658 ** When finished, drop the ephemeral table.
74659 **
74660 ** (note1) Actually, if we know in advance that (A) is always the same
74661 ** as (B) we only store (A), then duplicate (A) when pulling
74662 ** it out of the ephemeral table before calling VUpdate.
74663 */
74664 static void updateVirtualTable(
74665   Parse *pParse,       /* The parsing context */
74666   SrcList *pSrc,       /* The virtual table to be modified */
74667   Table *pTab,         /* The virtual table */
74668   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
74669   Expr *pRowid,        /* Expression used to recompute the rowid */
74670   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
74671   Expr *pWhere         /* WHERE clause of the UPDATE statement */
74672 ){
74673   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
74674   ExprList *pEList = 0;     /* The result set of the SELECT statement */
74675   Select *pSelect = 0;      /* The SELECT statement */
74676   Expr *pExpr;              /* Temporary expression */
74677   int ephemTab;             /* Table holding the result of the SELECT */
74678   int i;                    /* Loop counter */
74679   int addr;                 /* Address of top of loop */
74680   int iReg;                 /* First register in set passed to OP_VUpdate */
74681   sqlite3 *db = pParse->db; /* Database connection */
74682   const char *pVtab = (const char*)pTab->pVtab;
74683   SelectDest dest;
74684
74685   /* Construct the SELECT statement that will find the new values for
74686   ** all updated rows. 
74687   */
74688   pEList = sqlite3ExprListAppend(pParse, 0, 
74689                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
74690   if( pRowid ){
74691     pEList = sqlite3ExprListAppend(pParse, pEList,
74692                                    sqlite3ExprDup(db, pRowid), 0);
74693   }
74694   assert( pTab->iPKey<0 );
74695   for(i=0; i<pTab->nCol; i++){
74696     if( aXRef[i]>=0 ){
74697       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
74698     }else{
74699       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
74700     }
74701     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
74702   }
74703   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
74704   
74705   /* Create the ephemeral table into which the update results will
74706   ** be stored.
74707   */
74708   assert( v );
74709   ephemTab = pParse->nTab++;
74710   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
74711
74712   /* fill the ephemeral table 
74713   */
74714   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
74715   sqlite3Select(pParse, pSelect, &dest);
74716
74717   /* Generate code to scan the ephemeral table and call VUpdate. */
74718   iReg = ++pParse->nMem;
74719   pParse->nMem += pTab->nCol+1;
74720   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
74721   addr = sqlite3VdbeCurrentAddr(v);
74722   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
74723   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
74724   for(i=0; i<pTab->nCol; i++){
74725     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
74726   }
74727   sqlite3VtabMakeWritable(pParse, pTab);
74728   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
74729   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
74730   sqlite3VdbeJumpHere(v, addr-1);
74731   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
74732
74733   /* Cleanup */
74734   sqlite3SelectDelete(db, pSelect);  
74735 }
74736 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74737
74738 /* Make sure "isView" gets undefined in case this file becomes part of
74739 ** the amalgamation - so that subsequent files do not see isView as a
74740 ** macro. */
74741 #undef isView
74742
74743 /************** End of update.c **********************************************/
74744 /************** Begin file vacuum.c ******************************************/
74745 /*
74746 ** 2003 April 6
74747 **
74748 ** The author disclaims copyright to this source code.  In place of
74749 ** a legal notice, here is a blessing:
74750 **
74751 **    May you do good and not evil.
74752 **    May you find forgiveness for yourself and forgive others.
74753 **    May you share freely, never taking more than you give.
74754 **
74755 *************************************************************************
74756 ** This file contains code used to implement the VACUUM command.
74757 **
74758 ** Most of the code in this file may be omitted by defining the
74759 ** SQLITE_OMIT_VACUUM macro.
74760 **
74761 ** $Id: vacuum.c,v 1.83 2008/08/26 21:07:27 drh Exp $
74762 */
74763
74764 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
74765 /*
74766 ** Execute zSql on database db. Return an error code.
74767 */
74768 static int execSql(sqlite3 *db, const char *zSql){
74769   sqlite3_stmt *pStmt;
74770   if( !zSql ){
74771     return SQLITE_NOMEM;
74772   }
74773   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
74774     return sqlite3_errcode(db);
74775   }
74776   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
74777   return sqlite3_finalize(pStmt);
74778 }
74779
74780 /*
74781 ** Execute zSql on database db. The statement returns exactly
74782 ** one column. Execute this as SQL on the same database.
74783 */
74784 static int execExecSql(sqlite3 *db, const char *zSql){
74785   sqlite3_stmt *pStmt;
74786   int rc;
74787
74788   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
74789   if( rc!=SQLITE_OK ) return rc;
74790
74791   while( SQLITE_ROW==sqlite3_step(pStmt) ){
74792     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
74793     if( rc!=SQLITE_OK ){
74794       sqlite3_finalize(pStmt);
74795       return rc;
74796     }
74797   }
74798
74799   return sqlite3_finalize(pStmt);
74800 }
74801
74802 /*
74803 ** The non-standard VACUUM command is used to clean up the database,
74804 ** collapse free space, etc.  It is modelled after the VACUUM command
74805 ** in PostgreSQL.
74806 **
74807 ** In version 1.0.x of SQLite, the VACUUM command would call
74808 ** gdbm_reorganize() on all the database tables.  But beginning
74809 ** with 2.0.0, SQLite no longer uses GDBM so this command has
74810 ** become a no-op.
74811 */
74812 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
74813   Vdbe *v = sqlite3GetVdbe(pParse);
74814   if( v ){
74815     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
74816   }
74817   return;
74818 }
74819
74820 /*
74821 ** This routine implements the OP_Vacuum opcode of the VDBE.
74822 */
74823 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
74824   int rc = SQLITE_OK;     /* Return code from service routines */
74825   Btree *pMain;           /* The database being vacuumed */
74826   Pager *pMainPager;      /* Pager for database being vacuumed */
74827   Btree *pTemp;           /* The temporary database we vacuum into */
74828   char *zSql = 0;         /* SQL statements */
74829   int saved_flags;        /* Saved value of the db->flags */
74830   int saved_nChange;      /* Saved value of db->nChange */
74831   int saved_nTotalChange; /* Saved value of db->nTotalChange */
74832   Db *pDb = 0;            /* Database to detach at end of vacuum */
74833   int isMemDb;            /* True is vacuuming a :memory: database */
74834   int nRes;
74835
74836   /* Save the current value of the write-schema flag before setting it. */
74837   saved_flags = db->flags;
74838   saved_nChange = db->nChange;
74839   saved_nTotalChange = db->nTotalChange;
74840   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
74841
74842   if( !db->autoCommit ){
74843     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
74844     rc = SQLITE_ERROR;
74845     goto end_of_vacuum;
74846   }
74847   pMain = db->aDb[0].pBt;
74848   pMainPager = sqlite3BtreePager(pMain);
74849   isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
74850
74851   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
74852   ** can be set to 'off' for this file, as it is not recovered if a crash
74853   ** occurs anyway. The integrity of the database is maintained by a
74854   ** (possibly synchronous) transaction opened on the main database before
74855   ** sqlite3BtreeCopyFile() is called.
74856   **
74857   ** An optimisation would be to use a non-journaled pager.
74858   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
74859   ** that actually made the VACUUM run slower.  Very little journalling
74860   ** actually occurs when doing a vacuum since the vacuum_db is initially
74861   ** empty.  Only the journal header is written.  Apparently it takes more
74862   ** time to parse and run the PRAGMA to turn journalling off than it does
74863   ** to write the journal header file.
74864   */
74865   zSql = "ATTACH '' AS vacuum_db;";
74866   rc = execSql(db, zSql);
74867   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74868   pDb = &db->aDb[db->nDb-1];
74869   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
74870   pTemp = db->aDb[db->nDb-1].pBt;
74871
74872   nRes = sqlite3BtreeGetReserve(pMain);
74873
74874   /* A VACUUM cannot change the pagesize of an encrypted database. */
74875 #ifdef SQLITE_HAS_CODEC
74876   if( db->nextPagesize ){
74877     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
74878     int nKey;
74879     char *zKey;
74880     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
74881     if( nKey ) db->nextPagesize = 0;
74882   }
74883 #endif
74884
74885   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
74886    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes))
74887    || db->mallocFailed 
74888   ){
74889     rc = SQLITE_NOMEM;
74890     goto end_of_vacuum;
74891   }
74892   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
74893   if( rc!=SQLITE_OK ){
74894     goto end_of_vacuum;
74895   }
74896
74897 #ifndef SQLITE_OMIT_AUTOVACUUM
74898   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
74899                                            sqlite3BtreeGetAutoVacuum(pMain));
74900 #endif
74901
74902   /* Begin a transaction */
74903   rc = execSql(db, "BEGIN EXCLUSIVE;");
74904   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74905
74906   /* Query the schema of the main database. Create a mirror schema
74907   ** in the temporary database.
74908   */
74909   rc = execExecSql(db, 
74910       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
74911       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
74912       "   AND rootpage>0"
74913   );
74914   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74915   rc = execExecSql(db, 
74916       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
74917       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
74918   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74919   rc = execExecSql(db, 
74920       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
74921       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
74922   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74923
74924   /* Loop through the tables in the main database. For each, do
74925   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
74926   ** the contents to the temporary database.
74927   */
74928   rc = execExecSql(db, 
74929       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
74930       "|| ' SELECT * FROM ' || quote(name) || ';'"
74931       "FROM sqlite_master "
74932       "WHERE type = 'table' AND name!='sqlite_sequence' "
74933       "  AND rootpage>0"
74934
74935   );
74936   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74937
74938   /* Copy over the sequence table
74939   */
74940   rc = execExecSql(db, 
74941       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
74942       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
74943   );
74944   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74945   rc = execExecSql(db, 
74946       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
74947       "|| ' SELECT * FROM ' || quote(name) || ';' "
74948       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
74949   );
74950   if( rc!=SQLITE_OK ) goto end_of_vacuum;
74951
74952
74953   /* Copy the triggers, views, and virtual tables from the main database
74954   ** over to the temporary database.  None of these objects has any
74955   ** associated storage, so all we have to do is copy their entries
74956   ** from the SQLITE_MASTER table.
74957   */
74958   rc = execSql(db,
74959       "INSERT INTO vacuum_db.sqlite_master "
74960       "  SELECT type, name, tbl_name, rootpage, sql"
74961       "    FROM sqlite_master"
74962       "   WHERE type='view' OR type='trigger'"
74963       "      OR (type='table' AND rootpage=0)"
74964   );
74965   if( rc ) goto end_of_vacuum;
74966
74967   /* At this point, unless the main db was completely empty, there is now a
74968   ** transaction open on the vacuum database, but not on the main database.
74969   ** Open a btree level transaction on the main database. This allows a
74970   ** call to sqlite3BtreeCopyFile(). The main database btree level
74971   ** transaction is then committed, so the SQL level never knows it was
74972   ** opened for writing. This way, the SQL transaction used to create the
74973   ** temporary database never needs to be committed.
74974   */
74975   if( rc==SQLITE_OK ){
74976     u32 meta;
74977     int i;
74978
74979     /* This array determines which meta meta values are preserved in the
74980     ** vacuum.  Even entries are the meta value number and odd entries
74981     ** are an increment to apply to the meta value after the vacuum.
74982     ** The increment is used to increase the schema cookie so that other
74983     ** connections to the same database will know to reread the schema.
74984     */
74985     static const unsigned char aCopy[] = {
74986        1, 1,    /* Add one to the old schema cookie */
74987        3, 0,    /* Preserve the default page cache size */
74988        5, 0,    /* Preserve the default text encoding */
74989        6, 0,    /* Preserve the user version */
74990     };
74991
74992     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
74993     assert( 1==sqlite3BtreeIsInTrans(pMain) );
74994
74995     /* Copy Btree meta values */
74996     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
74997       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
74998       if( rc!=SQLITE_OK ) goto end_of_vacuum;
74999       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
75000       if( rc!=SQLITE_OK ) goto end_of_vacuum;
75001     }
75002
75003     rc = sqlite3BtreeCopyFile(pMain, pTemp);
75004     if( rc!=SQLITE_OK ) goto end_of_vacuum;
75005     rc = sqlite3BtreeCommit(pTemp);
75006     if( rc!=SQLITE_OK ) goto end_of_vacuum;
75007 #ifndef SQLITE_OMIT_AUTOVACUUM
75008     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
75009 #endif
75010     rc = sqlite3BtreeCommit(pMain);
75011   }
75012
75013   if( rc==SQLITE_OK ){
75014     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
75015   }
75016
75017 end_of_vacuum:
75018   /* Restore the original value of db->flags */
75019   db->flags = saved_flags;
75020   db->nChange = saved_nChange;
75021   db->nTotalChange = saved_nTotalChange;
75022
75023   /* Currently there is an SQL level transaction open on the vacuum
75024   ** database. No locks are held on any other files (since the main file
75025   ** was committed at the btree level). So it safe to end the transaction
75026   ** by manually setting the autoCommit flag to true and detaching the
75027   ** vacuum database. The vacuum_db journal file is deleted when the pager
75028   ** is closed by the DETACH.
75029   */
75030   db->autoCommit = 1;
75031
75032   if( pDb ){
75033     sqlite3BtreeClose(pDb->pBt);
75034     pDb->pBt = 0;
75035     pDb->pSchema = 0;
75036   }
75037
75038   sqlite3ResetInternalSchema(db, 0);
75039
75040   return rc;
75041 }
75042 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
75043
75044 /************** End of vacuum.c **********************************************/
75045 /************** Begin file vtab.c ********************************************/
75046 /*
75047 ** 2006 June 10
75048 **
75049 ** The author disclaims copyright to this source code.  In place of
75050 ** a legal notice, here is a blessing:
75051 **
75052 **    May you do good and not evil.
75053 **    May you find forgiveness for yourself and forgive others.
75054 **    May you share freely, never taking more than you give.
75055 **
75056 *************************************************************************
75057 ** This file contains code used to help implement virtual tables.
75058 **
75059 ** $Id: vtab.c,v 1.76 2008/08/20 16:35:10 drh Exp $
75060 */
75061 #ifndef SQLITE_OMIT_VIRTUALTABLE
75062
75063 static int createModule(
75064   sqlite3 *db,                    /* Database in which module is registered */
75065   const char *zName,              /* Name assigned to this module */
75066   const sqlite3_module *pModule,  /* The definition of the module */
75067   void *pAux,                     /* Context pointer for xCreate/xConnect */
75068   void (*xDestroy)(void *)        /* Module destructor function */
75069 ) {
75070   int rc, nName;
75071   Module *pMod;
75072
75073   sqlite3_mutex_enter(db->mutex);
75074   nName = strlen(zName);
75075   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
75076   if( pMod ){
75077     Module *pDel;
75078     char *zCopy = (char *)(&pMod[1]);
75079     memcpy(zCopy, zName, nName+1);
75080     pMod->zName = zCopy;
75081     pMod->pModule = pModule;
75082     pMod->pAux = pAux;
75083     pMod->xDestroy = xDestroy;
75084     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
75085     if( pDel && pDel->xDestroy ){
75086       pDel->xDestroy(pDel->pAux);
75087     }
75088     sqlite3DbFree(db, pDel);
75089     if( pDel==pMod ){
75090       db->mallocFailed = 1;
75091     }
75092     sqlite3ResetInternalSchema(db, 0);
75093   }
75094   rc = sqlite3ApiExit(db, SQLITE_OK);
75095   sqlite3_mutex_leave(db->mutex);
75096   return rc;
75097 }
75098
75099
75100 /*
75101 ** External API function used to create a new virtual-table module.
75102 */
75103 SQLITE_API int sqlite3_create_module(
75104   sqlite3 *db,                    /* Database in which module is registered */
75105   const char *zName,              /* Name assigned to this module */
75106   const sqlite3_module *pModule,  /* The definition of the module */
75107   void *pAux                      /* Context pointer for xCreate/xConnect */
75108 ){
75109   return createModule(db, zName, pModule, pAux, 0);
75110 }
75111
75112 /*
75113 ** External API function used to create a new virtual-table module.
75114 */
75115 SQLITE_API int sqlite3_create_module_v2(
75116   sqlite3 *db,                    /* Database in which module is registered */
75117   const char *zName,              /* Name assigned to this module */
75118   const sqlite3_module *pModule,  /* The definition of the module */
75119   void *pAux,                     /* Context pointer for xCreate/xConnect */
75120   void (*xDestroy)(void *)        /* Module destructor function */
75121 ){
75122   return createModule(db, zName, pModule, pAux, xDestroy);
75123 }
75124
75125 /*
75126 ** Lock the virtual table so that it cannot be disconnected.
75127 ** Locks nest.  Every lock should have a corresponding unlock.
75128 ** If an unlock is omitted, resources leaks will occur.  
75129 **
75130 ** If a disconnect is attempted while a virtual table is locked,
75131 ** the disconnect is deferred until all locks have been removed.
75132 */
75133 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
75134   pVtab->nRef++;
75135 }
75136
75137 /*
75138 ** Unlock a virtual table.  When the last lock is removed,
75139 ** disconnect the virtual table.
75140 */
75141 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
75142   pVtab->nRef--;
75143   assert(db);
75144   assert( sqlite3SafetyCheckOk(db) );
75145   if( pVtab->nRef==0 ){
75146     if( db->magic==SQLITE_MAGIC_BUSY ){
75147       (void)sqlite3SafetyOff(db);
75148       pVtab->pModule->xDisconnect(pVtab);
75149       (void)sqlite3SafetyOn(db);
75150     } else {
75151       pVtab->pModule->xDisconnect(pVtab);
75152     }
75153   }
75154 }
75155
75156 /*
75157 ** Clear any and all virtual-table information from the Table record.
75158 ** This routine is called, for example, just before deleting the Table
75159 ** record.
75160 */
75161 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
75162   sqlite3_vtab *pVtab = p->pVtab;
75163   sqlite3 *db = p->db;
75164   if( pVtab ){
75165     assert( p->pMod && p->pMod->pModule );
75166     sqlite3VtabUnlock(db, pVtab);
75167     p->pVtab = 0;
75168   }
75169   if( p->azModuleArg ){
75170     int i;
75171     for(i=0; i<p->nModuleArg; i++){
75172       sqlite3DbFree(db, p->azModuleArg[i]);
75173     }
75174     sqlite3DbFree(db, p->azModuleArg);
75175   }
75176 }
75177
75178 /*
75179 ** Add a new module argument to pTable->azModuleArg[].
75180 ** The string is not copied - the pointer is stored.  The
75181 ** string will be freed automatically when the table is
75182 ** deleted.
75183 */
75184 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
75185   int i = pTable->nModuleArg++;
75186   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
75187   char **azModuleArg;
75188   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
75189   if( azModuleArg==0 ){
75190     int j;
75191     for(j=0; j<i; j++){
75192       sqlite3DbFree(db, pTable->azModuleArg[j]);
75193     }
75194     sqlite3DbFree(db, zArg);
75195     sqlite3DbFree(db, pTable->azModuleArg);
75196     pTable->nModuleArg = 0;
75197   }else{
75198     azModuleArg[i] = zArg;
75199     azModuleArg[i+1] = 0;
75200   }
75201   pTable->azModuleArg = azModuleArg;
75202 }
75203
75204 /*
75205 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
75206 ** statement.  The module name has been parsed, but the optional list
75207 ** of parameters that follow the module name are still pending.
75208 */
75209 SQLITE_PRIVATE void sqlite3VtabBeginParse(
75210   Parse *pParse,        /* Parsing context */
75211   Token *pName1,        /* Name of new table, or database name */
75212   Token *pName2,        /* Name of new table or NULL */
75213   Token *pModuleName    /* Name of the module for the virtual table */
75214 ){
75215   int iDb;              /* The database the table is being created in */
75216   Table *pTable;        /* The new virtual table */
75217   sqlite3 *db;          /* Database connection */
75218
75219   if( pParse->db->flags & SQLITE_SharedCache ){
75220     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
75221     return;
75222   }
75223
75224   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
75225   pTable = pParse->pNewTable;
75226   if( pTable==0 || pParse->nErr ) return;
75227   assert( 0==pTable->pIndex );
75228
75229   db = pParse->db;
75230   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
75231   assert( iDb>=0 );
75232
75233   pTable->tabFlags |= TF_Virtual;
75234   pTable->nModuleArg = 0;
75235   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
75236   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
75237   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
75238   pParse->sNameToken.n = pModuleName->z + pModuleName->n - pName1->z;
75239
75240 #ifndef SQLITE_OMIT_AUTHORIZATION
75241   /* Creating a virtual table invokes the authorization callback twice.
75242   ** The first invocation, to obtain permission to INSERT a row into the
75243   ** sqlite_master table, has already been made by sqlite3StartTable().
75244   ** The second call, to obtain permission to create the table, is made now.
75245   */
75246   if( pTable->azModuleArg ){
75247     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
75248             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
75249   }
75250 #endif
75251 }
75252
75253 /*
75254 ** This routine takes the module argument that has been accumulating
75255 ** in pParse->zArg[] and appends it to the list of arguments on the
75256 ** virtual table currently under construction in pParse->pTable.
75257 */
75258 static void addArgumentToVtab(Parse *pParse){
75259   if( pParse->sArg.z && pParse->pNewTable ){
75260     const char *z = (const char*)pParse->sArg.z;
75261     int n = pParse->sArg.n;
75262     sqlite3 *db = pParse->db;
75263     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
75264   }
75265 }
75266
75267 /*
75268 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
75269 ** has been completely parsed.
75270 */
75271 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
75272   Table *pTab;        /* The table being constructed */
75273   sqlite3 *db;        /* The database connection */
75274   char *zModule;      /* The module name of the table: USING modulename */
75275   Module *pMod = 0;
75276
75277   addArgumentToVtab(pParse);
75278   pParse->sArg.z = 0;
75279
75280   /* Lookup the module name. */
75281   pTab = pParse->pNewTable;
75282   if( pTab==0 ) return;
75283   db = pParse->db;
75284   if( pTab->nModuleArg<1 ) return;
75285   zModule = pTab->azModuleArg[0];
75286   pMod = (Module *)sqlite3HashFind(&db->aModule, zModule, strlen(zModule));
75287   pTab->pMod = pMod;
75288   
75289   /* If the CREATE VIRTUAL TABLE statement is being entered for the
75290   ** first time (in other words if the virtual table is actually being
75291   ** created now instead of just being read out of sqlite_master) then
75292   ** do additional initialization work and store the statement text
75293   ** in the sqlite_master table.
75294   */
75295   if( !db->init.busy ){
75296     char *zStmt;
75297     char *zWhere;
75298     int iDb;
75299     Vdbe *v;
75300
75301     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
75302     if( pEnd ){
75303       pParse->sNameToken.n = pEnd->z - pParse->sNameToken.z + pEnd->n;
75304     }
75305     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
75306
75307     /* A slot for the record has already been allocated in the 
75308     ** SQLITE_MASTER table.  We just need to update that slot with all
75309     ** the information we've collected.  
75310     **
75311     ** The VM register number pParse->regRowid holds the rowid of an
75312     ** entry in the sqlite_master table tht was created for this vtab
75313     ** by sqlite3StartTable().
75314     */
75315     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75316     sqlite3NestedParse(pParse,
75317       "UPDATE %Q.%s "
75318          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
75319        "WHERE rowid=#%d",
75320       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75321       pTab->zName,
75322       pTab->zName,
75323       zStmt,
75324       pParse->regRowid
75325     );
75326     sqlite3DbFree(db, zStmt);
75327     v = sqlite3GetVdbe(pParse);
75328     sqlite3ChangeCookie(pParse, iDb);
75329
75330     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
75331     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
75332     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
75333     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
75334                          pTab->zName, strlen(pTab->zName) + 1);
75335   }
75336
75337   /* If we are rereading the sqlite_master table create the in-memory
75338   ** record of the table. If the module has already been registered,
75339   ** also call the xConnect method here.
75340   */
75341   else {
75342     Table *pOld;
75343     Schema *pSchema = pTab->pSchema;
75344     const char *zName = pTab->zName;
75345     int nName = strlen(zName) + 1;
75346     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
75347     if( pOld ){
75348       db->mallocFailed = 1;
75349       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
75350       return;
75351     }
75352     pSchema->db = pParse->db;
75353     pParse->pNewTable = 0;
75354   }
75355 }
75356
75357 /*
75358 ** The parser calls this routine when it sees the first token
75359 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
75360 */
75361 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
75362   addArgumentToVtab(pParse);
75363   pParse->sArg.z = 0;
75364   pParse->sArg.n = 0;
75365 }
75366
75367 /*
75368 ** The parser calls this routine for each token after the first token
75369 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
75370 */
75371 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
75372   Token *pArg = &pParse->sArg;
75373   if( pArg->z==0 ){
75374     pArg->z = p->z;
75375     pArg->n = p->n;
75376   }else{
75377     assert(pArg->z < p->z);
75378     pArg->n = (p->z + p->n - pArg->z);
75379   }
75380 }
75381
75382 /*
75383 ** Invoke a virtual table constructor (either xCreate or xConnect). The
75384 ** pointer to the function to invoke is passed as the fourth parameter
75385 ** to this procedure.
75386 */
75387 static int vtabCallConstructor(
75388   sqlite3 *db, 
75389   Table *pTab,
75390   Module *pMod,
75391   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
75392   char **pzErr
75393 ){
75394   int rc;
75395   int rc2;
75396   sqlite3_vtab *pVtab = 0;
75397   const char *const*azArg = (const char *const*)pTab->azModuleArg;
75398   int nArg = pTab->nModuleArg;
75399   char *zErr = 0;
75400   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
75401
75402   if( !zModuleName ){
75403     return SQLITE_NOMEM;
75404   }
75405
75406   assert( !db->pVTab );
75407   assert( xConstruct );
75408
75409   db->pVTab = pTab;
75410   rc = sqlite3SafetyOff(db);
75411   assert( rc==SQLITE_OK );
75412   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
75413   rc2 = sqlite3SafetyOn(db);
75414   if( rc==SQLITE_OK && pVtab ){
75415     pVtab->pModule = pMod->pModule;
75416     pVtab->nRef = 1;
75417     pTab->pVtab = pVtab;
75418   }
75419
75420   if( SQLITE_OK!=rc ){
75421     if( zErr==0 ){
75422       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
75423     }else {
75424       *pzErr = sqlite3MPrintf(db, "%s", zErr);
75425       sqlite3DbFree(db, zErr);
75426     }
75427   }else if( db->pVTab ){
75428     const char *zFormat = "vtable constructor did not declare schema: %s";
75429     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
75430     rc = SQLITE_ERROR;
75431   } 
75432   if( rc==SQLITE_OK ){
75433     rc = rc2;
75434   }
75435   db->pVTab = 0;
75436   sqlite3DbFree(db, zModuleName);
75437
75438   /* If everything went according to plan, loop through the columns
75439   ** of the table to see if any of them contain the token "hidden".
75440   ** If so, set the Column.isHidden flag and remove the token from
75441   ** the type string.
75442   */
75443   if( rc==SQLITE_OK ){
75444     int iCol;
75445     for(iCol=0; iCol<pTab->nCol; iCol++){
75446       char *zType = pTab->aCol[iCol].zType;
75447       int nType;
75448       int i = 0;
75449       if( !zType ) continue;
75450       nType = strlen(zType);
75451       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
75452         for(i=0; i<nType; i++){
75453           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
75454            && (zType[i+7]=='\0' || zType[i+7]==' ')
75455           ){
75456             i++;
75457             break;
75458           }
75459         }
75460       }
75461       if( i<nType ){
75462         int j;
75463         int nDel = 6 + (zType[i+6] ? 1 : 0);
75464         for(j=i; (j+nDel)<=nType; j++){
75465           zType[j] = zType[j+nDel];
75466         }
75467         if( zType[i]=='\0' && i>0 ){
75468           assert(zType[i-1]==' ');
75469           zType[i-1] = '\0';
75470         }
75471         pTab->aCol[iCol].isHidden = 1;
75472       }
75473     }
75474   }
75475   return rc;
75476 }
75477
75478 /*
75479 ** This function is invoked by the parser to call the xConnect() method
75480 ** of the virtual table pTab. If an error occurs, an error code is returned 
75481 ** and an error left in pParse.
75482 **
75483 ** This call is a no-op if table pTab is not a virtual table.
75484 */
75485 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
75486   Module *pMod;
75487   int rc = SQLITE_OK;
75488
75489   if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
75490     return SQLITE_OK;
75491   }
75492
75493   pMod = pTab->pMod;
75494   if( !pMod ){
75495     const char *zModule = pTab->azModuleArg[0];
75496     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
75497     rc = SQLITE_ERROR;
75498   } else {
75499     char *zErr = 0;
75500     sqlite3 *db = pParse->db;
75501     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
75502     if( rc!=SQLITE_OK ){
75503       sqlite3ErrorMsg(pParse, "%s", zErr);
75504     }
75505     sqlite3DbFree(db, zErr);
75506   }
75507
75508   return rc;
75509 }
75510
75511 /*
75512 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
75513 */
75514 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
75515   const int ARRAY_INCR = 5;
75516
75517   /* Grow the sqlite3.aVTrans array if required */
75518   if( (db->nVTrans%ARRAY_INCR)==0 ){
75519     sqlite3_vtab **aVTrans;
75520     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
75521     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
75522     if( !aVTrans ){
75523       return SQLITE_NOMEM;
75524     }
75525     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
75526     db->aVTrans = aVTrans;
75527   }
75528
75529   /* Add pVtab to the end of sqlite3.aVTrans */
75530   db->aVTrans[db->nVTrans++] = pVtab;
75531   sqlite3VtabLock(pVtab);
75532   return SQLITE_OK;
75533 }
75534
75535 /*
75536 ** This function is invoked by the vdbe to call the xCreate method
75537 ** of the virtual table named zTab in database iDb. 
75538 **
75539 ** If an error occurs, *pzErr is set to point an an English language
75540 ** description of the error and an SQLITE_XXX error code is returned.
75541 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
75542 */
75543 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
75544   int rc = SQLITE_OK;
75545   Table *pTab;
75546   Module *pMod;
75547   const char *zModule;
75548
75549   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
75550   assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
75551   pMod = pTab->pMod;
75552   zModule = pTab->azModuleArg[0];
75553
75554   /* If the module has been registered and includes a Create method, 
75555   ** invoke it now. If the module has not been registered, return an 
75556   ** error. Otherwise, do nothing.
75557   */
75558   if( !pMod ){
75559     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
75560     rc = SQLITE_ERROR;
75561   }else{
75562     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
75563   }
75564
75565   if( rc==SQLITE_OK && pTab->pVtab ){
75566       rc = addToVTrans(db, pTab->pVtab);
75567   }
75568
75569   return rc;
75570 }
75571
75572 /*
75573 ** This function is used to set the schema of a virtual table.  It is only
75574 ** valid to call this function from within the xCreate() or xConnect() of a
75575 ** virtual table module.
75576 */
75577 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
75578   Parse sParse;
75579
75580   int rc = SQLITE_OK;
75581   Table *pTab;
75582   char *zErr = 0;
75583
75584   sqlite3_mutex_enter(db->mutex);
75585   pTab = db->pVTab;
75586   if( !pTab ){
75587     sqlite3Error(db, SQLITE_MISUSE, 0);
75588     sqlite3_mutex_leave(db->mutex);
75589     return SQLITE_MISUSE;
75590   }
75591   assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
75592
75593   memset(&sParse, 0, sizeof(Parse));
75594   sParse.declareVtab = 1;
75595   sParse.db = db;
75596
75597   if( 
75598       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
75599       sParse.pNewTable && 
75600       !sParse.pNewTable->pSelect && 
75601       (sParse.pNewTable->tabFlags & TF_Virtual)==0
75602   ){
75603     pTab->aCol = sParse.pNewTable->aCol;
75604     pTab->nCol = sParse.pNewTable->nCol;
75605     sParse.pNewTable->nCol = 0;
75606     sParse.pNewTable->aCol = 0;
75607     db->pVTab = 0;
75608   } else {
75609     sqlite3Error(db, SQLITE_ERROR, zErr);
75610     sqlite3DbFree(db, zErr);
75611     rc = SQLITE_ERROR;
75612   }
75613   sParse.declareVtab = 0;
75614
75615   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
75616   sqlite3DeleteTable(sParse.pNewTable);
75617   sParse.pNewTable = 0;
75618
75619   assert( (rc&0xff)==rc );
75620   rc = sqlite3ApiExit(db, rc);
75621   sqlite3_mutex_leave(db->mutex);
75622   return rc;
75623 }
75624
75625 /*
75626 ** This function is invoked by the vdbe to call the xDestroy method
75627 ** of the virtual table named zTab in database iDb. This occurs
75628 ** when a DROP TABLE is mentioned.
75629 **
75630 ** This call is a no-op if zTab is not a virtual table.
75631 */
75632 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
75633 {
75634   int rc = SQLITE_OK;
75635   Table *pTab;
75636
75637   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
75638   assert(pTab);
75639   if( pTab->pVtab ){
75640     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
75641     rc = sqlite3SafetyOff(db);
75642     assert( rc==SQLITE_OK );
75643     if( xDestroy ){
75644       rc = xDestroy(pTab->pVtab);
75645     }
75646     (void)sqlite3SafetyOn(db);
75647     if( rc==SQLITE_OK ){
75648       int i;
75649       for(i=0; i<db->nVTrans; i++){
75650         if( db->aVTrans[i]==pTab->pVtab ){
75651           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
75652           break;
75653         }
75654       }
75655       pTab->pVtab = 0;
75656     }
75657   }
75658
75659   return rc;
75660 }
75661
75662 /*
75663 ** This function invokes either the xRollback or xCommit method
75664 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
75665 ** called is identified by the second argument, "offset", which is
75666 ** the offset of the method to call in the sqlite3_module structure.
75667 **
75668 ** The array is cleared after invoking the callbacks. 
75669 */
75670 static void callFinaliser(sqlite3 *db, int offset){
75671   int i;
75672   if( db->aVTrans ){
75673     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
75674       sqlite3_vtab *pVtab = db->aVTrans[i];
75675       int (*x)(sqlite3_vtab *);
75676       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
75677       if( x ) x(pVtab);
75678       sqlite3VtabUnlock(db, pVtab);
75679     }
75680     sqlite3DbFree(db, db->aVTrans);
75681     db->nVTrans = 0;
75682     db->aVTrans = 0;
75683   }
75684 }
75685
75686 /*
75687 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
75688 ** array. Return the error code for the first error that occurs, or
75689 ** SQLITE_OK if all xSync operations are successful.
75690 **
75691 ** Set *pzErrmsg to point to a buffer that should be released using 
75692 ** sqlite3DbFree() containing an error message, if one is available.
75693 */
75694 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
75695   int i;
75696   int rc = SQLITE_OK;
75697   int rcsafety;
75698   sqlite3_vtab **aVTrans = db->aVTrans;
75699
75700   rc = sqlite3SafetyOff(db);
75701   db->aVTrans = 0;
75702   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
75703     sqlite3_vtab *pVtab = aVTrans[i];
75704     int (*x)(sqlite3_vtab *);
75705     x = pVtab->pModule->xSync;
75706     if( x ){
75707       rc = x(pVtab);
75708       sqlite3DbFree(db, *pzErrmsg);
75709       *pzErrmsg = pVtab->zErrMsg;
75710       pVtab->zErrMsg = 0;
75711     }
75712   }
75713   db->aVTrans = aVTrans;
75714   rcsafety = sqlite3SafetyOn(db);
75715
75716   if( rc==SQLITE_OK ){
75717     rc = rcsafety;
75718   }
75719   return rc;
75720 }
75721
75722 /*
75723 ** Invoke the xRollback method of all virtual tables in the 
75724 ** sqlite3.aVTrans array. Then clear the array itself.
75725 */
75726 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
75727   callFinaliser(db, offsetof(sqlite3_module,xRollback));
75728   return SQLITE_OK;
75729 }
75730
75731 /*
75732 ** Invoke the xCommit method of all virtual tables in the 
75733 ** sqlite3.aVTrans array. Then clear the array itself.
75734 */
75735 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
75736   callFinaliser(db, offsetof(sqlite3_module,xCommit));
75737   return SQLITE_OK;
75738 }
75739
75740 /*
75741 ** If the virtual table pVtab supports the transaction interface
75742 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
75743 ** not currently open, invoke the xBegin method now.
75744 **
75745 ** If the xBegin call is successful, place the sqlite3_vtab pointer
75746 ** in the sqlite3.aVTrans array.
75747 */
75748 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
75749   int rc = SQLITE_OK;
75750   const sqlite3_module *pModule;
75751
75752   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
75753   ** than zero, then this function is being called from within a
75754   ** virtual module xSync() callback. It is illegal to write to 
75755   ** virtual module tables in this case, so return SQLITE_LOCKED.
75756   */
75757   if( 0==db->aVTrans && db->nVTrans>0 ){
75758     return SQLITE_LOCKED;
75759   }
75760   if( !pVtab ){
75761     return SQLITE_OK;
75762   } 
75763   pModule = pVtab->pModule;
75764
75765   if( pModule->xBegin ){
75766     int i;
75767
75768
75769     /* If pVtab is already in the aVTrans array, return early */
75770     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
75771       if( db->aVTrans[i]==pVtab ){
75772         return SQLITE_OK;
75773       }
75774     }
75775
75776     /* Invoke the xBegin method */
75777     rc = pModule->xBegin(pVtab);
75778     if( rc==SQLITE_OK ){
75779       rc = addToVTrans(db, pVtab);
75780     }
75781   }
75782   return rc;
75783 }
75784
75785 /*
75786 ** The first parameter (pDef) is a function implementation.  The
75787 ** second parameter (pExpr) is the first argument to this function.
75788 ** If pExpr is a column in a virtual table, then let the virtual
75789 ** table implementation have an opportunity to overload the function.
75790 **
75791 ** This routine is used to allow virtual table implementations to
75792 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
75793 **
75794 ** Return either the pDef argument (indicating no change) or a 
75795 ** new FuncDef structure that is marked as ephemeral using the
75796 ** SQLITE_FUNC_EPHEM flag.
75797 */
75798 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
75799   sqlite3 *db,    /* Database connection for reporting malloc problems */
75800   FuncDef *pDef,  /* Function to possibly overload */
75801   int nArg,       /* Number of arguments to the function */
75802   Expr *pExpr     /* First argument to the function */
75803 ){
75804   Table *pTab;
75805   sqlite3_vtab *pVtab;
75806   sqlite3_module *pMod;
75807   void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
75808   void *pArg;
75809   FuncDef *pNew;
75810   int rc = 0;
75811   char *zLowerName;
75812   unsigned char *z;
75813
75814
75815   /* Check to see the left operand is a column in a virtual table */
75816   if( pExpr==0 ) return pDef;
75817   if( pExpr->op!=TK_COLUMN ) return pDef;
75818   pTab = pExpr->pTab;
75819   if( pTab==0 ) return pDef;
75820   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
75821   pVtab = pTab->pVtab;
75822   assert( pVtab!=0 );
75823   assert( pVtab->pModule!=0 );
75824   pMod = (sqlite3_module *)pVtab->pModule;
75825   if( pMod->xFindFunction==0 ) return pDef;
75826  
75827   /* Call the xFindFunction method on the virtual table implementation
75828   ** to see if the implementation wants to overload this function 
75829   */
75830   zLowerName = sqlite3DbStrDup(db, pDef->zName);
75831   if( zLowerName ){
75832     for(z=(unsigned char*)zLowerName; *z; z++){
75833       *z = sqlite3UpperToLower[*z];
75834     }
75835     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
75836     sqlite3DbFree(db, zLowerName);
75837     if( pVtab->zErrMsg ){
75838       sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
75839       sqlite3DbFree(db, pVtab->zErrMsg);
75840       pVtab->zErrMsg = 0;
75841     }
75842   }
75843   if( rc==0 ){
75844     return pDef;
75845   }
75846
75847   /* Create a new ephemeral function definition for the overloaded
75848   ** function */
75849   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) + strlen(pDef->zName) );
75850   if( pNew==0 ){
75851     return pDef;
75852   }
75853   *pNew = *pDef;
75854   pNew->zName = (char *)&pNew[1];
75855   memcpy(pNew->zName, pDef->zName, strlen(pDef->zName)+1);
75856   pNew->xFunc = xFunc;
75857   pNew->pUserData = pArg;
75858   pNew->flags |= SQLITE_FUNC_EPHEM;
75859   return pNew;
75860 }
75861
75862 /*
75863 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
75864 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
75865 ** array if it is missing.  If pTab is already in the array, this routine
75866 ** is a no-op.
75867 */
75868 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
75869   int i, n;
75870   assert( IsVirtual(pTab) );
75871   for(i=0; i<pParse->nVtabLock; i++){
75872     if( pTab==pParse->apVtabLock[i] ) return;
75873   }
75874   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
75875   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
75876   if( pParse->apVtabLock ){
75877     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
75878   }else{
75879     pParse->db->mallocFailed = 1;
75880   }
75881 }
75882
75883 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75884
75885 /************** End of vtab.c ************************************************/
75886 /************** Begin file where.c *******************************************/
75887 /*
75888 ** 2001 September 15
75889 **
75890 ** The author disclaims copyright to this source code.  In place of
75891 ** a legal notice, here is a blessing:
75892 **
75893 **    May you do good and not evil.
75894 **    May you find forgiveness for yourself and forgive others.
75895 **    May you share freely, never taking more than you give.
75896 **
75897 *************************************************************************
75898 ** This module contains C code that generates VDBE code used to process
75899 ** the WHERE clause of SQL statements.  This module is responsible for
75900 ** generating the code that loops through a table looking for applicable
75901 ** rows.  Indices are selected and used to speed the search when doing
75902 ** so is applicable.  Because this module is responsible for selecting
75903 ** indices, you might also think of this module as the "query optimizer".
75904 **
75905 ** $Id: where.c,v 1.326 2008/10/11 16:47:36 drh Exp $
75906 */
75907
75908 /*
75909 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
75910 */
75911 #define BMS  (sizeof(Bitmask)*8)
75912
75913 /*
75914 ** Trace output macros
75915 */
75916 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
75917 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
75918 #endif
75919 #if 0
75920 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
75921 #else
75922 # define WHERETRACE(X)
75923 #endif
75924
75925 /* Forward reference
75926 */
75927 typedef struct WhereClause WhereClause;
75928 typedef struct ExprMaskSet ExprMaskSet;
75929
75930 /*
75931 ** The query generator uses an array of instances of this structure to
75932 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
75933 ** clause subexpression is separated from the others by an AND operator.
75934 **
75935 ** All WhereTerms are collected into a single WhereClause structure.  
75936 ** The following identity holds:
75937 **
75938 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
75939 **
75940 ** When a term is of the form:
75941 **
75942 **              X <op> <expr>
75943 **
75944 ** where X is a column name and <op> is one of certain operators,
75945 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
75946 ** cursor number and column number for X.  WhereTerm.operator records
75947 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
75948 ** use of a bitmask encoding for the operator allows us to search
75949 ** quickly for terms that match any of several different operators.
75950 **
75951 ** prereqRight and prereqAll record sets of cursor numbers,
75952 ** but they do so indirectly.  A single ExprMaskSet structure translates
75953 ** cursor number into bits and the translated bit is stored in the prereq
75954 ** fields.  The translation is used in order to maximize the number of
75955 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
75956 ** spread out over the non-negative integers.  For example, the cursor
75957 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
75958 ** translates these sparse cursor numbers into consecutive integers
75959 ** beginning with 0 in order to make the best possible use of the available
75960 ** bits in the Bitmask.  So, in the example above, the cursor numbers
75961 ** would be mapped into integers 0 through 7.
75962 */
75963 typedef struct WhereTerm WhereTerm;
75964 struct WhereTerm {
75965   Expr *pExpr;            /* Pointer to the subexpression */
75966   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
75967   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
75968   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
75969   u16 eOperator;          /* A WO_xx value describing <op> */
75970   u8 flags;               /* Bit flags.  See below */
75971   u8 nChild;              /* Number of children that must disable us */
75972   WhereClause *pWC;       /* The clause this term is part of */
75973   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
75974   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
75975 };
75976
75977 /*
75978 ** Allowed values of WhereTerm.flags
75979 */
75980 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
75981 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
75982 #define TERM_CODED      0x04   /* This term is already coded */
75983 #define TERM_COPIED     0x08   /* Has a child */
75984 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
75985
75986 /*
75987 ** An instance of the following structure holds all information about a
75988 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
75989 */
75990 struct WhereClause {
75991   Parse *pParse;           /* The parser context */
75992   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
75993   int nTerm;               /* Number of terms */
75994   int nSlot;               /* Number of entries in a[] */
75995   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
75996   WhereTerm aStatic[10];   /* Initial static space for a[] */
75997 };
75998
75999 /*
76000 ** An instance of the following structure keeps track of a mapping
76001 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
76002 **
76003 ** The VDBE cursor numbers are small integers contained in 
76004 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
76005 ** clause, the cursor numbers might not begin with 0 and they might
76006 ** contain gaps in the numbering sequence.  But we want to make maximum
76007 ** use of the bits in our bitmasks.  This structure provides a mapping
76008 ** from the sparse cursor numbers into consecutive integers beginning
76009 ** with 0.
76010 **
76011 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
76012 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
76013 **
76014 ** For example, if the WHERE clause expression used these VDBE
76015 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
76016 ** would map those cursor numbers into bits 0 through 5.
76017 **
76018 ** Note that the mapping is not necessarily ordered.  In the example
76019 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
76020 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
76021 ** does not really matter.  What is important is that sparse cursor
76022 ** numbers all get mapped into bit numbers that begin with 0 and contain
76023 ** no gaps.
76024 */
76025 struct ExprMaskSet {
76026   int n;                        /* Number of assigned cursor values */
76027   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
76028 };
76029
76030
76031 /*
76032 ** Bitmasks for the operators that indices are able to exploit.  An
76033 ** OR-ed combination of these values can be used when searching for
76034 ** terms in the where clause.
76035 */
76036 #define WO_IN     1
76037 #define WO_EQ     2
76038 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
76039 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
76040 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
76041 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
76042 #define WO_MATCH  64
76043 #define WO_ISNULL 128
76044
76045 /*
76046 ** Value for flags returned by bestIndex().  
76047 **
76048 ** The least significant byte is reserved as a mask for WO_ values above.
76049 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
76050 ** But if the table is the right table of a left join, WhereLevel.flags
76051 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
76052 ** the "op" parameter to findTerm when we are resolving equality constraints.
76053 ** ISNULL constraints will then not be used on the right table of a left
76054 ** join.  Tickets #2177 and #2189.
76055 */
76056 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
76057 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
76058 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
76059 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
76060 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
76061 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
76062 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
76063 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
76064 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
76065 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
76066 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
76067 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
76068
76069 /*
76070 ** Initialize a preallocated WhereClause structure.
76071 */
76072 static void whereClauseInit(
76073   WhereClause *pWC,        /* The WhereClause to be initialized */
76074   Parse *pParse,           /* The parsing context */
76075   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
76076 ){
76077   pWC->pParse = pParse;
76078   pWC->pMaskSet = pMaskSet;
76079   pWC->nTerm = 0;
76080   pWC->nSlot = ArraySize(pWC->aStatic);
76081   pWC->a = pWC->aStatic;
76082 }
76083
76084 /*
76085 ** Deallocate a WhereClause structure.  The WhereClause structure
76086 ** itself is not freed.  This routine is the inverse of whereClauseInit().
76087 */
76088 static void whereClauseClear(WhereClause *pWC){
76089   int i;
76090   WhereTerm *a;
76091   sqlite3 *db = pWC->pParse->db;
76092   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
76093     if( a->flags & TERM_DYNAMIC ){
76094       sqlite3ExprDelete(db, a->pExpr);
76095     }
76096   }
76097   if( pWC->a!=pWC->aStatic ){
76098     sqlite3DbFree(db, pWC->a);
76099   }
76100 }
76101
76102 /*
76103 ** Add a new entries to the WhereClause structure.  Increase the allocated
76104 ** space as necessary.
76105 **
76106 ** If the flags argument includes TERM_DYNAMIC, then responsibility
76107 ** for freeing the expression p is assumed by the WhereClause object.
76108 **
76109 ** WARNING:  This routine might reallocate the space used to store
76110 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
76111 ** calling this routine.  Such pointers may be reinitialized by referencing
76112 ** the pWC->a[] array.
76113 */
76114 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
76115   WhereTerm *pTerm;
76116   int idx;
76117   if( pWC->nTerm>=pWC->nSlot ){
76118     WhereTerm *pOld = pWC->a;
76119     sqlite3 *db = pWC->pParse->db;
76120     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
76121     if( pWC->a==0 ){
76122       if( flags & TERM_DYNAMIC ){
76123         sqlite3ExprDelete(db, p);
76124       }
76125       pWC->a = pOld;
76126       return 0;
76127     }
76128     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
76129     if( pOld!=pWC->aStatic ){
76130       sqlite3DbFree(db, pOld);
76131     }
76132     pWC->nSlot *= 2;
76133   }
76134   pTerm = &pWC->a[idx = pWC->nTerm];
76135   pWC->nTerm++;
76136   pTerm->pExpr = p;
76137   pTerm->flags = flags;
76138   pTerm->pWC = pWC;
76139   pTerm->iParent = -1;
76140   return idx;
76141 }
76142
76143 /*
76144 ** This routine identifies subexpressions in the WHERE clause where
76145 ** each subexpression is separated by the AND operator or some other
76146 ** operator specified in the op parameter.  The WhereClause structure
76147 ** is filled with pointers to subexpressions.  For example:
76148 **
76149 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
76150 **           \________/     \_______________/     \________________/
76151 **            slot[0]            slot[1]               slot[2]
76152 **
76153 ** The original WHERE clause in pExpr is unaltered.  All this routine
76154 ** does is make slot[] entries point to substructure within pExpr.
76155 **
76156 ** In the previous sentence and in the diagram, "slot[]" refers to
76157 ** the WhereClause.a[] array.  This array grows as needed to contain
76158 ** all terms of the WHERE clause.
76159 */
76160 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
76161   if( pExpr==0 ) return;
76162   if( pExpr->op!=op ){
76163     whereClauseInsert(pWC, pExpr, 0);
76164   }else{
76165     whereSplit(pWC, pExpr->pLeft, op);
76166     whereSplit(pWC, pExpr->pRight, op);
76167   }
76168 }
76169
76170 /*
76171 ** Initialize an expression mask set
76172 */
76173 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
76174
76175 /*
76176 ** Return the bitmask for the given cursor number.  Return 0 if
76177 ** iCursor is not in the set.
76178 */
76179 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
76180   int i;
76181   for(i=0; i<pMaskSet->n; i++){
76182     if( pMaskSet->ix[i]==iCursor ){
76183       return ((Bitmask)1)<<i;
76184     }
76185   }
76186   return 0;
76187 }
76188
76189 /*
76190 ** Create a new mask for cursor iCursor.
76191 **
76192 ** There is one cursor per table in the FROM clause.  The number of
76193 ** tables in the FROM clause is limited by a test early in the
76194 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
76195 ** array will never overflow.
76196 */
76197 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
76198   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
76199   pMaskSet->ix[pMaskSet->n++] = iCursor;
76200 }
76201
76202 /*
76203 ** This routine walks (recursively) an expression tree and generates
76204 ** a bitmask indicating which tables are used in that expression
76205 ** tree.
76206 **
76207 ** In order for this routine to work, the calling function must have
76208 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
76209 ** the header comment on that routine for additional information.
76210 ** The sqlite3ResolveExprNames() routines looks for column names and
76211 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
76212 ** the VDBE cursor number of the table.  This routine just has to
76213 ** translate the cursor numbers into bitmask values and OR all
76214 ** the bitmasks together.
76215 */
76216 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
76217 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
76218 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
76219   Bitmask mask = 0;
76220   if( p==0 ) return 0;
76221   if( p->op==TK_COLUMN ){
76222     mask = getMask(pMaskSet, p->iTable);
76223     return mask;
76224   }
76225   mask = exprTableUsage(pMaskSet, p->pRight);
76226   mask |= exprTableUsage(pMaskSet, p->pLeft);
76227   mask |= exprListTableUsage(pMaskSet, p->pList);
76228   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
76229   return mask;
76230 }
76231 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
76232   int i;
76233   Bitmask mask = 0;
76234   if( pList ){
76235     for(i=0; i<pList->nExpr; i++){
76236       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
76237     }
76238   }
76239   return mask;
76240 }
76241 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
76242   Bitmask mask = 0;
76243   while( pS ){
76244     mask |= exprListTableUsage(pMaskSet, pS->pEList);
76245     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
76246     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
76247     mask |= exprTableUsage(pMaskSet, pS->pWhere);
76248     mask |= exprTableUsage(pMaskSet, pS->pHaving);
76249     pS = pS->pPrior;
76250   }
76251   return mask;
76252 }
76253
76254 /*
76255 ** Return TRUE if the given operator is one of the operators that is
76256 ** allowed for an indexable WHERE clause term.  The allowed operators are
76257 ** "=", "<", ">", "<=", ">=", and "IN".
76258 */
76259 static int allowedOp(int op){
76260   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
76261   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
76262   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
76263   assert( TK_GE==TK_EQ+4 );
76264   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
76265 }
76266
76267 /*
76268 ** Swap two objects of type T.
76269 */
76270 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
76271
76272 /*
76273 ** Commute a comparison operator.  Expressions of the form "X op Y"
76274 ** are converted into "Y op X".
76275 **
76276 ** If a collation sequence is associated with either the left or right
76277 ** side of the comparison, it remains associated with the same side after
76278 ** the commutation. So "Y collate NOCASE op X" becomes 
76279 ** "X collate NOCASE op Y". This is because any collation sequence on
76280 ** the left hand side of a comparison overrides any collation sequence 
76281 ** attached to the right. For the same reason the EP_ExpCollate flag
76282 ** is not commuted.
76283 */
76284 static void exprCommute(Parse *pParse, Expr *pExpr){
76285   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
76286   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
76287   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
76288   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
76289   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
76290   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
76291   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
76292   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
76293   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
76294   if( pExpr->op>=TK_GT ){
76295     assert( TK_LT==TK_GT+2 );
76296     assert( TK_GE==TK_LE+2 );
76297     assert( TK_GT>TK_EQ );
76298     assert( TK_GT<TK_LE );
76299     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
76300     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
76301   }
76302 }
76303
76304 /*
76305 ** Translate from TK_xx operator to WO_xx bitmask.
76306 */
76307 static int operatorMask(int op){
76308   int c;
76309   assert( allowedOp(op) );
76310   if( op==TK_IN ){
76311     c = WO_IN;
76312   }else if( op==TK_ISNULL ){
76313     c = WO_ISNULL;
76314   }else{
76315     c = WO_EQ<<(op-TK_EQ);
76316   }
76317   assert( op!=TK_ISNULL || c==WO_ISNULL );
76318   assert( op!=TK_IN || c==WO_IN );
76319   assert( op!=TK_EQ || c==WO_EQ );
76320   assert( op!=TK_LT || c==WO_LT );
76321   assert( op!=TK_LE || c==WO_LE );
76322   assert( op!=TK_GT || c==WO_GT );
76323   assert( op!=TK_GE || c==WO_GE );
76324   return c;
76325 }
76326
76327 /*
76328 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
76329 ** where X is a reference to the iColumn of table iCur and <op> is one of
76330 ** the WO_xx operator codes specified by the op parameter.
76331 ** Return a pointer to the term.  Return 0 if not found.
76332 */
76333 static WhereTerm *findTerm(
76334   WhereClause *pWC,     /* The WHERE clause to be searched */
76335   int iCur,             /* Cursor number of LHS */
76336   int iColumn,          /* Column number of LHS */
76337   Bitmask notReady,     /* RHS must not overlap with this mask */
76338   u16 op,               /* Mask of WO_xx values describing operator */
76339   Index *pIdx           /* Must be compatible with this index, if not NULL */
76340 ){
76341   WhereTerm *pTerm;
76342   int k;
76343   assert( iCur>=0 );
76344   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
76345     if( pTerm->leftCursor==iCur
76346        && (pTerm->prereqRight & notReady)==0
76347        && pTerm->leftColumn==iColumn
76348        && (pTerm->eOperator & op)!=0
76349     ){
76350       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
76351         Expr *pX = pTerm->pExpr;
76352         CollSeq *pColl;
76353         char idxaff;
76354         int j;
76355         Parse *pParse = pWC->pParse;
76356
76357         idxaff = pIdx->pTable->aCol[iColumn].affinity;
76358         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
76359
76360         /* Figure out the collation sequence required from an index for
76361         ** it to be useful for optimising expression pX. Store this
76362         ** value in variable pColl.
76363         */
76364         assert(pX->pLeft);
76365         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
76366         if( !pColl ){
76367           pColl = pParse->db->pDfltColl;
76368         }
76369
76370         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
76371           if( NEVER(j>=pIdx->nColumn) ) return 0;
76372         }
76373         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
76374       }
76375       return pTerm;
76376     }
76377   }
76378   return 0;
76379 }
76380
76381 /* Forward reference */
76382 static void exprAnalyze(SrcList*, WhereClause*, int);
76383
76384 /*
76385 ** Call exprAnalyze on all terms in a WHERE clause.  
76386 **
76387 **
76388 */
76389 static void exprAnalyzeAll(
76390   SrcList *pTabList,       /* the FROM clause */
76391   WhereClause *pWC         /* the WHERE clause to be analyzed */
76392 ){
76393   int i;
76394   for(i=pWC->nTerm-1; i>=0; i--){
76395     exprAnalyze(pTabList, pWC, i);
76396   }
76397 }
76398
76399 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
76400 /*
76401 ** Check to see if the given expression is a LIKE or GLOB operator that
76402 ** can be optimized using inequality constraints.  Return TRUE if it is
76403 ** so and false if not.
76404 **
76405 ** In order for the operator to be optimizible, the RHS must be a string
76406 ** literal that does not begin with a wildcard.  
76407 */
76408 static int isLikeOrGlob(
76409   Parse *pParse,    /* Parsing and code generating context */
76410   Expr *pExpr,      /* Test this expression */
76411   int *pnPattern,   /* Number of non-wildcard prefix characters */
76412   int *pisComplete, /* True if the only wildcard is % in the last character */
76413   int *pnoCase      /* True if uppercase is equivalent to lowercase */
76414 ){
76415   const char *z;
76416   Expr *pRight, *pLeft;
76417   ExprList *pList;
76418   int c, cnt;
76419   char wc[3];
76420   CollSeq *pColl;
76421   sqlite3 *db = pParse->db;
76422
76423   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
76424     return 0;
76425   }
76426 #ifdef SQLITE_EBCDIC
76427   if( *pnoCase ) return 0;
76428 #endif
76429   pList = pExpr->pList;
76430   pRight = pList->a[0].pExpr;
76431   if( pRight->op!=TK_STRING
76432    && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){
76433     return 0;
76434   }
76435   pLeft = pList->a[1].pExpr;
76436   if( pLeft->op!=TK_COLUMN ){
76437     return 0;
76438   }
76439   pColl = sqlite3ExprCollSeq(pParse, pLeft);
76440   assert( pColl!=0 || pLeft->iColumn==-1 );
76441   if( pColl==0 ){
76442     /* No collation is defined for the ROWID.  Use the default. */
76443     pColl = db->pDfltColl;
76444   }
76445   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
76446       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
76447     return 0;
76448   }
76449   sqlite3DequoteExpr(db, pRight);
76450   z = (char *)pRight->token.z;
76451   cnt = 0;
76452   if( z ){
76453     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
76454   }
76455   if( cnt==0 || 255==(u8)z[cnt] ){
76456     return 0;
76457   }
76458   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
76459   *pnPattern = cnt;
76460   return 1;
76461 }
76462 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
76463
76464
76465 #ifndef SQLITE_OMIT_VIRTUALTABLE
76466 /*
76467 ** Check to see if the given expression is of the form
76468 **
76469 **         column MATCH expr
76470 **
76471 ** If it is then return TRUE.  If not, return FALSE.
76472 */
76473 static int isMatchOfColumn(
76474   Expr *pExpr      /* Test this expression */
76475 ){
76476   ExprList *pList;
76477
76478   if( pExpr->op!=TK_FUNCTION ){
76479     return 0;
76480   }
76481   if( pExpr->token.n!=5 ||
76482        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
76483     return 0;
76484   }
76485   pList = pExpr->pList;
76486   if( pList->nExpr!=2 ){
76487     return 0;
76488   }
76489   if( pList->a[1].pExpr->op != TK_COLUMN ){
76490     return 0;
76491   }
76492   return 1;
76493 }
76494 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76495
76496 /*
76497 ** If the pBase expression originated in the ON or USING clause of
76498 ** a join, then transfer the appropriate markings over to derived.
76499 */
76500 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
76501   pDerived->flags |= pBase->flags & EP_FromJoin;
76502   pDerived->iRightJoinTable = pBase->iRightJoinTable;
76503 }
76504
76505 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
76506 /*
76507 ** Return TRUE if the given term of an OR clause can be converted
76508 ** into an IN clause.  The iCursor and iColumn define the left-hand
76509 ** side of the IN clause.
76510 **
76511 ** The context is that we have multiple OR-connected equality terms
76512 ** like this:
76513 **
76514 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
76515 **
76516 ** The pOrTerm input to this routine corresponds to a single term of
76517 ** this OR clause.  In order for the term to be a candidate for
76518 ** conversion to an IN operator, the following must be true:
76519 **
76520 **     *  The left-hand side of the term must be the column which
76521 **        is identified by iCursor and iColumn.
76522 **
76523 **     *  If the right-hand side is also a column, then the affinities
76524 **        of both right and left sides must be such that no type
76525 **        conversions are required on the right.  (Ticket #2249)
76526 **
76527 ** If both of these conditions are true, then return true.  Otherwise
76528 ** return false.
76529 */
76530 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
76531   int affLeft, affRight;
76532   assert( pOrTerm->eOperator==WO_EQ );
76533   if( pOrTerm->leftCursor!=iCursor ){
76534     return 0;
76535   }
76536   if( pOrTerm->leftColumn!=iColumn ){
76537     return 0;
76538   }
76539   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
76540   if( affRight==0 ){
76541     return 1;
76542   }
76543   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
76544   if( affRight!=affLeft ){
76545     return 0;
76546   }
76547   return 1;
76548 }
76549
76550 /*
76551 ** Return true if the given term of an OR clause can be ignored during
76552 ** a check to make sure all OR terms are candidates for optimization.
76553 ** In other words, return true if a call to the orTermIsOptCandidate()
76554 ** above returned false but it is not necessary to disqualify the
76555 ** optimization.
76556 **
76557 ** Suppose the original OR phrase was this:
76558 **
76559 **           a=4  OR  a=11  OR  a=b
76560 **
76561 ** During analysis, the third term gets flipped around and duplicate
76562 ** so that we are left with this:
76563 **
76564 **           a=4  OR  a=11  OR  a=b  OR  b=a
76565 **
76566 ** Since the last two terms are duplicates, only one of them
76567 ** has to qualify in order for the whole phrase to qualify.  When
76568 ** this routine is called, we know that pOrTerm did not qualify.
76569 ** This routine merely checks to see if pOrTerm has a duplicate that
76570 ** might qualify.  If there is a duplicate that has not yet been
76571 ** disqualified, then return true.  If there are no duplicates, or
76572 ** the duplicate has also been disqualified, return false.
76573 */
76574 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
76575   if( pOrTerm->flags & TERM_COPIED ){
76576     /* This is the original term.  The duplicate is to the left had
76577     ** has not yet been analyzed and thus has not yet been disqualified. */
76578     return 1;
76579   }
76580   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
76581      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
76582     /* This is a duplicate term.  The original qualified so this one
76583     ** does not have to. */
76584     return 1;
76585   }
76586   /* This is either a singleton term or else it is a duplicate for
76587   ** which the original did not qualify.  Either way we are done for. */
76588   return 0;
76589 }
76590 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
76591
76592 /*
76593 ** The input to this routine is an WhereTerm structure with only the
76594 ** "pExpr" field filled in.  The job of this routine is to analyze the
76595 ** subexpression and populate all the other fields of the WhereTerm
76596 ** structure.
76597 **
76598 ** If the expression is of the form "<expr> <op> X" it gets commuted
76599 ** to the standard form of "X <op> <expr>".  If the expression is of
76600 ** the form "X <op> Y" where both X and Y are columns, then the original
76601 ** expression is unchanged and a new virtual expression of the form
76602 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
76603 */
76604 static void exprAnalyze(
76605   SrcList *pSrc,            /* the FROM clause */
76606   WhereClause *pWC,         /* the WHERE clause */
76607   int idxTerm               /* Index of the term to be analyzed */
76608 ){
76609   WhereTerm *pTerm;
76610   ExprMaskSet *pMaskSet;
76611   Expr *pExpr;
76612   Bitmask prereqLeft;
76613   Bitmask prereqAll;
76614   Bitmask extraRight = 0;
76615   int nPattern;
76616   int isComplete;
76617   int noCase;
76618   int op;
76619   Parse *pParse = pWC->pParse;
76620   sqlite3 *db = pParse->db;
76621
76622   if( db->mallocFailed ){
76623     return;
76624   }
76625   pTerm = &pWC->a[idxTerm];
76626   pMaskSet = pWC->pMaskSet;
76627   pExpr = pTerm->pExpr;
76628   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
76629   op = pExpr->op;
76630   if( op==TK_IN ){
76631     assert( pExpr->pRight==0 );
76632     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
76633                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
76634   }else if( op==TK_ISNULL ){
76635     pTerm->prereqRight = 0;
76636   }else{
76637     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
76638   }
76639   prereqAll = exprTableUsage(pMaskSet, pExpr);
76640   if( ExprHasProperty(pExpr, EP_FromJoin) ){
76641     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
76642     prereqAll |= x;
76643     extraRight = x-1;  /* ON clause terms may not be used with an index
76644                        ** on left table of a LEFT JOIN.  Ticket #3015 */
76645   }
76646   pTerm->prereqAll = prereqAll;
76647   pTerm->leftCursor = -1;
76648   pTerm->iParent = -1;
76649   pTerm->eOperator = 0;
76650   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
76651     Expr *pLeft = pExpr->pLeft;
76652     Expr *pRight = pExpr->pRight;
76653     if( pLeft->op==TK_COLUMN ){
76654       pTerm->leftCursor = pLeft->iTable;
76655       pTerm->leftColumn = pLeft->iColumn;
76656       pTerm->eOperator = operatorMask(op);
76657     }
76658     if( pRight && pRight->op==TK_COLUMN ){
76659       WhereTerm *pNew;
76660       Expr *pDup;
76661       if( pTerm->leftCursor>=0 ){
76662         int idxNew;
76663         pDup = sqlite3ExprDup(db, pExpr);
76664         if( db->mallocFailed ){
76665           sqlite3ExprDelete(db, pDup);
76666           return;
76667         }
76668         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
76669         if( idxNew==0 ) return;
76670         pNew = &pWC->a[idxNew];
76671         pNew->iParent = idxTerm;
76672         pTerm = &pWC->a[idxTerm];
76673         pTerm->nChild = 1;
76674         pTerm->flags |= TERM_COPIED;
76675       }else{
76676         pDup = pExpr;
76677         pNew = pTerm;
76678       }
76679       exprCommute(pParse, pDup);
76680       pLeft = pDup->pLeft;
76681       pNew->leftCursor = pLeft->iTable;
76682       pNew->leftColumn = pLeft->iColumn;
76683       pNew->prereqRight = prereqLeft;
76684       pNew->prereqAll = prereqAll;
76685       pNew->eOperator = operatorMask(pDup->op);
76686     }
76687   }
76688
76689 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
76690   /* If a term is the BETWEEN operator, create two new virtual terms
76691   ** that define the range that the BETWEEN implements.
76692   */
76693   else if( pExpr->op==TK_BETWEEN ){
76694     ExprList *pList = pExpr->pList;
76695     int i;
76696     static const u8 ops[] = {TK_GE, TK_LE};
76697     assert( pList!=0 );
76698     assert( pList->nExpr==2 );
76699     for(i=0; i<2; i++){
76700       Expr *pNewExpr;
76701       int idxNew;
76702       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
76703                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
76704       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
76705       exprAnalyze(pSrc, pWC, idxNew);
76706       pTerm = &pWC->a[idxTerm];
76707       pWC->a[idxNew].iParent = idxTerm;
76708     }
76709     pTerm->nChild = 2;
76710   }
76711 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
76712
76713 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
76714   /* Attempt to convert OR-connected terms into an IN operator so that
76715   ** they can make use of indices.  Example:
76716   **
76717   **      x = expr1  OR  expr2 = x  OR  x = expr3
76718   **
76719   ** is converted into
76720   **
76721   **      x IN (expr1,expr2,expr3)
76722   **
76723   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
76724   ** the compiler for the the IN operator is part of sub-queries.
76725   */
76726   else if( pExpr->op==TK_OR ){
76727     int ok;
76728     int i, j;
76729     int iColumn, iCursor;
76730     WhereClause sOr;
76731     WhereTerm *pOrTerm;
76732
76733     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
76734     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
76735     whereSplit(&sOr, pExpr, TK_OR);
76736     exprAnalyzeAll(pSrc, &sOr);
76737     assert( sOr.nTerm>=2 );
76738     j = 0;
76739     if( db->mallocFailed ) goto or_not_possible;
76740     do{
76741       assert( j<sOr.nTerm );
76742       iColumn = sOr.a[j].leftColumn;
76743       iCursor = sOr.a[j].leftCursor;
76744       ok = iCursor>=0;
76745       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
76746         if( pOrTerm->eOperator!=WO_EQ ){
76747           goto or_not_possible;
76748         }
76749         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
76750           pOrTerm->flags |= TERM_OR_OK;
76751         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
76752           pOrTerm->flags &= ~TERM_OR_OK;
76753         }else{
76754           ok = 0;
76755         }
76756       }
76757     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
76758     if( ok ){
76759       ExprList *pList = 0;
76760       Expr *pNew, *pDup;
76761       Expr *pLeft = 0;
76762       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0; i--, pOrTerm++){
76763         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
76764         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
76765         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
76766         pLeft = pOrTerm->pExpr->pLeft;
76767       }
76768       assert( pLeft!=0 );
76769       pDup = sqlite3ExprDup(db, pLeft);
76770       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
76771       if( pNew ){
76772         int idxNew;
76773         transferJoinMarkings(pNew, pExpr);
76774         pNew->pList = pList;
76775         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
76776         exprAnalyze(pSrc, pWC, idxNew);
76777         pTerm = &pWC->a[idxTerm];
76778         pWC->a[idxNew].iParent = idxTerm;
76779         pTerm->nChild = 1;
76780       }else{
76781         sqlite3ExprListDelete(db, pList);
76782       }
76783     }
76784 or_not_possible:
76785     whereClauseClear(&sOr);
76786   }
76787 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
76788
76789 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
76790   /* Add constraints to reduce the search space on a LIKE or GLOB
76791   ** operator.
76792   **
76793   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
76794   **
76795   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
76796   **
76797   ** The last character of the prefix "abc" is incremented to form the
76798   ** termination condition "abd".
76799   */
76800   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase) ){
76801     Expr *pLeft, *pRight;
76802     Expr *pStr1, *pStr2;
76803     Expr *pNewExpr1, *pNewExpr2;
76804     int idxNew1, idxNew2;
76805
76806     pLeft = pExpr->pList->a[1].pExpr;
76807     pRight = pExpr->pList->a[0].pExpr;
76808     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
76809     if( pStr1 ){
76810       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
76811       pStr1->token.n = nPattern;
76812       pStr1->flags = EP_Dequoted;
76813     }
76814     pStr2 = sqlite3ExprDup(db, pStr1);
76815     if( !db->mallocFailed ){
76816       u8 c, *pC;
76817       assert( pStr2->token.dyn );
76818       pC = (u8*)&pStr2->token.z[nPattern-1];
76819       c = *pC;
76820       if( noCase ){
76821         if( c=='@' ) isComplete = 0;
76822         c = sqlite3UpperToLower[c];
76823       }
76824       *pC = c + 1;
76825     }
76826     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
76827     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
76828     exprAnalyze(pSrc, pWC, idxNew1);
76829     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
76830     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
76831     exprAnalyze(pSrc, pWC, idxNew2);
76832     pTerm = &pWC->a[idxTerm];
76833     if( isComplete ){
76834       pWC->a[idxNew1].iParent = idxTerm;
76835       pWC->a[idxNew2].iParent = idxTerm;
76836       pTerm->nChild = 2;
76837     }
76838   }
76839 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
76840
76841 #ifndef SQLITE_OMIT_VIRTUALTABLE
76842   /* Add a WO_MATCH auxiliary term to the constraint set if the
76843   ** current expression is of the form:  column MATCH expr.
76844   ** This information is used by the xBestIndex methods of
76845   ** virtual tables.  The native query optimizer does not attempt
76846   ** to do anything with MATCH functions.
76847   */
76848   if( isMatchOfColumn(pExpr) ){
76849     int idxNew;
76850     Expr *pRight, *pLeft;
76851     WhereTerm *pNewTerm;
76852     Bitmask prereqColumn, prereqExpr;
76853
76854     pRight = pExpr->pList->a[0].pExpr;
76855     pLeft = pExpr->pList->a[1].pExpr;
76856     prereqExpr = exprTableUsage(pMaskSet, pRight);
76857     prereqColumn = exprTableUsage(pMaskSet, pLeft);
76858     if( (prereqExpr & prereqColumn)==0 ){
76859       Expr *pNewExpr;
76860       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
76861       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
76862       pNewTerm = &pWC->a[idxNew];
76863       pNewTerm->prereqRight = prereqExpr;
76864       pNewTerm->leftCursor = pLeft->iTable;
76865       pNewTerm->leftColumn = pLeft->iColumn;
76866       pNewTerm->eOperator = WO_MATCH;
76867       pNewTerm->iParent = idxTerm;
76868       pTerm = &pWC->a[idxTerm];
76869       pTerm->nChild = 1;
76870       pTerm->flags |= TERM_COPIED;
76871       pNewTerm->prereqAll = pTerm->prereqAll;
76872     }
76873   }
76874 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76875
76876   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
76877   ** an index for tables to the left of the join.
76878   */
76879   pTerm->prereqRight |= extraRight;
76880 }
76881
76882 /*
76883 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
76884 ** a reference to any table other than the iBase table.
76885 */
76886 static int referencesOtherTables(
76887   ExprList *pList,          /* Search expressions in ths list */
76888   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
76889   int iFirst,               /* Be searching with the iFirst-th expression */
76890   int iBase                 /* Ignore references to this table */
76891 ){
76892   Bitmask allowed = ~getMask(pMaskSet, iBase);
76893   while( iFirst<pList->nExpr ){
76894     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
76895       return 1;
76896     }
76897   }
76898   return 0;
76899 }
76900
76901
76902 /*
76903 ** This routine decides if pIdx can be used to satisfy the ORDER BY
76904 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
76905 ** ORDER BY clause, this routine returns 0.
76906 **
76907 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
76908 ** left-most table in the FROM clause of that same SELECT statement and
76909 ** the table has a cursor number of "base".  pIdx is an index on pTab.
76910 **
76911 ** nEqCol is the number of columns of pIdx that are used as equality
76912 ** constraints.  Any of these columns may be missing from the ORDER BY
76913 ** clause and the match can still be a success.
76914 **
76915 ** All terms of the ORDER BY that match against the index must be either
76916 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
76917 ** index do not need to satisfy this constraint.)  The *pbRev value is
76918 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
76919 ** the ORDER BY clause is all ASC.
76920 */
76921 static int isSortingIndex(
76922   Parse *pParse,          /* Parsing context */
76923   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
76924   Index *pIdx,            /* The index we are testing */
76925   int base,               /* Cursor number for the table to be sorted */
76926   ExprList *pOrderBy,     /* The ORDER BY clause */
76927   int nEqCol,             /* Number of index columns with == constraints */
76928   int *pbRev              /* Set to 1 if ORDER BY is DESC */
76929 ){
76930   int i, j;                       /* Loop counters */
76931   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
76932   int nTerm;                      /* Number of ORDER BY terms */
76933   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
76934   sqlite3 *db = pParse->db;
76935
76936   assert( pOrderBy!=0 );
76937   nTerm = pOrderBy->nExpr;
76938   assert( nTerm>0 );
76939
76940   /* Match terms of the ORDER BY clause against columns of
76941   ** the index.
76942   **
76943   ** Note that indices have pIdx->nColumn regular columns plus
76944   ** one additional column containing the rowid.  The rowid column
76945   ** of the index is also allowed to match against the ORDER BY
76946   ** clause.
76947   */
76948   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
76949     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
76950     CollSeq *pColl;    /* The collating sequence of pExpr */
76951     int termSortOrder; /* Sort order for this term */
76952     int iColumn;       /* The i-th column of the index.  -1 for rowid */
76953     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
76954     const char *zColl; /* Name of the collating sequence for i-th index term */
76955
76956     pExpr = pTerm->pExpr;
76957     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
76958       /* Can not use an index sort on anything that is not a column in the
76959       ** left-most table of the FROM clause */
76960       break;
76961     }
76962     pColl = sqlite3ExprCollSeq(pParse, pExpr);
76963     if( !pColl ){
76964       pColl = db->pDfltColl;
76965     }
76966     if( i<pIdx->nColumn ){
76967       iColumn = pIdx->aiColumn[i];
76968       if( iColumn==pIdx->pTable->iPKey ){
76969         iColumn = -1;
76970       }
76971       iSortOrder = pIdx->aSortOrder[i];
76972       zColl = pIdx->azColl[i];
76973     }else{
76974       iColumn = -1;
76975       iSortOrder = 0;
76976       zColl = pColl->zName;
76977     }
76978     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
76979       /* Term j of the ORDER BY clause does not match column i of the index */
76980       if( i<nEqCol ){
76981         /* If an index column that is constrained by == fails to match an
76982         ** ORDER BY term, that is OK.  Just ignore that column of the index
76983         */
76984         continue;
76985       }else if( i==pIdx->nColumn ){
76986         /* Index column i is the rowid.  All other terms match. */
76987         break;
76988       }else{
76989         /* If an index column fails to match and is not constrained by ==
76990         ** then the index cannot satisfy the ORDER BY constraint.
76991         */
76992         return 0;
76993       }
76994     }
76995     assert( pIdx->aSortOrder!=0 );
76996     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
76997     assert( iSortOrder==0 || iSortOrder==1 );
76998     termSortOrder = iSortOrder ^ pTerm->sortOrder;
76999     if( i>nEqCol ){
77000       if( termSortOrder!=sortOrder ){
77001         /* Indices can only be used if all ORDER BY terms past the
77002         ** equality constraints are all either DESC or ASC. */
77003         return 0;
77004       }
77005     }else{
77006       sortOrder = termSortOrder;
77007     }
77008     j++;
77009     pTerm++;
77010     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
77011       /* If the indexed column is the primary key and everything matches
77012       ** so far and none of the ORDER BY terms to the right reference other
77013       ** tables in the join, then we are assured that the index can be used 
77014       ** to sort because the primary key is unique and so none of the other
77015       ** columns will make any difference
77016       */
77017       j = nTerm;
77018     }
77019   }
77020
77021   *pbRev = sortOrder!=0;
77022   if( j>=nTerm ){
77023     /* All terms of the ORDER BY clause are covered by this index so
77024     ** this index can be used for sorting. */
77025     return 1;
77026   }
77027   if( pIdx->onError!=OE_None && i==pIdx->nColumn
77028       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
77029     /* All terms of this index match some prefix of the ORDER BY clause
77030     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
77031     ** clause reference other tables in a join.  If this is all true then
77032     ** the order by clause is superfluous. */
77033     return 1;
77034   }
77035   return 0;
77036 }
77037
77038 /*
77039 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
77040 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
77041 ** true for reverse ROWID and false for forward ROWID order.
77042 */
77043 static int sortableByRowid(
77044   int base,               /* Cursor number for table to be sorted */
77045   ExprList *pOrderBy,     /* The ORDER BY clause */
77046   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
77047   int *pbRev              /* Set to 1 if ORDER BY is DESC */
77048 ){
77049   Expr *p;
77050
77051   assert( pOrderBy!=0 );
77052   assert( pOrderBy->nExpr>0 );
77053   p = pOrderBy->a[0].pExpr;
77054   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
77055     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
77056     *pbRev = pOrderBy->a[0].sortOrder;
77057     return 1;
77058   }
77059   return 0;
77060 }
77061
77062 /*
77063 ** Prepare a crude estimate of the logarithm of the input value.
77064 ** The results need not be exact.  This is only used for estimating
77065 ** the total cost of performing operations with O(logN) or O(NlogN)
77066 ** complexity.  Because N is just a guess, it is no great tragedy if
77067 ** logN is a little off.
77068 */
77069 static double estLog(double N){
77070   double logN = 1;
77071   double x = 10;
77072   while( N>x ){
77073     logN += 1;
77074     x *= 10;
77075   }
77076   return logN;
77077 }
77078
77079 /*
77080 ** Two routines for printing the content of an sqlite3_index_info
77081 ** structure.  Used for testing and debugging only.  If neither
77082 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
77083 ** are no-ops.
77084 */
77085 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
77086 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
77087   int i;
77088   if( !sqlite3WhereTrace ) return;
77089   for(i=0; i<p->nConstraint; i++){
77090     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
77091        i,
77092        p->aConstraint[i].iColumn,
77093        p->aConstraint[i].iTermOffset,
77094        p->aConstraint[i].op,
77095        p->aConstraint[i].usable);
77096   }
77097   for(i=0; i<p->nOrderBy; i++){
77098     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
77099        i,
77100        p->aOrderBy[i].iColumn,
77101        p->aOrderBy[i].desc);
77102   }
77103 }
77104 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
77105   int i;
77106   if( !sqlite3WhereTrace ) return;
77107   for(i=0; i<p->nConstraint; i++){
77108     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
77109        i,
77110        p->aConstraintUsage[i].argvIndex,
77111        p->aConstraintUsage[i].omit);
77112   }
77113   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
77114   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
77115   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
77116   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
77117 }
77118 #else
77119 #define TRACE_IDX_INPUTS(A)
77120 #define TRACE_IDX_OUTPUTS(A)
77121 #endif
77122
77123 #ifndef SQLITE_OMIT_VIRTUALTABLE
77124 /*
77125 ** Compute the best index for a virtual table.
77126 **
77127 ** The best index is computed by the xBestIndex method of the virtual
77128 ** table module.  This routine is really just a wrapper that sets up
77129 ** the sqlite3_index_info structure that is used to communicate with
77130 ** xBestIndex.
77131 **
77132 ** In a join, this routine might be called multiple times for the
77133 ** same virtual table.  The sqlite3_index_info structure is created
77134 ** and initialized on the first invocation and reused on all subsequent
77135 ** invocations.  The sqlite3_index_info structure is also used when
77136 ** code is generated to access the virtual table.  The whereInfoDelete() 
77137 ** routine takes care of freeing the sqlite3_index_info structure after
77138 ** everybody has finished with it.
77139 */
77140 static double bestVirtualIndex(
77141   Parse *pParse,                 /* The parsing context */
77142   WhereClause *pWC,              /* The WHERE clause */
77143   struct SrcList_item *pSrc,     /* The FROM clause term to search */
77144   Bitmask notReady,              /* Mask of cursors that are not available */
77145   ExprList *pOrderBy,            /* The order by clause */
77146   int orderByUsable,             /* True if we can potential sort */
77147   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
77148 ){
77149   Table *pTab = pSrc->pTab;
77150   sqlite3_vtab *pVtab = pTab->pVtab;
77151   sqlite3_index_info *pIdxInfo;
77152   struct sqlite3_index_constraint *pIdxCons;
77153   struct sqlite3_index_orderby *pIdxOrderBy;
77154   struct sqlite3_index_constraint_usage *pUsage;
77155   WhereTerm *pTerm;
77156   int i, j;
77157   int nOrderBy;
77158   int rc;
77159
77160   /* If the sqlite3_index_info structure has not been previously
77161   ** allocated and initialized for this virtual table, then allocate
77162   ** and initialize it now
77163   */
77164   pIdxInfo = *ppIdxInfo;
77165   if( pIdxInfo==0 ){
77166     WhereTerm *pTerm;
77167     int nTerm;
77168     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
77169
77170     /* Count the number of possible WHERE clause constraints referring
77171     ** to this virtual table */
77172     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
77173       if( pTerm->leftCursor != pSrc->iCursor ) continue;
77174       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
77175       testcase( pTerm->eOperator==WO_IN );
77176       testcase( pTerm->eOperator==WO_ISNULL );
77177       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
77178       nTerm++;
77179     }
77180
77181     /* If the ORDER BY clause contains only columns in the current 
77182     ** virtual table then allocate space for the aOrderBy part of
77183     ** the sqlite3_index_info structure.
77184     */
77185     nOrderBy = 0;
77186     if( pOrderBy ){
77187       for(i=0; i<pOrderBy->nExpr; i++){
77188         Expr *pExpr = pOrderBy->a[i].pExpr;
77189         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
77190       }
77191       if( i==pOrderBy->nExpr ){
77192         nOrderBy = pOrderBy->nExpr;
77193       }
77194     }
77195
77196     /* Allocate the sqlite3_index_info structure
77197     */
77198     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
77199                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
77200                              + sizeof(*pIdxOrderBy)*nOrderBy );
77201     if( pIdxInfo==0 ){
77202       sqlite3ErrorMsg(pParse, "out of memory");
77203       return 0.0;
77204     }
77205     *ppIdxInfo = pIdxInfo;
77206
77207     /* Initialize the structure.  The sqlite3_index_info structure contains
77208     ** many fields that are declared "const" to prevent xBestIndex from
77209     ** changing them.  We have to do some funky casting in order to
77210     ** initialize those fields.
77211     */
77212     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
77213     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
77214     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
77215     *(int*)&pIdxInfo->nConstraint = nTerm;
77216     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
77217     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
77218     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
77219     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
77220                                                                      pUsage;
77221
77222     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
77223       if( pTerm->leftCursor != pSrc->iCursor ) continue;
77224       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
77225       testcase( pTerm->eOperator==WO_IN );
77226       testcase( pTerm->eOperator==WO_ISNULL );
77227       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
77228       pIdxCons[j].iColumn = pTerm->leftColumn;
77229       pIdxCons[j].iTermOffset = i;
77230       pIdxCons[j].op = pTerm->eOperator;
77231       /* The direct assignment in the previous line is possible only because
77232       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
77233       ** following asserts verify this fact. */
77234       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
77235       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
77236       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
77237       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
77238       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
77239       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
77240       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
77241       j++;
77242     }
77243     for(i=0; i<nOrderBy; i++){
77244       Expr *pExpr = pOrderBy->a[i].pExpr;
77245       pIdxOrderBy[i].iColumn = pExpr->iColumn;
77246       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
77247     }
77248   }
77249
77250   /* At this point, the sqlite3_index_info structure that pIdxInfo points
77251   ** to will have been initialized, either during the current invocation or
77252   ** during some prior invocation.  Now we just have to customize the
77253   ** details of pIdxInfo for the current invocation and pass it to
77254   ** xBestIndex.
77255   */
77256
77257   /* The module name must be defined. Also, by this point there must
77258   ** be a pointer to an sqlite3_vtab structure. Otherwise
77259   ** sqlite3ViewGetColumnNames() would have picked up the error. 
77260   */
77261   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
77262   assert( pVtab );
77263 #if 0
77264   if( pTab->pVtab==0 ){
77265     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
77266         pTab->azModuleArg[0], pTab->zName);
77267     return 0.0;
77268   }
77269 #endif
77270
77271   /* Set the aConstraint[].usable fields and initialize all 
77272   ** output variables to zero.
77273   **
77274   ** aConstraint[].usable is true for constraints where the right-hand
77275   ** side contains only references to tables to the left of the current
77276   ** table.  In other words, if the constraint is of the form:
77277   **
77278   **           column = expr
77279   **
77280   ** and we are evaluating a join, then the constraint on column is 
77281   ** only valid if all tables referenced in expr occur to the left
77282   ** of the table containing column.
77283   **
77284   ** The aConstraints[] array contains entries for all constraints
77285   ** on the current table.  That way we only have to compute it once
77286   ** even though we might try to pick the best index multiple times.
77287   ** For each attempt at picking an index, the order of tables in the
77288   ** join might be different so we have to recompute the usable flag
77289   ** each time.
77290   */
77291   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
77292   pUsage = pIdxInfo->aConstraintUsage;
77293   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
77294     j = pIdxCons->iTermOffset;
77295     pTerm = &pWC->a[j];
77296     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
77297   }
77298   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
77299   if( pIdxInfo->needToFreeIdxStr ){
77300     sqlite3_free(pIdxInfo->idxStr);
77301   }
77302   pIdxInfo->idxStr = 0;
77303   pIdxInfo->idxNum = 0;
77304   pIdxInfo->needToFreeIdxStr = 0;
77305   pIdxInfo->orderByConsumed = 0;
77306   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
77307   nOrderBy = pIdxInfo->nOrderBy;
77308   if( pIdxInfo->nOrderBy && !orderByUsable ){
77309     *(int*)&pIdxInfo->nOrderBy = 0;
77310   }
77311
77312   (void)sqlite3SafetyOff(pParse->db);
77313   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
77314   TRACE_IDX_INPUTS(pIdxInfo);
77315   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
77316   TRACE_IDX_OUTPUTS(pIdxInfo);
77317   (void)sqlite3SafetyOn(pParse->db);
77318
77319   if( rc!=SQLITE_OK ){
77320     if( rc==SQLITE_NOMEM ){
77321       pParse->db->mallocFailed = 1;
77322     }else if( !pVtab->zErrMsg ){
77323       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
77324     }else{
77325       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
77326     }
77327   }
77328   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
77329   pVtab->zErrMsg = 0;
77330
77331   for(i=0; i<pIdxInfo->nConstraint; i++){
77332     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
77333       sqlite3ErrorMsg(pParse, 
77334           "table %s: xBestIndex returned an invalid plan", pTab->zName);
77335       return 0.0;
77336     }
77337   }
77338
77339   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
77340   return pIdxInfo->estimatedCost;
77341 }
77342 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77343
77344 /*
77345 ** Find the best index for accessing a particular table.  Return a pointer
77346 ** to the index, flags that describe how the index should be used, the
77347 ** number of equality constraints, and the "cost" for this index.
77348 **
77349 ** The lowest cost index wins.  The cost is an estimate of the amount of
77350 ** CPU and disk I/O need to process the request using the selected index.
77351 ** Factors that influence cost include:
77352 **
77353 **    *  The estimated number of rows that will be retrieved.  (The
77354 **       fewer the better.)
77355 **
77356 **    *  Whether or not sorting must occur.
77357 **
77358 **    *  Whether or not there must be separate lookups in the
77359 **       index and in the main table.
77360 **
77361 ** If there was an INDEXED BY clause attached to the table in the SELECT
77362 ** statement, then this function only considers strategies using the 
77363 ** named index. If one cannot be found, then the returned cost is
77364 ** SQLITE_BIG_DBL. If a strategy can be found that uses the named index, 
77365 ** then the cost is calculated in the usual way.
77366 **
77367 ** If a NOT INDEXED clause was attached to the table in the SELECT 
77368 ** statement, then no indexes are considered. However, the selected 
77369 ** stategy may still take advantage of the tables built-in rowid
77370 ** index.
77371 */
77372 static double bestIndex(
77373   Parse *pParse,              /* The parsing context */
77374   WhereClause *pWC,           /* The WHERE clause */
77375   struct SrcList_item *pSrc,  /* The FROM clause term to search */
77376   Bitmask notReady,           /* Mask of cursors that are not available */
77377   ExprList *pOrderBy,         /* The order by clause */
77378   Index **ppIndex,            /* Make *ppIndex point to the best index */
77379   int *pFlags,                /* Put flags describing this choice in *pFlags */
77380   int *pnEq                   /* Put the number of == or IN constraints here */
77381 ){
77382   WhereTerm *pTerm;
77383   Index *bestIdx = 0;         /* Index that gives the lowest cost */
77384   double lowestCost;          /* The cost of using bestIdx */
77385   int bestFlags = 0;          /* Flags associated with bestIdx */
77386   int bestNEq = 0;            /* Best value for nEq */
77387   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
77388   Index *pProbe;              /* An index we are evaluating */
77389   int rev;                    /* True to scan in reverse order */
77390   int flags;                  /* Flags associated with pProbe */
77391   int nEq;                    /* Number of == or IN constraints */
77392   int eqTermMask;             /* Mask of valid equality operators */
77393   double cost;                /* Cost of using pProbe */
77394
77395   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady));
77396   lowestCost = SQLITE_BIG_DBL;
77397   pProbe = pSrc->pTab->pIndex;
77398   if( pSrc->notIndexed ){
77399     pProbe = 0;
77400   }
77401
77402   /* If the table has no indices and there are no terms in the where
77403   ** clause that refer to the ROWID, then we will never be able to do
77404   ** anything other than a full table scan on this table.  We might as
77405   ** well put it first in the join order.  That way, perhaps it can be
77406   ** referenced by other tables in the join.
77407   */
77408   if( pProbe==0 &&
77409      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
77410      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
77411     *pFlags = 0;
77412     *ppIndex = 0;
77413     *pnEq = 0;
77414     return 0.0;
77415   }
77416
77417   /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
77418   ** an INDEXED BY clause attached to this table, skip this step.
77419   */
77420   if( !pSrc->pIndex ){
77421     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
77422     if( pTerm ){
77423       Expr *pExpr;
77424       *ppIndex = 0;
77425       bestFlags = WHERE_ROWID_EQ;
77426       if( pTerm->eOperator & WO_EQ ){
77427         /* Rowid== is always the best pick.  Look no further.  Because only
77428         ** a single row is generated, output is always in sorted order */
77429         *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
77430         *pnEq = 1;
77431         WHERETRACE(("... best is rowid\n"));
77432         return 0.0;
77433       }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
77434         /* Rowid IN (LIST): cost is NlogN where N is the number of list
77435         ** elements.  */
77436         lowestCost = pExpr->pList->nExpr;
77437         lowestCost *= estLog(lowestCost);
77438       }else{
77439         /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
77440         ** in the result of the inner select.  We have no way to estimate
77441         ** that value so make a wild guess. */
77442         lowestCost = 200;
77443       }
77444       WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
77445     }
77446   
77447     /* Estimate the cost of a table scan.  If we do not know how many
77448     ** entries are in the table, use 1 million as a guess.
77449     */
77450     cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
77451     WHERETRACE(("... table scan base cost: %.9g\n", cost));
77452     flags = WHERE_ROWID_RANGE;
77453   
77454     /* Check for constraints on a range of rowids in a table scan.
77455     */
77456     pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
77457     if( pTerm ){
77458       if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
77459         flags |= WHERE_TOP_LIMIT;
77460         cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
77461       }
77462       if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
77463         flags |= WHERE_BTM_LIMIT;
77464         cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
77465       }
77466       WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
77467     }else{
77468       flags = 0;
77469     }
77470   
77471     /* If the table scan does not satisfy the ORDER BY clause, increase
77472     ** the cost by NlogN to cover the expense of sorting. */
77473     if( pOrderBy ){
77474       if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
77475         flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
77476         if( rev ){
77477           flags |= WHERE_REVERSE;
77478         }
77479       }else{
77480         cost += cost*estLog(cost);
77481         WHERETRACE(("... sorting increases cost to %.9g\n", cost));
77482       }
77483     }
77484     if( cost<lowestCost ){
77485       lowestCost = cost;
77486       bestFlags = flags;
77487     }
77488   }
77489
77490   /* If the pSrc table is the right table of a LEFT JOIN then we may not
77491   ** use an index to satisfy IS NULL constraints on that table.  This is
77492   ** because columns might end up being NULL if the table does not match -
77493   ** a circumstance which the index cannot help us discover.  Ticket #2177.
77494   */
77495   if( (pSrc->jointype & JT_LEFT)!=0 ){
77496     eqTermMask = WO_EQ|WO_IN;
77497   }else{
77498     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
77499   }
77500
77501   /* Look at each index.
77502   */
77503   if( pSrc->pIndex ){
77504     pProbe = pSrc->pIndex;
77505   }
77506   for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
77507     int i;                       /* Loop counter */
77508     double inMultiplier = 1;
77509
77510     WHERETRACE(("... index %s:\n", pProbe->zName));
77511
77512     /* Count the number of columns in the index that are satisfied
77513     ** by x=EXPR constraints or x IN (...) constraints.
77514     */
77515     flags = 0;
77516     for(i=0; i<pProbe->nColumn; i++){
77517       int j = pProbe->aiColumn[i];
77518       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
77519       if( pTerm==0 ) break;
77520       flags |= WHERE_COLUMN_EQ;
77521       if( pTerm->eOperator & WO_IN ){
77522         Expr *pExpr = pTerm->pExpr;
77523         flags |= WHERE_COLUMN_IN;
77524         if( pExpr->pSelect!=0 ){
77525           inMultiplier *= 25;
77526         }else if( ALWAYS(pExpr->pList) ){
77527           inMultiplier *= pExpr->pList->nExpr + 1;
77528         }
77529       }
77530     }
77531     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
77532     nEq = i;
77533     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
77534          && nEq==pProbe->nColumn ){
77535       flags |= WHERE_UNIQUE;
77536     }
77537     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
77538
77539     /* Look for range constraints
77540     */
77541     if( nEq<pProbe->nColumn ){
77542       int j = pProbe->aiColumn[nEq];
77543       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
77544       if( pTerm ){
77545         flags |= WHERE_COLUMN_RANGE;
77546         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
77547           flags |= WHERE_TOP_LIMIT;
77548           cost /= 3;
77549         }
77550         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
77551           flags |= WHERE_BTM_LIMIT;
77552           cost /= 3;
77553         }
77554         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
77555       }
77556     }
77557
77558     /* Add the additional cost of sorting if that is a factor.
77559     */
77560     if( pOrderBy ){
77561       if( (flags & WHERE_COLUMN_IN)==0 &&
77562            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
77563         if( flags==0 ){
77564           flags = WHERE_COLUMN_RANGE;
77565         }
77566         flags |= WHERE_ORDERBY;
77567         if( rev ){
77568           flags |= WHERE_REVERSE;
77569         }
77570       }else{
77571         cost += cost*estLog(cost);
77572         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
77573       }
77574     }
77575
77576     /* Check to see if we can get away with using just the index without
77577     ** ever reading the table.  If that is the case, then halve the
77578     ** cost of this index.
77579     */
77580     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
77581       Bitmask m = pSrc->colUsed;
77582       int j;
77583       for(j=0; j<pProbe->nColumn; j++){
77584         int x = pProbe->aiColumn[j];
77585         if( x<BMS-1 ){
77586           m &= ~(((Bitmask)1)<<x);
77587         }
77588       }
77589       if( m==0 ){
77590         flags |= WHERE_IDX_ONLY;
77591         cost /= 2;
77592         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
77593       }
77594     }
77595
77596     /* If this index has achieved the lowest cost so far, then use it.
77597     */
77598     if( flags && cost < lowestCost ){
77599       bestIdx = pProbe;
77600       lowestCost = cost;
77601       bestFlags = flags;
77602       bestNEq = nEq;
77603     }
77604   }
77605
77606   /* Report the best result
77607   */
77608   *ppIndex = bestIdx;
77609   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
77610         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
77611   *pFlags = bestFlags | eqTermMask;
77612   *pnEq = bestNEq;
77613   return lowestCost;
77614 }
77615
77616
77617 /*
77618 ** Disable a term in the WHERE clause.  Except, do not disable the term
77619 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
77620 ** or USING clause of that join.
77621 **
77622 ** Consider the term t2.z='ok' in the following queries:
77623 **
77624 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
77625 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
77626 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
77627 **
77628 ** The t2.z='ok' is disabled in the in (2) because it originates
77629 ** in the ON clause.  The term is disabled in (3) because it is not part
77630 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
77631 **
77632 ** Disabling a term causes that term to not be tested in the inner loop
77633 ** of the join.  Disabling is an optimization.  When terms are satisfied
77634 ** by indices, we disable them to prevent redundant tests in the inner
77635 ** loop.  We would get the correct results if nothing were ever disabled,
77636 ** but joins might run a little slower.  The trick is to disable as much
77637 ** as we can without disabling too much.  If we disabled in (1), we'd get
77638 ** the wrong answer.  See ticket #813.
77639 */
77640 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
77641   if( pTerm
77642       && ALWAYS((pTerm->flags & TERM_CODED)==0)
77643       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
77644   ){
77645     pTerm->flags |= TERM_CODED;
77646     if( pTerm->iParent>=0 ){
77647       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
77648       if( (--pOther->nChild)==0 ){
77649         disableTerm(pLevel, pOther);
77650       }
77651     }
77652   }
77653 }
77654
77655 /*
77656 ** Apply the affinities associated with the first n columns of index
77657 ** pIdx to the values in the n registers starting at base.
77658 */
77659 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
77660   if( n>0 ){
77661     Vdbe *v = pParse->pVdbe;
77662     assert( v!=0 );
77663     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
77664     sqlite3IndexAffinityStr(v, pIdx);
77665     sqlite3ExprCacheAffinityChange(pParse, base, n);
77666   }
77667 }
77668
77669
77670 /*
77671 ** Generate code for a single equality term of the WHERE clause.  An equality
77672 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
77673 ** coded.
77674 **
77675 ** The current value for the constraint is left in register iReg.
77676 **
77677 ** For a constraint of the form X=expr, the expression is evaluated and its
77678 ** result is left on the stack.  For constraints of the form X IN (...)
77679 ** this routine sets up a loop that will iterate over all values of X.
77680 */
77681 static int codeEqualityTerm(
77682   Parse *pParse,      /* The parsing context */
77683   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
77684   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
77685   int iTarget         /* Attempt to leave results in this register */
77686 ){
77687   Expr *pX = pTerm->pExpr;
77688   Vdbe *v = pParse->pVdbe;
77689   int iReg;                  /* Register holding results */
77690
77691   assert( iTarget>0 );
77692   if( pX->op==TK_EQ ){
77693     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
77694   }else if( pX->op==TK_ISNULL ){
77695     iReg = iTarget;
77696     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
77697 #ifndef SQLITE_OMIT_SUBQUERY
77698   }else{
77699     int eType;
77700     int iTab;
77701     struct InLoop *pIn;
77702
77703     assert( pX->op==TK_IN );
77704     iReg = iTarget;
77705     eType = sqlite3FindInIndex(pParse, pX, 0);
77706     iTab = pX->iTable;
77707     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
77708     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
77709     if( pLevel->nIn==0 ){
77710       pLevel->nxt = sqlite3VdbeMakeLabel(v);
77711     }
77712     pLevel->nIn++;
77713     pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop,
77714                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
77715     pIn = pLevel->aInLoop;
77716     if( pIn ){
77717       pIn += pLevel->nIn - 1;
77718       pIn->iCur = iTab;
77719       if( eType==IN_INDEX_ROWID ){
77720         pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
77721       }else{
77722         pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
77723       }
77724       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
77725     }else{
77726       pLevel->nIn = 0;
77727     }
77728 #endif
77729   }
77730   disableTerm(pLevel, pTerm);
77731   return iReg;
77732 }
77733
77734 /*
77735 ** Generate code that will evaluate all == and IN constraints for an
77736 ** index.  The values for all constraints are left on the stack.
77737 **
77738 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
77739 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
77740 ** The index has as many as three equality constraints, but in this
77741 ** example, the third "c" value is an inequality.  So only two 
77742 ** constraints are coded.  This routine will generate code to evaluate
77743 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
77744 ** on the stack - a is the deepest and b the shallowest.
77745 **
77746 ** In the example above nEq==2.  But this subroutine works for any value
77747 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
77748 ** The only thing it does is allocate the pLevel->iMem memory cell.
77749 **
77750 ** This routine always allocates at least one memory cell and puts
77751 ** the address of that memory cell in pLevel->iMem.  The code that
77752 ** calls this routine will use pLevel->iMem to store the termination
77753 ** key value of the loop.  If one or more IN operators appear, then
77754 ** this routine allocates an additional nEq memory cells for internal
77755 ** use.
77756 */
77757 static int codeAllEqualityTerms(
77758   Parse *pParse,        /* Parsing context */
77759   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
77760   WhereClause *pWC,     /* The WHERE clause */
77761   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
77762   int nExtraReg         /* Number of extra registers to allocate */
77763 ){
77764   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
77765   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
77766   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
77767   int iCur = pLevel->iTabCur;   /* The cursor of the table */
77768   WhereTerm *pTerm;             /* A single constraint term */
77769   int j;                        /* Loop counter */
77770   int regBase;                  /* Base register */
77771
77772   /* Figure out how many memory cells we will need then allocate them.
77773   ** We always need at least one used to store the loop terminator
77774   ** value.  If there are IN operators we'll need one for each == or
77775   ** IN constraint.
77776   */
77777   pLevel->iMem = pParse->nMem + 1;
77778   regBase = pParse->nMem + 2;
77779   pParse->nMem += pLevel->nEq + 2 + nExtraReg;
77780
77781   /* Evaluate the equality constraints
77782   */
77783   assert( pIdx->nColumn>=nEq );
77784   for(j=0; j<nEq; j++){
77785     int r1;
77786     int k = pIdx->aiColumn[j];
77787     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
77788     if( NEVER(pTerm==0) ) break;
77789     assert( (pTerm->flags & TERM_CODED)==0 );
77790     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
77791     if( r1!=regBase+j ){
77792       sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
77793     }
77794     testcase( pTerm->eOperator & WO_ISNULL );
77795     testcase( pTerm->eOperator & WO_IN );
77796     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
77797       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk);
77798     }
77799   }
77800   return regBase;
77801 }
77802
77803 #if defined(SQLITE_TEST)
77804 /*
77805 ** The following variable holds a text description of query plan generated
77806 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
77807 ** overwrites the previous.  This information is used for testing and
77808 ** analysis only.
77809 */
77810 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
77811 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
77812
77813 #endif /* SQLITE_TEST */
77814
77815
77816 /*
77817 ** Free a WhereInfo structure
77818 */
77819 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
77820   if( pWInfo ){
77821     int i;
77822     for(i=0; i<pWInfo->nLevel; i++){
77823       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
77824       if( pInfo ){
77825         assert( pInfo->needToFreeIdxStr==0 );
77826         sqlite3DbFree(db, pInfo);
77827       }
77828     }
77829     sqlite3DbFree(db, pWInfo);
77830   }
77831 }
77832
77833
77834 /*
77835 ** Generate the beginning of the loop used for WHERE clause processing.
77836 ** The return value is a pointer to an opaque structure that contains
77837 ** information needed to terminate the loop.  Later, the calling routine
77838 ** should invoke sqlite3WhereEnd() with the return value of this function
77839 ** in order to complete the WHERE clause processing.
77840 **
77841 ** If an error occurs, this routine returns NULL.
77842 **
77843 ** The basic idea is to do a nested loop, one loop for each table in
77844 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
77845 ** same as a SELECT with only a single table in the FROM clause.)  For
77846 ** example, if the SQL is this:
77847 **
77848 **       SELECT * FROM t1, t2, t3 WHERE ...;
77849 **
77850 ** Then the code generated is conceptually like the following:
77851 **
77852 **      foreach row1 in t1 do       \    Code generated
77853 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
77854 **          foreach row3 in t3 do   /
77855 **            ...
77856 **          end                     \    Code generated
77857 **        end                        |-- by sqlite3WhereEnd()
77858 **      end                         /
77859 **
77860 ** Note that the loops might not be nested in the order in which they
77861 ** appear in the FROM clause if a different order is better able to make
77862 ** use of indices.  Note also that when the IN operator appears in
77863 ** the WHERE clause, it might result in additional nested loops for
77864 ** scanning through all values on the right-hand side of the IN.
77865 **
77866 ** There are Btree cursors associated with each table.  t1 uses cursor
77867 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
77868 ** And so forth.  This routine generates code to open those VDBE cursors
77869 ** and sqlite3WhereEnd() generates the code to close them.
77870 **
77871 ** The code that sqlite3WhereBegin() generates leaves the cursors named
77872 ** in pTabList pointing at their appropriate entries.  The [...] code
77873 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
77874 ** data from the various tables of the loop.
77875 **
77876 ** If the WHERE clause is empty, the foreach loops must each scan their
77877 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
77878 ** the tables have indices and there are terms in the WHERE clause that
77879 ** refer to those indices, a complete table scan can be avoided and the
77880 ** code will run much faster.  Most of the work of this routine is checking
77881 ** to see if there are indices that can be used to speed up the loop.
77882 **
77883 ** Terms of the WHERE clause are also used to limit which rows actually
77884 ** make it to the "..." in the middle of the loop.  After each "foreach",
77885 ** terms of the WHERE clause that use only terms in that loop and outer
77886 ** loops are evaluated and if false a jump is made around all subsequent
77887 ** inner loops (or around the "..." if the test occurs within the inner-
77888 ** most loop)
77889 **
77890 ** OUTER JOINS
77891 **
77892 ** An outer join of tables t1 and t2 is conceptally coded as follows:
77893 **
77894 **    foreach row1 in t1 do
77895 **      flag = 0
77896 **      foreach row2 in t2 do
77897 **        start:
77898 **          ...
77899 **          flag = 1
77900 **      end
77901 **      if flag==0 then
77902 **        move the row2 cursor to a null row
77903 **        goto start
77904 **      fi
77905 **    end
77906 **
77907 ** ORDER BY CLAUSE PROCESSING
77908 **
77909 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
77910 ** if there is one.  If there is no ORDER BY clause or if this routine
77911 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
77912 **
77913 ** If an index can be used so that the natural output order of the table
77914 ** scan is correct for the ORDER BY clause, then that index is used and
77915 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
77916 ** unnecessary sort of the result set if an index appropriate for the
77917 ** ORDER BY clause already exists.
77918 **
77919 ** If the where clause loops cannot be arranged to provide the correct
77920 ** output order, then the *ppOrderBy is unchanged.
77921 */
77922 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
77923   Parse *pParse,        /* The parser context */
77924   SrcList *pTabList,    /* A list of all tables to be scanned */
77925   Expr *pWhere,         /* The WHERE clause */
77926   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
77927   u8 wflags             /* One of the WHERE_* flags defined in sqliteInt.h */
77928 ){
77929   int i;                     /* Loop counter */
77930   WhereInfo *pWInfo;         /* Will become the return value of this function */
77931   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
77932   int brk, cont = 0;         /* Addresses used during code generation */
77933   Bitmask notReady;          /* Cursors that are not yet positioned */
77934   WhereTerm *pTerm;          /* A single term in the WHERE clause */
77935   ExprMaskSet maskSet;       /* The expression mask set */
77936   WhereClause wc;            /* The WHERE clause is divided into these terms */
77937   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
77938   WhereLevel *pLevel;             /* A single level in the pWInfo list */
77939   int iFrom;                      /* First unused FROM clause element */
77940   int andFlags;              /* AND-ed combination of all wc.a[].flags */
77941   sqlite3 *db;               /* Database connection */
77942   ExprList *pOrderBy = 0;
77943
77944   /* The number of tables in the FROM clause is limited by the number of
77945   ** bits in a Bitmask 
77946   */
77947   if( pTabList->nSrc>BMS ){
77948     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
77949     return 0;
77950   }
77951
77952   if( ppOrderBy ){
77953     pOrderBy = *ppOrderBy;
77954   }
77955
77956   /* Split the WHERE clause into separate subexpressions where each
77957   ** subexpression is separated by an AND operator.
77958   */
77959   initMaskSet(&maskSet);
77960   whereClauseInit(&wc, pParse, &maskSet);
77961   sqlite3ExprCodeConstants(pParse, pWhere);
77962   whereSplit(&wc, pWhere, TK_AND);
77963     
77964   /* Allocate and initialize the WhereInfo structure that will become the
77965   ** return value.
77966   */
77967   db = pParse->db;
77968   pWInfo = sqlite3DbMallocZero(db,  
77969                       sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
77970   if( db->mallocFailed ){
77971     goto whereBeginError;
77972   }
77973   pWInfo->nLevel = pTabList->nSrc;
77974   pWInfo->pParse = pParse;
77975   pWInfo->pTabList = pTabList;
77976   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
77977
77978   /* Special case: a WHERE clause that is constant.  Evaluate the
77979   ** expression and either jump over all of the code or fall thru.
77980   */
77981   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
77982     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
77983     pWhere = 0;
77984   }
77985
77986   /* Assign a bit from the bitmask to every term in the FROM clause.
77987   **
77988   ** When assigning bitmask values to FROM clause cursors, it must be
77989   ** the case that if X is the bitmask for the N-th FROM clause term then
77990   ** the bitmask for all FROM clause terms to the left of the N-th term
77991   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
77992   ** its Expr.iRightJoinTable value to find the bitmask of the right table
77993   ** of the join.  Subtracting one from the right table bitmask gives a
77994   ** bitmask for all tables to the left of the join.  Knowing the bitmask
77995   ** for all tables to the left of a left join is important.  Ticket #3015.
77996   */
77997   for(i=0; i<pTabList->nSrc; i++){
77998     createMask(&maskSet, pTabList->a[i].iCursor);
77999   }
78000 #ifndef NDEBUG
78001   {
78002     Bitmask toTheLeft = 0;
78003     for(i=0; i<pTabList->nSrc; i++){
78004       Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor);
78005       assert( (m-1)==toTheLeft );
78006       toTheLeft |= m;
78007     }
78008   }
78009 #endif
78010
78011   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
78012   ** add new virtual terms onto the end of the WHERE clause.  We do not
78013   ** want to analyze these virtual terms, so start analyzing at the end
78014   ** and work forward so that the added virtual terms are never processed.
78015   */
78016   exprAnalyzeAll(pTabList, &wc);
78017   if( db->mallocFailed ){
78018     goto whereBeginError;
78019   }
78020
78021   /* Chose the best index to use for each table in the FROM clause.
78022   **
78023   ** This loop fills in the following fields:
78024   **
78025   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
78026   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
78027   **   pWInfo->a[].nEq       The number of == and IN constraints
78028   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
78029   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
78030   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
78031   **
78032   ** This loop also figures out the nesting order of tables in the FROM
78033   ** clause.
78034   */
78035   notReady = ~(Bitmask)0;
78036   pTabItem = pTabList->a;
78037   pLevel = pWInfo->a;
78038   andFlags = ~0;
78039   WHERETRACE(("*** Optimizer Start ***\n"));
78040   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78041     Index *pIdx;                /* Index for FROM table at pTabItem */
78042     int flags;                  /* Flags asssociated with pIdx */
78043     int nEq;                    /* Number of == or IN constraints */
78044     double cost;                /* The cost for pIdx */
78045     int j;                      /* For looping over FROM tables */
78046     Index *pBest = 0;           /* The best index seen so far */
78047     int bestFlags = 0;          /* Flags associated with pBest */
78048     int bestNEq = 0;            /* nEq associated with pBest */
78049     double lowestCost;          /* Cost of the pBest */
78050     int bestJ = 0;              /* The value of j */
78051     Bitmask m;                  /* Bitmask value for j or bestJ */
78052     int once = 0;               /* True when first table is seen */
78053     sqlite3_index_info *pIndex; /* Current virtual index */
78054
78055     lowestCost = SQLITE_BIG_DBL;
78056     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
78057       int doNotReorder;  /* True if this table should not be reordered */
78058
78059       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
78060       if( once && doNotReorder ) break;
78061       m = getMask(&maskSet, pTabItem->iCursor);
78062       if( (m & notReady)==0 ){
78063         if( j==iFrom ) iFrom++;
78064         continue;
78065       }
78066       assert( pTabItem->pTab );
78067 #ifndef SQLITE_OMIT_VIRTUALTABLE
78068       if( IsVirtual(pTabItem->pTab) ){
78069         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
78070         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
78071                                 ppOrderBy ? *ppOrderBy : 0, i==0,
78072                                 ppIdxInfo);
78073         flags = WHERE_VIRTUALTABLE;
78074         pIndex = *ppIdxInfo;
78075         if( pIndex && pIndex->orderByConsumed ){
78076           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
78077         }
78078         pIdx = 0;
78079         nEq = 0;
78080         if( (SQLITE_BIG_DBL/2.0)<cost ){
78081           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
78082           ** inital value of lowestCost in this loop. If it is, then
78083           ** the (cost<lowestCost) test below will never be true and
78084           ** pLevel->pBestIdx never set.
78085           */ 
78086           cost = (SQLITE_BIG_DBL/2.0);
78087         }
78088       }else 
78089 #endif
78090       {
78091         cost = bestIndex(pParse, &wc, pTabItem, notReady,
78092                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
78093                          &pIdx, &flags, &nEq);
78094         pIndex = 0;
78095       }
78096       if( cost<lowestCost ){
78097         once = 1;
78098         lowestCost = cost;
78099         pBest = pIdx;
78100         bestFlags = flags;
78101         bestNEq = nEq;
78102         bestJ = j;
78103         pLevel->pBestIdx = pIndex;
78104       }
78105       if( doNotReorder ) break;
78106     }
78107     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
78108            pLevel-pWInfo->a));
78109     if( (bestFlags & WHERE_ORDERBY)!=0 ){
78110       *ppOrderBy = 0;
78111     }
78112     andFlags &= bestFlags;
78113     pLevel->flags = bestFlags;
78114     pLevel->pIdx = pBest;
78115     pLevel->nEq = bestNEq;
78116     pLevel->aInLoop = 0;
78117     pLevel->nIn = 0;
78118     if( pBest ){
78119       pLevel->iIdxCur = pParse->nTab++;
78120     }else{
78121       pLevel->iIdxCur = -1;
78122     }
78123     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
78124     pLevel->iFrom = bestJ;
78125
78126     /* Check that if the table scanned by this loop iteration had an
78127     ** INDEXED BY clause attached to it, that the named index is being
78128     ** used for the scan. If not, then query compilation has failed.
78129     ** Return an error.
78130     */
78131     pIdx = pTabList->a[bestJ].pIndex;
78132     assert( !pIdx || !pBest || pIdx==pBest );
78133     if( pIdx && pBest!=pIdx ){
78134       sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
78135       goto whereBeginError;
78136     }
78137   }
78138   WHERETRACE(("*** Optimizer Finished ***\n"));
78139
78140   /* If the total query only selects a single row, then the ORDER BY
78141   ** clause is irrelevant.
78142   */
78143   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
78144     *ppOrderBy = 0;
78145   }
78146
78147   /* If the caller is an UPDATE or DELETE statement that is requesting
78148   ** to use a one-pass algorithm, determine if this is appropriate.
78149   ** The one-pass algorithm only works if the WHERE clause constraints
78150   ** the statement to update a single row.
78151   */
78152   assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
78153   if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
78154     pWInfo->okOnePass = 1;
78155     pWInfo->a[0].flags &= ~WHERE_IDX_ONLY;
78156   }
78157
78158   /* Open all tables in the pTabList and any indices selected for
78159   ** searching those tables.
78160   */
78161   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
78162   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78163     Table *pTab;     /* Table to open */
78164     Index *pIx;      /* Index used to access pTab (if any) */
78165     int iDb;         /* Index of database containing table/index */
78166     int iIdxCur = pLevel->iIdxCur;
78167
78168 #ifndef SQLITE_OMIT_EXPLAIN
78169     if( pParse->explain==2 ){
78170       char *zMsg;
78171       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
78172       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
78173       if( pItem->zAlias ){
78174         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
78175       }
78176       if( (pIx = pLevel->pIdx)!=0 ){
78177         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", zMsg, pIx->zName);
78178       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
78179         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
78180       }
78181 #ifndef SQLITE_OMIT_VIRTUALTABLE
78182       else if( pLevel->pBestIdx ){
78183         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
78184         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
78185                     pBestIdx->idxNum, pBestIdx->idxStr);
78186       }
78187 #endif
78188       if( pLevel->flags & WHERE_ORDERBY ){
78189         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
78190       }
78191       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
78192     }
78193 #endif /* SQLITE_OMIT_EXPLAIN */
78194     pTabItem = &pTabList->a[pLevel->iFrom];
78195     pTab = pTabItem->pTab;
78196     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78197     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
78198 #ifndef SQLITE_OMIT_VIRTUALTABLE
78199     if( pLevel->pBestIdx ){
78200       int iCur = pTabItem->iCursor;
78201       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
78202                         (const char*)pTab->pVtab, P4_VTAB);
78203     }else
78204 #endif
78205     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
78206       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
78207       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
78208       if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){
78209         Bitmask b = pTabItem->colUsed;
78210         int n = 0;
78211         for(; b; b=b>>1, n++){}
78212         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
78213         assert( n<=pTab->nCol );
78214       }
78215     }else{
78216       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
78217     }
78218     pLevel->iTabCur = pTabItem->iCursor;
78219     if( (pIx = pLevel->pIdx)!=0 ){
78220       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
78221       assert( pIx->pSchema==pTab->pSchema );
78222       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
78223       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
78224                         (char*)pKey, P4_KEYINFO_HANDOFF);
78225       VdbeComment((v, "%s", pIx->zName));
78226     }
78227     sqlite3CodeVerifySchema(pParse, iDb);
78228   }
78229   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
78230
78231   /* Generate the code to do the search.  Each iteration of the for
78232   ** loop below generates code for a single nested loop of the VM
78233   ** program.
78234   */
78235   notReady = ~(Bitmask)0;
78236   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78237     int j;
78238     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
78239     Index *pIdx;       /* The index we will be using */
78240     int nxt;           /* Where to jump to continue with the next IN case */
78241     int iIdxCur;       /* The VDBE cursor for the index */
78242     int omitTable;     /* True if we use the index only */
78243     int bRev;          /* True if we need to scan in reverse order */
78244
78245     pTabItem = &pTabList->a[pLevel->iFrom];
78246     iCur = pTabItem->iCursor;
78247     pIdx = pLevel->pIdx;
78248     iIdxCur = pLevel->iIdxCur;
78249     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
78250     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
78251
78252     /* Create labels for the "break" and "continue" instructions
78253     ** for the current loop.  Jump to brk to break out of a loop.
78254     ** Jump to cont to go immediately to the next iteration of the
78255     ** loop.
78256     **
78257     ** When there is an IN operator, we also have a "nxt" label that
78258     ** means to continue with the next IN value combination.  When
78259     ** there are no IN operators in the constraints, the "nxt" label
78260     ** is the same as "brk".
78261     */
78262     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
78263     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
78264
78265     /* If this is the right table of a LEFT OUTER JOIN, allocate and
78266     ** initialize a memory cell that records if this table matches any
78267     ** row of the left table of the join.
78268     */
78269     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
78270       pLevel->iLeftJoin = ++pParse->nMem;
78271       sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
78272       VdbeComment((v, "init LEFT JOIN no-match flag"));
78273     }
78274
78275 #ifndef SQLITE_OMIT_VIRTUALTABLE
78276     if( pLevel->pBestIdx ){
78277       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
78278       **          to access the data.
78279       */
78280       int j;
78281       int iReg;   /* P3 Value for OP_VFilter */
78282       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
78283       int nConstraint = pBestIdx->nConstraint;
78284       struct sqlite3_index_constraint_usage *aUsage =
78285                                                   pBestIdx->aConstraintUsage;
78286       const struct sqlite3_index_constraint *aConstraint =
78287                                                   pBestIdx->aConstraint;
78288
78289       iReg = sqlite3GetTempRange(pParse, nConstraint+2);
78290       pParse->disableColCache++;
78291       for(j=1; j<=nConstraint; j++){
78292         int k;
78293         for(k=0; k<nConstraint; k++){
78294           if( aUsage[k].argvIndex==j ){
78295             int iTerm = aConstraint[k].iTermOffset;
78296             assert( pParse->disableColCache );
78297             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1);
78298             break;
78299           }
78300         }
78301         if( k==nConstraint ) break;
78302       }
78303       assert( pParse->disableColCache );
78304       pParse->disableColCache--;
78305       sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg);
78306       sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
78307       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr,
78308                         pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
78309       sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
78310       pBestIdx->needToFreeIdxStr = 0;
78311       for(j=0; j<nConstraint; j++){
78312         if( aUsage[j].omit ){
78313           int iTerm = aConstraint[j].iTermOffset;
78314           disableTerm(pLevel, &wc.a[iTerm]);
78315         }
78316       }
78317       pLevel->op = OP_VNext;
78318       pLevel->p1 = iCur;
78319       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
78320     }else
78321 #endif /* SQLITE_OMIT_VIRTUALTABLE */
78322
78323     if( pLevel->flags & WHERE_ROWID_EQ ){
78324       /* Case 1:  We can directly reference a single row using an
78325       **          equality comparison against the ROWID field.  Or
78326       **          we reference multiple rows using a "rowid IN (...)"
78327       **          construct.
78328       */
78329       int r1;
78330       int rtmp = sqlite3GetTempReg(pParse);
78331       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
78332       assert( pTerm!=0 );
78333       assert( pTerm->pExpr!=0 );
78334       assert( pTerm->leftCursor==iCur );
78335       assert( omitTable==0 );
78336       r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
78337       nxt = pLevel->nxt;
78338       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt);
78339       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1);
78340       sqlite3ReleaseTempReg(pParse, rtmp);
78341       VdbeComment((v, "pk"));
78342       pLevel->op = OP_Noop;
78343     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
78344       /* Case 2:  We have an inequality comparison against the ROWID field.
78345       */
78346       int testOp = OP_Noop;
78347       int start;
78348       WhereTerm *pStart, *pEnd;
78349
78350       assert( omitTable==0 );
78351       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
78352       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
78353       if( bRev ){
78354         pTerm = pStart;
78355         pStart = pEnd;
78356         pEnd = pTerm;
78357       }
78358       if( pStart ){
78359         Expr *pX;
78360         int r1, regFree1;
78361         pX = pStart->pExpr;
78362         assert( pX!=0 );
78363         assert( pStart->leftCursor==iCur );
78364         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &regFree1);
78365         sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, 
78366                              pX->op==TK_LE || pX->op==TK_GT);
78367         sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1);
78368         VdbeComment((v, "pk"));
78369         sqlite3ReleaseTempReg(pParse, regFree1);
78370         disableTerm(pLevel, pStart);
78371       }else{
78372         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
78373       }
78374       if( pEnd ){
78375         Expr *pX;
78376         pX = pEnd->pExpr;
78377         assert( pX!=0 );
78378         assert( pEnd->leftCursor==iCur );
78379         pLevel->iMem = ++pParse->nMem;
78380         sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem);
78381         if( pX->op==TK_LT || pX->op==TK_GT ){
78382           testOp = bRev ? OP_Le : OP_Ge;
78383         }else{
78384           testOp = bRev ? OP_Lt : OP_Gt;
78385         }
78386         disableTerm(pLevel, pEnd);
78387       }
78388       start = sqlite3VdbeCurrentAddr(v);
78389       pLevel->op = bRev ? OP_Prev : OP_Next;
78390       pLevel->p1 = iCur;
78391       pLevel->p2 = start;
78392       if( testOp!=OP_Noop ){
78393         int r1 = sqlite3GetTempReg(pParse);
78394         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
78395         /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */
78396         sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1);
78397         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
78398         sqlite3ReleaseTempReg(pParse, r1);
78399       }
78400     }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
78401       /* Case 3: A scan using an index.
78402       **
78403       **         The WHERE clause may contain zero or more equality 
78404       **         terms ("==" or "IN" operators) that refer to the N
78405       **         left-most columns of the index. It may also contain
78406       **         inequality constraints (>, <, >= or <=) on the indexed
78407       **         column that immediately follows the N equalities. Only 
78408       **         the right-most column can be an inequality - the rest must
78409       **         use the "==" and "IN" operators. For example, if the 
78410       **         index is on (x,y,z), then the following clauses are all 
78411       **         optimized:
78412       **
78413       **            x=5
78414       **            x=5 AND y=10
78415       **            x=5 AND y<10
78416       **            x=5 AND y>5 AND y<10
78417       **            x=5 AND y=5 AND z<=10
78418       **
78419       **         The z<10 term of the following cannot be used, only
78420       **         the x=5 term:
78421       **
78422       **            x=5 AND z<10
78423       **
78424       **         N may be zero if there are inequality constraints.
78425       **         If there are no inequality constraints, then N is at
78426       **         least one.
78427       **
78428       **         This case is also used when there are no WHERE clause
78429       **         constraints but an index is selected anyway, in order
78430       **         to force the output order to conform to an ORDER BY.
78431       */  
78432       int aStartOp[] = {
78433         0,
78434         0,
78435         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
78436         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
78437         OP_MoveGt,           /* 4: (start_constraints  && !startEq && !bRev) */
78438         OP_MoveLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
78439         OP_MoveGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
78440         OP_MoveLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
78441       };
78442       int aEndOp[] = {
78443         OP_Noop,             /* 0: (!end_constraints) */
78444         OP_IdxGE,            /* 1: (end_constraints && !bRev) */
78445         OP_IdxLT             /* 2: (end_constraints && bRev) */
78446       };
78447       int nEq = pLevel->nEq;
78448       int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
78449       int regBase;                 /* Base register holding constraint values */
78450       int r1;                      /* Temp register */
78451       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
78452       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
78453       int startEq;                 /* True if range start uses ==, >= or <= */
78454       int endEq;                   /* True if range end uses ==, >= or <= */
78455       int start_constraints;       /* Start of range is constrained */
78456       int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
78457       int nConstraint;             /* Number of constraint terms */
78458       int op;
78459
78460       /* Generate code to evaluate all constraint terms using == or IN
78461       ** and store the values of those terms in an array of registers
78462       ** starting at regBase.
78463       */
78464       regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2);
78465       nxt = pLevel->nxt;
78466
78467       /* If this loop satisfies a sort order (pOrderBy) request that 
78468       ** was passed to this function to implement a "SELECT min(x) ..." 
78469       ** query, then the caller will only allow the loop to run for
78470       ** a single iteration. This means that the first row returned
78471       ** should not have a NULL value stored in 'x'. If column 'x' is
78472       ** the first one after the nEq equality constraints in the index,
78473       ** this requires some special handling.
78474       */
78475       if( (wflags&WHERE_ORDERBY_MIN)!=0
78476        && (pLevel->flags&WHERE_ORDERBY)
78477        && (pIdx->nColumn>nEq)
78478       ){
78479         assert( pOrderBy->nExpr==1 );
78480         assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] );
78481         isMinQuery = 1;
78482       }
78483
78484       /* Find any inequality constraint terms for the start and end 
78485       ** of the range. 
78486       */
78487       if( pLevel->flags & WHERE_TOP_LIMIT ){
78488         pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
78489       }
78490       if( pLevel->flags & WHERE_BTM_LIMIT ){
78491         pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
78492       }
78493
78494       /* If we are doing a reverse order scan on an ascending index, or
78495       ** a forward order scan on a descending index, interchange the 
78496       ** start and end terms (pRangeStart and pRangeEnd).
78497       */
78498       if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
78499         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
78500       }
78501
78502       testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
78503       testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
78504       testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
78505       testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
78506       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
78507       endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
78508       start_constraints = pRangeStart || nEq>0;
78509
78510       /* Seek the index cursor to the start of the range. */
78511       nConstraint = nEq;
78512       if( pRangeStart ){
78513         int dcc = pParse->disableColCache;
78514         if( pRangeEnd ){
78515           pParse->disableColCache++;
78516         }
78517         sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
78518         pParse->disableColCache = dcc;
78519         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
78520         nConstraint++;
78521       }else if( isMinQuery ){
78522         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
78523         nConstraint++;
78524         startEq = 0;
78525         start_constraints = 1;
78526       }
78527       codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
78528       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
78529       assert( op!=0 );
78530       testcase( op==OP_Rewind );
78531       testcase( op==OP_Last );
78532       testcase( op==OP_MoveGt );
78533       testcase( op==OP_MoveGe );
78534       testcase( op==OP_MoveLe );
78535       testcase( op==OP_MoveLt );
78536       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, 
78537                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
78538
78539       /* Load the value for the inequality constraint at the end of the
78540       ** range (if any).
78541       */
78542       nConstraint = nEq;
78543       if( pRangeEnd ){
78544         sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
78545         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt);
78546         codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
78547         nConstraint++;
78548       }
78549
78550       /* Top of the loop body */
78551       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
78552
78553       /* Check if the index cursor is past the end of the range. */
78554       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
78555       testcase( op==OP_Noop );
78556       testcase( op==OP_IdxGE );
78557       testcase( op==OP_IdxLT );
78558       sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase,
78559                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
78560       sqlite3VdbeChangeP5(v, endEq!=bRev);
78561
78562       /* If there are inequality constraints, check that the value
78563       ** of the table column that the inequality contrains is not NULL.
78564       ** If it is, jump to the next iteration of the loop.
78565       */
78566       r1 = sqlite3GetTempReg(pParse);
78567       testcase( pLevel->flags & WHERE_BTM_LIMIT );
78568       testcase( pLevel->flags & WHERE_TOP_LIMIT );
78569       if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
78570         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
78571         sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont);
78572       }
78573
78574       /* Seek the table cursor, if required */
78575       if( !omitTable ){
78576         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
78577         sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1);  /* Deferred seek */
78578       }
78579       sqlite3ReleaseTempReg(pParse, r1);
78580
78581       /* Record the instruction used to terminate the loop. Disable 
78582       ** WHERE clause terms made redundant by the index range scan.
78583       */
78584       pLevel->op = bRev ? OP_Prev : OP_Next;
78585       pLevel->p1 = iIdxCur;
78586       disableTerm(pLevel, pRangeStart);
78587       disableTerm(pLevel, pRangeEnd);
78588     }else{
78589       /* Case 4:  There is no usable index.  We must do a complete
78590       **          scan of the entire table.
78591       */
78592       assert( omitTable==0 );
78593       assert( bRev==0 );
78594       pLevel->op = OP_Next;
78595       pLevel->p1 = iCur;
78596       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk);
78597       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
78598     }
78599     notReady &= ~getMask(&maskSet, iCur);
78600
78601     /* Insert code to test every subexpression that can be completely
78602     ** computed using the current set of tables.
78603     */
78604     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
78605       Expr *pE;
78606       testcase( pTerm->flags & TERM_VIRTUAL );
78607       testcase( pTerm->flags & TERM_CODED );
78608       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78609       if( (pTerm->prereqAll & notReady)!=0 ) continue;
78610       pE = pTerm->pExpr;
78611       assert( pE!=0 );
78612       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
78613         continue;
78614       }
78615       sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL);
78616       pTerm->flags |= TERM_CODED;
78617     }
78618
78619     /* For a LEFT OUTER JOIN, generate code that will record the fact that
78620     ** at least one row of the right table has matched the left table.  
78621     */
78622     if( pLevel->iLeftJoin ){
78623       pLevel->top = sqlite3VdbeCurrentAddr(v);
78624       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
78625       VdbeComment((v, "record LEFT JOIN hit"));
78626       sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
78627       sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
78628       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
78629         testcase( pTerm->flags & TERM_VIRTUAL );
78630         testcase( pTerm->flags & TERM_CODED );
78631         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
78632         if( (pTerm->prereqAll & notReady)!=0 ) continue;
78633         assert( pTerm->pExpr );
78634         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL);
78635         pTerm->flags |= TERM_CODED;
78636       }
78637     }
78638   }
78639
78640 #ifdef SQLITE_TEST  /* For testing and debugging use only */
78641   /* Record in the query plan information about the current table
78642   ** and the index used to access it (if any).  If the table itself
78643   ** is not used, its name is just '{}'.  If no index is used
78644   ** the index is listed as "{}".  If the primary key is used the
78645   ** index name is '*'.
78646   */
78647   for(i=0; i<pTabList->nSrc; i++){
78648     char *z;
78649     int n;
78650     pLevel = &pWInfo->a[i];
78651     pTabItem = &pTabList->a[pLevel->iFrom];
78652     z = pTabItem->zAlias;
78653     if( z==0 ) z = pTabItem->pTab->zName;
78654     n = strlen(z);
78655     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
78656       if( pLevel->flags & WHERE_IDX_ONLY ){
78657         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
78658         nQPlan += 2;
78659       }else{
78660         memcpy(&sqlite3_query_plan[nQPlan], z, n);
78661         nQPlan += n;
78662       }
78663       sqlite3_query_plan[nQPlan++] = ' ';
78664     }
78665     testcase( pLevel->flags & WHERE_ROWID_EQ );
78666     testcase( pLevel->flags & WHERE_ROWID_RANGE );
78667     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
78668       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
78669       nQPlan += 2;
78670     }else if( pLevel->pIdx==0 ){
78671       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
78672       nQPlan += 3;
78673     }else{
78674       n = strlen(pLevel->pIdx->zName);
78675       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
78676         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
78677         nQPlan += n;
78678         sqlite3_query_plan[nQPlan++] = ' ';
78679       }
78680     }
78681   }
78682   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
78683     sqlite3_query_plan[--nQPlan] = 0;
78684   }
78685   sqlite3_query_plan[nQPlan] = 0;
78686   nQPlan = 0;
78687 #endif /* SQLITE_TEST // Testing and debugging use only */
78688
78689   /* Record the continuation address in the WhereInfo structure.  Then
78690   ** clean up and return.
78691   */
78692   pWInfo->iContinue = cont;
78693   whereClauseClear(&wc);
78694   return pWInfo;
78695
78696   /* Jump here if malloc fails */
78697 whereBeginError:
78698   whereClauseClear(&wc);
78699   whereInfoFree(db, pWInfo);
78700   return 0;
78701 }
78702
78703 /*
78704 ** Generate the end of the WHERE loop.  See comments on 
78705 ** sqlite3WhereBegin() for additional information.
78706 */
78707 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
78708   Parse *pParse = pWInfo->pParse;
78709   Vdbe *v = pParse->pVdbe;
78710   int i;
78711   WhereLevel *pLevel;
78712   SrcList *pTabList = pWInfo->pTabList;
78713   sqlite3 *db = pParse->db;
78714
78715   /* Generate loop termination code.
78716   */
78717   sqlite3ExprClearColumnCache(pParse, -1);
78718   for(i=pTabList->nSrc-1; i>=0; i--){
78719     pLevel = &pWInfo->a[i];
78720     sqlite3VdbeResolveLabel(v, pLevel->cont);
78721     if( pLevel->op!=OP_Noop ){
78722       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
78723       sqlite3VdbeChangeP5(v, pLevel->p5);
78724     }
78725     if( pLevel->nIn ){
78726       struct InLoop *pIn;
78727       int j;
78728       sqlite3VdbeResolveLabel(v, pLevel->nxt);
78729       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
78730         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
78731         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr);
78732         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
78733       }
78734       sqlite3DbFree(db, pLevel->aInLoop);
78735     }
78736     sqlite3VdbeResolveLabel(v, pLevel->brk);
78737     if( pLevel->iLeftJoin ){
78738       int addr;
78739       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
78740       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
78741       if( pLevel->iIdxCur>=0 ){
78742         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
78743       }
78744       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top);
78745       sqlite3VdbeJumpHere(v, addr);
78746     }
78747   }
78748
78749   /* The "break" point is here, just past the end of the outer loop.
78750   ** Set it.
78751   */
78752   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
78753
78754   /* Close all of the cursors that were opened by sqlite3WhereBegin.
78755   */
78756   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
78757     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
78758     Table *pTab = pTabItem->pTab;
78759     assert( pTab!=0 );
78760     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
78761     if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){
78762       sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
78763     }
78764     if( pLevel->pIdx!=0 ){
78765       sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
78766     }
78767
78768     /* If this scan uses an index, make code substitutions to read data
78769     ** from the index in preference to the table. Sometimes, this means
78770     ** the table need never be read from. This is a performance boost,
78771     ** as the vdbe level waits until the table is read before actually
78772     ** seeking the table cursor to the record corresponding to the current
78773     ** position in the index.
78774     ** 
78775     ** Calls to the code generator in between sqlite3WhereBegin and
78776     ** sqlite3WhereEnd will have created code that references the table
78777     ** directly.  This loop scans all that code looking for opcodes
78778     ** that reference the table and converts them into opcodes that
78779     ** reference the index.
78780     */
78781     if( pLevel->pIdx ){
78782       int k, j, last;
78783       VdbeOp *pOp;
78784       Index *pIdx = pLevel->pIdx;
78785       int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY;
78786
78787       assert( pIdx!=0 );
78788       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
78789       last = sqlite3VdbeCurrentAddr(v);
78790       for(k=pWInfo->iTop; k<last; k++, pOp++){
78791         if( pOp->p1!=pLevel->iTabCur ) continue;
78792         if( pOp->opcode==OP_Column ){
78793           for(j=0; j<pIdx->nColumn; j++){
78794             if( pOp->p2==pIdx->aiColumn[j] ){
78795               pOp->p2 = j;
78796               pOp->p1 = pLevel->iIdxCur;
78797               break;
78798             }
78799           }
78800           assert(!useIndexOnly || j<pIdx->nColumn);
78801         }else if( pOp->opcode==OP_Rowid ){
78802           pOp->p1 = pLevel->iIdxCur;
78803           pOp->opcode = OP_IdxRowid;
78804         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
78805           pOp->opcode = OP_Noop;
78806         }
78807       }
78808     }
78809   }
78810
78811   /* Final cleanup
78812   */
78813   whereInfoFree(db, pWInfo);
78814   return;
78815 }
78816
78817 /************** End of where.c ***********************************************/
78818 /************** Begin file parse.c *******************************************/
78819 /* Driver template for the LEMON parser generator.
78820 ** The author disclaims copyright to this source code.
78821 */
78822 /* First off, code is included that follows the "include" declaration
78823 ** in the input grammar file. */
78824
78825
78826 /*
78827 ** An instance of this structure holds information about the
78828 ** LIMIT clause of a SELECT statement.
78829 */
78830 struct LimitVal {
78831   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
78832   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
78833 };
78834
78835 /*
78836 ** An instance of this structure is used to store the LIKE,
78837 ** GLOB, NOT LIKE, and NOT GLOB operators.
78838 */
78839 struct LikeOp {
78840   Token eOperator;  /* "like" or "glob" or "regexp" */
78841   int not;         /* True if the NOT keyword is present */
78842 };
78843
78844 /*
78845 ** An instance of the following structure describes the event of a
78846 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
78847 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
78848 **
78849 **      UPDATE ON (a,b,c)
78850 **
78851 ** Then the "b" IdList records the list "a,b,c".
78852 */
78853 struct TrigEvent { int a; IdList * b; };
78854
78855 /*
78856 ** An instance of this structure holds the ATTACH key and the key type.
78857 */
78858 struct AttachKey { int type;  Token key; };
78859
78860 /* Next is all token values, in a form suitable for use by makeheaders.
78861 ** This section will be null unless lemon is run with the -m switch.
78862 */
78863 /* 
78864 ** These constants (all generated automatically by the parser generator)
78865 ** specify the various kinds of tokens (terminals) that the parser
78866 ** understands. 
78867 **
78868 ** Each symbol here is a terminal symbol in the grammar.
78869 */
78870 /* Make sure the INTERFACE macro is defined.
78871 */
78872 #ifndef INTERFACE
78873 # define INTERFACE 1
78874 #endif
78875 /* The next thing included is series of defines which control
78876 ** various aspects of the generated parser.
78877 **    YYCODETYPE         is the data type used for storing terminal
78878 **                       and nonterminal numbers.  "unsigned char" is
78879 **                       used if there are fewer than 250 terminals
78880 **                       and nonterminals.  "int" is used otherwise.
78881 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
78882 **                       to no legal terminal or nonterminal number.  This
78883 **                       number is used to fill in empty slots of the hash 
78884 **                       table.
78885 **    YYFALLBACK         If defined, this indicates that one or more tokens
78886 **                       have fall-back values which should be used if the
78887 **                       original value of the token will not parse.
78888 **    YYACTIONTYPE       is the data type used for storing terminal
78889 **                       and nonterminal numbers.  "unsigned char" is
78890 **                       used if there are fewer than 250 rules and
78891 **                       states combined.  "int" is used otherwise.
78892 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
78893 **                       directly to the parser from the tokenizer.
78894 **    YYMINORTYPE        is the data type used for all minor tokens.
78895 **                       This is typically a union of many types, one of
78896 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
78897 **                       for base tokens is called "yy0".
78898 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
78899 **                       zero the stack is dynamically sized using realloc()
78900 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
78901 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
78902 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
78903 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
78904 **    YYNSTATE           the combined number of states.
78905 **    YYNRULE            the number of rules in the grammar
78906 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
78907 **                       defined, then do no error processing.
78908 */
78909 #define YYCODETYPE unsigned char
78910 #define YYNOCODE 249
78911 #define YYACTIONTYPE unsigned short int
78912 #define YYWILDCARD 59
78913 #define sqlite3ParserTOKENTYPE Token
78914 typedef union {
78915   sqlite3ParserTOKENTYPE yy0;
78916   Select* yy43;
78917   TriggerStep* yy75;
78918   struct LimitVal yy84;
78919   struct LikeOp yy86;
78920   struct {int value; int mask;} yy207;
78921   ExprList* yy242;
78922   int yy316;
78923   IdList* yy352;
78924   struct TrigEvent yy354;
78925   SrcList* yy419;
78926   Expr* yy450;
78927 } YYMINORTYPE;
78928 #ifndef YYSTACKDEPTH
78929 #define YYSTACKDEPTH 100
78930 #endif
78931 #define sqlite3ParserARG_SDECL Parse *pParse;
78932 #define sqlite3ParserARG_PDECL ,Parse *pParse
78933 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
78934 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
78935 #define YYNSTATE 598
78936 #define YYNRULE 315
78937 #define YYFALLBACK 1
78938 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
78939 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
78940 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
78941
78942 /* The yyzerominor constant is used to initialize instances of
78943 ** YYMINORTYPE objects to zero. */
78944 #if 0
78945 static YYMINORTYPE yyzerominor;
78946 #else
78947 static const YYMINORTYPE yyzerominor;
78948 #endif
78949
78950 /* Next are the tables used to determine what action to take based on the
78951 ** current state and lookahead token.  These tables are used to implement
78952 ** functions that take a state number and lookahead value and return an
78953 ** action integer.  
78954 **
78955 ** Suppose the action integer is N.  Then the action is determined as
78956 ** follows
78957 **
78958 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
78959 **                                      token onto the stack and goto state N.
78960 **
78961 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
78962 **
78963 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
78964 **
78965 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
78966 **
78967 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
78968 **                                      slots in the yy_action[] table.
78969 **
78970 ** The action table is constructed as a single large table named yy_action[].
78971 ** Given state S and lookahead X, the action is computed as
78972 **
78973 **      yy_action[ yy_shift_ofst[S] + X ]
78974 **
78975 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
78976 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
78977 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
78978 ** and that yy_default[S] should be used instead.  
78979 **
78980 ** The formula above is for computing the action when the lookahead is
78981 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
78982 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
78983 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
78984 ** YY_SHIFT_USE_DFLT.
78985 **
78986 ** The following are the tables generated in this section:
78987 **
78988 **  yy_action[]        A single table containing all actions.
78989 **  yy_lookahead[]     A table containing the lookahead for each entry in
78990 **                     yy_action.  Used to detect hash collisions.
78991 **  yy_shift_ofst[]    For each state, the offset into yy_action for
78992 **                     shifting terminals.
78993 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
78994 **                     shifting non-terminals after a reduce.
78995 **  yy_default[]       Default action for each state.
78996 */
78997 static const YYACTIONTYPE yy_action[] = {
78998  /*     0 */   296,  914,  120,  597,    2,  172,  425,  425,   62,   62,
78999  /*    10 */    62,   62,  210,   64,   64,   64,   64,   65,   65,   66,
79000  /*    20 */    66,   66,   67,  212,  398,  395,  432,  438,   69,   64,
79001  /*    30 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79002  /*    40 */   458,  456,  327,  168,   61,   60,  301,  442,  443,  439,
79003  /*    50 */   439,   63,   63,   62,   62,   62,   62,  256,   64,   64,
79004  /*    60 */    64,   64,   65,   65,   66,   66,   66,   67,  212,  296,
79005  /*    70 */   498,  425,  425,  212,  427,   83,   68,  469,   70,  154,
79006  /*    80 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79007  /*    90 */   212,   68,  307,   70,  154,  432,  438,  454,  214,   59,
79008  /*   100 */    65,   65,   66,   66,   66,   67,  212,  429,  429,  429,
79009  /*   110 */   497,  583,  296,   61,   60,  301,  442,  443,  439,  439,
79010  /*   120 */    63,   63,   62,   62,   62,   62,  321,   64,   64,   64,
79011  /*   130 */    64,   65,   65,   66,   66,   66,   67,  212,  432,  438,
79012  /*   140 */    95,   66,   66,   66,   67,  212,  403,  256,  421,   35,
79013  /*   150 */    57,   67,  212,  175,  417,  499,   61,   60,  301,  442,
79014  /*   160 */   443,  439,  439,   63,   63,   62,   62,   62,   62,   19,
79015  /*   170 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79016  /*   180 */   212,  296,  225,  532,  299,  581,  109,  422,  242,  458,
79017  /*   190 */   416,  335,  414,   21,  502,  503,  346,  403,  527,  176,
79018  /*   200 */   160,  454,  214,  580,  579,  344,  500,  432,  438,  149,
79019  /*   210 */   150,  404,  405,  539,  514,  418,  151,  541,    8,  498,
79020  /*   220 */   538,  577,  578,  427,  296,   61,   60,  301,  442,  443,
79021  /*   230 */   439,  439,   63,   63,   62,   62,   62,   62,  196,   64,
79022  /*   240 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79023  /*   250 */   432,  438,  454,  598,  398,  395,  429,  429,  429,  369,
79024  /*   260 */   558,  481,  404,  405,  372,  576,  213,  296,   61,   60,
79025  /*   270 */   301,  442,  443,  439,  439,   63,   63,   62,   62,   62,
79026  /*   280 */    62,  321,   64,   64,   64,   64,   65,   65,   66,   66,
79027  /*   290 */    66,   67,  212,  432,  438,  555,  503,  304,  557,  532,
79028  /*   300 */   218,  557,  552,  421,   36,  234,  397,    2,  542,   21,
79029  /*   310 */   540,   61,   60,  301,  442,  443,  439,  439,   63,   63,
79030  /*   320 */    62,   62,   62,   62,  388,   64,   64,   64,   64,   65,
79031  /*   330 */    65,   66,   66,   66,   67,  212,  415,  530,   85,  381,
79032  /*   340 */    78,  323,  296,  210,  304,  527,  493,  492,  379,  274,
79033  /*   350 */   273,  379,  274,  273,  347,  463,  241,  387,  268,  210,
79034  /*   360 */   533,  581,  210,  403,   20,  224,  144,  464,  432,  438,
79035  /*   370 */   485,  164,  114,  248,  349,  253,  350,  177,  554,  580,
79036  /*   380 */   465,  420,  331,   81,  257,  419,   61,   60,  301,  442,
79037  /*   390 */   443,  439,  439,   63,   63,   62,   62,   62,   62,  391,
79038  /*   400 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
79039  /*   410 */   212,  296,  224,  203,  249,  496,  403,  440,  837,  114,
79040  /*   420 */   248,  349,  253,  350,  177,  250,  321,  152,  404,  405,
79041  /*   430 */   321,  257,  303,  324,  155,  445,  445,  432,  438,  317,
79042  /*   440 */   400,  389,  213,   68,  209,   70,  154,  422,  421,   35,
79043  /*   450 */   393,  202,  421,   42,  481,   61,   60,  301,  442,  443,
79044  /*   460 */   439,  439,   63,   63,   62,   62,   62,   62,  422,   64,
79045  /*   470 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79046  /*   480 */   296,  404,  405,  183,  513,  422,  351,  354,  355,  403,
79047  /*   490 */    77,  335,   79,  489,  216,  183,  334,  356,  351,  354,
79048  /*   500 */   355,  433,  434,  406,  407,  408,  432,  438,  235,  356,
79049  /*   510 */   386,   68,  291,   70,  154,  456,  531,  168,  198,  302,
79050  /*   520 */   449,  450,  436,  437,   61,   60,  301,  442,  443,  439,
79051  /*   530 */   439,   63,   63,   62,   62,   62,   62,  394,   64,   64,
79052  /*   540 */    64,   64,   65,   65,   66,   66,   66,   67,  212,  296,
79053  /*   550 */   321,  435,  422,  260,  404,  405,  321,  183,  153,  321,
79054  /*   560 */   351,  354,  355,  446,  332,  321,  595,  905,  321,  905,
79055  /*   570 */     1,  356,  421,   28,  403,  432,  438,  376,  421,   42,
79056  /*   580 */   477,  421,   35,  213,  548,  366,  548,  421,   50,  159,
79057  /*   590 */   421,   50,  422,   61,   60,  301,  442,  443,  439,  439,
79058  /*   600 */    63,   63,   62,   62,   62,   62,  592,   64,   64,   64,
79059  /*   610 */    64,   65,   65,   66,   66,   66,   67,  212,  296,  337,
79060  /*   620 */   217,  463,  256,   94,  339,  326,  449,  450,  172,  340,
79061  /*   630 */   425,  345,  532,  464,  312,  595,  904,  313,  904,  404,
79062  /*   640 */   405,  588,   21,  226,  432,  438,  465,  243,  504,  324,
79063  /*   650 */   322,  445,  445,  421,    3,  459,  230,  308,  505,  194,
79064  /*   660 */   278,  296,   61,   60,  301,  442,  443,  439,  439,   63,
79065  /*   670 */    63,   62,   62,   62,   62,  592,   64,   64,   64,   64,
79066  /*   680 */    65,   65,   66,   66,   66,   67,  212,  432,  438,  213,
79067  /*   690 */   179,  180,  181,  422,  324,  425,  445,  445,  281,  262,
79068  /*   700 */   279,  402,  194,  481,  296,   61,   60,  301,  442,  443,
79069  /*   710 */   439,  439,   63,   63,   62,   62,   62,   62,  377,   64,
79070  /*   720 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  212,
79071  /*   730 */   432,  438,  591,  295,  115,  268,  422,  266,  211,  264,
79072  /*   740 */   373,  324,  246,  445,  445,   56,  256,  296,   61,   71,
79073  /*   750 */   301,  442,  443,  439,  439,   63,   63,   62,   62,   62,
79074  /*   760 */    62,  377,   64,   64,   64,   64,   65,   65,   66,   66,
79075  /*   770 */    66,   67,  212,  432,  438,  550,  269,  474,   18,  549,
79076  /*   780 */   280,  309,  343,  380,  171,  160,  256,  268,    5,  268,
79077  /*   790 */   296,  368,   60,  301,  442,  443,  439,  439,   63,   63,
79078  /*   800 */    62,   62,   62,   62,  321,   64,   64,   64,   64,   65,
79079  /*   810 */    65,   66,   66,   66,   67,  212,  432,  438,  403,   10,
79080  /*   820 */   403,  310,  268,  403,  268,  485,  421,   29,  566,   22,
79081  /*   830 */   568,  420,  428,  425,  376,  419,  301,  442,  443,  439,
79082  /*   840 */   439,   63,   63,   62,   62,   62,   62,  321,   64,   64,
79083  /*   850 */    64,   64,   65,   65,   66,   66,   66,   67,  212,   73,
79084  /*   860 */   328,  485,    4,  569,  268,  570,  300,  268,  147,  421,
79085  /*   870 */    24,  321,  359,  321,  325,   73,  328,  491,    4,  455,
79086  /*   880 */   321,  342,  300,  404,  405,  404,  405,  367,  404,  405,
79087  /*   890 */   325,  330,  321,  421,   33,  421,   54,  321,  425,  178,
79088  /*   900 */   229,  458,  421,   53,  321,  227,  321,  330,  228,  478,
79089  /*   910 */   165,  321,  315,  119,  421,   99,  333,  458,  321,  421,
79090  /*   920 */    97,   76,   75,  311,  268,  519,  421,  102,  421,  103,
79091  /*   930 */    74,  319,  320,  421,  108,  427,  467,   76,   75,  490,
79092  /*   940 */   421,  110,  452,  452,  321,  520,   74,  319,  320,   73,
79093  /*   950 */   328,  427,    4,  210,  298,  321,  300,  321,  156,  257,
79094  /*   960 */   321,  210,  185,  182,  325,  284,  421,   17,  429,  429,
79095  /*   970 */   429,  430,  431,   12,  593,  378,  188,  421,  100,  421,
79096  /*   980 */    34,  330,  421,   98,  429,  429,  429,  430,  431,   12,
79097  /*   990 */   475,  458,  422,  162,  480,  321,  422,  306,  231,  232,
79098  /*  1000 */   233,  105,  484,  632,  476,  321,  486,  447,  321,   23,
79099  /*  1010 */   422,   76,   75,  594,  207,  178,  286,  421,   25,  254,
79100  /*  1020 */    74,  319,  320,  287,  321,  427,  321,  421,   55,  321,
79101  /*  1030 */   421,  111,  321,  471,  321,  205,  515,  557,  511,  363,
79102  /*  1040 */   472,  204,  321,  516,  206,  321,  421,  112,  421,  113,
79103  /*  1050 */   321,  421,   26,  321,  421,   37,  421,   38,  429,  429,
79104  /*  1060 */   429,  430,  431,   12,  421,   27,  521,  421,   39,  321,
79105  /*  1070 */   298,  158,  421,   40,  255,  421,   41,  321,  483,  321,
79106  /*  1080 */   173,  523,  321,  182,  321,  522,  321,  384,  283,  273,
79107  /*  1090 */   321,  421,   43,  297,  534,  321,  476,  321,  210,  421,
79108  /*  1100 */    44,  421,   45,  321,  421,   30,  421,   31,  421,   46,
79109  /*  1110 */   508,  509,  421,   47,  259,  321,  182,  421,   48,  421,
79110  /*  1120 */    49,  321,  358,  390,  182,  421,   32,  321,  261,  518,
79111  /*  1130 */   517,  553,  561,  182,  173,  412,  191,  421,   11,  562,
79112  /*  1140 */   573,   92,   92,  421,   51,  590,  263,  294,  265,  421,
79113  /*  1150 */    52,  267,  272,  371,  146,  374,  375,  275,  276,  277,
79114  /*  1160 */   565,  575,  285,  288,  289,  587,  470,  451,  236,  453,
79115  /*  1170 */   329,  244,  473,  514,  251,  524,  560,  163,  401,  572,
79116  /*  1180 */   426,  525,  282,  528,  409,    7,  410,  411,  385,  318,
79117  /*  1190 */    85,  237,  338,  526,   84,  336,  353,   58,   80,  215,
79118  /*  1200 */   170,  468,  121,   86,  341,  348,  305,  501,  506,  124,
79119  /*  1210 */   511,  222,  360,  423,  252,  186,  512,  510,  221,  223,
79120  /*  1220 */   238,  507,  239,  535,  240,  292,  424,  529,  536,  537,
79121  /*  1230 */   293,  543,  187,  189,  245,  362,  482,  488,  247,  190,
79122  /*  1240 */   364,   89,  545,  192,  117,  370,  132,  556,  563,  195,
79123  /*  1250 */   382,  383,  314,  133,  134,  571,  138,  135,  136,  584,
79124  /*  1260 */   589,  585,  142,  399,  101,  413,  220,  586,  270,  104,
79125  /*  1270 */   141,  633,  634,  166,  167,  441,  444,   72,  460,  448,
79126  /*  1280 */   457,  546,  143,  157,    6,  461,   14,  479,  169,  462,
79127  /*  1290 */    93,  466,   82,  122,   13,  174,  487,   96,  123,  161,
79128  /*  1300 */   494,  495,   87,  125,  126,  116,  258,   88,  127,  184,
79129  /*  1310 */   250,  361,  219,  107,  544,  145,  128,  193,  365,  118,
79130  /*  1320 */   352,  357,  173,  271,  130,    9,  316,  559,  197,   90,
79131  /*  1330 */   547,  131,  129,   15,  199,  551,  564,  200,  567,  201,
79132  /*  1340 */   139,  137,  582,   91,   16,  106,  140,  208,  574,  392,
79133  /*  1350 */   396,  290,  148,  596,
79134 };
79135 static const YYCODETYPE yy_lookahead[] = {
79136  /*     0 */    16,  140,  141,  142,  143,   21,   23,   23,   69,   70,
79137  /*    10 */    71,   72,  110,   74,   75,   76,   77,   78,   79,   80,
79138  /*    20 */    81,   82,   83,   84,    1,    2,   42,   43,   73,   74,
79139  /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
79140  /*    40 */    58,  162,  163,  164,   60,   61,   62,   63,   64,   65,
79141  /*    50 */    66,   67,   68,   69,   70,   71,   72,  148,   74,   75,
79142  /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
79143  /*    70 */    88,   88,   88,   84,   92,   22,  219,  220,  221,  222,
79144  /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
79145  /*    90 */    84,  219,  183,  221,  222,   42,   43,   78,   79,   46,
79146  /*   100 */    78,   79,   80,   81,   82,   83,   84,  125,  126,  127,
79147  /*   110 */   170,  239,   16,   60,   61,   62,   63,   64,   65,   66,
79148  /*   120 */    67,   68,   69,   70,   71,   72,  148,   74,   75,   76,
79149  /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
79150  /*   140 */    44,   80,   81,   82,   83,   84,   23,  148,  170,  171,
79151  /*   150 */    19,   83,   84,  156,   23,  170,   60,   61,   62,   63,
79152  /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,   19,
79153  /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
79154  /*   180 */    84,   16,  183,  148,  151,  148,   21,  190,  148,   58,
79155  /*   190 */   169,  213,  157,  158,  186,  187,  218,   23,  177,  202,
79156  /*   200 */   203,   78,   79,  166,  167,  208,  161,   42,   43,   78,
79157  /*   210 */    79,   88,   89,  177,  178,  170,  181,  182,   68,   88,
79158  /*   220 */   184,   98,   99,   92,   16,   60,   61,   62,   63,   64,
79159  /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,   22,   74,
79160  /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
79161  /*   250 */    42,   43,   78,    0,    1,    2,  125,  126,  127,  226,
79162  /*   260 */    11,  162,   88,   89,  231,  228,  229,   16,   60,   61,
79163  /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
79164  /*   280 */    72,  148,   74,   75,   76,   77,   78,   79,   80,   81,
79165  /*   290 */    82,   83,   84,   42,   43,  186,  187,   16,   49,  148,
79166  /*   300 */   201,   49,   18,  170,  171,  154,  142,  143,  157,  158,
79167  /*   310 */   182,   60,   61,   62,   63,   64,   65,   66,   67,   68,
79168  /*   320 */    69,   70,   71,   72,   91,   74,   75,   76,   77,   78,
79169  /*   330 */    79,   80,   81,   82,   83,   84,  168,  169,  122,   55,
79170  /*   340 */   132,   16,   16,  110,   16,  177,   20,   20,   99,  100,
79171  /*   350 */   101,   99,  100,  101,   80,   12,  223,  124,  148,  110,
79172  /*   360 */   182,  148,  110,   23,   19,   84,   21,   24,   42,   43,
79173  /*   370 */   148,   90,   91,   92,   93,   94,   95,   96,   94,  166,
79174  /*   380 */    37,  107,   39,  132,  103,  111,   60,   61,   62,   63,
79175  /*   390 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  189,
79176  /*   400 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
79177  /*   410 */    84,   16,   84,  156,   92,   20,   23,   92,  134,   91,
79178  /*   420 */    92,   93,   94,   95,   96,  103,  148,   22,   88,   89,
79179  /*   430 */   148,  103,  210,  106,  156,  108,  109,   42,   43,  144,
79180  /*   440 */   145,  228,  229,  219,  149,  221,  222,  190,  170,  171,
79181  /*   450 */   240,  156,  170,  171,  162,   60,   61,   62,   63,   64,
79182  /*   460 */    65,   66,   67,   68,   69,   70,   71,   72,  190,   74,
79183  /*   470 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
79184  /*   480 */    16,   88,   89,   90,   20,  190,   93,   94,   95,   23,
79185  /*   490 */   131,  213,  133,  201,  212,   90,  218,  104,   93,   94,
79186  /*   500 */    95,   42,   43,    7,    8,    9,   42,   43,  191,  104,
79187  /*   510 */   215,  219,  159,  221,  222,  162,  163,  164,  156,  165,
79188  /*   520 */   166,  167,   63,   64,   60,   61,   62,   63,   64,   65,
79189  /*   530 */    66,   67,   68,   69,   70,   71,   72,  242,   74,   75,
79190  /*   540 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
79191  /*   550 */   148,   92,  190,   20,   88,   89,  148,   90,  156,  148,
79192  /*   560 */    93,   94,   95,   20,  187,  148,   19,   20,  148,   22,
79193  /*   570 */    19,  104,  170,  171,   23,   42,   43,  148,  170,  171,
79194  /*   580 */   114,  170,  171,  229,   99,  100,  101,  170,  171,  148,
79195  /*   590 */   170,  171,  190,   60,   61,   62,   63,   64,   65,   66,
79196  /*   600 */    67,   68,   69,   70,   71,   72,   59,   74,   75,   76,
79197  /*   610 */    77,   78,   79,   80,   81,   82,   83,   84,   16,  211,
79198  /*   620 */   212,   12,  148,   21,  213,  165,  166,  167,   21,  148,
79199  /*   630 */    23,  148,  148,   24,  217,   19,   20,  217,   22,   88,
79200  /*   640 */    89,  157,  158,  214,   42,   43,   37,  148,   39,  106,
79201  /*   650 */   148,  108,  109,  170,  171,   20,  146,  183,   49,  156,
79202  /*   660 */    14,   16,   60,   61,   62,   63,   64,   65,   66,   67,
79203  /*   670 */    68,   69,   70,   71,   72,   59,   74,   75,   76,   77,
79204  /*   680 */    78,   79,   80,   81,   82,   83,   84,   42,   43,  229,
79205  /*   690 */    99,  100,  101,  190,  106,   88,  108,  109,   52,   14,
79206  /*   700 */    54,  148,  156,  162,   16,   60,   61,   62,   63,   64,
79207  /*   710 */    65,   66,   67,   68,   69,   70,   71,   72,  215,   74,
79208  /*   720 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
79209  /*   730 */    42,   43,  245,  246,  148,  148,  190,   52,  193,   54,
79210  /*   740 */   237,  106,  201,  108,  109,  200,  148,   16,   60,   61,
79211  /*   750 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
79212  /*   760 */    72,  215,   74,   75,   76,   77,   78,   79,   80,   81,
79213  /*   770 */    82,   83,   84,   42,   43,   25,  189,   22,  232,   29,
79214  /*   780 */   134,  183,   16,  237,  202,  203,  148,  148,  192,  148,
79215  /*   790 */    16,   41,   61,   62,   63,   64,   65,   66,   67,   68,
79216  /*   800 */    69,   70,   71,   72,  148,   74,   75,   76,   77,   78,
79217  /*   810 */    79,   80,   81,   82,   83,   84,   42,   43,   23,   19,
79218  /*   820 */    23,  183,  148,   23,  148,  148,  170,  171,  189,   19,
79219  /*   830 */   189,  107,  148,   23,  148,  111,   62,   63,   64,   65,
79220  /*   840 */    66,   67,   68,   69,   70,   71,   72,  148,   74,   75,
79221  /*   850 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
79222  /*   860 */    17,  148,   19,  189,  148,  189,   23,  148,  113,  170,
79223  /*   870 */   171,  148,   16,  148,   31,   16,   17,   80,   19,  162,
79224  /*   880 */   148,  115,   23,   88,   89,   88,   89,  210,   88,   89,
79225  /*   890 */    31,   48,  148,  170,  171,  170,  171,  148,   88,   43,
79226  /*   900 */   214,   58,  170,  171,  148,  189,  148,   48,  189,  114,
79227  /*   910 */    19,  148,  243,  244,  170,  171,  148,   58,  148,  170,
79228  /*   920 */   171,   78,   79,  210,  148,   30,  170,  171,  170,  171,
79229  /*   930 */    87,   88,   89,  170,  171,   92,  148,   78,   79,   80,
79230  /*   940 */   170,  171,  125,  126,  148,   50,   87,   88,   89,   16,
79231  /*   950 */    17,   92,   19,  110,   98,  148,   23,  148,  156,  103,
79232  /*   960 */   148,  110,  156,   22,   31,  189,  170,  171,  125,  126,
79233  /*   970 */   127,  128,  129,  130,   20,  124,  156,  170,  171,  170,
79234  /*   980 */   171,   48,  170,  171,  125,  126,  127,  128,  129,  130,
79235  /*   990 */   204,   58,  190,    5,  148,  148,  190,  102,   10,   11,
79236  /*  1000 */    12,   13,  148,  112,   22,  148,  148,   20,  148,   22,
79237  /*  1010 */   190,   78,   79,   59,   26,   43,   28,  170,  171,  148,
79238  /*  1020 */    87,   88,   89,   35,  148,   92,  148,  170,  171,  148,
79239  /*  1030 */   170,  171,  148,   27,  148,   47,  148,   49,   97,  234,
79240  /*  1040 */    34,   53,  148,  179,   56,  148,  170,  171,  170,  171,
79241  /*  1050 */   148,  170,  171,  148,  170,  171,  170,  171,  125,  126,
79242  /*  1060 */   127,  128,  129,  130,  170,  171,  179,  170,  171,  148,
79243  /*  1070 */    98,   89,  170,  171,  148,  170,  171,  148,   20,  148,
79244  /*  1080 */    22,   20,  148,   22,  148,  179,  148,   99,  100,  101,
79245  /*  1090 */   148,  170,  171,  105,  148,  148,  114,  148,  110,  170,
79246  /*  1100 */   171,  170,  171,  148,  170,  171,  170,  171,  170,  171,
79247  /*  1110 */     7,    8,  170,  171,   20,  148,   22,  170,  171,  170,
79248  /*  1120 */   171,  148,   20,  135,   22,  170,  171,  148,  148,   91,
79249  /*  1130 */    92,   20,   20,   22,   22,  150,  233,  170,  171,   20,
79250  /*  1140 */    20,   22,   22,  170,  171,   20,  148,   22,  148,  170,
79251  /*  1150 */   171,  148,  148,  148,  192,  148,  148,  148,  148,  148,
79252  /*  1160 */   148,  148,  148,  148,  148,  148,  173,  230,  194,  230,
79253  /*  1170 */   225,  205,  173,  178,  173,  173,  195,    6,  147,  195,
79254  /*  1180 */   162,  162,  205,  162,  147,   22,  147,  147,  205,  155,
79255  /*  1190 */   122,  195,  119,  173,  120,  118,  174,  121,  131,  224,
79256  /*  1200 */   112,  153,  153,   98,  117,   98,   40,  172,  172,   19,
79257  /*  1210 */    97,   84,   15,  190,  172,  152,  172,  174,  227,  227,
79258  /*  1220 */   196,  180,  197,  172,  198,  175,  199,  180,  172,  172,
79259  /*  1230 */   175,  153,  152,  152,  206,  153,  207,  207,  206,  153,
79260  /*  1240 */    38,  131,  153,  152,   60,  153,   19,  185,  195,  185,
79261  /*  1250 */   153,   15,  153,  188,  188,  195,  185,  188,  188,   33,
79262  /*  1260 */   138,  153,  216,    1,  160,   20,  176,  153,  235,  176,
79263  /*  1270 */   216,  112,  112,  112,  112,   92,  107,   19,   11,   20,
79264  /*  1280 */    20,  236,   19,   19,  116,   20,  116,  114,   22,   20,
79265  /*  1290 */   238,   20,   22,   19,   22,  116,  115,  238,   20,  112,
79266  /*  1300 */    20,   20,   19,   19,   19,   32,   20,   19,   19,   96,
79267  /*  1310 */   103,   16,   44,  241,   17,   21,   98,   98,   36,  244,
79268  /*  1320 */    44,   44,   22,  134,   19,    5,  247,    1,  123,   68,
79269  /*  1330 */    51,  102,   45,   19,  113,   45,    1,   14,   17,  117,
79270  /*  1340 */   102,  113,   20,   68,   19,   14,  123,  136,  124,   57,
79271  /*  1350 */     3,  137,   19,    4,
79272 };
79273 #define YY_SHIFT_USE_DFLT (-99)
79274 #define YY_SHIFT_MAX 396
79275 static const short yy_shift_ofst[] = {
79276  /*     0 */    23,  843,  988,  -16,  843,  933,  933,  393,  123,  252,
79277  /*    10 */   -98,   96,  933,  933,  933,  933,  933,  -45,  249,  174,
79278  /*    20 */   340,  -17,   19,   19,   53,  165,  208,  251,  326,  395,
79279  /*    30 */   464,  533,  602,  645,  688,  645,  645,  645,  645,  645,
79280  /*    40 */   645,  645,  645,  645,  645,  645,  645,  645,  645,  645,
79281  /*    50 */   645,  645,  645,  731,  774,  774,  859,  933,  933,  933,
79282  /*    60 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
79283  /*    70 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
79284  /*    80 */   933,  933,  933,  933,  933,  933,  933,  933,  933,  933,
79285  /*    90 */   933,  933,  933,  933,  933,  933,  933,  -61,  -61,    6,
79286  /*   100 */     6,  281,   22,   61,  856,  284,  340,  340,   68,  -17,
79287  /*   110 */   -11,  -99,  -99,  -99,  131,  328,  609,  609,  547,  616,
79288  /*   120 */   253,  607,  340,  607,  340,  340,  340,  340,  340,  340,
79289  /*   130 */   340,  340,  340,  340,  340,  340,  340,  340,  340,  340,
79290  /*   140 */   340,  233,  851,  -98,  -98,  -98,  -99,  -99,  -99,  -18,
79291  /*   150 */   -18,  405,  467,  327,  551,  543,  635,  343,  466,  795,
79292  /*   160 */   800,  797,  496,  340,  340,  274,  340,  340,  810,  340,
79293  /*   170 */   340,  982,  340,  340,  340,  588,  982,  340,  340,  895,
79294  /*   180 */   895,  895,  340,  340,  340,  588,  340,  340,  588,  340,
79295  /*   190 */   750,  485,  340,  340,  588,  340,  340,  340,  588,  340,
79296  /*   200 */   340,  340,  588,  588,  340,  340,  340,  340,  340,  345,
79297  /*   210 */   724,  755,  -17,  817,  817,  359, 1006, 1006,  766, 1006,
79298  /*   220 */   972, 1006,  -17, 1006,  -17,  941,  216,  766,  766,  216,
79299  /*   230 */  1171, 1171, 1171, 1171, 1163,  -98, 1068, 1073, 1074, 1077,
79300  /*   240 */  1076, 1067, 1088, 1088, 1105, 1087, 1105, 1087, 1107, 1107,
79301  /*   250 */  1166, 1107, 1113, 1107, 1190, 1127, 1127, 1166, 1107, 1107,
79302  /*   260 */  1107, 1190, 1197, 1088, 1197, 1088, 1197, 1088, 1088, 1202,
79303  /*   270 */  1110, 1197, 1088, 1184, 1184, 1227, 1068, 1088, 1236, 1236,
79304  /*   280 */  1236, 1236, 1068, 1184, 1227, 1088, 1226, 1226, 1088, 1088,
79305  /*   290 */  1122,  -99,  -99,  -99,  -99,  -99,  459,  646,  591,  685,
79306  /*   300 */   891,  325,  987, 1058,  322, 1103, 1038, 1061, 1094, 1102,
79307  /*   310 */  1111, 1112, 1119, 1120,  150, 1125,  954, 1262, 1245, 1159,
79308  /*   320 */  1160, 1161, 1162, 1183, 1169, 1258, 1259, 1260, 1263, 1267,
79309  /*   330 */  1264, 1265, 1266, 1269, 1271, 1270, 1168, 1272, 1170, 1270,
79310  /*   340 */  1173, 1274, 1179, 1181, 1278, 1187, 1280, 1281, 1273, 1268,
79311  /*   350 */  1283, 1276, 1284, 1286, 1285, 1288, 1277, 1289, 1213, 1207,
79312  /*   360 */  1295, 1297, 1294, 1218, 1282, 1279, 1287, 1300, 1290, 1189,
79313  /*   370 */  1219, 1305, 1320, 1326, 1229, 1261, 1275, 1205, 1314, 1221,
79314  /*   380 */  1335, 1323, 1222, 1321, 1228, 1238, 1223, 1325, 1224, 1322,
79315  /*   390 */  1331, 1292, 1211, 1214, 1333, 1347, 1349,
79316 };
79317 #define YY_REDUCE_USE_DFLT (-144)
79318 #define YY_REDUCE_MAX 295
79319 static const short yy_reduce_ofst[] = {
79320  /*     0 */  -139,  278,  295,  292,  402,  -22,  408,   35,   37,  546,
79321  /*    10 */    -3, -128,  133,  282,  411,  417,  420, -143,  503,  213,
79322  /*    20 */   151,  353,  354,  460,  224,  224,  224,  224,  224,  224,
79323  /*    30 */   224,  224,  224,  224,  224,  224,  224,  224,  224,  224,
79324  /*    40 */   224,  224,  224,  224,  224,  224,  224,  224,  224,  224,
79325  /*    50 */   224,  224,  224,  224,  224,  224,  483,  656,  699,  723,
79326  /*    60 */   725,  732,  744,  749,  756,  758,  763,  770,  796,  807,
79327  /*    70 */   809,  812,  847,  857,  860,  876,  878,  881,  884,  886,
79328  /*    80 */   894,  897,  902,  905,  921,  929,  931,  934,  936,  938,
79329  /*    90 */   942,  947,  949,  955,  967,  973,  979,  224,  224,  224,
79330  /*   100 */   224,  168,  224,  224,   36,   33,  210,  484,  224, -121,
79331  /*   110 */   224,  224,  224,  224,   45,   21,    8,  109,  487,  487,
79332  /*   120 */   164,   99,  222,  541,  -91,   -1,  474,  598,  587,  677,
79333  /*   130 */   638,  429,  713,  639,  641,  674,  676,  716,  719,  686,
79334  /*   140 */   776,  257,  362,  802,  806,  820,  545,  582,  669,  -60,
79335  /*   150 */   -15,  128,  178,  317,   40,  317,  317,  377,  441,  481,
79336  /*   160 */   499,  502,  510,  553,  586,  596,  502,  684,  717,  768,
79337  /*   170 */   788,  786,  846,  854,  858,  317,  786,  871,  888,  864,
79338  /*   180 */   887,  906,  926,  946,  980,  317,  998, 1000,  317, 1003,
79339  /*   190 */   903,  805, 1004, 1005,  317, 1007, 1008, 1009,  317, 1010,
79340  /*   200 */  1011, 1012,  317,  317, 1013, 1014, 1015, 1016, 1017,  985,
79341  /*   210 */   962,  974, 1018,  937,  939,  945,  993,  999,  966, 1001,
79342  /*   220 */   995, 1002, 1019, 1020, 1021, 1022,  981,  977,  983,  984,
79343  /*   230 */  1031, 1037, 1039, 1040, 1034, 1023,  996, 1024, 1025, 1026,
79344  /*   240 */  1027,  975, 1048, 1049, 1028, 1029, 1032, 1030, 1035, 1036,
79345  /*   250 */  1041, 1042, 1043, 1044, 1050,  991,  992, 1047, 1051, 1056,
79346  /*   260 */  1057, 1055, 1063, 1078, 1080, 1082, 1081, 1086, 1089, 1033,
79347  /*   270 */  1045, 1091, 1092, 1062, 1064, 1046, 1053, 1097, 1065, 1066,
79348  /*   280 */  1069, 1070, 1060, 1071, 1054, 1099, 1052, 1059, 1108, 1114,
79349  /*   290 */  1072, 1104, 1090, 1093, 1075, 1079,
79350 };
79351 static const YYACTIONTYPE yy_default[] = {
79352  /*     0 */   603,  832,  913,  719,  913,  832,  913,  913,  859,  913,
79353  /*    10 */   723,  888,  830,  913,  913,  913,  913,  804,  913,  859,
79354  /*    20 */   913,  635,  859,  859,  755,  913,  913,  913,  913,  913,
79355  /*    30 */   913,  913,  913,  756,  913,  834,  829,  825,  827,  826,
79356  /*    40 */   833,  757,  746,  753,  760,  735,  872,  762,  763,  769,
79357  /*    50 */   770,  889,  887,  792,  791,  810,  913,  913,  913,  913,
79358  /*    60 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79359  /*    70 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79360  /*    80 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79361  /*    90 */   913,  913,  913,  913,  913,  913,  913,  794,  816,  793,
79362  /*   100 */   803,  628,  795,  796,  688,  623,  913,  913,  797,  913,
79363  /*   110 */   798,  811,  812,  813,  913,  913,  913,  913,  913,  913,
79364  /*   120 */   603,  719,  913,  719,  913,  913,  913,  913,  913,  913,
79365  /*   130 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79366  /*   140 */   913,  913,  913,  913,  913,  913,  713,  723,  906,  913,
79367  /*   150 */   913,  679,  913,  913,  913,  913,  913,  913,  913,  913,
79368  /*   160 */   913,  913,  611,  609,  913,  711,  913,  913,  637,  913,
79369  /*   170 */   913,  721,  913,  913,  913,  726,  727,  913,  913,  913,
79370  /*   180 */   913,  913,  913,  913,  913,  625,  913,  913,  700,  913,
79371  /*   190 */   865,  913,  913,  913,  879,  913,  913,  913,  877,  913,
79372  /*   200 */   913,  913,  702,  765,  845,  913,  892,  894,  913,  913,
79373  /*   210 */   711,  720,  913,  913,  913,  828,  749,  749,  737,  749,
79374  /*   220 */   658,  749,  913,  749,  913,  661,  759,  737,  737,  759,
79375  /*   230 */   608,  608,  608,  608,  678,  913,  759,  750,  752,  742,
79376  /*   240 */   754,  913,  728,  728,  736,  741,  736,  741,  690,  690,
79377  /*   250 */   675,  690,  661,  690,  838,  842,  842,  675,  690,  690,
79378  /*   260 */   690,  838,  620,  728,  620,  728,  620,  728,  728,  869,
79379  /*   270 */   871,  620,  728,  692,  692,  771,  759,  728,  699,  699,
79380  /*   280 */   699,  699,  759,  692,  771,  728,  891,  891,  728,  728,
79381  /*   290 */   899,  645,  663,  663,  906,  911,  913,  913,  913,  913,
79382  /*   300 */   778,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79383  /*   310 */   913,  913,  913,  913,  852,  913,  913,  913,  913,  783,
79384  /*   320 */   779,  913,  780,  913,  705,  913,  913,  913,  913,  913,
79385  /*   330 */   913,  913,  913,  913,  913,  831,  913,  743,  913,  751,
79386  /*   340 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79387  /*   350 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79388  /*   360 */   913,  913,  913,  913,  913,  913,  867,  868,  913,  913,
79389  /*   370 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79390  /*   380 */   913,  913,  913,  913,  913,  913,  913,  913,  913,  913,
79391  /*   390 */   913,  898,  913,  913,  901,  604,  913,  599,  601,  602,
79392  /*   400 */   606,  607,  610,  632,  633,  634,  612,  613,  614,  615,
79393  /*   410 */   616,  617,  618,  624,  626,  644,  646,  630,  648,  709,
79394  /*   420 */   710,  775,  703,  704,  708,  631,  786,  777,  781,  782,
79395  /*   430 */   784,  785,  799,  800,  802,  808,  815,  818,  801,  806,
79396  /*   440 */   807,  809,  814,  817,  706,  707,  821,  638,  639,  642,
79397  /*   450 */   643,  855,  857,  856,  858,  641,  640,  787,  790,  823,
79398  /*   460 */   824,  880,  881,  882,  883,  884,  819,  729,  822,  805,
79399  /*   470 */   744,  747,  748,  745,  712,  722,  731,  732,  733,  734,
79400  /*   480 */   717,  718,  724,  740,  773,  774,  738,  739,  725,  714,
79401  /*   490 */   715,  716,  820,  776,  788,  789,  649,  650,  783,  651,
79402  /*   500 */   652,  653,  691,  694,  695,  696,  654,  673,  676,  677,
79403  /*   510 */   655,  662,  656,  657,  664,  665,  666,  669,  670,  671,
79404  /*   520 */   672,  667,  668,  839,  840,  843,  841,  659,  660,  674,
79405  /*   530 */   647,  636,  629,  680,  683,  684,  685,  686,  687,  689,
79406  /*   540 */   681,  682,  627,  619,  621,  730,  861,  870,  866,  862,
79407  /*   550 */   863,  864,  622,  835,  836,  693,  767,  768,  860,  873,
79408  /*   560 */   875,  772,  876,  878,  874,  903,  697,  698,  701,  844,
79409  /*   570 */   885,  758,  761,  764,  766,  846,  847,  848,  849,  850,
79410  /*   580 */   853,  854,  851,  886,  890,  893,  895,  896,  897,  900,
79411  /*   590 */   902,  907,  908,  909,  912,  910,  605,  600,
79412 };
79413 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
79414
79415 /* The next table maps tokens into fallback tokens.  If a construct
79416 ** like the following:
79417 ** 
79418 **      %fallback ID X Y Z.
79419 **
79420 ** appears in the grammar, then ID becomes a fallback token for X, Y,
79421 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
79422 ** but it does not parse, the type of the token is changed to ID and
79423 ** the parse is retried before an error is thrown.
79424 */
79425 #ifdef YYFALLBACK
79426 static const YYCODETYPE yyFallback[] = {
79427     0,  /*          $ => nothing */
79428     0,  /*       SEMI => nothing */
79429    23,  /*    EXPLAIN => ID */
79430    23,  /*      QUERY => ID */
79431    23,  /*       PLAN => ID */
79432    23,  /*      BEGIN => ID */
79433     0,  /* TRANSACTION => nothing */
79434    23,  /*   DEFERRED => ID */
79435    23,  /*  IMMEDIATE => ID */
79436    23,  /*  EXCLUSIVE => ID */
79437     0,  /*     COMMIT => nothing */
79438    23,  /*        END => ID */
79439     0,  /*   ROLLBACK => nothing */
79440     0,  /*     CREATE => nothing */
79441     0,  /*      TABLE => nothing */
79442    23,  /*         IF => ID */
79443     0,  /*        NOT => nothing */
79444     0,  /*     EXISTS => nothing */
79445    23,  /*       TEMP => ID */
79446     0,  /*         LP => nothing */
79447     0,  /*         RP => nothing */
79448     0,  /*         AS => nothing */
79449     0,  /*      COMMA => nothing */
79450     0,  /*         ID => nothing */
79451    23,  /*      ABORT => ID */
79452    23,  /*      AFTER => ID */
79453    23,  /*    ANALYZE => ID */
79454    23,  /*        ASC => ID */
79455    23,  /*     ATTACH => ID */
79456    23,  /*     BEFORE => ID */
79457    23,  /*    CASCADE => ID */
79458    23,  /*       CAST => ID */
79459    23,  /*   CONFLICT => ID */
79460    23,  /*   DATABASE => ID */
79461    23,  /*       DESC => ID */
79462    23,  /*     DETACH => ID */
79463    23,  /*       EACH => ID */
79464    23,  /*       FAIL => ID */
79465    23,  /*        FOR => ID */
79466    23,  /*     IGNORE => ID */
79467    23,  /*  INITIALLY => ID */
79468    23,  /*    INSTEAD => ID */
79469    23,  /*    LIKE_KW => ID */
79470    23,  /*      MATCH => ID */
79471    23,  /*        KEY => ID */
79472    23,  /*         OF => ID */
79473    23,  /*     OFFSET => ID */
79474    23,  /*     PRAGMA => ID */
79475    23,  /*      RAISE => ID */
79476    23,  /*    REPLACE => ID */
79477    23,  /*   RESTRICT => ID */
79478    23,  /*        ROW => ID */
79479    23,  /*    TRIGGER => ID */
79480    23,  /*     VACUUM => ID */
79481    23,  /*       VIEW => ID */
79482    23,  /*    VIRTUAL => ID */
79483    23,  /*    REINDEX => ID */
79484    23,  /*     RENAME => ID */
79485    23,  /*   CTIME_KW => ID */
79486     0,  /*        ANY => nothing */
79487     0,  /*         OR => nothing */
79488     0,  /*        AND => nothing */
79489     0,  /*         IS => nothing */
79490     0,  /*    BETWEEN => nothing */
79491     0,  /*         IN => nothing */
79492     0,  /*     ISNULL => nothing */
79493     0,  /*    NOTNULL => nothing */
79494     0,  /*         NE => nothing */
79495     0,  /*         EQ => nothing */
79496     0,  /*         GT => nothing */
79497     0,  /*         LE => nothing */
79498     0,  /*         LT => nothing */
79499     0,  /*         GE => nothing */
79500     0,  /*     ESCAPE => nothing */
79501     0,  /*     BITAND => nothing */
79502     0,  /*      BITOR => nothing */
79503     0,  /*     LSHIFT => nothing */
79504     0,  /*     RSHIFT => nothing */
79505     0,  /*       PLUS => nothing */
79506     0,  /*      MINUS => nothing */
79507     0,  /*       STAR => nothing */
79508     0,  /*      SLASH => nothing */
79509     0,  /*        REM => nothing */
79510     0,  /*     CONCAT => nothing */
79511     0,  /*    COLLATE => nothing */
79512     0,  /*     UMINUS => nothing */
79513     0,  /*      UPLUS => nothing */
79514     0,  /*     BITNOT => nothing */
79515     0,  /*     STRING => nothing */
79516     0,  /*    JOIN_KW => nothing */
79517     0,  /* CONSTRAINT => nothing */
79518     0,  /*    DEFAULT => nothing */
79519     0,  /*       NULL => nothing */
79520     0,  /*    PRIMARY => nothing */
79521     0,  /*     UNIQUE => nothing */
79522     0,  /*      CHECK => nothing */
79523     0,  /* REFERENCES => nothing */
79524     0,  /*   AUTOINCR => nothing */
79525     0,  /*         ON => nothing */
79526     0,  /*     DELETE => nothing */
79527     0,  /*     UPDATE => nothing */
79528     0,  /*     INSERT => nothing */
79529     0,  /*        SET => nothing */
79530     0,  /* DEFERRABLE => nothing */
79531     0,  /*    FOREIGN => nothing */
79532     0,  /*       DROP => nothing */
79533     0,  /*      UNION => nothing */
79534     0,  /*        ALL => nothing */
79535     0,  /*     EXCEPT => nothing */
79536     0,  /*  INTERSECT => nothing */
79537     0,  /*     SELECT => nothing */
79538     0,  /*   DISTINCT => nothing */
79539     0,  /*        DOT => nothing */
79540     0,  /*       FROM => nothing */
79541     0,  /*       JOIN => nothing */
79542     0,  /*    INDEXED => nothing */
79543     0,  /*         BY => nothing */
79544     0,  /*      USING => nothing */
79545     0,  /*      ORDER => nothing */
79546     0,  /*      GROUP => nothing */
79547     0,  /*     HAVING => nothing */
79548     0,  /*      LIMIT => nothing */
79549     0,  /*      WHERE => nothing */
79550     0,  /*       INTO => nothing */
79551     0,  /*     VALUES => nothing */
79552     0,  /*    INTEGER => nothing */
79553     0,  /*      FLOAT => nothing */
79554     0,  /*       BLOB => nothing */
79555     0,  /*   REGISTER => nothing */
79556     0,  /*   VARIABLE => nothing */
79557     0,  /*       CASE => nothing */
79558     0,  /*       WHEN => nothing */
79559     0,  /*       THEN => nothing */
79560     0,  /*       ELSE => nothing */
79561     0,  /*      INDEX => nothing */
79562     0,  /*      ALTER => nothing */
79563     0,  /*         TO => nothing */
79564     0,  /*        ADD => nothing */
79565     0,  /*   COLUMNKW => nothing */
79566 };
79567 #endif /* YYFALLBACK */
79568
79569 /* The following structure represents a single element of the
79570 ** parser's stack.  Information stored includes:
79571 **
79572 **   +  The state number for the parser at this level of the stack.
79573 **
79574 **   +  The value of the token stored at this level of the stack.
79575 **      (In other words, the "major" token.)
79576 **
79577 **   +  The semantic value stored at this level of the stack.  This is
79578 **      the information used by the action routines in the grammar.
79579 **      It is sometimes called the "minor" token.
79580 */
79581 struct yyStackEntry {
79582   YYACTIONTYPE stateno;  /* The state-number */
79583   YYCODETYPE major;      /* The major token value.  This is the code
79584                          ** number for the token at this stack level */
79585   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
79586                          ** is the value of the token  */
79587 };
79588 typedef struct yyStackEntry yyStackEntry;
79589
79590 /* The state of the parser is completely contained in an instance of
79591 ** the following structure */
79592 struct yyParser {
79593   int yyidx;                    /* Index of top element in stack */
79594 #ifdef YYTRACKMAXSTACKDEPTH
79595   int yyidxMax;                 /* Maximum value of yyidx */
79596 #endif
79597   int yyerrcnt;                 /* Shifts left before out of the error */
79598   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
79599 #if YYSTACKDEPTH<=0
79600   int yystksz;                  /* Current side of the stack */
79601   yyStackEntry *yystack;        /* The parser's stack */
79602 #else
79603   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
79604 #endif
79605 };
79606 typedef struct yyParser yyParser;
79607
79608 #ifndef NDEBUG
79609 static FILE *yyTraceFILE = 0;
79610 static char *yyTracePrompt = 0;
79611 #endif /* NDEBUG */
79612
79613 #ifndef NDEBUG
79614 /* 
79615 ** Turn parser tracing on by giving a stream to which to write the trace
79616 ** and a prompt to preface each trace message.  Tracing is turned off
79617 ** by making either argument NULL 
79618 **
79619 ** Inputs:
79620 ** <ul>
79621 ** <li> A FILE* to which trace output should be written.
79622 **      If NULL, then tracing is turned off.
79623 ** <li> A prefix string written at the beginning of every
79624 **      line of trace output.  If NULL, then tracing is
79625 **      turned off.
79626 ** </ul>
79627 **
79628 ** Outputs:
79629 ** None.
79630 */
79631 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
79632   yyTraceFILE = TraceFILE;
79633   yyTracePrompt = zTracePrompt;
79634   if( yyTraceFILE==0 ) yyTracePrompt = 0;
79635   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
79636 }
79637 #endif /* NDEBUG */
79638
79639 #ifndef NDEBUG
79640 /* For tracing shifts, the names of all terminals and nonterminals
79641 ** are required.  The following table supplies these names */
79642 static const char *const yyTokenName[] = { 
79643   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
79644   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
79645   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
79646   "ROLLBACK",      "CREATE",        "TABLE",         "IF",          
79647   "NOT",           "EXISTS",        "TEMP",          "LP",          
79648   "RP",            "AS",            "COMMA",         "ID",          
79649   "ABORT",         "AFTER",         "ANALYZE",       "ASC",         
79650   "ATTACH",        "BEFORE",        "CASCADE",       "CAST",        
79651   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
79652   "EACH",          "FAIL",          "FOR",           "IGNORE",      
79653   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
79654   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
79655   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
79656   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
79657   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
79658   "OR",            "AND",           "IS",            "BETWEEN",     
79659   "IN",            "ISNULL",        "NOTNULL",       "NE",          
79660   "EQ",            "GT",            "LE",            "LT",          
79661   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
79662   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
79663   "STAR",          "SLASH",         "REM",           "CONCAT",      
79664   "COLLATE",       "UMINUS",        "UPLUS",         "BITNOT",      
79665   "STRING",        "JOIN_KW",       "CONSTRAINT",    "DEFAULT",     
79666   "NULL",          "PRIMARY",       "UNIQUE",        "CHECK",       
79667   "REFERENCES",    "AUTOINCR",      "ON",            "DELETE",      
79668   "UPDATE",        "INSERT",        "SET",           "DEFERRABLE",  
79669   "FOREIGN",       "DROP",          "UNION",         "ALL",         
79670   "EXCEPT",        "INTERSECT",     "SELECT",        "DISTINCT",    
79671   "DOT",           "FROM",          "JOIN",          "INDEXED",     
79672   "BY",            "USING",         "ORDER",         "GROUP",       
79673   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
79674   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
79675   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
79676   "THEN",          "ELSE",          "INDEX",         "ALTER",       
79677   "TO",            "ADD",           "COLUMNKW",      "error",       
79678   "input",         "cmdlist",       "ecmd",          "explain",     
79679   "cmdx",          "cmd",           "transtype",     "trans_opt",   
79680   "nm",            "create_table",  "create_table_args",  "temp",        
79681   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
79682   "select",        "column",        "columnid",      "type",        
79683   "carglist",      "id",            "ids",           "typetoken",   
79684   "typename",      "signed",        "plus_num",      "minus_num",   
79685   "carg",          "ccons",         "term",          "expr",        
79686   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
79687   "refargs",       "defer_subclause",  "refarg",        "refact",      
79688   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
79689   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
79690   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
79691   "distinct",      "selcollist",    "from",          "where_opt",   
79692   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
79693   "sclp",          "as",            "seltablist",    "stl_prefix",  
79694   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
79695   "seltablist_paren",  "joinop2",       "inscollist",    "sortlist",    
79696   "sortitem",      "nexprlist",     "setlist",       "insert_cmd",  
79697   "inscollist_opt",  "itemlist",      "exprlist",      "likeop",      
79698   "escape",        "between_op",    "in_op",         "case_operand",
79699   "case_exprlist",  "case_else",     "uniqueflag",    "collate",     
79700   "nmnum",         "plus_opt",      "number",        "trigger_decl",
79701   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
79702   "when_clause",   "trigger_cmd",   "database_kw_opt",  "key_opt",     
79703   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
79704   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
79705 };
79706 #endif /* NDEBUG */
79707
79708 #ifndef NDEBUG
79709 /* For tracing reduce actions, the names of all rules are required.
79710 */
79711 static const char *const yyRuleName[] = {
79712  /*   0 */ "input ::= cmdlist",
79713  /*   1 */ "cmdlist ::= cmdlist ecmd",
79714  /*   2 */ "cmdlist ::= ecmd",
79715  /*   3 */ "ecmd ::= SEMI",
79716  /*   4 */ "ecmd ::= explain cmdx SEMI",
79717  /*   5 */ "explain ::=",
79718  /*   6 */ "explain ::= EXPLAIN",
79719  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
79720  /*   8 */ "cmdx ::= cmd",
79721  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
79722  /*  10 */ "trans_opt ::=",
79723  /*  11 */ "trans_opt ::= TRANSACTION",
79724  /*  12 */ "trans_opt ::= TRANSACTION nm",
79725  /*  13 */ "transtype ::=",
79726  /*  14 */ "transtype ::= DEFERRED",
79727  /*  15 */ "transtype ::= IMMEDIATE",
79728  /*  16 */ "transtype ::= EXCLUSIVE",
79729  /*  17 */ "cmd ::= COMMIT trans_opt",
79730  /*  18 */ "cmd ::= END trans_opt",
79731  /*  19 */ "cmd ::= ROLLBACK trans_opt",
79732  /*  20 */ "cmd ::= create_table create_table_args",
79733  /*  21 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
79734  /*  22 */ "ifnotexists ::=",
79735  /*  23 */ "ifnotexists ::= IF NOT EXISTS",
79736  /*  24 */ "temp ::= TEMP",
79737  /*  25 */ "temp ::=",
79738  /*  26 */ "create_table_args ::= LP columnlist conslist_opt RP",
79739  /*  27 */ "create_table_args ::= AS select",
79740  /*  28 */ "columnlist ::= columnlist COMMA column",
79741  /*  29 */ "columnlist ::= column",
79742  /*  30 */ "column ::= columnid type carglist",
79743  /*  31 */ "columnid ::= nm",
79744  /*  32 */ "id ::= ID",
79745  /*  33 */ "ids ::= ID|STRING",
79746  /*  34 */ "nm ::= ID",
79747  /*  35 */ "nm ::= STRING",
79748  /*  36 */ "nm ::= JOIN_KW",
79749  /*  37 */ "type ::=",
79750  /*  38 */ "type ::= typetoken",
79751  /*  39 */ "typetoken ::= typename",
79752  /*  40 */ "typetoken ::= typename LP signed RP",
79753  /*  41 */ "typetoken ::= typename LP signed COMMA signed RP",
79754  /*  42 */ "typename ::= ids",
79755  /*  43 */ "typename ::= typename ids",
79756  /*  44 */ "signed ::= plus_num",
79757  /*  45 */ "signed ::= minus_num",
79758  /*  46 */ "carglist ::= carglist carg",
79759  /*  47 */ "carglist ::=",
79760  /*  48 */ "carg ::= CONSTRAINT nm ccons",
79761  /*  49 */ "carg ::= ccons",
79762  /*  50 */ "ccons ::= DEFAULT term",
79763  /*  51 */ "ccons ::= DEFAULT LP expr RP",
79764  /*  52 */ "ccons ::= DEFAULT PLUS term",
79765  /*  53 */ "ccons ::= DEFAULT MINUS term",
79766  /*  54 */ "ccons ::= DEFAULT id",
79767  /*  55 */ "ccons ::= NULL onconf",
79768  /*  56 */ "ccons ::= NOT NULL onconf",
79769  /*  57 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
79770  /*  58 */ "ccons ::= UNIQUE onconf",
79771  /*  59 */ "ccons ::= CHECK LP expr RP",
79772  /*  60 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
79773  /*  61 */ "ccons ::= defer_subclause",
79774  /*  62 */ "ccons ::= COLLATE ids",
79775  /*  63 */ "autoinc ::=",
79776  /*  64 */ "autoinc ::= AUTOINCR",
79777  /*  65 */ "refargs ::=",
79778  /*  66 */ "refargs ::= refargs refarg",
79779  /*  67 */ "refarg ::= MATCH nm",
79780  /*  68 */ "refarg ::= ON DELETE refact",
79781  /*  69 */ "refarg ::= ON UPDATE refact",
79782  /*  70 */ "refarg ::= ON INSERT refact",
79783  /*  71 */ "refact ::= SET NULL",
79784  /*  72 */ "refact ::= SET DEFAULT",
79785  /*  73 */ "refact ::= CASCADE",
79786  /*  74 */ "refact ::= RESTRICT",
79787  /*  75 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
79788  /*  76 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
79789  /*  77 */ "init_deferred_pred_opt ::=",
79790  /*  78 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
79791  /*  79 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
79792  /*  80 */ "conslist_opt ::=",
79793  /*  81 */ "conslist_opt ::= COMMA conslist",
79794  /*  82 */ "conslist ::= conslist COMMA tcons",
79795  /*  83 */ "conslist ::= conslist tcons",
79796  /*  84 */ "conslist ::= tcons",
79797  /*  85 */ "tcons ::= CONSTRAINT nm",
79798  /*  86 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
79799  /*  87 */ "tcons ::= UNIQUE LP idxlist RP onconf",
79800  /*  88 */ "tcons ::= CHECK LP expr RP onconf",
79801  /*  89 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
79802  /*  90 */ "defer_subclause_opt ::=",
79803  /*  91 */ "defer_subclause_opt ::= defer_subclause",
79804  /*  92 */ "onconf ::=",
79805  /*  93 */ "onconf ::= ON CONFLICT resolvetype",
79806  /*  94 */ "orconf ::=",
79807  /*  95 */ "orconf ::= OR resolvetype",
79808  /*  96 */ "resolvetype ::= raisetype",
79809  /*  97 */ "resolvetype ::= IGNORE",
79810  /*  98 */ "resolvetype ::= REPLACE",
79811  /*  99 */ "cmd ::= DROP TABLE ifexists fullname",
79812  /* 100 */ "ifexists ::= IF EXISTS",
79813  /* 101 */ "ifexists ::=",
79814  /* 102 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
79815  /* 103 */ "cmd ::= DROP VIEW ifexists fullname",
79816  /* 104 */ "cmd ::= select",
79817  /* 105 */ "select ::= oneselect",
79818  /* 106 */ "select ::= select multiselect_op oneselect",
79819  /* 107 */ "multiselect_op ::= UNION",
79820  /* 108 */ "multiselect_op ::= UNION ALL",
79821  /* 109 */ "multiselect_op ::= EXCEPT|INTERSECT",
79822  /* 110 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
79823  /* 111 */ "distinct ::= DISTINCT",
79824  /* 112 */ "distinct ::= ALL",
79825  /* 113 */ "distinct ::=",
79826  /* 114 */ "sclp ::= selcollist COMMA",
79827  /* 115 */ "sclp ::=",
79828  /* 116 */ "selcollist ::= sclp expr as",
79829  /* 117 */ "selcollist ::= sclp STAR",
79830  /* 118 */ "selcollist ::= sclp nm DOT STAR",
79831  /* 119 */ "as ::= AS nm",
79832  /* 120 */ "as ::= ids",
79833  /* 121 */ "as ::=",
79834  /* 122 */ "from ::=",
79835  /* 123 */ "from ::= FROM seltablist",
79836  /* 124 */ "stl_prefix ::= seltablist joinop",
79837  /* 125 */ "stl_prefix ::=",
79838  /* 126 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
79839  /* 127 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
79840  /* 128 */ "seltablist_paren ::= select",
79841  /* 129 */ "seltablist_paren ::= seltablist",
79842  /* 130 */ "dbnm ::=",
79843  /* 131 */ "dbnm ::= DOT nm",
79844  /* 132 */ "fullname ::= nm dbnm",
79845  /* 133 */ "joinop ::= COMMA|JOIN",
79846  /* 134 */ "joinop ::= JOIN_KW JOIN",
79847  /* 135 */ "joinop ::= JOIN_KW nm JOIN",
79848  /* 136 */ "joinop ::= JOIN_KW nm nm JOIN",
79849  /* 137 */ "on_opt ::= ON expr",
79850  /* 138 */ "on_opt ::=",
79851  /* 139 */ "indexed_opt ::=",
79852  /* 140 */ "indexed_opt ::= INDEXED BY nm",
79853  /* 141 */ "indexed_opt ::= NOT INDEXED",
79854  /* 142 */ "using_opt ::= USING LP inscollist RP",
79855  /* 143 */ "using_opt ::=",
79856  /* 144 */ "orderby_opt ::=",
79857  /* 145 */ "orderby_opt ::= ORDER BY sortlist",
79858  /* 146 */ "sortlist ::= sortlist COMMA sortitem sortorder",
79859  /* 147 */ "sortlist ::= sortitem sortorder",
79860  /* 148 */ "sortitem ::= expr",
79861  /* 149 */ "sortorder ::= ASC",
79862  /* 150 */ "sortorder ::= DESC",
79863  /* 151 */ "sortorder ::=",
79864  /* 152 */ "groupby_opt ::=",
79865  /* 153 */ "groupby_opt ::= GROUP BY nexprlist",
79866  /* 154 */ "having_opt ::=",
79867  /* 155 */ "having_opt ::= HAVING expr",
79868  /* 156 */ "limit_opt ::=",
79869  /* 157 */ "limit_opt ::= LIMIT expr",
79870  /* 158 */ "limit_opt ::= LIMIT expr OFFSET expr",
79871  /* 159 */ "limit_opt ::= LIMIT expr COMMA expr",
79872  /* 160 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
79873  /* 161 */ "where_opt ::=",
79874  /* 162 */ "where_opt ::= WHERE expr",
79875  /* 163 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
79876  /* 164 */ "setlist ::= setlist COMMA nm EQ expr",
79877  /* 165 */ "setlist ::= nm EQ expr",
79878  /* 166 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
79879  /* 167 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
79880  /* 168 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
79881  /* 169 */ "insert_cmd ::= INSERT orconf",
79882  /* 170 */ "insert_cmd ::= REPLACE",
79883  /* 171 */ "itemlist ::= itemlist COMMA expr",
79884  /* 172 */ "itemlist ::= expr",
79885  /* 173 */ "inscollist_opt ::=",
79886  /* 174 */ "inscollist_opt ::= LP inscollist RP",
79887  /* 175 */ "inscollist ::= inscollist COMMA nm",
79888  /* 176 */ "inscollist ::= nm",
79889  /* 177 */ "expr ::= term",
79890  /* 178 */ "expr ::= LP expr RP",
79891  /* 179 */ "term ::= NULL",
79892  /* 180 */ "expr ::= ID",
79893  /* 181 */ "expr ::= JOIN_KW",
79894  /* 182 */ "expr ::= nm DOT nm",
79895  /* 183 */ "expr ::= nm DOT nm DOT nm",
79896  /* 184 */ "term ::= INTEGER|FLOAT|BLOB",
79897  /* 185 */ "term ::= STRING",
79898  /* 186 */ "expr ::= REGISTER",
79899  /* 187 */ "expr ::= VARIABLE",
79900  /* 188 */ "expr ::= expr COLLATE ids",
79901  /* 189 */ "expr ::= CAST LP expr AS typetoken RP",
79902  /* 190 */ "expr ::= ID LP distinct exprlist RP",
79903  /* 191 */ "expr ::= ID LP STAR RP",
79904  /* 192 */ "term ::= CTIME_KW",
79905  /* 193 */ "expr ::= expr AND expr",
79906  /* 194 */ "expr ::= expr OR expr",
79907  /* 195 */ "expr ::= expr LT|GT|GE|LE expr",
79908  /* 196 */ "expr ::= expr EQ|NE expr",
79909  /* 197 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
79910  /* 198 */ "expr ::= expr PLUS|MINUS expr",
79911  /* 199 */ "expr ::= expr STAR|SLASH|REM expr",
79912  /* 200 */ "expr ::= expr CONCAT expr",
79913  /* 201 */ "likeop ::= LIKE_KW",
79914  /* 202 */ "likeop ::= NOT LIKE_KW",
79915  /* 203 */ "likeop ::= MATCH",
79916  /* 204 */ "likeop ::= NOT MATCH",
79917  /* 205 */ "escape ::= ESCAPE expr",
79918  /* 206 */ "escape ::=",
79919  /* 207 */ "expr ::= expr likeop expr escape",
79920  /* 208 */ "expr ::= expr ISNULL|NOTNULL",
79921  /* 209 */ "expr ::= expr IS NULL",
79922  /* 210 */ "expr ::= expr NOT NULL",
79923  /* 211 */ "expr ::= expr IS NOT NULL",
79924  /* 212 */ "expr ::= NOT expr",
79925  /* 213 */ "expr ::= BITNOT expr",
79926  /* 214 */ "expr ::= MINUS expr",
79927  /* 215 */ "expr ::= PLUS expr",
79928  /* 216 */ "between_op ::= BETWEEN",
79929  /* 217 */ "between_op ::= NOT BETWEEN",
79930  /* 218 */ "expr ::= expr between_op expr AND expr",
79931  /* 219 */ "in_op ::= IN",
79932  /* 220 */ "in_op ::= NOT IN",
79933  /* 221 */ "expr ::= expr in_op LP exprlist RP",
79934  /* 222 */ "expr ::= LP select RP",
79935  /* 223 */ "expr ::= expr in_op LP select RP",
79936  /* 224 */ "expr ::= expr in_op nm dbnm",
79937  /* 225 */ "expr ::= EXISTS LP select RP",
79938  /* 226 */ "expr ::= CASE case_operand case_exprlist case_else END",
79939  /* 227 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
79940  /* 228 */ "case_exprlist ::= WHEN expr THEN expr",
79941  /* 229 */ "case_else ::= ELSE expr",
79942  /* 230 */ "case_else ::=",
79943  /* 231 */ "case_operand ::= expr",
79944  /* 232 */ "case_operand ::=",
79945  /* 233 */ "exprlist ::= nexprlist",
79946  /* 234 */ "exprlist ::=",
79947  /* 235 */ "nexprlist ::= nexprlist COMMA expr",
79948  /* 236 */ "nexprlist ::= expr",
79949  /* 237 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
79950  /* 238 */ "uniqueflag ::= UNIQUE",
79951  /* 239 */ "uniqueflag ::=",
79952  /* 240 */ "idxlist_opt ::=",
79953  /* 241 */ "idxlist_opt ::= LP idxlist RP",
79954  /* 242 */ "idxlist ::= idxlist COMMA nm collate sortorder",
79955  /* 243 */ "idxlist ::= nm collate sortorder",
79956  /* 244 */ "collate ::=",
79957  /* 245 */ "collate ::= COLLATE ids",
79958  /* 246 */ "cmd ::= DROP INDEX ifexists fullname",
79959  /* 247 */ "cmd ::= VACUUM",
79960  /* 248 */ "cmd ::= VACUUM nm",
79961  /* 249 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
79962  /* 250 */ "cmd ::= PRAGMA nm dbnm EQ ON",
79963  /* 251 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
79964  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
79965  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
79966  /* 254 */ "cmd ::= PRAGMA nm dbnm",
79967  /* 255 */ "nmnum ::= plus_num",
79968  /* 256 */ "nmnum ::= nm",
79969  /* 257 */ "plus_num ::= plus_opt number",
79970  /* 258 */ "minus_num ::= MINUS number",
79971  /* 259 */ "number ::= INTEGER|FLOAT",
79972  /* 260 */ "plus_opt ::= PLUS",
79973  /* 261 */ "plus_opt ::=",
79974  /* 262 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
79975  /* 263 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
79976  /* 264 */ "trigger_time ::= BEFORE",
79977  /* 265 */ "trigger_time ::= AFTER",
79978  /* 266 */ "trigger_time ::= INSTEAD OF",
79979  /* 267 */ "trigger_time ::=",
79980  /* 268 */ "trigger_event ::= DELETE|INSERT",
79981  /* 269 */ "trigger_event ::= UPDATE",
79982  /* 270 */ "trigger_event ::= UPDATE OF inscollist",
79983  /* 271 */ "foreach_clause ::=",
79984  /* 272 */ "foreach_clause ::= FOR EACH ROW",
79985  /* 273 */ "when_clause ::=",
79986  /* 274 */ "when_clause ::= WHEN expr",
79987  /* 275 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
79988  /* 276 */ "trigger_cmd_list ::= trigger_cmd SEMI",
79989  /* 277 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
79990  /* 278 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
79991  /* 279 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
79992  /* 280 */ "trigger_cmd ::= DELETE FROM nm where_opt",
79993  /* 281 */ "trigger_cmd ::= select",
79994  /* 282 */ "expr ::= RAISE LP IGNORE RP",
79995  /* 283 */ "expr ::= RAISE LP raisetype COMMA nm RP",
79996  /* 284 */ "raisetype ::= ROLLBACK",
79997  /* 285 */ "raisetype ::= ABORT",
79998  /* 286 */ "raisetype ::= FAIL",
79999  /* 287 */ "cmd ::= DROP TRIGGER ifexists fullname",
80000  /* 288 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
80001  /* 289 */ "cmd ::= DETACH database_kw_opt expr",
80002  /* 290 */ "key_opt ::=",
80003  /* 291 */ "key_opt ::= KEY expr",
80004  /* 292 */ "database_kw_opt ::= DATABASE",
80005  /* 293 */ "database_kw_opt ::=",
80006  /* 294 */ "cmd ::= REINDEX",
80007  /* 295 */ "cmd ::= REINDEX nm dbnm",
80008  /* 296 */ "cmd ::= ANALYZE",
80009  /* 297 */ "cmd ::= ANALYZE nm dbnm",
80010  /* 298 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
80011  /* 299 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
80012  /* 300 */ "add_column_fullname ::= fullname",
80013  /* 301 */ "kwcolumn_opt ::=",
80014  /* 302 */ "kwcolumn_opt ::= COLUMNKW",
80015  /* 303 */ "cmd ::= create_vtab",
80016  /* 304 */ "cmd ::= create_vtab LP vtabarglist RP",
80017  /* 305 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
80018  /* 306 */ "vtabarglist ::= vtabarg",
80019  /* 307 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
80020  /* 308 */ "vtabarg ::=",
80021  /* 309 */ "vtabarg ::= vtabarg vtabargtoken",
80022  /* 310 */ "vtabargtoken ::= ANY",
80023  /* 311 */ "vtabargtoken ::= lp anylist RP",
80024  /* 312 */ "lp ::= LP",
80025  /* 313 */ "anylist ::=",
80026  /* 314 */ "anylist ::= anylist ANY",
80027 };
80028 #endif /* NDEBUG */
80029
80030
80031 #if YYSTACKDEPTH<=0
80032 /*
80033 ** Try to increase the size of the parser stack.
80034 */
80035 static void yyGrowStack(yyParser *p){
80036   int newSize;
80037   yyStackEntry *pNew;
80038
80039   newSize = p->yystksz*2 + 100;
80040   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
80041   if( pNew ){
80042     p->yystack = pNew;
80043     p->yystksz = newSize;
80044 #ifndef NDEBUG
80045     if( yyTraceFILE ){
80046       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
80047               yyTracePrompt, p->yystksz);
80048     }
80049 #endif
80050   }
80051 }
80052 #endif
80053
80054 /* 
80055 ** This function allocates a new parser.
80056 ** The only argument is a pointer to a function which works like
80057 ** malloc.
80058 **
80059 ** Inputs:
80060 ** A pointer to the function used to allocate memory.
80061 **
80062 ** Outputs:
80063 ** A pointer to a parser.  This pointer is used in subsequent calls
80064 ** to sqlite3Parser and sqlite3ParserFree.
80065 */
80066 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
80067   yyParser *pParser;
80068   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
80069   if( pParser ){
80070     pParser->yyidx = -1;
80071 #ifdef YYTRACKMAXSTACKDEPTH
80072     pParser->yyidxMax = 0;
80073 #endif
80074 #if YYSTACKDEPTH<=0
80075     yyGrowStack(pParser);
80076 #endif
80077   }
80078   return pParser;
80079 }
80080
80081 /* The following function deletes the value associated with a
80082 ** symbol.  The symbol can be either a terminal or nonterminal.
80083 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
80084 ** the value.
80085 */
80086 static void yy_destructor(
80087   yyParser *yypParser,    /* The parser */
80088   YYCODETYPE yymajor,     /* Type code for object to destroy */
80089   YYMINORTYPE *yypminor   /* The object to be destroyed */
80090 ){
80091   sqlite3ParserARG_FETCH;
80092   switch( yymajor ){
80093     /* Here is inserted the actions which take place when a
80094     ** terminal or non-terminal is destroyed.  This can happen
80095     ** when the symbol is popped from the stack during a
80096     ** reduce or during error processing or when a parser is 
80097     ** being destroyed before it is finished parsing.
80098     **
80099     ** Note: during a reduce, the only symbols destroyed are those
80100     ** which appear on the RHS of the rule, but which are not used
80101     ** inside the C code.
80102     */
80103     case 156: /* select */
80104     case 190: /* oneselect */
80105     case 208: /* seltablist_paren */
80106 {
80107 sqlite3SelectDelete(pParse->db, (yypminor->yy43));
80108 }
80109       break;
80110     case 170: /* term */
80111     case 171: /* expr */
80112     case 195: /* where_opt */
80113     case 197: /* having_opt */
80114     case 206: /* on_opt */
80115     case 212: /* sortitem */
80116     case 220: /* escape */
80117     case 223: /* case_operand */
80118     case 225: /* case_else */
80119     case 236: /* when_clause */
80120     case 239: /* key_opt */
80121 {
80122 sqlite3ExprDelete(pParse->db, (yypminor->yy450));
80123 }
80124       break;
80125     case 175: /* idxlist_opt */
80126     case 183: /* idxlist */
80127     case 193: /* selcollist */
80128     case 196: /* groupby_opt */
80129     case 198: /* orderby_opt */
80130     case 200: /* sclp */
80131     case 211: /* sortlist */
80132     case 213: /* nexprlist */
80133     case 214: /* setlist */
80134     case 217: /* itemlist */
80135     case 218: /* exprlist */
80136     case 224: /* case_exprlist */
80137 {
80138 sqlite3ExprListDelete(pParse->db, (yypminor->yy242));
80139 }
80140       break;
80141     case 189: /* fullname */
80142     case 194: /* from */
80143     case 202: /* seltablist */
80144     case 203: /* stl_prefix */
80145 {
80146 sqlite3SrcListDelete(pParse->db, (yypminor->yy419));
80147 }
80148       break;
80149     case 207: /* using_opt */
80150     case 210: /* inscollist */
80151     case 216: /* inscollist_opt */
80152 {
80153 sqlite3IdListDelete(pParse->db, (yypminor->yy352));
80154 }
80155       break;
80156     case 232: /* trigger_cmd_list */
80157     case 237: /* trigger_cmd */
80158 {
80159 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy75));
80160 }
80161       break;
80162     case 234: /* trigger_event */
80163 {
80164 sqlite3IdListDelete(pParse->db, (yypminor->yy354).b);
80165 }
80166       break;
80167     default:  break;   /* If no destructor action specified: do nothing */
80168   }
80169 }
80170
80171 /*
80172 ** Pop the parser's stack once.
80173 **
80174 ** If there is a destructor routine associated with the token which
80175 ** is popped from the stack, then call it.
80176 **
80177 ** Return the major token number for the symbol popped.
80178 */
80179 static int yy_pop_parser_stack(yyParser *pParser){
80180   YYCODETYPE yymajor;
80181   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
80182
80183   if( pParser->yyidx<0 ) return 0;
80184 #ifndef NDEBUG
80185   if( yyTraceFILE && pParser->yyidx>=0 ){
80186     fprintf(yyTraceFILE,"%sPopping %s\n",
80187       yyTracePrompt,
80188       yyTokenName[yytos->major]);
80189   }
80190 #endif
80191   yymajor = yytos->major;
80192   yy_destructor(pParser, yymajor, &yytos->minor);
80193   pParser->yyidx--;
80194   return yymajor;
80195 }
80196
80197 /* 
80198 ** Deallocate and destroy a parser.  Destructors are all called for
80199 ** all stack elements before shutting the parser down.
80200 **
80201 ** Inputs:
80202 ** <ul>
80203 ** <li>  A pointer to the parser.  This should be a pointer
80204 **       obtained from sqlite3ParserAlloc.
80205 ** <li>  A pointer to a function used to reclaim memory obtained
80206 **       from malloc.
80207 ** </ul>
80208 */
80209 SQLITE_PRIVATE void sqlite3ParserFree(
80210   void *p,                    /* The parser to be deleted */
80211   void (*freeProc)(void*)     /* Function used to reclaim memory */
80212 ){
80213   yyParser *pParser = (yyParser*)p;
80214   if( pParser==0 ) return;
80215   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
80216 #if YYSTACKDEPTH<=0
80217   free(pParser->yystack);
80218 #endif
80219   (*freeProc)((void*)pParser);
80220 }
80221
80222 /*
80223 ** Return the peak depth of the stack for a parser.
80224 */
80225 #ifdef YYTRACKMAXSTACKDEPTH
80226 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
80227   yyParser *pParser = (yyParser*)p;
80228   return pParser->yyidxMax;
80229 }
80230 #endif
80231
80232 /*
80233 ** Find the appropriate action for a parser given the terminal
80234 ** look-ahead token iLookAhead.
80235 **
80236 ** If the look-ahead token is YYNOCODE, then check to see if the action is
80237 ** independent of the look-ahead.  If it is, return the action, otherwise
80238 ** return YY_NO_ACTION.
80239 */
80240 static int yy_find_shift_action(
80241   yyParser *pParser,        /* The parser */
80242   YYCODETYPE iLookAhead     /* The look-ahead token */
80243 ){
80244   int i;
80245   int stateno = pParser->yystack[pParser->yyidx].stateno;
80246  
80247   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
80248     return yy_default[stateno];
80249   }
80250   assert( iLookAhead!=YYNOCODE );
80251   i += iLookAhead;
80252   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
80253     if( iLookAhead>0 ){
80254 #ifdef YYFALLBACK
80255       int iFallback;            /* Fallback token */
80256       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
80257              && (iFallback = yyFallback[iLookAhead])!=0 ){
80258 #ifndef NDEBUG
80259         if( yyTraceFILE ){
80260           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
80261              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
80262         }
80263 #endif
80264         return yy_find_shift_action(pParser, iFallback);
80265       }
80266 #endif
80267 #ifdef YYWILDCARD
80268       {
80269         int j = i - iLookAhead + YYWILDCARD;
80270         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
80271 #ifndef NDEBUG
80272           if( yyTraceFILE ){
80273             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
80274                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
80275           }
80276 #endif /* NDEBUG */
80277           return yy_action[j];
80278         }
80279       }
80280 #endif /* YYWILDCARD */
80281     }
80282     return yy_default[stateno];
80283   }else{
80284     return yy_action[i];
80285   }
80286 }
80287
80288 /*
80289 ** Find the appropriate action for a parser given the non-terminal
80290 ** look-ahead token iLookAhead.
80291 **
80292 ** If the look-ahead token is YYNOCODE, then check to see if the action is
80293 ** independent of the look-ahead.  If it is, return the action, otherwise
80294 ** return YY_NO_ACTION.
80295 */
80296 static int yy_find_reduce_action(
80297   int stateno,              /* Current state number */
80298   YYCODETYPE iLookAhead     /* The look-ahead token */
80299 ){
80300   int i;
80301 #ifdef YYERRORSYMBOL
80302   if( stateno>YY_REDUCE_MAX ){
80303     return yy_default[stateno];
80304   }
80305 #else
80306   assert( stateno<=YY_REDUCE_MAX );
80307 #endif
80308   i = yy_reduce_ofst[stateno];
80309   assert( i!=YY_REDUCE_USE_DFLT );
80310   assert( iLookAhead!=YYNOCODE );
80311   i += iLookAhead;
80312 #ifdef YYERRORSYMBOL
80313   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
80314     return yy_default[stateno];
80315   }
80316 #else
80317   assert( i>=0 && i<YY_SZ_ACTTAB );
80318   assert( yy_lookahead[i]==iLookAhead );
80319 #endif
80320   return yy_action[i];
80321 }
80322
80323 /*
80324 ** The following routine is called if the stack overflows.
80325 */
80326 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
80327    sqlite3ParserARG_FETCH;
80328    yypParser->yyidx--;
80329 #ifndef NDEBUG
80330    if( yyTraceFILE ){
80331      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
80332    }
80333 #endif
80334    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
80335    /* Here code is inserted which will execute if the parser
80336    ** stack every overflows */
80337
80338   sqlite3ErrorMsg(pParse, "parser stack overflow");
80339   pParse->parseError = 1;
80340    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
80341 }
80342
80343 /*
80344 ** Perform a shift action.
80345 */
80346 static void yy_shift(
80347   yyParser *yypParser,          /* The parser to be shifted */
80348   int yyNewState,               /* The new state to shift in */
80349   int yyMajor,                  /* The major token to shift in */
80350   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
80351 ){
80352   yyStackEntry *yytos;
80353   yypParser->yyidx++;
80354 #ifdef YYTRACKMAXSTACKDEPTH
80355   if( yypParser->yyidx>yypParser->yyidxMax ){
80356     yypParser->yyidxMax = yypParser->yyidx;
80357   }
80358 #endif
80359 #if YYSTACKDEPTH>0 
80360   if( yypParser->yyidx>=YYSTACKDEPTH ){
80361     yyStackOverflow(yypParser, yypMinor);
80362     return;
80363   }
80364 #else
80365   if( yypParser->yyidx>=yypParser->yystksz ){
80366     yyGrowStack(yypParser);
80367     if( yypParser->yyidx>=yypParser->yystksz ){
80368       yyStackOverflow(yypParser, yypMinor);
80369       return;
80370     }
80371   }
80372 #endif
80373   yytos = &yypParser->yystack[yypParser->yyidx];
80374   yytos->stateno = yyNewState;
80375   yytos->major = yyMajor;
80376   yytos->minor = *yypMinor;
80377 #ifndef NDEBUG
80378   if( yyTraceFILE && yypParser->yyidx>0 ){
80379     int i;
80380     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
80381     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
80382     for(i=1; i<=yypParser->yyidx; i++)
80383       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
80384     fprintf(yyTraceFILE,"\n");
80385   }
80386 #endif
80387 }
80388
80389 /* The following table contains information about every rule that
80390 ** is used during the reduce.
80391 */
80392 static const struct {
80393   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
80394   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
80395 } yyRuleInfo[] = {
80396   { 140, 1 },
80397   { 141, 2 },
80398   { 141, 1 },
80399   { 142, 1 },
80400   { 142, 3 },
80401   { 143, 0 },
80402   { 143, 1 },
80403   { 143, 3 },
80404   { 144, 1 },
80405   { 145, 3 },
80406   { 147, 0 },
80407   { 147, 1 },
80408   { 147, 2 },
80409   { 146, 0 },
80410   { 146, 1 },
80411   { 146, 1 },
80412   { 146, 1 },
80413   { 145, 2 },
80414   { 145, 2 },
80415   { 145, 2 },
80416   { 145, 2 },
80417   { 149, 6 },
80418   { 152, 0 },
80419   { 152, 3 },
80420   { 151, 1 },
80421   { 151, 0 },
80422   { 150, 4 },
80423   { 150, 2 },
80424   { 154, 3 },
80425   { 154, 1 },
80426   { 157, 3 },
80427   { 158, 1 },
80428   { 161, 1 },
80429   { 162, 1 },
80430   { 148, 1 },
80431   { 148, 1 },
80432   { 148, 1 },
80433   { 159, 0 },
80434   { 159, 1 },
80435   { 163, 1 },
80436   { 163, 4 },
80437   { 163, 6 },
80438   { 164, 1 },
80439   { 164, 2 },
80440   { 165, 1 },
80441   { 165, 1 },
80442   { 160, 2 },
80443   { 160, 0 },
80444   { 168, 3 },
80445   { 168, 1 },
80446   { 169, 2 },
80447   { 169, 4 },
80448   { 169, 3 },
80449   { 169, 3 },
80450   { 169, 2 },
80451   { 169, 2 },
80452   { 169, 3 },
80453   { 169, 5 },
80454   { 169, 2 },
80455   { 169, 4 },
80456   { 169, 4 },
80457   { 169, 1 },
80458   { 169, 2 },
80459   { 174, 0 },
80460   { 174, 1 },
80461   { 176, 0 },
80462   { 176, 2 },
80463   { 178, 2 },
80464   { 178, 3 },
80465   { 178, 3 },
80466   { 178, 3 },
80467   { 179, 2 },
80468   { 179, 2 },
80469   { 179, 1 },
80470   { 179, 1 },
80471   { 177, 3 },
80472   { 177, 2 },
80473   { 180, 0 },
80474   { 180, 2 },
80475   { 180, 2 },
80476   { 155, 0 },
80477   { 155, 2 },
80478   { 181, 3 },
80479   { 181, 2 },
80480   { 181, 1 },
80481   { 182, 2 },
80482   { 182, 7 },
80483   { 182, 5 },
80484   { 182, 5 },
80485   { 182, 10 },
80486   { 184, 0 },
80487   { 184, 1 },
80488   { 172, 0 },
80489   { 172, 3 },
80490   { 185, 0 },
80491   { 185, 2 },
80492   { 186, 1 },
80493   { 186, 1 },
80494   { 186, 1 },
80495   { 145, 4 },
80496   { 188, 2 },
80497   { 188, 0 },
80498   { 145, 8 },
80499   { 145, 4 },
80500   { 145, 1 },
80501   { 156, 1 },
80502   { 156, 3 },
80503   { 191, 1 },
80504   { 191, 2 },
80505   { 191, 1 },
80506   { 190, 9 },
80507   { 192, 1 },
80508   { 192, 1 },
80509   { 192, 0 },
80510   { 200, 2 },
80511   { 200, 0 },
80512   { 193, 3 },
80513   { 193, 2 },
80514   { 193, 4 },
80515   { 201, 2 },
80516   { 201, 1 },
80517   { 201, 0 },
80518   { 194, 0 },
80519   { 194, 2 },
80520   { 203, 2 },
80521   { 203, 0 },
80522   { 202, 7 },
80523   { 202, 7 },
80524   { 208, 1 },
80525   { 208, 1 },
80526   { 153, 0 },
80527   { 153, 2 },
80528   { 189, 2 },
80529   { 204, 1 },
80530   { 204, 2 },
80531   { 204, 3 },
80532   { 204, 4 },
80533   { 206, 2 },
80534   { 206, 0 },
80535   { 205, 0 },
80536   { 205, 3 },
80537   { 205, 2 },
80538   { 207, 4 },
80539   { 207, 0 },
80540   { 198, 0 },
80541   { 198, 3 },
80542   { 211, 4 },
80543   { 211, 2 },
80544   { 212, 1 },
80545   { 173, 1 },
80546   { 173, 1 },
80547   { 173, 0 },
80548   { 196, 0 },
80549   { 196, 3 },
80550   { 197, 0 },
80551   { 197, 2 },
80552   { 199, 0 },
80553   { 199, 2 },
80554   { 199, 4 },
80555   { 199, 4 },
80556   { 145, 5 },
80557   { 195, 0 },
80558   { 195, 2 },
80559   { 145, 7 },
80560   { 214, 5 },
80561   { 214, 3 },
80562   { 145, 8 },
80563   { 145, 5 },
80564   { 145, 6 },
80565   { 215, 2 },
80566   { 215, 1 },
80567   { 217, 3 },
80568   { 217, 1 },
80569   { 216, 0 },
80570   { 216, 3 },
80571   { 210, 3 },
80572   { 210, 1 },
80573   { 171, 1 },
80574   { 171, 3 },
80575   { 170, 1 },
80576   { 171, 1 },
80577   { 171, 1 },
80578   { 171, 3 },
80579   { 171, 5 },
80580   { 170, 1 },
80581   { 170, 1 },
80582   { 171, 1 },
80583   { 171, 1 },
80584   { 171, 3 },
80585   { 171, 6 },
80586   { 171, 5 },
80587   { 171, 4 },
80588   { 170, 1 },
80589   { 171, 3 },
80590   { 171, 3 },
80591   { 171, 3 },
80592   { 171, 3 },
80593   { 171, 3 },
80594   { 171, 3 },
80595   { 171, 3 },
80596   { 171, 3 },
80597   { 219, 1 },
80598   { 219, 2 },
80599   { 219, 1 },
80600   { 219, 2 },
80601   { 220, 2 },
80602   { 220, 0 },
80603   { 171, 4 },
80604   { 171, 2 },
80605   { 171, 3 },
80606   { 171, 3 },
80607   { 171, 4 },
80608   { 171, 2 },
80609   { 171, 2 },
80610   { 171, 2 },
80611   { 171, 2 },
80612   { 221, 1 },
80613   { 221, 2 },
80614   { 171, 5 },
80615   { 222, 1 },
80616   { 222, 2 },
80617   { 171, 5 },
80618   { 171, 3 },
80619   { 171, 5 },
80620   { 171, 4 },
80621   { 171, 4 },
80622   { 171, 5 },
80623   { 224, 5 },
80624   { 224, 4 },
80625   { 225, 2 },
80626   { 225, 0 },
80627   { 223, 1 },
80628   { 223, 0 },
80629   { 218, 1 },
80630   { 218, 0 },
80631   { 213, 3 },
80632   { 213, 1 },
80633   { 145, 11 },
80634   { 226, 1 },
80635   { 226, 0 },
80636   { 175, 0 },
80637   { 175, 3 },
80638   { 183, 5 },
80639   { 183, 3 },
80640   { 227, 0 },
80641   { 227, 2 },
80642   { 145, 4 },
80643   { 145, 1 },
80644   { 145, 2 },
80645   { 145, 5 },
80646   { 145, 5 },
80647   { 145, 5 },
80648   { 145, 5 },
80649   { 145, 6 },
80650   { 145, 3 },
80651   { 228, 1 },
80652   { 228, 1 },
80653   { 166, 2 },
80654   { 167, 2 },
80655   { 230, 1 },
80656   { 229, 1 },
80657   { 229, 0 },
80658   { 145, 5 },
80659   { 231, 11 },
80660   { 233, 1 },
80661   { 233, 1 },
80662   { 233, 2 },
80663   { 233, 0 },
80664   { 234, 1 },
80665   { 234, 1 },
80666   { 234, 3 },
80667   { 235, 0 },
80668   { 235, 3 },
80669   { 236, 0 },
80670   { 236, 2 },
80671   { 232, 3 },
80672   { 232, 2 },
80673   { 237, 6 },
80674   { 237, 8 },
80675   { 237, 5 },
80676   { 237, 4 },
80677   { 237, 1 },
80678   { 171, 4 },
80679   { 171, 6 },
80680   { 187, 1 },
80681   { 187, 1 },
80682   { 187, 1 },
80683   { 145, 4 },
80684   { 145, 6 },
80685   { 145, 3 },
80686   { 239, 0 },
80687   { 239, 2 },
80688   { 238, 1 },
80689   { 238, 0 },
80690   { 145, 1 },
80691   { 145, 3 },
80692   { 145, 1 },
80693   { 145, 3 },
80694   { 145, 6 },
80695   { 145, 6 },
80696   { 240, 1 },
80697   { 241, 0 },
80698   { 241, 1 },
80699   { 145, 1 },
80700   { 145, 4 },
80701   { 242, 7 },
80702   { 243, 1 },
80703   { 243, 3 },
80704   { 244, 0 },
80705   { 244, 2 },
80706   { 245, 1 },
80707   { 245, 3 },
80708   { 246, 1 },
80709   { 247, 0 },
80710   { 247, 2 },
80711 };
80712
80713 static void yy_accept(yyParser*);  /* Forward Declaration */
80714
80715 /*
80716 ** Perform a reduce action and the shift that must immediately
80717 ** follow the reduce.
80718 */
80719 static void yy_reduce(
80720   yyParser *yypParser,         /* The parser */
80721   int yyruleno                 /* Number of the rule by which to reduce */
80722 ){
80723   int yygoto;                     /* The next state */
80724   int yyact;                      /* The next action */
80725   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
80726   yyStackEntry *yymsp;            /* The top of the parser's stack */
80727   int yysize;                     /* Amount to pop the stack */
80728   sqlite3ParserARG_FETCH;
80729   yymsp = &yypParser->yystack[yypParser->yyidx];
80730 #ifndef NDEBUG
80731   if( yyTraceFILE && yyruleno>=0 
80732         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
80733     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
80734       yyRuleName[yyruleno]);
80735   }
80736 #endif /* NDEBUG */
80737
80738   /* Silence complaints from purify about yygotominor being uninitialized
80739   ** in some cases when it is copied into the stack after the following
80740   ** switch.  yygotominor is uninitialized when a rule reduces that does
80741   ** not set the value of its left-hand side nonterminal.  Leaving the
80742   ** value of the nonterminal uninitialized is utterly harmless as long
80743   ** as the value is never used.  So really the only thing this code
80744   ** accomplishes is to quieten purify.  
80745   **
80746   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
80747   ** without this code, their parser segfaults.  I'm not sure what there
80748   ** parser is doing to make this happen.  This is the second bug report
80749   ** from wireshark this week.  Clearly they are stressing Lemon in ways
80750   ** that it has not been previously stressed...  (SQLite ticket #2172)
80751   */
80752   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
80753   yygotominor = yyzerominor;
80754
80755
80756   switch( yyruleno ){
80757   /* Beginning here are the reduction cases.  A typical example
80758   ** follows:
80759   **   case 0:
80760   **  #line <lineno> <grammarfile>
80761   **     { ... }           // User supplied code
80762   **  #line <lineno> <thisfile>
80763   **     break;
80764   */
80765       case 0: /* input ::= cmdlist */
80766       case 1: /* cmdlist ::= cmdlist ecmd */
80767       case 2: /* cmdlist ::= ecmd */
80768       case 3: /* ecmd ::= SEMI */
80769       case 4: /* ecmd ::= explain cmdx SEMI */
80770       case 10: /* trans_opt ::= */
80771       case 11: /* trans_opt ::= TRANSACTION */
80772       case 12: /* trans_opt ::= TRANSACTION nm */
80773       case 20: /* cmd ::= create_table create_table_args */
80774       case 28: /* columnlist ::= columnlist COMMA column */
80775       case 29: /* columnlist ::= column */
80776       case 37: /* type ::= */
80777       case 44: /* signed ::= plus_num */
80778       case 45: /* signed ::= minus_num */
80779       case 46: /* carglist ::= carglist carg */
80780       case 47: /* carglist ::= */
80781       case 48: /* carg ::= CONSTRAINT nm ccons */
80782       case 49: /* carg ::= ccons */
80783       case 55: /* ccons ::= NULL onconf */
80784       case 82: /* conslist ::= conslist COMMA tcons */
80785       case 83: /* conslist ::= conslist tcons */
80786       case 84: /* conslist ::= tcons */
80787       case 85: /* tcons ::= CONSTRAINT nm */
80788       case 260: /* plus_opt ::= PLUS */
80789       case 261: /* plus_opt ::= */
80790       case 271: /* foreach_clause ::= */
80791       case 272: /* foreach_clause ::= FOR EACH ROW */
80792       case 292: /* database_kw_opt ::= DATABASE */
80793       case 293: /* database_kw_opt ::= */
80794       case 301: /* kwcolumn_opt ::= */
80795       case 302: /* kwcolumn_opt ::= COLUMNKW */
80796       case 306: /* vtabarglist ::= vtabarg */
80797       case 307: /* vtabarglist ::= vtabarglist COMMA vtabarg */
80798       case 309: /* vtabarg ::= vtabarg vtabargtoken */
80799       case 313: /* anylist ::= */
80800 {
80801 }
80802         break;
80803       case 5: /* explain ::= */
80804 { sqlite3BeginParse(pParse, 0); }
80805         break;
80806       case 6: /* explain ::= EXPLAIN */
80807 { sqlite3BeginParse(pParse, 1); }
80808         break;
80809       case 7: /* explain ::= EXPLAIN QUERY PLAN */
80810 { sqlite3BeginParse(pParse, 2); }
80811         break;
80812       case 8: /* cmdx ::= cmd */
80813 { sqlite3FinishCoding(pParse); }
80814         break;
80815       case 9: /* cmd ::= BEGIN transtype trans_opt */
80816 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy316);}
80817         break;
80818       case 13: /* transtype ::= */
80819 {yygotominor.yy316 = TK_DEFERRED;}
80820         break;
80821       case 14: /* transtype ::= DEFERRED */
80822       case 15: /* transtype ::= IMMEDIATE */
80823       case 16: /* transtype ::= EXCLUSIVE */
80824       case 107: /* multiselect_op ::= UNION */
80825       case 109: /* multiselect_op ::= EXCEPT|INTERSECT */
80826 {yygotominor.yy316 = yymsp[0].major;}
80827         break;
80828       case 17: /* cmd ::= COMMIT trans_opt */
80829       case 18: /* cmd ::= END trans_opt */
80830 {sqlite3CommitTransaction(pParse);}
80831         break;
80832       case 19: /* cmd ::= ROLLBACK trans_opt */
80833 {sqlite3RollbackTransaction(pParse);}
80834         break;
80835       case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
80836 {
80837    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy316,0,0,yymsp[-2].minor.yy316);
80838 }
80839         break;
80840       case 22: /* ifnotexists ::= */
80841       case 25: /* temp ::= */
80842       case 63: /* autoinc ::= */
80843       case 77: /* init_deferred_pred_opt ::= */
80844       case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
80845       case 90: /* defer_subclause_opt ::= */
80846       case 101: /* ifexists ::= */
80847       case 112: /* distinct ::= ALL */
80848       case 113: /* distinct ::= */
80849       case 216: /* between_op ::= BETWEEN */
80850       case 219: /* in_op ::= IN */
80851 {yygotominor.yy316 = 0;}
80852         break;
80853       case 23: /* ifnotexists ::= IF NOT EXISTS */
80854       case 24: /* temp ::= TEMP */
80855       case 64: /* autoinc ::= AUTOINCR */
80856       case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
80857       case 100: /* ifexists ::= IF EXISTS */
80858       case 111: /* distinct ::= DISTINCT */
80859       case 217: /* between_op ::= NOT BETWEEN */
80860       case 220: /* in_op ::= NOT IN */
80861 {yygotominor.yy316 = 1;}
80862         break;
80863       case 26: /* create_table_args ::= LP columnlist conslist_opt RP */
80864 {
80865   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
80866 }
80867         break;
80868       case 27: /* create_table_args ::= AS select */
80869 {
80870   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy43);
80871   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy43);
80872 }
80873         break;
80874       case 30: /* column ::= columnid type carglist */
80875 {
80876   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
80877   yygotominor.yy0.n = (pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
80878 }
80879         break;
80880       case 31: /* columnid ::= nm */
80881 {
80882   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
80883   yygotominor.yy0 = yymsp[0].minor.yy0;
80884 }
80885         break;
80886       case 32: /* id ::= ID */
80887       case 33: /* ids ::= ID|STRING */
80888       case 34: /* nm ::= ID */
80889       case 35: /* nm ::= STRING */
80890       case 36: /* nm ::= JOIN_KW */
80891       case 39: /* typetoken ::= typename */
80892       case 42: /* typename ::= ids */
80893       case 119: /* as ::= AS nm */
80894       case 120: /* as ::= ids */
80895       case 131: /* dbnm ::= DOT nm */
80896       case 140: /* indexed_opt ::= INDEXED BY nm */
80897       case 245: /* collate ::= COLLATE ids */
80898       case 255: /* nmnum ::= plus_num */
80899       case 256: /* nmnum ::= nm */
80900       case 257: /* plus_num ::= plus_opt number */
80901       case 258: /* minus_num ::= MINUS number */
80902       case 259: /* number ::= INTEGER|FLOAT */
80903 {yygotominor.yy0 = yymsp[0].minor.yy0;}
80904         break;
80905       case 38: /* type ::= typetoken */
80906 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
80907         break;
80908       case 40: /* typetoken ::= typename LP signed RP */
80909 {
80910   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
80911   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z;
80912 }
80913         break;
80914       case 41: /* typetoken ::= typename LP signed COMMA signed RP */
80915 {
80916   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
80917   yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z;
80918 }
80919         break;
80920       case 43: /* typename ::= typename ids */
80921 {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);}
80922         break;
80923       case 50: /* ccons ::= DEFAULT term */
80924       case 52: /* ccons ::= DEFAULT PLUS term */
80925 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy450);}
80926         break;
80927       case 51: /* ccons ::= DEFAULT LP expr RP */
80928 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy450);}
80929         break;
80930       case 53: /* ccons ::= DEFAULT MINUS term */
80931 {
80932   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy450, 0, 0);
80933   sqlite3AddDefaultValue(pParse,p);
80934 }
80935         break;
80936       case 54: /* ccons ::= DEFAULT id */
80937 {
80938   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
80939   sqlite3AddDefaultValue(pParse,p);
80940 }
80941         break;
80942       case 56: /* ccons ::= NOT NULL onconf */
80943 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy316);}
80944         break;
80945       case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
80946 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy316,yymsp[0].minor.yy316,yymsp[-2].minor.yy316);}
80947         break;
80948       case 58: /* ccons ::= UNIQUE onconf */
80949 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy316,0,0,0,0);}
80950         break;
80951       case 59: /* ccons ::= CHECK LP expr RP */
80952 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy450);}
80953         break;
80954       case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */
80955 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy316);}
80956         break;
80957       case 61: /* ccons ::= defer_subclause */
80958 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy316);}
80959         break;
80960       case 62: /* ccons ::= COLLATE ids */
80961 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
80962         break;
80963       case 65: /* refargs ::= */
80964 { yygotominor.yy316 = OE_Restrict * 0x010101; }
80965         break;
80966       case 66: /* refargs ::= refargs refarg */
80967 { yygotominor.yy316 = (yymsp[-1].minor.yy316 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
80968         break;
80969       case 67: /* refarg ::= MATCH nm */
80970 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
80971         break;
80972       case 68: /* refarg ::= ON DELETE refact */
80973 { yygotominor.yy207.value = yymsp[0].minor.yy316;     yygotominor.yy207.mask = 0x0000ff; }
80974         break;
80975       case 69: /* refarg ::= ON UPDATE refact */
80976 { yygotominor.yy207.value = yymsp[0].minor.yy316<<8;  yygotominor.yy207.mask = 0x00ff00; }
80977         break;
80978       case 70: /* refarg ::= ON INSERT refact */
80979 { yygotominor.yy207.value = yymsp[0].minor.yy316<<16; yygotominor.yy207.mask = 0xff0000; }
80980         break;
80981       case 71: /* refact ::= SET NULL */
80982 { yygotominor.yy316 = OE_SetNull; }
80983         break;
80984       case 72: /* refact ::= SET DEFAULT */
80985 { yygotominor.yy316 = OE_SetDflt; }
80986         break;
80987       case 73: /* refact ::= CASCADE */
80988 { yygotominor.yy316 = OE_Cascade; }
80989         break;
80990       case 74: /* refact ::= RESTRICT */
80991 { yygotominor.yy316 = OE_Restrict; }
80992         break;
80993       case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
80994       case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
80995       case 91: /* defer_subclause_opt ::= defer_subclause */
80996       case 93: /* onconf ::= ON CONFLICT resolvetype */
80997       case 95: /* orconf ::= OR resolvetype */
80998       case 96: /* resolvetype ::= raisetype */
80999       case 169: /* insert_cmd ::= INSERT orconf */
81000 {yygotominor.yy316 = yymsp[0].minor.yy316;}
81001         break;
81002       case 80: /* conslist_opt ::= */
81003 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
81004         break;
81005       case 81: /* conslist_opt ::= COMMA conslist */
81006 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
81007         break;
81008       case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
81009 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy316,yymsp[-2].minor.yy316,0);}
81010         break;
81011       case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */
81012 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy316,0,0,0,0);}
81013         break;
81014       case 88: /* tcons ::= CHECK LP expr RP onconf */
81015 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy450);}
81016         break;
81017       case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
81018 {
81019     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy316);
81020     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy316);
81021 }
81022         break;
81023       case 92: /* onconf ::= */
81024       case 94: /* orconf ::= */
81025 {yygotominor.yy316 = OE_Default;}
81026         break;
81027       case 97: /* resolvetype ::= IGNORE */
81028 {yygotominor.yy316 = OE_Ignore;}
81029         break;
81030       case 98: /* resolvetype ::= REPLACE */
81031       case 170: /* insert_cmd ::= REPLACE */
81032 {yygotominor.yy316 = OE_Replace;}
81033         break;
81034       case 99: /* cmd ::= DROP TABLE ifexists fullname */
81035 {
81036   sqlite3DropTable(pParse, yymsp[0].minor.yy419, 0, yymsp[-1].minor.yy316);
81037 }
81038         break;
81039       case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
81040 {
81041   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);
81042 }
81043         break;
81044       case 103: /* cmd ::= DROP VIEW ifexists fullname */
81045 {
81046   sqlite3DropTable(pParse, yymsp[0].minor.yy419, 1, yymsp[-1].minor.yy316);
81047 }
81048         break;
81049       case 104: /* cmd ::= select */
81050 {
81051   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
81052   sqlite3Select(pParse, yymsp[0].minor.yy43, &dest);
81053   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy43);
81054 }
81055         break;
81056       case 105: /* select ::= oneselect */
81057       case 128: /* seltablist_paren ::= select */
81058 {yygotominor.yy43 = yymsp[0].minor.yy43;}
81059         break;
81060       case 106: /* select ::= select multiselect_op oneselect */
81061 {
81062   if( yymsp[0].minor.yy43 ){
81063     yymsp[0].minor.yy43->op = yymsp[-1].minor.yy316;
81064     yymsp[0].minor.yy43->pPrior = yymsp[-2].minor.yy43;
81065   }else{
81066     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy43);
81067   }
81068   yygotominor.yy43 = yymsp[0].minor.yy43;
81069 }
81070         break;
81071       case 108: /* multiselect_op ::= UNION ALL */
81072 {yygotominor.yy316 = TK_ALL;}
81073         break;
81074       case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
81075 {
81076   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);
81077 }
81078         break;
81079       case 114: /* sclp ::= selcollist COMMA */
81080       case 241: /* idxlist_opt ::= LP idxlist RP */
81081 {yygotominor.yy242 = yymsp[-1].minor.yy242;}
81082         break;
81083       case 115: /* sclp ::= */
81084       case 144: /* orderby_opt ::= */
81085       case 152: /* groupby_opt ::= */
81086       case 234: /* exprlist ::= */
81087       case 240: /* idxlist_opt ::= */
81088 {yygotominor.yy242 = 0;}
81089         break;
81090       case 116: /* selcollist ::= sclp expr as */
81091 {
81092    yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy450,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
81093 }
81094         break;
81095       case 117: /* selcollist ::= sclp STAR */
81096 {
81097   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
81098   yygotominor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy242, p, 0);
81099 }
81100         break;
81101       case 118: /* selcollist ::= sclp nm DOT STAR */
81102 {
81103   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
81104   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
81105   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
81106   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, pDot, 0);
81107 }
81108         break;
81109       case 121: /* as ::= */
81110 {yygotominor.yy0.n = 0;}
81111         break;
81112       case 122: /* from ::= */
81113 {yygotominor.yy419 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy419));}
81114         break;
81115       case 123: /* from ::= FROM seltablist */
81116 {
81117   yygotominor.yy419 = yymsp[0].minor.yy419;
81118   sqlite3SrcListShiftJoinType(yygotominor.yy419);
81119 }
81120         break;
81121       case 124: /* stl_prefix ::= seltablist joinop */
81122 {
81123    yygotominor.yy419 = yymsp[-1].minor.yy419;
81124    if( yygotominor.yy419 && yygotominor.yy419->nSrc>0 ) yygotominor.yy419->a[yygotominor.yy419->nSrc-1].jointype = yymsp[0].minor.yy316;
81125 }
81126         break;
81127       case 125: /* stl_prefix ::= */
81128 {yygotominor.yy419 = 0;}
81129         break;
81130       case 126: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
81131 {
81132   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);
81133   sqlite3SrcListIndexedBy(pParse, yygotominor.yy419, &yymsp[-2].minor.yy0);
81134 }
81135         break;
81136       case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
81137 {
81138     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);
81139   }
81140         break;
81141       case 129: /* seltablist_paren ::= seltablist */
81142 {
81143      sqlite3SrcListShiftJoinType(yymsp[0].minor.yy419);
81144      yygotominor.yy43 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy419,0,0,0,0,0,0,0);
81145   }
81146         break;
81147       case 130: /* dbnm ::= */
81148       case 139: /* indexed_opt ::= */
81149 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
81150         break;
81151       case 132: /* fullname ::= nm dbnm */
81152 {yygotominor.yy419 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
81153         break;
81154       case 133: /* joinop ::= COMMA|JOIN */
81155 { yygotominor.yy316 = JT_INNER; }
81156         break;
81157       case 134: /* joinop ::= JOIN_KW JOIN */
81158 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
81159         break;
81160       case 135: /* joinop ::= JOIN_KW nm JOIN */
81161 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
81162         break;
81163       case 136: /* joinop ::= JOIN_KW nm nm JOIN */
81164 { yygotominor.yy316 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
81165         break;
81166       case 137: /* on_opt ::= ON expr */
81167       case 148: /* sortitem ::= expr */
81168       case 155: /* having_opt ::= HAVING expr */
81169       case 162: /* where_opt ::= WHERE expr */
81170       case 177: /* expr ::= term */
81171       case 205: /* escape ::= ESCAPE expr */
81172       case 229: /* case_else ::= ELSE expr */
81173       case 231: /* case_operand ::= expr */
81174 {yygotominor.yy450 = yymsp[0].minor.yy450;}
81175         break;
81176       case 138: /* on_opt ::= */
81177       case 154: /* having_opt ::= */
81178       case 161: /* where_opt ::= */
81179       case 206: /* escape ::= */
81180       case 230: /* case_else ::= */
81181       case 232: /* case_operand ::= */
81182 {yygotominor.yy450 = 0;}
81183         break;
81184       case 141: /* indexed_opt ::= NOT INDEXED */
81185 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
81186         break;
81187       case 142: /* using_opt ::= USING LP inscollist RP */
81188       case 174: /* inscollist_opt ::= LP inscollist RP */
81189 {yygotominor.yy352 = yymsp[-1].minor.yy352;}
81190         break;
81191       case 143: /* using_opt ::= */
81192       case 173: /* inscollist_opt ::= */
81193 {yygotominor.yy352 = 0;}
81194         break;
81195       case 145: /* orderby_opt ::= ORDER BY sortlist */
81196       case 153: /* groupby_opt ::= GROUP BY nexprlist */
81197       case 233: /* exprlist ::= nexprlist */
81198 {yygotominor.yy242 = yymsp[0].minor.yy242;}
81199         break;
81200       case 146: /* sortlist ::= sortlist COMMA sortitem sortorder */
81201 {
81202   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242,yymsp[-1].minor.yy450,0);
81203   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
81204 }
81205         break;
81206       case 147: /* sortlist ::= sortitem sortorder */
81207 {
81208   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy450,0);
81209   if( yygotominor.yy242 && yygotominor.yy242->a ) yygotominor.yy242->a[0].sortOrder = yymsp[0].minor.yy316;
81210 }
81211         break;
81212       case 149: /* sortorder ::= ASC */
81213       case 151: /* sortorder ::= */
81214 {yygotominor.yy316 = SQLITE_SO_ASC;}
81215         break;
81216       case 150: /* sortorder ::= DESC */
81217 {yygotominor.yy316 = SQLITE_SO_DESC;}
81218         break;
81219       case 156: /* limit_opt ::= */
81220 {yygotominor.yy84.pLimit = 0; yygotominor.yy84.pOffset = 0;}
81221         break;
81222       case 157: /* limit_opt ::= LIMIT expr */
81223 {yygotominor.yy84.pLimit = yymsp[0].minor.yy450; yygotominor.yy84.pOffset = 0;}
81224         break;
81225       case 158: /* limit_opt ::= LIMIT expr OFFSET expr */
81226 {yygotominor.yy84.pLimit = yymsp[-2].minor.yy450; yygotominor.yy84.pOffset = yymsp[0].minor.yy450;}
81227         break;
81228       case 159: /* limit_opt ::= LIMIT expr COMMA expr */
81229 {yygotominor.yy84.pOffset = yymsp[-2].minor.yy450; yygotominor.yy84.pLimit = yymsp[0].minor.yy450;}
81230         break;
81231       case 160: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
81232 {
81233   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy419, &yymsp[-1].minor.yy0);
81234   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy419,yymsp[0].minor.yy450);
81235 }
81236         break;
81237       case 163: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
81238 {
81239   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy419, &yymsp[-3].minor.yy0);
81240   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy242,"set list"); 
81241   sqlite3Update(pParse,yymsp[-4].minor.yy419,yymsp[-1].minor.yy242,yymsp[0].minor.yy450,yymsp[-5].minor.yy316);
81242 }
81243         break;
81244       case 164: /* setlist ::= setlist COMMA nm EQ expr */
81245 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[0].minor.yy450,&yymsp[-2].minor.yy0);}
81246         break;
81247       case 165: /* setlist ::= nm EQ expr */
81248 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy450,&yymsp[-2].minor.yy0);}
81249         break;
81250       case 166: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
81251 {sqlite3Insert(pParse, yymsp[-5].minor.yy419, yymsp[-1].minor.yy242, 0, yymsp[-4].minor.yy352, yymsp[-7].minor.yy316);}
81252         break;
81253       case 167: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
81254 {sqlite3Insert(pParse, yymsp[-2].minor.yy419, 0, yymsp[0].minor.yy43, yymsp[-1].minor.yy352, yymsp[-4].minor.yy316);}
81255         break;
81256       case 168: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
81257 {sqlite3Insert(pParse, yymsp[-3].minor.yy419, 0, 0, yymsp[-2].minor.yy352, yymsp[-5].minor.yy316);}
81258         break;
81259       case 171: /* itemlist ::= itemlist COMMA expr */
81260       case 235: /* nexprlist ::= nexprlist COMMA expr */
81261 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy450,0);}
81262         break;
81263       case 172: /* itemlist ::= expr */
81264       case 236: /* nexprlist ::= expr */
81265 {yygotominor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy450,0);}
81266         break;
81267       case 175: /* inscollist ::= inscollist COMMA nm */
81268 {yygotominor.yy352 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy352,&yymsp[0].minor.yy0);}
81269         break;
81270       case 176: /* inscollist ::= nm */
81271 {yygotominor.yy352 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
81272         break;
81273       case 178: /* expr ::= LP expr RP */
81274 {yygotominor.yy450 = yymsp[-1].minor.yy450; sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
81275         break;
81276       case 179: /* term ::= NULL */
81277       case 184: /* term ::= INTEGER|FLOAT|BLOB */
81278       case 185: /* term ::= STRING */
81279 {yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
81280         break;
81281       case 180: /* expr ::= ID */
81282       case 181: /* expr ::= JOIN_KW */
81283 {yygotominor.yy450 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
81284         break;
81285       case 182: /* expr ::= nm DOT nm */
81286 {
81287   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
81288   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
81289   yygotominor.yy450 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
81290 }
81291         break;
81292       case 183: /* expr ::= nm DOT nm DOT nm */
81293 {
81294   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
81295   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
81296   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
81297   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
81298   yygotominor.yy450 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
81299 }
81300         break;
81301       case 186: /* expr ::= REGISTER */
81302 {yygotominor.yy450 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
81303         break;
81304       case 187: /* expr ::= VARIABLE */
81305 {
81306   Token *pToken = &yymsp[0].minor.yy0;
81307   Expr *pExpr = yygotominor.yy450 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
81308   sqlite3ExprAssignVarNumber(pParse, pExpr);
81309 }
81310         break;
81311       case 188: /* expr ::= expr COLLATE ids */
81312 {
81313   yygotominor.yy450 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy450, &yymsp[0].minor.yy0);
81314 }
81315         break;
81316       case 189: /* expr ::= CAST LP expr AS typetoken RP */
81317 {
81318   yygotominor.yy450 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy450, 0, &yymsp[-1].minor.yy0);
81319   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
81320 }
81321         break;
81322       case 190: /* expr ::= ID LP distinct exprlist RP */
81323 {
81324   if( yymsp[-1].minor.yy242 && yymsp[-1].minor.yy242->nExpr>SQLITE_MAX_FUNCTION_ARG ){
81325     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
81326   }
81327   yygotominor.yy450 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);
81328   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
81329   if( yymsp[-2].minor.yy316 && yygotominor.yy450 ){
81330     yygotominor.yy450->flags |= EP_Distinct;
81331   }
81332 }
81333         break;
81334       case 191: /* expr ::= ID LP STAR RP */
81335 {
81336   yygotominor.yy450 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
81337   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
81338 }
81339         break;
81340       case 192: /* term ::= CTIME_KW */
81341 {
81342   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
81343   ** treated as functions that return constants */
81344   yygotominor.yy450 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
81345   if( yygotominor.yy450 ){
81346     yygotominor.yy450->op = TK_CONST_FUNC;  
81347     yygotominor.yy450->span = yymsp[0].minor.yy0;
81348   }
81349 }
81350         break;
81351       case 193: /* expr ::= expr AND expr */
81352       case 194: /* expr ::= expr OR expr */
81353       case 195: /* expr ::= expr LT|GT|GE|LE expr */
81354       case 196: /* expr ::= expr EQ|NE expr */
81355       case 197: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
81356       case 198: /* expr ::= expr PLUS|MINUS expr */
81357       case 199: /* expr ::= expr STAR|SLASH|REM expr */
81358       case 200: /* expr ::= expr CONCAT expr */
81359 {yygotominor.yy450 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy450,yymsp[0].minor.yy450,0);}
81360         break;
81361       case 201: /* likeop ::= LIKE_KW */
81362       case 203: /* likeop ::= MATCH */
81363 {yygotominor.yy86.eOperator = yymsp[0].minor.yy0; yygotominor.yy86.not = 0;}
81364         break;
81365       case 202: /* likeop ::= NOT LIKE_KW */
81366       case 204: /* likeop ::= NOT MATCH */
81367 {yygotominor.yy86.eOperator = yymsp[0].minor.yy0; yygotominor.yy86.not = 1;}
81368         break;
81369       case 207: /* expr ::= expr likeop expr escape */
81370 {
81371   ExprList *pList;
81372   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy450, 0);
81373   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy450, 0);
81374   if( yymsp[0].minor.yy450 ){
81375     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy450, 0);
81376   }
81377   yygotominor.yy450 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy86.eOperator);
81378   if( yymsp[-2].minor.yy86.not ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
81379   sqlite3ExprSpan(yygotominor.yy450, &yymsp[-3].minor.yy450->span, &yymsp[-1].minor.yy450->span);
81380   if( yygotominor.yy450 ) yygotominor.yy450->flags |= EP_InfixFunc;
81381 }
81382         break;
81383       case 208: /* expr ::= expr ISNULL|NOTNULL */
81384 {
81385   yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy450, 0, 0);
81386   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy450->span,&yymsp[0].minor.yy0);
81387 }
81388         break;
81389       case 209: /* expr ::= expr IS NULL */
81390 {
81391   yygotominor.yy450 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy450, 0, 0);
81392   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy450->span,&yymsp[0].minor.yy0);
81393 }
81394         break;
81395       case 210: /* expr ::= expr NOT NULL */
81396 {
81397   yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy450, 0, 0);
81398   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy450->span,&yymsp[0].minor.yy0);
81399 }
81400         break;
81401       case 211: /* expr ::= expr IS NOT NULL */
81402 {
81403   yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy450, 0, 0);
81404   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy450->span,&yymsp[0].minor.yy0);
81405 }
81406         break;
81407       case 212: /* expr ::= NOT expr */
81408       case 213: /* expr ::= BITNOT expr */
81409 {
81410   yygotominor.yy450 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy450, 0, 0);
81411   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
81412 }
81413         break;
81414       case 214: /* expr ::= MINUS expr */
81415 {
81416   yygotominor.yy450 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy450, 0, 0);
81417   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
81418 }
81419         break;
81420       case 215: /* expr ::= PLUS expr */
81421 {
81422   yygotominor.yy450 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy450, 0, 0);
81423   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy450->span);
81424 }
81425         break;
81426       case 218: /* expr ::= expr between_op expr AND expr */
81427 {
81428   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy450, 0);
81429   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy450, 0);
81430   yygotominor.yy450 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy450, 0, 0);
81431   if( yygotominor.yy450 ){
81432     yygotominor.yy450->pList = pList;
81433   }else{
81434     sqlite3ExprListDelete(pParse->db, pList);
81435   } 
81436   if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
81437   sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy450->span);
81438 }
81439         break;
81440       case 221: /* expr ::= expr in_op LP exprlist RP */
81441 {
81442     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy450, 0, 0);
81443     if( yygotominor.yy450 ){
81444       yygotominor.yy450->pList = yymsp[-1].minor.yy242;
81445       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81446     }else{
81447       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
81448     }
81449     if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
81450     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy0);
81451   }
81452         break;
81453       case 222: /* expr ::= LP select RP */
81454 {
81455     yygotominor.yy450 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
81456     if( yygotominor.yy450 ){
81457       yygotominor.yy450->pSelect = yymsp[-1].minor.yy43;
81458       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81459     }else{
81460       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
81461     }
81462     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
81463   }
81464         break;
81465       case 223: /* expr ::= expr in_op LP select RP */
81466 {
81467     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy450, 0, 0);
81468     if( yygotominor.yy450 ){
81469       yygotominor.yy450->pSelect = yymsp[-1].minor.yy43;
81470       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81471     }else{
81472       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
81473     }
81474     if( yymsp[-3].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
81475     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-4].minor.yy450->span,&yymsp[0].minor.yy0);
81476   }
81477         break;
81478       case 224: /* expr ::= expr in_op nm dbnm */
81479 {
81480     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
81481     yygotominor.yy450 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy450, 0, 0);
81482     if( yygotominor.yy450 ){
81483       yygotominor.yy450->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
81484       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81485     }else{
81486       sqlite3SrcListDelete(pParse->db, pSrc);
81487     }
81488     if( yymsp[-2].minor.yy316 ) yygotominor.yy450 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy450, 0, 0);
81489     sqlite3ExprSpan(yygotominor.yy450,&yymsp[-3].minor.yy450->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
81490   }
81491         break;
81492       case 225: /* expr ::= EXISTS LP select RP */
81493 {
81494     Expr *p = yygotominor.yy450 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
81495     if( p ){
81496       p->pSelect = yymsp[-1].minor.yy43;
81497       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
81498       sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81499     }else{
81500       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy43);
81501     }
81502   }
81503         break;
81504       case 226: /* expr ::= CASE case_operand case_exprlist case_else END */
81505 {
81506   yygotominor.yy450 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy450, yymsp[-1].minor.yy450, 0);
81507   if( yygotominor.yy450 ){
81508     yygotominor.yy450->pList = yymsp[-2].minor.yy242;
81509     sqlite3ExprSetHeight(pParse, yygotominor.yy450);
81510   }else{
81511     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);
81512   }
81513   sqlite3ExprSpan(yygotominor.yy450, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
81514 }
81515         break;
81516       case 227: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
81517 {
81518   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy450, 0);
81519   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yygotominor.yy242, yymsp[0].minor.yy450, 0);
81520 }
81521         break;
81522       case 228: /* case_exprlist ::= WHEN expr THEN expr */
81523 {
81524   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy450, 0);
81525   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yygotominor.yy242, yymsp[0].minor.yy450, 0);
81526 }
81527         break;
81528       case 237: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
81529 {
81530   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
81531                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy242, yymsp[-9].minor.yy316,
81532                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy316);
81533 }
81534         break;
81535       case 238: /* uniqueflag ::= UNIQUE */
81536       case 285: /* raisetype ::= ABORT */
81537 {yygotominor.yy316 = OE_Abort;}
81538         break;
81539       case 239: /* uniqueflag ::= */
81540 {yygotominor.yy316 = OE_None;}
81541         break;
81542       case 242: /* idxlist ::= idxlist COMMA nm collate sortorder */
81543 {
81544   Expr *p = 0;
81545   if( yymsp[-1].minor.yy0.n>0 ){
81546     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
81547     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
81548   }
81549   yygotominor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, p, &yymsp[-2].minor.yy0);
81550   sqlite3ExprListCheckLength(pParse, yygotominor.yy242, "index");
81551   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
81552 }
81553         break;
81554       case 243: /* idxlist ::= nm collate sortorder */
81555 {
81556   Expr *p = 0;
81557   if( yymsp[-1].minor.yy0.n>0 ){
81558     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
81559     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
81560   }
81561   yygotominor.yy242 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
81562   sqlite3ExprListCheckLength(pParse, yygotominor.yy242, "index");
81563   if( yygotominor.yy242 ) yygotominor.yy242->a[yygotominor.yy242->nExpr-1].sortOrder = yymsp[0].minor.yy316;
81564 }
81565         break;
81566       case 244: /* collate ::= */
81567 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
81568         break;
81569       case 246: /* cmd ::= DROP INDEX ifexists fullname */
81570 {sqlite3DropIndex(pParse, yymsp[0].minor.yy419, yymsp[-1].minor.yy316);}
81571         break;
81572       case 247: /* cmd ::= VACUUM */
81573       case 248: /* cmd ::= VACUUM nm */
81574 {sqlite3Vacuum(pParse);}
81575         break;
81576       case 249: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
81577       case 250: /* cmd ::= PRAGMA nm dbnm EQ ON */
81578       case 251: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
81579 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
81580         break;
81581       case 252: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
81582 {
81583   sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
81584 }
81585         break;
81586       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
81587 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
81588         break;
81589       case 254: /* cmd ::= PRAGMA nm dbnm */
81590 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
81591         break;
81592       case 262: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
81593 {
81594   Token all;
81595   all.z = yymsp[-3].minor.yy0.z;
81596   all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
81597   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy75, &all);
81598 }
81599         break;
81600       case 263: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
81601 {
81602   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);
81603   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
81604 }
81605         break;
81606       case 264: /* trigger_time ::= BEFORE */
81607       case 267: /* trigger_time ::= */
81608 { yygotominor.yy316 = TK_BEFORE; }
81609         break;
81610       case 265: /* trigger_time ::= AFTER */
81611 { yygotominor.yy316 = TK_AFTER;  }
81612         break;
81613       case 266: /* trigger_time ::= INSTEAD OF */
81614 { yygotominor.yy316 = TK_INSTEAD;}
81615         break;
81616       case 268: /* trigger_event ::= DELETE|INSERT */
81617       case 269: /* trigger_event ::= UPDATE */
81618 {yygotominor.yy354.a = yymsp[0].major; yygotominor.yy354.b = 0;}
81619         break;
81620       case 270: /* trigger_event ::= UPDATE OF inscollist */
81621 {yygotominor.yy354.a = TK_UPDATE; yygotominor.yy354.b = yymsp[0].minor.yy352;}
81622         break;
81623       case 273: /* when_clause ::= */
81624       case 290: /* key_opt ::= */
81625 { yygotominor.yy450 = 0; }
81626         break;
81627       case 274: /* when_clause ::= WHEN expr */
81628       case 291: /* key_opt ::= KEY expr */
81629 { yygotominor.yy450 = yymsp[0].minor.yy450; }
81630         break;
81631       case 275: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
81632 {
81633 /*
81634   if( yymsp[-2].minor.yy75 ){
81635     yymsp[-2].minor.yy75->pLast->pNext = yymsp[-1].minor.yy75;
81636   }else{
81637     yymsp[-2].minor.yy75 = yymsp[-1].minor.yy75;
81638   }
81639 */
81640   assert( yymsp[-2].minor.yy75!=0 );
81641   yymsp[-2].minor.yy75->pLast->pNext = yymsp[-1].minor.yy75;
81642   yymsp[-2].minor.yy75->pLast = yymsp[-1].minor.yy75;
81643   yygotominor.yy75 = yymsp[-2].minor.yy75;
81644 }
81645         break;
81646       case 276: /* trigger_cmd_list ::= trigger_cmd SEMI */
81647
81648   /* if( yymsp[-1].minor.yy75 ) */
81649   assert( yymsp[-1].minor.yy75!=0 );
81650   yymsp[-1].minor.yy75->pLast = yymsp[-1].minor.yy75;
81651   yygotominor.yy75 = yymsp[-1].minor.yy75;
81652 }
81653         break;
81654       case 277: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
81655 { yygotominor.yy75 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy242, yymsp[0].minor.yy450, yymsp[-4].minor.yy316); }
81656         break;
81657       case 278: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
81658 {yygotominor.yy75 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy352, yymsp[-1].minor.yy242, 0, yymsp[-7].minor.yy316);}
81659         break;
81660       case 279: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
81661 {yygotominor.yy75 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy352, 0, yymsp[0].minor.yy43, yymsp[-4].minor.yy316);}
81662         break;
81663       case 280: /* trigger_cmd ::= DELETE FROM nm where_opt */
81664 {yygotominor.yy75 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy450);}
81665         break;
81666       case 281: /* trigger_cmd ::= select */
81667 {yygotominor.yy75 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy43); }
81668         break;
81669       case 282: /* expr ::= RAISE LP IGNORE RP */
81670 {
81671   yygotominor.yy450 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
81672   if( yygotominor.yy450 ){
81673     yygotominor.yy450->iColumn = OE_Ignore;
81674     sqlite3ExprSpan(yygotominor.yy450, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
81675   }
81676 }
81677         break;
81678       case 283: /* expr ::= RAISE LP raisetype COMMA nm RP */
81679 {
81680   yygotominor.yy450 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
81681   if( yygotominor.yy450 ) {
81682     yygotominor.yy450->iColumn = yymsp[-3].minor.yy316;
81683     sqlite3ExprSpan(yygotominor.yy450, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
81684   }
81685 }
81686         break;
81687       case 284: /* raisetype ::= ROLLBACK */
81688 {yygotominor.yy316 = OE_Rollback;}
81689         break;
81690       case 286: /* raisetype ::= FAIL */
81691 {yygotominor.yy316 = OE_Fail;}
81692         break;
81693       case 287: /* cmd ::= DROP TRIGGER ifexists fullname */
81694 {
81695   sqlite3DropTrigger(pParse,yymsp[0].minor.yy419,yymsp[-1].minor.yy316);
81696 }
81697         break;
81698       case 288: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
81699 {
81700   sqlite3Attach(pParse, yymsp[-3].minor.yy450, yymsp[-1].minor.yy450, yymsp[0].minor.yy450);
81701 }
81702         break;
81703       case 289: /* cmd ::= DETACH database_kw_opt expr */
81704 {
81705   sqlite3Detach(pParse, yymsp[0].minor.yy450);
81706 }
81707         break;
81708       case 294: /* cmd ::= REINDEX */
81709 {sqlite3Reindex(pParse, 0, 0);}
81710         break;
81711       case 295: /* cmd ::= REINDEX nm dbnm */
81712 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
81713         break;
81714       case 296: /* cmd ::= ANALYZE */
81715 {sqlite3Analyze(pParse, 0, 0);}
81716         break;
81717       case 297: /* cmd ::= ANALYZE nm dbnm */
81718 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
81719         break;
81720       case 298: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
81721 {
81722   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy419,&yymsp[0].minor.yy0);
81723 }
81724         break;
81725       case 299: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
81726 {
81727   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
81728 }
81729         break;
81730       case 300: /* add_column_fullname ::= fullname */
81731 {
81732   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy419);
81733 }
81734         break;
81735       case 303: /* cmd ::= create_vtab */
81736 {sqlite3VtabFinishParse(pParse,0);}
81737         break;
81738       case 304: /* cmd ::= create_vtab LP vtabarglist RP */
81739 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
81740         break;
81741       case 305: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
81742 {
81743     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
81744 }
81745         break;
81746       case 308: /* vtabarg ::= */
81747 {sqlite3VtabArgInit(pParse);}
81748         break;
81749       case 310: /* vtabargtoken ::= ANY */
81750       case 311: /* vtabargtoken ::= lp anylist RP */
81751       case 312: /* lp ::= LP */
81752       case 314: /* anylist ::= anylist ANY */
81753 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
81754         break;
81755   };
81756   yygoto = yyRuleInfo[yyruleno].lhs;
81757   yysize = yyRuleInfo[yyruleno].nrhs;
81758   yypParser->yyidx -= yysize;
81759   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,yygoto);
81760   if( yyact < YYNSTATE ){
81761 #ifdef NDEBUG
81762     /* If we are not debugging and the reduce action popped at least
81763     ** one element off the stack, then we can push the new element back
81764     ** onto the stack here, and skip the stack overflow test in yy_shift().
81765     ** That gives a significant speed improvement. */
81766     if( yysize ){
81767       yypParser->yyidx++;
81768       yymsp -= yysize-1;
81769       yymsp->stateno = yyact;
81770       yymsp->major = yygoto;
81771       yymsp->minor = yygotominor;
81772     }else
81773 #endif
81774     {
81775       yy_shift(yypParser,yyact,yygoto,&yygotominor);
81776     }
81777   }else{
81778     assert( yyact == YYNSTATE + YYNRULE + 1 );
81779     yy_accept(yypParser);
81780   }
81781 }
81782
81783 /*
81784 ** The following code executes when the parse fails
81785 */
81786 static void yy_parse_failed(
81787   yyParser *yypParser           /* The parser */
81788 ){
81789   sqlite3ParserARG_FETCH;
81790 #ifndef NDEBUG
81791   if( yyTraceFILE ){
81792     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
81793   }
81794 #endif
81795   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
81796   /* Here code is inserted which will be executed whenever the
81797   ** parser fails */
81798   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81799 }
81800
81801 /*
81802 ** The following code executes when a syntax error first occurs.
81803 */
81804 static void yy_syntax_error(
81805   yyParser *yypParser,           /* The parser */
81806   int yymajor,                   /* The major type of the error token */
81807   YYMINORTYPE yyminor            /* The minor type of the error token */
81808 ){
81809   sqlite3ParserARG_FETCH;
81810 #define TOKEN (yyminor.yy0)
81811
81812   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
81813   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
81814   pParse->parseError = 1;
81815   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81816 }
81817
81818 /*
81819 ** The following is executed when the parser accepts
81820 */
81821 static void yy_accept(
81822   yyParser *yypParser           /* The parser */
81823 ){
81824   sqlite3ParserARG_FETCH;
81825 #ifndef NDEBUG
81826   if( yyTraceFILE ){
81827     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
81828   }
81829 #endif
81830   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
81831   /* Here code is inserted which will be executed whenever the
81832   ** parser accepts */
81833   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
81834 }
81835
81836 /* The main parser program.
81837 ** The first argument is a pointer to a structure obtained from
81838 ** "sqlite3ParserAlloc" which describes the current state of the parser.
81839 ** The second argument is the major token number.  The third is
81840 ** the minor token.  The fourth optional argument is whatever the
81841 ** user wants (and specified in the grammar) and is available for
81842 ** use by the action routines.
81843 **
81844 ** Inputs:
81845 ** <ul>
81846 ** <li> A pointer to the parser (an opaque structure.)
81847 ** <li> The major token number.
81848 ** <li> The minor token number.
81849 ** <li> An option argument of a grammar-specified type.
81850 ** </ul>
81851 **
81852 ** Outputs:
81853 ** None.
81854 */
81855 SQLITE_PRIVATE void sqlite3Parser(
81856   void *yyp,                   /* The parser */
81857   int yymajor,                 /* The major token code number */
81858   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
81859   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
81860 ){
81861   YYMINORTYPE yyminorunion;
81862   int yyact;            /* The parser action. */
81863   int yyendofinput;     /* True if we are at the end of input */
81864 #ifdef YYERRORSYMBOL
81865   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
81866 #endif
81867   yyParser *yypParser;  /* The parser */
81868
81869   /* (re)initialize the parser, if necessary */
81870   yypParser = (yyParser*)yyp;
81871   if( yypParser->yyidx<0 ){
81872 #if YYSTACKDEPTH<=0
81873     if( yypParser->yystksz <=0 ){
81874       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
81875       yyminorunion = yyzerominor;
81876       yyStackOverflow(yypParser, &yyminorunion);
81877       return;
81878     }
81879 #endif
81880     yypParser->yyidx = 0;
81881     yypParser->yyerrcnt = -1;
81882     yypParser->yystack[0].stateno = 0;
81883     yypParser->yystack[0].major = 0;
81884   }
81885   yyminorunion.yy0 = yyminor;
81886   yyendofinput = (yymajor==0);
81887   sqlite3ParserARG_STORE;
81888
81889 #ifndef NDEBUG
81890   if( yyTraceFILE ){
81891     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
81892   }
81893 #endif
81894
81895   do{
81896     yyact = yy_find_shift_action(yypParser,yymajor);
81897     if( yyact<YYNSTATE ){
81898       assert( !yyendofinput );  /* Impossible to shift the $ token */
81899       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
81900       yypParser->yyerrcnt--;
81901       yymajor = YYNOCODE;
81902     }else if( yyact < YYNSTATE + YYNRULE ){
81903       yy_reduce(yypParser,yyact-YYNSTATE);
81904     }else{
81905       assert( yyact == YY_ERROR_ACTION );
81906 #ifdef YYERRORSYMBOL
81907       int yymx;
81908 #endif
81909 #ifndef NDEBUG
81910       if( yyTraceFILE ){
81911         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
81912       }
81913 #endif
81914 #ifdef YYERRORSYMBOL
81915       /* A syntax error has occurred.
81916       ** The response to an error depends upon whether or not the
81917       ** grammar defines an error token "ERROR".  
81918       **
81919       ** This is what we do if the grammar does define ERROR:
81920       **
81921       **  * Call the %syntax_error function.
81922       **
81923       **  * Begin popping the stack until we enter a state where
81924       **    it is legal to shift the error symbol, then shift
81925       **    the error symbol.
81926       **
81927       **  * Set the error count to three.
81928       **
81929       **  * Begin accepting and shifting new tokens.  No new error
81930       **    processing will occur until three tokens have been
81931       **    shifted successfully.
81932       **
81933       */
81934       if( yypParser->yyerrcnt<0 ){
81935         yy_syntax_error(yypParser,yymajor,yyminorunion);
81936       }
81937       yymx = yypParser->yystack[yypParser->yyidx].major;
81938       if( yymx==YYERRORSYMBOL || yyerrorhit ){
81939 #ifndef NDEBUG
81940         if( yyTraceFILE ){
81941           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
81942              yyTracePrompt,yyTokenName[yymajor]);
81943         }
81944 #endif
81945         yy_destructor(yypParser, yymajor,&yyminorunion);
81946         yymajor = YYNOCODE;
81947       }else{
81948          while(
81949           yypParser->yyidx >= 0 &&
81950           yymx != YYERRORSYMBOL &&
81951           (yyact = yy_find_reduce_action(
81952                         yypParser->yystack[yypParser->yyidx].stateno,
81953                         YYERRORSYMBOL)) >= YYNSTATE
81954         ){
81955           yy_pop_parser_stack(yypParser);
81956         }
81957         if( yypParser->yyidx < 0 || yymajor==0 ){
81958           yy_destructor(yypParser,yymajor,&yyminorunion);
81959           yy_parse_failed(yypParser);
81960           yymajor = YYNOCODE;
81961         }else if( yymx!=YYERRORSYMBOL ){
81962           YYMINORTYPE u2;
81963           u2.YYERRSYMDT = 0;
81964           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
81965         }
81966       }
81967       yypParser->yyerrcnt = 3;
81968       yyerrorhit = 1;
81969 #else  /* YYERRORSYMBOL is not defined */
81970       /* This is what we do if the grammar does not define ERROR:
81971       **
81972       **  * Report an error message, and throw away the input token.
81973       **
81974       **  * If the input token is $, then fail the parse.
81975       **
81976       ** As before, subsequent error messages are suppressed until
81977       ** three input tokens have been successfully shifted.
81978       */
81979       if( yypParser->yyerrcnt<=0 ){
81980         yy_syntax_error(yypParser,yymajor,yyminorunion);
81981       }
81982       yypParser->yyerrcnt = 3;
81983       yy_destructor(yypParser,yymajor,&yyminorunion);
81984       if( yyendofinput ){
81985         yy_parse_failed(yypParser);
81986       }
81987       yymajor = YYNOCODE;
81988 #endif
81989     }
81990   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
81991   return;
81992 }
81993
81994 /************** End of parse.c ***********************************************/
81995 /************** Begin file tokenize.c ****************************************/
81996 /*
81997 ** 2001 September 15
81998 **
81999 ** The author disclaims copyright to this source code.  In place of
82000 ** a legal notice, here is a blessing:
82001 **
82002 **    May you do good and not evil.
82003 **    May you find forgiveness for yourself and forgive others.
82004 **    May you share freely, never taking more than you give.
82005 **
82006 *************************************************************************
82007 ** An tokenizer for SQL
82008 **
82009 ** This file contains C code that splits an SQL input string up into
82010 ** individual tokens and sends those tokens one-by-one over to the
82011 ** parser for analysis.
82012 **
82013 ** $Id: tokenize.c,v 1.152 2008/09/01 15:52:11 drh Exp $
82014 */
82015
82016 /*
82017 ** The charMap() macro maps alphabetic characters into their
82018 ** lower-case ASCII equivalent.  On ASCII machines, this is just
82019 ** an upper-to-lower case map.  On EBCDIC machines we also need
82020 ** to adjust the encoding.  Only alphabetic characters and underscores
82021 ** need to be translated.
82022 */
82023 #ifdef SQLITE_ASCII
82024 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
82025 #endif
82026 #ifdef SQLITE_EBCDIC
82027 # define charMap(X) ebcdicToAscii[(unsigned char)X]
82028 const unsigned char ebcdicToAscii[] = {
82029 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
82030    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
82031    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
82032    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
82033    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
82034    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
82035    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
82036    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
82037    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
82038    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
82039    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
82040    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
82041    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
82042    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
82043    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
82044    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
82045    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
82046 };
82047 #endif
82048
82049 /*
82050 ** The sqlite3KeywordCode function looks up an identifier to determine if
82051 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
82052 ** returned.  If the input is not a keyword, TK_ID is returned.
82053 **
82054 ** The implementation of this routine was generated by a program,
82055 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
82056 ** The output of the mkkeywordhash.c program is written into a file
82057 ** named keywordhash.h and then included into this source file by
82058 ** the #include below.
82059 */
82060 /************** Include keywordhash.h in the middle of tokenize.c ************/
82061 /************** Begin file keywordhash.h *************************************/
82062 /***** This file contains automatically generated code ******
82063 **
82064 ** The code in this file has been automatically generated by
82065 **
82066 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.32 2008/10/06 05:32:19 danielk1977 Exp $
82067 **
82068 ** The code in this file implements a function that determines whether
82069 ** or not a given identifier is really an SQL keyword.  The same thing
82070 ** might be implemented more directly using a hand-written hash table.
82071 ** But by using this automatically generated code, the size of the code
82072 ** is substantially reduced.  This is important for embedded applications
82073 ** on platforms with limited memory.
82074 */
82075 /* Hash score: 167 */
82076 static int keywordCode(const char *z, int n){
82077   /* zText[] encodes 783 bytes of keywords in 528 bytes */
82078   static const char zText[528] =
82079     "REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECTABLE"
82080     "FTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTSCONSTRAINT"
82081     "ERSECTRIGGEREFERENCESUNIQUERYATTACHAVINGROUPDATEMPORARYBEGINNER"
82082     "ENAMEBETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATE"
82083     "DETACHIMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMIT"
82084     "WHENWHEREPLACEAFTERESTRICTANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT"
82085     "CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROM"
82086     "FULLGLOBYIFINTOFFSETISNULLORDERIGHTOUTEROLLBACKROWUNIONUSINGVACUUM"
82087     "VIEWINITIALLY";
82088   static const unsigned char aHash[127] = {
82089       65,  94, 110,  63,   0,  44,   0,   0,  71,   0,  66,   0,   0,
82090      104,  12,  67,  15,   0, 108,  74, 105, 101,   0,  19,   0,   0,
82091      114,   0, 112,  78,   0,  22,  82,   0,   9,   0,   0,  59,  60,
82092        0,  58,   6,   0,  39,  79,  91,   0, 111,  90,   0,   0,  45,
82093        0,  92,  24,   0,  17,   0, 115,  40,  23,   0,   5,  99,  25,
82094       85,   0,   0, 117,  95,  50, 116,  47,   7,  42,   0,  80,   0,
82095       89,  26,   0,  88,   0,   0,   0,  84,  81,  86,  77,  98,  14,
82096       34,  97,   0,  70,   0,  18,  76, 100,  31,   0, 113,  69, 106,
82097       52,  46,  73,   0,   0,  83, 102,   0, 109,   0,  35,   0,   0,
82098       28,   0,  75,  48,  53,   0,  20,  51,   0,  43,
82099   };
82100   static const unsigned char aNext[117] = {
82101        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
82102        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
82103        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
82104        0,   0,   3,  38,   0,  32,  21,   0,   0,   0,   0,  29,   0,
82105        0,  37,   0,   0,   0,   1,  55,   0,   0,  56,   0,   0,   0,
82106        0,   0,   0,   0,   0,   0,  54,   0,   0,   0,   0,  30,   0,
82107       16,  33,  10,   0,   0,   0,   0,   0,   0,   0,  11,  61,  68,
82108        0,   8,   0,  93,  87,   0,  96,   0,  49,   0,   0,  64,   0,
82109       41, 103,   0,  27, 107,  36,  62,  72,   0,   0,  57,   0,   0,
82110   };
82111   static const unsigned char aLen[117] = {
82112        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
82113        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
82114       11,   2,   7,   5,   5,   9,   6,  10,   9,   7,  10,   6,   5,
82115        6,   6,   5,   6,   4,   9,   2,   5,   5,   6,   7,   7,   3,
82116        4,   4,   7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,
82117        5,   4,   7,   6,   5,   6,   7,   5,   4,   5,   7,   5,   8,
82118        3,   7,  13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,
82119        8,   8,   2,   4,   4,   4,   4,   4,   2,   2,   4,   6,   2,
82120        3,   6,   5,   5,   5,   8,   3,   5,   5,   6,   4,   9,   3,
82121   };
82122   static const unsigned short int aOffset[117] = {
82123        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
82124       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
82125       86,  95,  96, 101, 105, 109, 117, 123, 130, 138, 144, 154, 157,
82126      162, 167, 172, 175, 179, 179, 183, 188, 191, 195, 201, 207, 207,
82127      210, 213, 217, 218, 222, 228, 232, 239, 245, 257, 263, 272, 274,
82128      280, 285, 287, 294, 299, 304, 310, 316, 321, 325, 328, 335, 339,
82129      347, 349, 356, 358, 360, 369, 373, 379, 385, 393, 398, 398, 414,
82130      421, 428, 429, 436, 440, 444, 448, 452, 455, 457, 459, 462, 462,
82131      465, 468, 474, 478, 483, 487, 495, 498, 503, 508, 514, 518, 523,
82132   };
82133   static const unsigned char aCode[117] = {
82134     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
82135     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
82136     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
82137     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
82138     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
82139     TK_EXCEPT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    TK_ALTER,      
82140     TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT, TK_INTERSECT,  
82141     TK_TRIGGER,    TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     
82142     TK_HAVING,     TK_GROUP,      TK_UPDATE,     TK_TEMP,       TK_TEMP,       
82143     TK_OR,         TK_BEGIN,      TK_JOIN_KW,    TK_RENAME,     TK_BETWEEN,    
82144     TK_NOTNULL,    TK_NOT,        TK_NULL,       TK_LIKE_KW,    TK_CASCADE,    
82145     TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    TK_CREATE,     
82146     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     
82147     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      
82148     TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       TK_WHERE,      
82149     TK_REPLACE,    TK_AFTER,      TK_RESTRICT,   TK_AND,        TK_DEFAULT,    
82150     TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       TK_COLUMNKW,   
82151     TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   
82152     TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       
82153     TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         
82154     TK_IF,         TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        
82155     TK_ISNULL,     TK_ORDER,      TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   
82156     TK_ROW,        TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       
82157     TK_INITIALLY,  TK_ALL,        
82158   };
82159   int h, i;
82160   if( n<2 ) return TK_ID;
82161   h = ((charMap(z[0])*4) ^
82162       (charMap(z[n-1])*3) ^
82163       n) % 127;
82164   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
82165     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
82166       return aCode[i];
82167     }
82168   }
82169   return TK_ID;
82170 }
82171 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
82172   return keywordCode((char*)z, n);
82173 }
82174
82175 /************** End of keywordhash.h *****************************************/
82176 /************** Continuing where we left off in tokenize.c *******************/
82177
82178
82179 /*
82180 ** If X is a character that can be used in an identifier then
82181 ** IdChar(X) will be true.  Otherwise it is false.
82182 **
82183 ** For ASCII, any character with the high-order bit set is
82184 ** allowed in an identifier.  For 7-bit characters, 
82185 ** sqlite3IsIdChar[X] must be 1.
82186 **
82187 ** For EBCDIC, the rules are more complex but have the same
82188 ** end result.
82189 **
82190 ** Ticket #1066.  the SQL standard does not allow '$' in the
82191 ** middle of identfiers.  But many SQL implementations do. 
82192 ** SQLite will allow '$' in identifiers for compatibility.
82193 ** But the feature is undocumented.
82194 */
82195 #ifdef SQLITE_ASCII
82196 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
82197 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
82198     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
82199     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
82200     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
82201     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
82202     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
82203     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
82204 };
82205 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
82206 #endif
82207 #ifdef SQLITE_EBCDIC
82208 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
82209 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
82210     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
82211     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
82212     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
82213     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
82214     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
82215     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
82216     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
82217     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
82218     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
82219     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
82220     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
82221     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
82222 };
82223 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
82224 #endif
82225
82226
82227 /*
82228 ** Return the length of the token that begins at z[0]. 
82229 ** Store the token type in *tokenType before returning.
82230 */
82231 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
82232   int i, c;
82233   switch( *z ){
82234     case ' ': case '\t': case '\n': case '\f': case '\r': {
82235       for(i=1; isspace(z[i]); i++){}
82236       *tokenType = TK_SPACE;
82237       return i;
82238     }
82239     case '-': {
82240       if( z[1]=='-' ){
82241         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
82242         *tokenType = TK_SPACE;
82243         return i;
82244       }
82245       *tokenType = TK_MINUS;
82246       return 1;
82247     }
82248     case '(': {
82249       *tokenType = TK_LP;
82250       return 1;
82251     }
82252     case ')': {
82253       *tokenType = TK_RP;
82254       return 1;
82255     }
82256     case ';': {
82257       *tokenType = TK_SEMI;
82258       return 1;
82259     }
82260     case '+': {
82261       *tokenType = TK_PLUS;
82262       return 1;
82263     }
82264     case '*': {
82265       *tokenType = TK_STAR;
82266       return 1;
82267     }
82268     case '/': {
82269       if( z[1]!='*' || z[2]==0 ){
82270         *tokenType = TK_SLASH;
82271         return 1;
82272       }
82273       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
82274       if( c ) i++;
82275       *tokenType = TK_SPACE;
82276       return i;
82277     }
82278     case '%': {
82279       *tokenType = TK_REM;
82280       return 1;
82281     }
82282     case '=': {
82283       *tokenType = TK_EQ;
82284       return 1 + (z[1]=='=');
82285     }
82286     case '<': {
82287       if( (c=z[1])=='=' ){
82288         *tokenType = TK_LE;
82289         return 2;
82290       }else if( c=='>' ){
82291         *tokenType = TK_NE;
82292         return 2;
82293       }else if( c=='<' ){
82294         *tokenType = TK_LSHIFT;
82295         return 2;
82296       }else{
82297         *tokenType = TK_LT;
82298         return 1;
82299       }
82300     }
82301     case '>': {
82302       if( (c=z[1])=='=' ){
82303         *tokenType = TK_GE;
82304         return 2;
82305       }else if( c=='>' ){
82306         *tokenType = TK_RSHIFT;
82307         return 2;
82308       }else{
82309         *tokenType = TK_GT;
82310         return 1;
82311       }
82312     }
82313     case '!': {
82314       if( z[1]!='=' ){
82315         *tokenType = TK_ILLEGAL;
82316         return 2;
82317       }else{
82318         *tokenType = TK_NE;
82319         return 2;
82320       }
82321     }
82322     case '|': {
82323       if( z[1]!='|' ){
82324         *tokenType = TK_BITOR;
82325         return 1;
82326       }else{
82327         *tokenType = TK_CONCAT;
82328         return 2;
82329       }
82330     }
82331     case ',': {
82332       *tokenType = TK_COMMA;
82333       return 1;
82334     }
82335     case '&': {
82336       *tokenType = TK_BITAND;
82337       return 1;
82338     }
82339     case '~': {
82340       *tokenType = TK_BITNOT;
82341       return 1;
82342     }
82343     case '`':
82344     case '\'':
82345     case '"': {
82346       int delim = z[0];
82347       for(i=1; (c=z[i])!=0; i++){
82348         if( c==delim ){
82349           if( z[i+1]==delim ){
82350             i++;
82351           }else{
82352             break;
82353           }
82354         }
82355       }
82356       if( c=='\'' ){
82357         *tokenType = TK_STRING;
82358         return i+1;
82359       }else if( c!=0 ){
82360         *tokenType = TK_ID;
82361         return i+1;
82362       }else{
82363         *tokenType = TK_ILLEGAL;
82364         return i;
82365       }
82366     }
82367     case '.': {
82368 #ifndef SQLITE_OMIT_FLOATING_POINT
82369       if( !isdigit(z[1]) )
82370 #endif
82371       {
82372         *tokenType = TK_DOT;
82373         return 1;
82374       }
82375       /* If the next character is a digit, this is a floating point
82376       ** number that begins with ".".  Fall thru into the next case */
82377     }
82378     case '0': case '1': case '2': case '3': case '4':
82379     case '5': case '6': case '7': case '8': case '9': {
82380       *tokenType = TK_INTEGER;
82381       for(i=0; isdigit(z[i]); i++){}
82382 #ifndef SQLITE_OMIT_FLOATING_POINT
82383       if( z[i]=='.' ){
82384         i++;
82385         while( isdigit(z[i]) ){ i++; }
82386         *tokenType = TK_FLOAT;
82387       }
82388       if( (z[i]=='e' || z[i]=='E') &&
82389            ( isdigit(z[i+1]) 
82390             || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
82391            )
82392       ){
82393         i += 2;
82394         while( isdigit(z[i]) ){ i++; }
82395         *tokenType = TK_FLOAT;
82396       }
82397 #endif
82398       while( IdChar(z[i]) ){
82399         *tokenType = TK_ILLEGAL;
82400         i++;
82401       }
82402       return i;
82403     }
82404     case '[': {
82405       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
82406       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
82407       return i;
82408     }
82409     case '?': {
82410       *tokenType = TK_VARIABLE;
82411       for(i=1; isdigit(z[i]); i++){}
82412       return i;
82413     }
82414     case '#': {
82415       for(i=1; isdigit(z[i]); i++){}
82416       if( i>1 ){
82417         /* Parameters of the form #NNN (where NNN is a number) are used
82418         ** internally by sqlite3NestedParse.  */
82419         *tokenType = TK_REGISTER;
82420         return i;
82421       }
82422       /* Fall through into the next case if the '#' is not followed by
82423       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
82424     }
82425 #ifndef SQLITE_OMIT_TCL_VARIABLE
82426     case '$':
82427 #endif
82428     case '@':  /* For compatibility with MS SQL Server */
82429     case ':': {
82430       int n = 0;
82431       *tokenType = TK_VARIABLE;
82432       for(i=1; (c=z[i])!=0; i++){
82433         if( IdChar(c) ){
82434           n++;
82435 #ifndef SQLITE_OMIT_TCL_VARIABLE
82436         }else if( c=='(' && n>0 ){
82437           do{
82438             i++;
82439           }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
82440           if( c==')' ){
82441             i++;
82442           }else{
82443             *tokenType = TK_ILLEGAL;
82444           }
82445           break;
82446         }else if( c==':' && z[i+1]==':' ){
82447           i++;
82448 #endif
82449         }else{
82450           break;
82451         }
82452       }
82453       if( n==0 ) *tokenType = TK_ILLEGAL;
82454       return i;
82455     }
82456 #ifndef SQLITE_OMIT_BLOB_LITERAL
82457     case 'x': case 'X': {
82458       if( z[1]=='\'' ){
82459         *tokenType = TK_BLOB;
82460         for(i=2; (c=z[i])!=0 && c!='\''; i++){
82461           if( !isxdigit(c) ){
82462             *tokenType = TK_ILLEGAL;
82463           }
82464         }
82465         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
82466         if( c ) i++;
82467         return i;
82468       }
82469       /* Otherwise fall through to the next case */
82470     }
82471 #endif
82472     default: {
82473       if( !IdChar(*z) ){
82474         break;
82475       }
82476       for(i=1; IdChar(z[i]); i++){}
82477       *tokenType = keywordCode((char*)z, i);
82478       return i;
82479     }
82480   }
82481   *tokenType = TK_ILLEGAL;
82482   return 1;
82483 }
82484
82485 /*
82486 ** Run the parser on the given SQL string.  The parser structure is
82487 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
82488 ** then an and attempt is made to write an error message into 
82489 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
82490 ** error message.
82491 */
82492 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
82493   int nErr = 0;
82494   int i;
82495   void *pEngine;
82496   int tokenType;
82497   int lastTokenParsed = -1;
82498   sqlite3 *db = pParse->db;
82499   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
82500
82501   if( db->activeVdbeCnt==0 ){
82502     db->u1.isInterrupted = 0;
82503   }
82504   pParse->rc = SQLITE_OK;
82505   pParse->zTail = pParse->zSql = zSql;
82506   i = 0;
82507   assert( pzErrMsg!=0 );
82508   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
82509   if( pEngine==0 ){
82510     db->mallocFailed = 1;
82511     return SQLITE_NOMEM;
82512   }
82513   assert( pParse->sLastToken.dyn==0 );
82514   assert( pParse->pNewTable==0 );
82515   assert( pParse->pNewTrigger==0 );
82516   assert( pParse->nVar==0 );
82517   assert( pParse->nVarExpr==0 );
82518   assert( pParse->nVarExprAlloc==0 );
82519   assert( pParse->apVarExpr==0 );
82520   while( !db->mallocFailed && zSql[i]!=0 ){
82521     assert( i>=0 );
82522     pParse->sLastToken.z = (u8*)&zSql[i];
82523     assert( pParse->sLastToken.dyn==0 );
82524     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
82525     i += pParse->sLastToken.n;
82526     if( i>mxSqlLen ){
82527       pParse->rc = SQLITE_TOOBIG;
82528       break;
82529     }
82530     switch( tokenType ){
82531       case TK_SPACE: {
82532         if( db->u1.isInterrupted ){
82533           pParse->rc = SQLITE_INTERRUPT;
82534           sqlite3SetString(pzErrMsg, db, "interrupt");
82535           goto abort_parse;
82536         }
82537         break;
82538       }
82539       case TK_ILLEGAL: {
82540         sqlite3DbFree(db, *pzErrMsg);
82541         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
82542                         &pParse->sLastToken);
82543         nErr++;
82544         goto abort_parse;
82545       }
82546       case TK_SEMI: {
82547         pParse->zTail = &zSql[i];
82548         /* Fall thru into the default case */
82549       }
82550       default: {
82551         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
82552         lastTokenParsed = tokenType;
82553         if( pParse->rc!=SQLITE_OK ){
82554           goto abort_parse;
82555         }
82556         break;
82557       }
82558     }
82559   }
82560 abort_parse:
82561   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
82562     if( lastTokenParsed!=TK_SEMI ){
82563       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
82564       pParse->zTail = &zSql[i];
82565     }
82566     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
82567   }
82568 #ifdef YYTRACKMAXSTACKDEPTH
82569   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
82570       sqlite3ParserStackPeak(pEngine)
82571   );
82572 #endif /* YYDEBUG */
82573   sqlite3ParserFree(pEngine, sqlite3_free);
82574   if( db->mallocFailed ){
82575     pParse->rc = SQLITE_NOMEM;
82576   }
82577   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
82578     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
82579   }
82580   if( pParse->zErrMsg ){
82581     if( *pzErrMsg==0 ){
82582       *pzErrMsg = pParse->zErrMsg;
82583     }else{
82584       sqlite3DbFree(db, pParse->zErrMsg);
82585     }
82586     pParse->zErrMsg = 0;
82587     nErr++;
82588   }
82589   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
82590     sqlite3VdbeDelete(pParse->pVdbe);
82591     pParse->pVdbe = 0;
82592   }
82593 #ifndef SQLITE_OMIT_SHARED_CACHE
82594   if( pParse->nested==0 ){
82595     sqlite3DbFree(db, pParse->aTableLock);
82596     pParse->aTableLock = 0;
82597     pParse->nTableLock = 0;
82598   }
82599 #endif
82600 #ifndef SQLITE_OMIT_VIRTUALTABLE
82601   sqlite3DbFree(db, pParse->apVtabLock);
82602 #endif
82603
82604   if( !IN_DECLARE_VTAB ){
82605     /* If the pParse->declareVtab flag is set, do not delete any table 
82606     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
82607     ** will take responsibility for freeing the Table structure.
82608     */
82609     sqlite3DeleteTable(pParse->pNewTable);
82610   }
82611
82612   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
82613   sqlite3DbFree(db, pParse->apVarExpr);
82614   sqlite3DbFree(db, pParse->aAlias);
82615   while( pParse->pZombieTab ){
82616     Table *p = pParse->pZombieTab;
82617     pParse->pZombieTab = p->pNextZombie;
82618     sqlite3DeleteTable(p);
82619   }
82620   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
82621     pParse->rc = SQLITE_ERROR;
82622   }
82623   return nErr;
82624 }
82625
82626 /************** End of tokenize.c ********************************************/
82627 /************** Begin file complete.c ****************************************/
82628 /*
82629 ** 2001 September 15
82630 **
82631 ** The author disclaims copyright to this source code.  In place of
82632 ** a legal notice, here is a blessing:
82633 **
82634 **    May you do good and not evil.
82635 **    May you find forgiveness for yourself and forgive others.
82636 **    May you share freely, never taking more than you give.
82637 **
82638 *************************************************************************
82639 ** An tokenizer for SQL
82640 **
82641 ** This file contains C code that implements the sqlite3_complete() API.
82642 ** This code used to be part of the tokenizer.c source file.  But by
82643 ** separating it out, the code will be automatically omitted from
82644 ** static links that do not use it.
82645 **
82646 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
82647 */
82648 #ifndef SQLITE_OMIT_COMPLETE
82649
82650 /*
82651 ** This is defined in tokenize.c.  We just have to import the definition.
82652 */
82653 #ifndef SQLITE_AMALGAMATION
82654 #ifdef SQLITE_ASCII
82655 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
82656 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
82657 #endif
82658 #ifdef SQLITE_EBCDIC
82659 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
82660 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
82661 #endif
82662 #endif /* SQLITE_AMALGAMATION */
82663
82664
82665 /*
82666 ** Token types used by the sqlite3_complete() routine.  See the header
82667 ** comments on that procedure for additional information.
82668 */
82669 #define tkSEMI    0
82670 #define tkWS      1
82671 #define tkOTHER   2
82672 #define tkEXPLAIN 3
82673 #define tkCREATE  4
82674 #define tkTEMP    5
82675 #define tkTRIGGER 6
82676 #define tkEND     7
82677
82678 /*
82679 ** Return TRUE if the given SQL string ends in a semicolon.
82680 **
82681 ** Special handling is require for CREATE TRIGGER statements.
82682 ** Whenever the CREATE TRIGGER keywords are seen, the statement
82683 ** must end with ";END;".
82684 **
82685 ** This implementation uses a state machine with 7 states:
82686 **
82687 **   (0) START     At the beginning or end of an SQL statement.  This routine
82688 **                 returns 1 if it ends in the START state and 0 if it ends
82689 **                 in any other state.
82690 **
82691 **   (1) NORMAL    We are in the middle of statement which ends with a single
82692 **                 semicolon.
82693 **
82694 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
82695 **                 a statement.
82696 **
82697 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
82698 **                 statement, possibly preceeded by EXPLAIN and/or followed by
82699 **                 TEMP or TEMPORARY
82700 **
82701 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
82702 **                 ended by a semicolon, the keyword END, and another semicolon.
82703 **
82704 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
82705 **                 the end of a trigger definition.
82706 **
82707 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
82708 **                 of a trigger difinition.
82709 **
82710 ** Transitions between states above are determined by tokens extracted
82711 ** from the input.  The following tokens are significant:
82712 **
82713 **   (0) tkSEMI      A semicolon.
82714 **   (1) tkWS        Whitespace
82715 **   (2) tkOTHER     Any other SQL token.
82716 **   (3) tkEXPLAIN   The "explain" keyword.
82717 **   (4) tkCREATE    The "create" keyword.
82718 **   (5) tkTEMP      The "temp" or "temporary" keyword.
82719 **   (6) tkTRIGGER   The "trigger" keyword.
82720 **   (7) tkEND       The "end" keyword.
82721 **
82722 ** Whitespace never causes a state transition and is always ignored.
82723 **
82724 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
82725 ** to recognize the end of a trigger can be omitted.  All we have to do
82726 ** is look for a semicolon that is not part of an string or comment.
82727 */
82728 SQLITE_API int sqlite3_complete(const char *zSql){
82729   u8 state = 0;   /* Current state, using numbers defined in header comment */
82730   u8 token;       /* Value of the next token */
82731
82732 #ifndef SQLITE_OMIT_TRIGGER
82733   /* A complex statement machine used to detect the end of a CREATE TRIGGER
82734   ** statement.  This is the normal case.
82735   */
82736   static const u8 trans[7][8] = {
82737                      /* Token:                                                */
82738      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
82739      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
82740      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
82741      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
82742      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
82743      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
82744      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
82745      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
82746   };
82747 #else
82748   /* If triggers are not suppored by this compile then the statement machine
82749   ** used to detect the end of a statement is much simplier
82750   */
82751   static const u8 trans[2][3] = {
82752                      /* Token:           */
82753      /* State:       **  SEMI  WS  OTHER */
82754      /* 0   START: */ {    0,  0,     1, },
82755      /* 1  NORMAL: */ {    0,  1,     1, },
82756   };
82757 #endif /* SQLITE_OMIT_TRIGGER */
82758
82759   while( *zSql ){
82760     switch( *zSql ){
82761       case ';': {  /* A semicolon */
82762         token = tkSEMI;
82763         break;
82764       }
82765       case ' ':
82766       case '\r':
82767       case '\t':
82768       case '\n':
82769       case '\f': {  /* White space is ignored */
82770         token = tkWS;
82771         break;
82772       }
82773       case '/': {   /* C-style comments */
82774         if( zSql[1]!='*' ){
82775           token = tkOTHER;
82776           break;
82777         }
82778         zSql += 2;
82779         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
82780         if( zSql[0]==0 ) return 0;
82781         zSql++;
82782         token = tkWS;
82783         break;
82784       }
82785       case '-': {   /* SQL-style comments from "--" to end of line */
82786         if( zSql[1]!='-' ){
82787           token = tkOTHER;
82788           break;
82789         }
82790         while( *zSql && *zSql!='\n' ){ zSql++; }
82791         if( *zSql==0 ) return state==0;
82792         token = tkWS;
82793         break;
82794       }
82795       case '[': {   /* Microsoft-style identifiers in [...] */
82796         zSql++;
82797         while( *zSql && *zSql!=']' ){ zSql++; }
82798         if( *zSql==0 ) return 0;
82799         token = tkOTHER;
82800         break;
82801       }
82802       case '`':     /* Grave-accent quoted symbols used by MySQL */
82803       case '"':     /* single- and double-quoted strings */
82804       case '\'': {
82805         int c = *zSql;
82806         zSql++;
82807         while( *zSql && *zSql!=c ){ zSql++; }
82808         if( *zSql==0 ) return 0;
82809         token = tkOTHER;
82810         break;
82811       }
82812       default: {
82813         int c;
82814         if( IdChar((u8)*zSql) ){
82815           /* Keywords and unquoted identifiers */
82816           int nId;
82817           for(nId=1; IdChar(zSql[nId]); nId++){}
82818 #ifdef SQLITE_OMIT_TRIGGER
82819           token = tkOTHER;
82820 #else
82821           switch( *zSql ){
82822             case 'c': case 'C': {
82823               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
82824                 token = tkCREATE;
82825               }else{
82826                 token = tkOTHER;
82827               }
82828               break;
82829             }
82830             case 't': case 'T': {
82831               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
82832                 token = tkTRIGGER;
82833               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
82834                 token = tkTEMP;
82835               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
82836                 token = tkTEMP;
82837               }else{
82838                 token = tkOTHER;
82839               }
82840               break;
82841             }
82842             case 'e':  case 'E': {
82843               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
82844                 token = tkEND;
82845               }else
82846 #ifndef SQLITE_OMIT_EXPLAIN
82847               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
82848                 token = tkEXPLAIN;
82849               }else
82850 #endif
82851               {
82852                 token = tkOTHER;
82853               }
82854               break;
82855             }
82856             default: {
82857               token = tkOTHER;
82858               break;
82859             }
82860           }
82861 #endif /* SQLITE_OMIT_TRIGGER */
82862           zSql += nId-1;
82863         }else{
82864           /* Operators and special symbols */
82865           token = tkOTHER;
82866         }
82867         break;
82868       }
82869     }
82870     state = trans[state][token];
82871     zSql++;
82872   }
82873   return state==0;
82874 }
82875
82876 #ifndef SQLITE_OMIT_UTF16
82877 /*
82878 ** This routine is the same as the sqlite3_complete() routine described
82879 ** above, except that the parameter is required to be UTF-16 encoded, not
82880 ** UTF-8.
82881 */
82882 SQLITE_API int sqlite3_complete16(const void *zSql){
82883   sqlite3_value *pVal;
82884   char const *zSql8;
82885   int rc = SQLITE_NOMEM;
82886
82887 #ifndef SQLITE_OMIT_AUTOINIT
82888   rc = sqlite3_initialize();
82889   if( rc ) return rc;
82890 #endif
82891   pVal = sqlite3ValueNew(0);
82892   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
82893   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
82894   if( zSql8 ){
82895     rc = sqlite3_complete(zSql8);
82896   }else{
82897     rc = SQLITE_NOMEM;
82898   }
82899   sqlite3ValueFree(pVal);
82900   return sqlite3ApiExit(0, rc);
82901 }
82902 #endif /* SQLITE_OMIT_UTF16 */
82903 #endif /* SQLITE_OMIT_COMPLETE */
82904
82905 /************** End of complete.c ********************************************/
82906 /************** Begin file main.c ********************************************/
82907 /*
82908 ** 2001 September 15
82909 **
82910 ** The author disclaims copyright to this source code.  In place of
82911 ** a legal notice, here is a blessing:
82912 **
82913 **    May you do good and not evil.
82914 **    May you find forgiveness for yourself and forgive others.
82915 **    May you share freely, never taking more than you give.
82916 **
82917 *************************************************************************
82918 ** Main file for the SQLite library.  The routines in this file
82919 ** implement the programmer interface to the library.  Routines in
82920 ** other files are for internal use by SQLite and should not be
82921 ** accessed by users of the library.
82922 **
82923 ** $Id: main.c,v 1.508 2008/10/12 00:27:53 shane Exp $
82924 */
82925
82926 #ifdef SQLITE_ENABLE_FTS3
82927 /************** Include fts3.h in the middle of main.c ***********************/
82928 /************** Begin file fts3.h ********************************************/
82929 /*
82930 ** 2006 Oct 10
82931 **
82932 ** The author disclaims copyright to this source code.  In place of
82933 ** a legal notice, here is a blessing:
82934 **
82935 **    May you do good and not evil.
82936 **    May you find forgiveness for yourself and forgive others.
82937 **    May you share freely, never taking more than you give.
82938 **
82939 ******************************************************************************
82940 **
82941 ** This header file is used by programs that want to link against the
82942 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
82943 */
82944
82945 #if 0
82946 extern "C" {
82947 #endif  /* __cplusplus */
82948
82949 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
82950
82951 #if 0
82952 }  /* extern "C" */
82953 #endif  /* __cplusplus */
82954
82955 /************** End of fts3.h ************************************************/
82956 /************** Continuing where we left off in main.c ***********************/
82957 #endif
82958 #ifdef SQLITE_ENABLE_RTREE
82959 /************** Include rtree.h in the middle of main.c **********************/
82960 /************** Begin file rtree.h *******************************************/
82961 /*
82962 ** 2008 May 26
82963 **
82964 ** The author disclaims copyright to this source code.  In place of
82965 ** a legal notice, here is a blessing:
82966 **
82967 **    May you do good and not evil.
82968 **    May you find forgiveness for yourself and forgive others.
82969 **    May you share freely, never taking more than you give.
82970 **
82971 ******************************************************************************
82972 **
82973 ** This header file is used by programs that want to link against the
82974 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
82975 */
82976
82977 #if 0
82978 extern "C" {
82979 #endif  /* __cplusplus */
82980
82981 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
82982
82983 #if 0
82984 }  /* extern "C" */
82985 #endif  /* __cplusplus */
82986
82987 /************** End of rtree.h ***********************************************/
82988 /************** Continuing where we left off in main.c ***********************/
82989 #endif
82990 #ifdef SQLITE_ENABLE_ICU
82991 /************** Include sqliteicu.h in the middle of main.c ******************/
82992 /************** Begin file sqliteicu.h ***************************************/
82993 /*
82994 ** 2008 May 26
82995 **
82996 ** The author disclaims copyright to this source code.  In place of
82997 ** a legal notice, here is a blessing:
82998 **
82999 **    May you do good and not evil.
83000 **    May you find forgiveness for yourself and forgive others.
83001 **    May you share freely, never taking more than you give.
83002 **
83003 ******************************************************************************
83004 **
83005 ** This header file is used by programs that want to link against the
83006 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
83007 */
83008
83009 #if 0
83010 extern "C" {
83011 #endif  /* __cplusplus */
83012
83013 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
83014
83015 #if 0
83016 }  /* extern "C" */
83017 #endif  /* __cplusplus */
83018
83019
83020 /************** End of sqliteicu.h *******************************************/
83021 /************** Continuing where we left off in main.c ***********************/
83022 #endif
83023
83024 /*
83025 ** The version of the library
83026 */
83027 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
83028 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
83029 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
83030 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
83031
83032 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
83033 /*
83034 ** If the following function pointer is not NULL and if
83035 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
83036 ** I/O active are written using this function.  These messages
83037 ** are intended for debugging activity only.
83038 */
83039 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
83040 #endif
83041
83042 /*
83043 ** If the following global variable points to a string which is the
83044 ** name of a directory, then that directory will be used to store
83045 ** temporary files.
83046 **
83047 ** See also the "PRAGMA temp_store_directory" SQL command.
83048 */
83049 SQLITE_API char *sqlite3_temp_directory = 0;
83050
83051 /*
83052 ** Initialize SQLite.  
83053 **
83054 ** This routine must be called to initialize the memory allocation,
83055 ** VFS, and mutex subsystems prior to doing any serious work with
83056 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
83057 ** this routine will be called automatically by key routines such as
83058 ** sqlite3_open().  
83059 **
83060 ** This routine is a no-op except on its very first call for the process,
83061 ** or for the first call after a call to sqlite3_shutdown.
83062 **
83063 ** The first thread to call this routine runs the initialization to
83064 ** completion.  If subsequent threads call this routine before the first
83065 ** thread has finished the initialization process, then the subsequent
83066 ** threads must block until the first thread finishes with the initialization.
83067 **
83068 ** The first thread might call this routine recursively.  Recursive
83069 ** calls to this routine should not block, of course.  Otherwise the
83070 ** initialization process would never complete.
83071 **
83072 ** Let X be the first thread to enter this routine.  Let Y be some other
83073 ** thread.  Then while the initial invocation of this routine by X is
83074 ** incomplete, it is required that:
83075 **
83076 **    *  Calls to this routine from Y must block until the outer-most
83077 **       call by X completes.
83078 **
83079 **    *  Recursive calls to this routine from thread X return immediately
83080 **       without blocking.
83081 */
83082 SQLITE_API int sqlite3_initialize(void){
83083   sqlite3_mutex *pMaster;                      /* The main static mutex */
83084   int rc;                                      /* Result code */
83085
83086 #ifdef SQLITE_OMIT_WSD
83087   rc = sqlite3_wsd_init(4096, 24);
83088   if( rc!=SQLITE_OK ){
83089     return rc;
83090   }
83091 #endif
83092
83093   /* If SQLite is already completely initialized, then this call
83094   ** to sqlite3_initialize() should be a no-op.  But the initialization
83095   ** must be complete.  So isInit must not be set until the very end
83096   ** of this routine.
83097   */
83098   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
83099
83100   /* Make sure the mutex subsystem is initialized.  If unable to 
83101   ** initialize the mutex subsystem, return early with the error.
83102   ** If the system is so sick that we are unable to allocate a mutex,
83103   ** there is not much SQLite is going to be able to do.
83104   **
83105   ** The mutex subsystem must take care of serializing its own
83106   ** initialization.
83107   */
83108   rc = sqlite3MutexInit();
83109   if( rc ) return rc;
83110
83111   /* Initialize the malloc() system and the recursive pInitMutex mutex.
83112   ** This operation is protected by the STATIC_MASTER mutex.  Note that
83113   ** MutexAlloc() is called for a static mutex prior to initializing the
83114   ** malloc subsystem - this implies that the allocation of a static
83115   ** mutex must not require support from the malloc subsystem.
83116   */
83117   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
83118   sqlite3_mutex_enter(pMaster);
83119   if( !sqlite3GlobalConfig.isMallocInit ){
83120     rc = sqlite3MallocInit();
83121   }
83122   if( rc==SQLITE_OK ){
83123     sqlite3GlobalConfig.isMallocInit = 1;
83124     if( !sqlite3GlobalConfig.pInitMutex ){
83125       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
83126       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
83127         rc = SQLITE_NOMEM;
83128       }
83129     }
83130   }
83131   if( rc==SQLITE_OK ){
83132     sqlite3GlobalConfig.nRefInitMutex++;
83133   }
83134   sqlite3_mutex_leave(pMaster);
83135
83136   /* If unable to initialize the malloc subsystem, then return early.
83137   ** There is little hope of getting SQLite to run if the malloc
83138   ** subsystem cannot be initialized.
83139   */
83140   if( rc!=SQLITE_OK ){
83141     return rc;
83142   }
83143
83144   /* Do the rest of the initialization under the recursive mutex so
83145   ** that we will be able to handle recursive calls into
83146   ** sqlite3_initialize().  The recursive calls normally come through
83147   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
83148   ** recursive calls might also be possible.
83149   */
83150   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
83151   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
83152     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83153     sqlite3GlobalConfig.inProgress = 1;
83154     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
83155     sqlite3RegisterGlobalFunctions();
83156     rc = sqlite3_os_init();
83157     if( rc==SQLITE_OK ){
83158       rc = sqlite3PcacheInitialize();
83159       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
83160           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
83161     }
83162     sqlite3GlobalConfig.inProgress = 0;
83163     sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
83164   }
83165   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
83166
83167   /* Go back under the static mutex and clean up the recursive
83168   ** mutex to prevent a resource leak.
83169   */
83170   sqlite3_mutex_enter(pMaster);
83171   sqlite3GlobalConfig.nRefInitMutex--;
83172   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
83173     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
83174     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
83175     sqlite3GlobalConfig.pInitMutex = 0;
83176   }
83177   sqlite3_mutex_leave(pMaster);
83178
83179   /* The following is just a sanity check to make sure SQLite has
83180   ** been compiled correctly.  It is important to run this code, but
83181   ** we don't want to run it too often and soak up CPU cycles for no
83182   ** reason.  So we run it once during initialization.
83183   */
83184 #ifndef NDEBUG
83185   /* This section of code's only "output" is via assert() statements. */
83186   if ( rc==SQLITE_OK ){
83187     u64 x = (((u64)1)<<63)-1;
83188     double y;
83189     assert(sizeof(x)==8);
83190     assert(sizeof(x)==sizeof(y));
83191     memcpy(&y, &x, 8);
83192     assert( sqlite3IsNaN(y) );
83193   }
83194 #endif
83195
83196   return rc;
83197 }
83198
83199 /*
83200 ** Undo the effects of sqlite3_initialize().  Must not be called while
83201 ** there are outstanding database connections or memory allocations or
83202 ** while any part of SQLite is otherwise in use in any thread.  This
83203 ** routine is not threadsafe.  Not by a long shot.
83204 */
83205 SQLITE_API int sqlite3_shutdown(void){
83206   sqlite3GlobalConfig.isMallocInit = 0;
83207   sqlite3PcacheShutdown();
83208   if( sqlite3GlobalConfig.isInit ){
83209     sqlite3_os_end();
83210   }
83211   sqlite3MallocEnd();
83212   sqlite3MutexEnd();
83213   sqlite3GlobalConfig.isInit = 0;
83214   return SQLITE_OK;
83215 }
83216
83217 /*
83218 ** This API allows applications to modify the global configuration of
83219 ** the SQLite library at run-time.
83220 **
83221 ** This routine should only be called when there are no outstanding
83222 ** database connections or memory allocations.  This routine is not
83223 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
83224 ** behavior.
83225 */
83226 SQLITE_API int sqlite3_config(int op, ...){
83227   va_list ap;
83228   int rc = SQLITE_OK;
83229
83230   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
83231   ** the SQLite library is in use. */
83232   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
83233
83234   va_start(ap, op);
83235   switch( op ){
83236
83237     /* Mutex configuration options are only available in a threadsafe
83238     ** compile. 
83239     */
83240 #if SQLITE_THREADSAFE
83241     case SQLITE_CONFIG_SINGLETHREAD: {
83242       /* Disable all mutexing */
83243       sqlite3GlobalConfig.bCoreMutex = 0;
83244       sqlite3GlobalConfig.bFullMutex = 0;
83245       break;
83246     }
83247     case SQLITE_CONFIG_MULTITHREAD: {
83248       /* Disable mutexing of database connections */
83249       /* Enable mutexing of core data structures */
83250       sqlite3GlobalConfig.bCoreMutex = 1;
83251       sqlite3GlobalConfig.bFullMutex = 0;
83252       break;
83253     }
83254     case SQLITE_CONFIG_SERIALIZED: {
83255       /* Enable all mutexing */
83256       sqlite3GlobalConfig.bCoreMutex = 1;
83257       sqlite3GlobalConfig.bFullMutex = 1;
83258       break;
83259     }
83260     case SQLITE_CONFIG_MUTEX: {
83261       /* Specify an alternative mutex implementation */
83262       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
83263       break;
83264     }
83265     case SQLITE_CONFIG_GETMUTEX: {
83266       /* Retrieve the current mutex implementation */
83267       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
83268       break;
83269     }
83270 #endif
83271
83272
83273     case SQLITE_CONFIG_MALLOC: {
83274       /* Specify an alternative malloc implementation */
83275       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
83276       break;
83277     }
83278     case SQLITE_CONFIG_GETMALLOC: {
83279       /* Retrieve the current malloc() implementation */
83280       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
83281       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
83282       break;
83283     }
83284     case SQLITE_CONFIG_MEMSTATUS: {
83285       /* Enable or disable the malloc status collection */
83286       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
83287       break;
83288     }
83289     case SQLITE_CONFIG_SCRATCH: {
83290       /* Designate a buffer for scratch memory space */
83291       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
83292       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
83293       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
83294       break;
83295     }
83296     case SQLITE_CONFIG_PAGECACHE: {
83297       /* Designate a buffer for scratch memory space */
83298       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
83299       sqlite3GlobalConfig.szPage = va_arg(ap, int);
83300       sqlite3GlobalConfig.nPage = va_arg(ap, int);
83301       break;
83302     }
83303
83304 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
83305     case SQLITE_CONFIG_HEAP: {
83306       /* Designate a buffer for heap memory space */
83307       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
83308       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
83309       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
83310
83311       if( sqlite3GlobalConfig.pHeap==0 ){
83312         /* If the heap pointer is NULL, then restore the malloc implementation
83313         ** back to NULL pointers too.  This will cause the malloc to go
83314         ** back to its default implementation when sqlite3_initialize() is
83315         ** run.
83316         */
83317         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
83318       }else{
83319         /* The heap pointer is not NULL, then install one of the
83320         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
83321         ** ENABLE_MEMSYS5 is defined, return an error.
83322         ** the default case and return an error.
83323         */
83324 #ifdef SQLITE_ENABLE_MEMSYS3
83325         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
83326 #endif
83327 #ifdef SQLITE_ENABLE_MEMSYS5
83328         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
83329 #endif
83330       }
83331       break;
83332     }
83333 #endif
83334
83335 #if defined(SQLITE_ENABLE_MEMSYS6)
83336     case SQLITE_CONFIG_CHUNKALLOC: {
83337       sqlite3GlobalConfig.nSmall = va_arg(ap, int);
83338       sqlite3GlobalConfig.m = *sqlite3MemGetMemsys6();
83339       break;
83340     }
83341 #endif
83342
83343     case SQLITE_CONFIG_LOOKASIDE: {
83344       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
83345       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
83346       break;
83347     }
83348
83349     default: {
83350       rc = SQLITE_ERROR;
83351       break;
83352     }
83353   }
83354   va_end(ap);
83355   return rc;
83356 }
83357
83358 /*
83359 ** Set up the lookaside buffers for a database connection.
83360 ** Return SQLITE_OK on success.  
83361 ** If lookaside is already active, return SQLITE_BUSY.
83362 **
83363 ** The sz parameter is the number of bytes in each lookaside slot.
83364 ** The cnt parameter is the number of slots.  If pStart is NULL the
83365 ** space for the lookaside memory is obtained from sqlite3_malloc().
83366 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
83367 ** the lookaside memory.
83368 */
83369 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
83370   void *pStart;
83371   if( db->lookaside.nOut ){
83372     return SQLITE_BUSY;
83373   }
83374   if( sz<0 ) sz = 0;
83375   if( cnt<0 ) cnt = 0;
83376   if( pBuf==0 ){
83377     sz = (sz + 7)&~7;
83378     sqlite3BeginBenignMalloc();
83379     pStart = sqlite3Malloc( sz*cnt );
83380     sqlite3EndBenignMalloc();
83381   }else{
83382     sz = sz&~7;
83383     pStart = pBuf;
83384   }
83385   if( db->lookaside.bMalloced ){
83386     sqlite3_free(db->lookaside.pStart);
83387   }
83388   db->lookaside.pStart = pStart;
83389   db->lookaside.pFree = 0;
83390   db->lookaside.sz = sz;
83391   db->lookaside.bMalloced = pBuf==0;
83392   if( pStart ){
83393     int i;
83394     LookasideSlot *p;
83395     p = (LookasideSlot*)pStart;
83396     for(i=cnt-1; i>=0; i--){
83397       p->pNext = db->lookaside.pFree;
83398       db->lookaside.pFree = p;
83399       p = (LookasideSlot*)&((u8*)p)[sz];
83400     }
83401     db->lookaside.pEnd = p;
83402     db->lookaside.bEnabled = 1;
83403   }else{
83404     db->lookaside.pEnd = 0;
83405     db->lookaside.bEnabled = 0;
83406   }
83407   return SQLITE_OK;
83408 }
83409
83410 /*
83411 ** Configuration settings for an individual database connection
83412 */
83413 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
83414   va_list ap;
83415   int rc;
83416   va_start(ap, op);
83417   switch( op ){
83418     case SQLITE_DBCONFIG_LOOKASIDE: {
83419       void *pBuf = va_arg(ap, void*);
83420       int sz = va_arg(ap, int);
83421       int cnt = va_arg(ap, int);
83422       rc = setupLookaside(db, pBuf, sz, cnt);
83423       break;
83424     }
83425     default: {
83426       rc = SQLITE_ERROR;
83427       break;
83428     }
83429   }
83430   va_end(ap);
83431   return rc;
83432 }
83433
83434 /*
83435 ** Routine needed to support the testcase() macro.
83436 */
83437 #ifdef SQLITE_COVERAGE_TEST
83438 SQLITE_PRIVATE void sqlite3Coverage(int x){
83439   static int dummy = 0;
83440   dummy += x;
83441 }
83442 #endif
83443
83444
83445 /*
83446 ** Return true if the buffer z[0..n-1] contains all spaces.
83447 */
83448 static int allSpaces(const char *z, int n){
83449   while( n>0 && z[n-1]==' ' ){ n--; }
83450   return n==0;
83451 }
83452
83453 /*
83454 ** This is the default collating function named "BINARY" which is always
83455 ** available.
83456 **
83457 ** If the padFlag argument is not NULL then space padding at the end
83458 ** of strings is ignored.  This implements the RTRIM collation.
83459 */
83460 static int binCollFunc(
83461   void *padFlag,
83462   int nKey1, const void *pKey1,
83463   int nKey2, const void *pKey2
83464 ){
83465   int rc, n;
83466   n = nKey1<nKey2 ? nKey1 : nKey2;
83467   rc = memcmp(pKey1, pKey2, n);
83468   if( rc==0 ){
83469     if( padFlag
83470      && allSpaces(((char*)pKey1)+n, nKey1-n)
83471      && allSpaces(((char*)pKey2)+n, nKey2-n)
83472     ){
83473       /* Leave rc unchanged at 0 */
83474     }else{
83475       rc = nKey1 - nKey2;
83476     }
83477   }
83478   return rc;
83479 }
83480
83481 /*
83482 ** Another built-in collating sequence: NOCASE. 
83483 **
83484 ** This collating sequence is intended to be used for "case independant
83485 ** comparison". SQLite's knowledge of upper and lower case equivalents
83486 ** extends only to the 26 characters used in the English language.
83487 **
83488 ** At the moment there is only a UTF-8 implementation.
83489 */
83490 static int nocaseCollatingFunc(
83491   void *NotUsed,
83492   int nKey1, const void *pKey1,
83493   int nKey2, const void *pKey2
83494 ){
83495   int r = sqlite3StrNICmp(
83496       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
83497   if( 0==r ){
83498     r = nKey1-nKey2;
83499   }
83500   return r;
83501 }
83502
83503 /*
83504 ** Return the ROWID of the most recent insert
83505 */
83506 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
83507   return db->lastRowid;
83508 }
83509
83510 /*
83511 ** Return the number of changes in the most recent call to sqlite3_exec().
83512 */
83513 SQLITE_API int sqlite3_changes(sqlite3 *db){
83514   return db->nChange;
83515 }
83516
83517 /*
83518 ** Return the number of changes since the database handle was opened.
83519 */
83520 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
83521   return db->nTotalChange;
83522 }
83523
83524 /*
83525 ** Close an existing SQLite database
83526 */
83527 SQLITE_API int sqlite3_close(sqlite3 *db){
83528   HashElem *i;
83529   int j;
83530
83531   if( !db ){
83532     return SQLITE_OK;
83533   }
83534   if( !sqlite3SafetyCheckSickOrOk(db) ){
83535     return SQLITE_MISUSE;
83536   }
83537   sqlite3_mutex_enter(db->mutex);
83538
83539 #ifdef SQLITE_SSE
83540   {
83541     extern void sqlite3SseCleanup(sqlite3*);
83542     sqlite3SseCleanup(db);
83543   }
83544 #endif 
83545
83546   sqlite3ResetInternalSchema(db, 0);
83547
83548   /* If a transaction is open, the ResetInternalSchema() call above
83549   ** will not have called the xDisconnect() method on any virtual
83550   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
83551   ** call will do so. We need to do this before the check for active
83552   ** SQL statements below, as the v-table implementation may be storing
83553   ** some prepared statements internally.
83554   */
83555   sqlite3VtabRollback(db);
83556
83557   /* If there are any outstanding VMs, return SQLITE_BUSY. */
83558   if( db->pVdbe ){
83559     sqlite3Error(db, SQLITE_BUSY, 
83560         "Unable to close due to unfinalised statements");
83561     sqlite3_mutex_leave(db->mutex);
83562     return SQLITE_BUSY;
83563   }
83564   assert( sqlite3SafetyCheckSickOrOk(db) );
83565
83566   for(j=0; j<db->nDb; j++){
83567     struct Db *pDb = &db->aDb[j];
83568     if( pDb->pBt ){
83569       sqlite3BtreeClose(pDb->pBt);
83570       pDb->pBt = 0;
83571       if( j!=1 ){
83572         pDb->pSchema = 0;
83573       }
83574     }
83575   }
83576   sqlite3ResetInternalSchema(db, 0);
83577   assert( db->nDb<=2 );
83578   assert( db->aDb==db->aDbStatic );
83579   for(j=0; j<ArraySize(db->aFunc.a); j++){
83580     FuncDef *pNext, *pHash, *p;
83581     for(p=db->aFunc.a[j]; p; p=pHash){
83582       pHash = p->pHash;
83583       while( p ){
83584         pNext = p->pNext;
83585         sqlite3DbFree(db, p);
83586         p = pNext;
83587       }
83588     }
83589   }
83590   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
83591     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
83592     /* Invoke any destructors registered for collation sequence user data. */
83593     for(j=0; j<3; j++){
83594       if( pColl[j].xDel ){
83595         pColl[j].xDel(pColl[j].pUser);
83596       }
83597     }
83598     sqlite3DbFree(db, pColl);
83599   }
83600   sqlite3HashClear(&db->aCollSeq);
83601 #ifndef SQLITE_OMIT_VIRTUALTABLE
83602   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
83603     Module *pMod = (Module *)sqliteHashData(i);
83604     if( pMod->xDestroy ){
83605       pMod->xDestroy(pMod->pAux);
83606     }
83607     sqlite3DbFree(db, pMod);
83608   }
83609   sqlite3HashClear(&db->aModule);
83610 #endif
83611
83612   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
83613   if( db->pErr ){
83614     sqlite3ValueFree(db->pErr);
83615   }
83616   sqlite3CloseExtensions(db);
83617
83618   db->magic = SQLITE_MAGIC_ERROR;
83619
83620   /* The temp-database schema is allocated differently from the other schema
83621   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
83622   ** So it needs to be freed here. Todo: Why not roll the temp schema into
83623   ** the same sqliteMalloc() as the one that allocates the database 
83624   ** structure?
83625   */
83626   sqlite3DbFree(db, db->aDb[1].pSchema);
83627   sqlite3_mutex_leave(db->mutex);
83628   db->magic = SQLITE_MAGIC_CLOSED;
83629   sqlite3_mutex_free(db->mutex);
83630   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
83631   if( db->lookaside.bMalloced ){
83632     sqlite3_free(db->lookaside.pStart);
83633   }
83634   sqlite3_free(db);
83635   return SQLITE_OK;
83636 }
83637
83638 /*
83639 ** Rollback all database files.
83640 */
83641 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
83642   int i;
83643   int inTrans = 0;
83644   assert( sqlite3_mutex_held(db->mutex) );
83645   sqlite3BeginBenignMalloc();
83646   for(i=0; i<db->nDb; i++){
83647     if( db->aDb[i].pBt ){
83648       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
83649         inTrans = 1;
83650       }
83651       sqlite3BtreeRollback(db->aDb[i].pBt);
83652       db->aDb[i].inTrans = 0;
83653     }
83654   }
83655   sqlite3VtabRollback(db);
83656   sqlite3EndBenignMalloc();
83657
83658   if( db->flags&SQLITE_InternChanges ){
83659     sqlite3ExpirePreparedStatements(db);
83660     sqlite3ResetInternalSchema(db, 0);
83661   }
83662
83663   /* If one has been configured, invoke the rollback-hook callback */
83664   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
83665     db->xRollbackCallback(db->pRollbackArg);
83666   }
83667 }
83668
83669 /*
83670 ** Return a static string that describes the kind of error specified in the
83671 ** argument.
83672 */
83673 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
83674   const char *z;
83675   switch( rc & 0xff ){
83676     case SQLITE_ROW:
83677     case SQLITE_DONE:
83678     case SQLITE_OK:         z = "not an error";                          break;
83679     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
83680     case SQLITE_PERM:       z = "access permission denied";              break;
83681     case SQLITE_ABORT:      z = "callback requested query abort";        break;
83682     case SQLITE_BUSY:       z = "database is locked";                    break;
83683     case SQLITE_LOCKED:     z = "database table is locked";              break;
83684     case SQLITE_NOMEM:      z = "out of memory";                         break;
83685     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
83686     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
83687     case SQLITE_IOERR:      z = "disk I/O error";                        break;
83688     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
83689     case SQLITE_FULL:       z = "database or disk is full";              break;
83690     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
83691     case SQLITE_EMPTY:      z = "table contains no data";                break;
83692     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
83693     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
83694     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
83695     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
83696     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
83697     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
83698     case SQLITE_AUTH:       z = "authorization denied";                  break;
83699     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
83700     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
83701     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
83702     default:                z = "unknown error";                         break;
83703   }
83704   return z;
83705 }
83706
83707 /*
83708 ** This routine implements a busy callback that sleeps and tries
83709 ** again until a timeout value is reached.  The timeout value is
83710 ** an integer number of milliseconds passed in as the first
83711 ** argument.
83712 */
83713 static int sqliteDefaultBusyCallback(
83714  void *ptr,               /* Database connection */
83715  int count                /* Number of times table has been busy */
83716 ){
83717 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
83718   static const u8 delays[] =
83719      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
83720   static const u8 totals[] =
83721      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
83722 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
83723   sqlite3 *db = (sqlite3 *)ptr;
83724   int timeout = db->busyTimeout;
83725   int delay, prior;
83726
83727   assert( count>=0 );
83728   if( count < NDELAY ){
83729     delay = delays[count];
83730     prior = totals[count];
83731   }else{
83732     delay = delays[NDELAY-1];
83733     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
83734   }
83735   if( prior + delay > timeout ){
83736     delay = timeout - prior;
83737     if( delay<=0 ) return 0;
83738   }
83739   sqlite3OsSleep(db->pVfs, delay*1000);
83740   return 1;
83741 #else
83742   sqlite3 *db = (sqlite3 *)ptr;
83743   int timeout = ((sqlite3 *)ptr)->busyTimeout;
83744   if( (count+1)*1000 > timeout ){
83745     return 0;
83746   }
83747   sqlite3OsSleep(db->pVfs, 1000000);
83748   return 1;
83749 #endif
83750 }
83751
83752 /*
83753 ** Invoke the given busy handler.
83754 **
83755 ** This routine is called when an operation failed with a lock.
83756 ** If this routine returns non-zero, the lock is retried.  If it
83757 ** returns 0, the operation aborts with an SQLITE_BUSY error.
83758 */
83759 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
83760   int rc;
83761   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
83762   rc = p->xFunc(p->pArg, p->nBusy);
83763   if( rc==0 ){
83764     p->nBusy = -1;
83765   }else{
83766     p->nBusy++;
83767   }
83768   return rc; 
83769 }
83770
83771 /*
83772 ** This routine sets the busy callback for an Sqlite database to the
83773 ** given callback function with the given argument.
83774 */
83775 SQLITE_API int sqlite3_busy_handler(
83776   sqlite3 *db,
83777   int (*xBusy)(void*,int),
83778   void *pArg
83779 ){
83780   sqlite3_mutex_enter(db->mutex);
83781   db->busyHandler.xFunc = xBusy;
83782   db->busyHandler.pArg = pArg;
83783   db->busyHandler.nBusy = 0;
83784   sqlite3_mutex_leave(db->mutex);
83785   return SQLITE_OK;
83786 }
83787
83788 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
83789 /*
83790 ** This routine sets the progress callback for an Sqlite database to the
83791 ** given callback function with the given argument. The progress callback will
83792 ** be invoked every nOps opcodes.
83793 */
83794 SQLITE_API void sqlite3_progress_handler(
83795   sqlite3 *db, 
83796   int nOps,
83797   int (*xProgress)(void*), 
83798   void *pArg
83799 ){
83800   sqlite3_mutex_enter(db->mutex);
83801   if( nOps>0 ){
83802     db->xProgress = xProgress;
83803     db->nProgressOps = nOps;
83804     db->pProgressArg = pArg;
83805   }else{
83806     db->xProgress = 0;
83807     db->nProgressOps = 0;
83808     db->pProgressArg = 0;
83809   }
83810   sqlite3_mutex_leave(db->mutex);
83811 }
83812 #endif
83813
83814
83815 /*
83816 ** This routine installs a default busy handler that waits for the
83817 ** specified number of milliseconds before returning 0.
83818 */
83819 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
83820   if( ms>0 ){
83821     db->busyTimeout = ms;
83822     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
83823   }else{
83824     sqlite3_busy_handler(db, 0, 0);
83825   }
83826   return SQLITE_OK;
83827 }
83828
83829 /*
83830 ** Cause any pending operation to stop at its earliest opportunity.
83831 */
83832 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
83833   db->u1.isInterrupted = 1;
83834 }
83835
83836
83837 /*
83838 ** This function is exactly the same as sqlite3_create_function(), except
83839 ** that it is designed to be called by internal code. The difference is
83840 ** that if a malloc() fails in sqlite3_create_function(), an error code
83841 ** is returned and the mallocFailed flag cleared. 
83842 */
83843 SQLITE_PRIVATE int sqlite3CreateFunc(
83844   sqlite3 *db,
83845   const char *zFunctionName,
83846   int nArg,
83847   int enc,
83848   void *pUserData,
83849   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
83850   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
83851   void (*xFinal)(sqlite3_context*)
83852 ){
83853   FuncDef *p;
83854   int nName;
83855
83856   assert( sqlite3_mutex_held(db->mutex) );
83857   if( zFunctionName==0 ||
83858       (xFunc && (xFinal || xStep)) || 
83859       (!xFunc && (xFinal && !xStep)) ||
83860       (!xFunc && (!xFinal && xStep)) ||
83861       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
83862       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
83863     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
83864     return SQLITE_ERROR;
83865   }
83866   
83867 #ifndef SQLITE_OMIT_UTF16
83868   /* If SQLITE_UTF16 is specified as the encoding type, transform this
83869   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
83870   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
83871   **
83872   ** If SQLITE_ANY is specified, add three versions of the function
83873   ** to the hash table.
83874   */
83875   if( enc==SQLITE_UTF16 ){
83876     enc = SQLITE_UTF16NATIVE;
83877   }else if( enc==SQLITE_ANY ){
83878     int rc;
83879     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
83880          pUserData, xFunc, xStep, xFinal);
83881     if( rc==SQLITE_OK ){
83882       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
83883           pUserData, xFunc, xStep, xFinal);
83884     }
83885     if( rc!=SQLITE_OK ){
83886       return rc;
83887     }
83888     enc = SQLITE_UTF16BE;
83889   }
83890 #else
83891   enc = SQLITE_UTF8;
83892 #endif
83893   
83894   /* Check if an existing function is being overridden or deleted. If so,
83895   ** and there are active VMs, then return SQLITE_BUSY. If a function
83896   ** is being overridden/deleted but there are no active VMs, allow the
83897   ** operation to continue but invalidate all precompiled statements.
83898   */
83899   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 0);
83900   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
83901     if( db->activeVdbeCnt ){
83902       sqlite3Error(db, SQLITE_BUSY, 
83903         "Unable to delete/modify user-function due to active statements");
83904       assert( !db->mallocFailed );
83905       return SQLITE_BUSY;
83906     }else{
83907       sqlite3ExpirePreparedStatements(db);
83908     }
83909   }
83910
83911   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, enc, 1);
83912   assert(p || db->mallocFailed);
83913   if( !p ){
83914     return SQLITE_NOMEM;
83915   }
83916   p->flags = 0;
83917   p->xFunc = xFunc;
83918   p->xStep = xStep;
83919   p->xFinalize = xFinal;
83920   p->pUserData = pUserData;
83921   p->nArg = nArg;
83922   return SQLITE_OK;
83923 }
83924
83925 /*
83926 ** Create new user functions.
83927 */
83928 SQLITE_API int sqlite3_create_function(
83929   sqlite3 *db,
83930   const char *zFunctionName,
83931   int nArg,
83932   int enc,
83933   void *p,
83934   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
83935   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
83936   void (*xFinal)(sqlite3_context*)
83937 ){
83938   int rc;
83939   sqlite3_mutex_enter(db->mutex);
83940   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
83941   rc = sqlite3ApiExit(db, rc);
83942   sqlite3_mutex_leave(db->mutex);
83943   return rc;
83944 }
83945
83946 #ifndef SQLITE_OMIT_UTF16
83947 SQLITE_API int sqlite3_create_function16(
83948   sqlite3 *db,
83949   const void *zFunctionName,
83950   int nArg,
83951   int eTextRep,
83952   void *p,
83953   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
83954   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
83955   void (*xFinal)(sqlite3_context*)
83956 ){
83957   int rc;
83958   char *zFunc8;
83959   sqlite3_mutex_enter(db->mutex);
83960   assert( !db->mallocFailed );
83961   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
83962   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
83963   sqlite3DbFree(db, zFunc8);
83964   rc = sqlite3ApiExit(db, rc);
83965   sqlite3_mutex_leave(db->mutex);
83966   return rc;
83967 }
83968 #endif
83969
83970
83971 /*
83972 ** Declare that a function has been overloaded by a virtual table.
83973 **
83974 ** If the function already exists as a regular global function, then
83975 ** this routine is a no-op.  If the function does not exist, then create
83976 ** a new one that always throws a run-time error.  
83977 **
83978 ** When virtual tables intend to provide an overloaded function, they
83979 ** should call this routine to make sure the global function exists.
83980 ** A global function must exist in order for name resolution to work
83981 ** properly.
83982 */
83983 SQLITE_API int sqlite3_overload_function(
83984   sqlite3 *db,
83985   const char *zName,
83986   int nArg
83987 ){
83988   int nName = sqlite3Strlen(db, zName);
83989   int rc;
83990   sqlite3_mutex_enter(db->mutex);
83991   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
83992     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
83993                       0, sqlite3InvalidFunction, 0, 0);
83994   }
83995   rc = sqlite3ApiExit(db, SQLITE_OK);
83996   sqlite3_mutex_leave(db->mutex);
83997   return rc;
83998 }
83999
84000 #ifndef SQLITE_OMIT_TRACE
84001 /*
84002 ** Register a trace function.  The pArg from the previously registered trace
84003 ** is returned.  
84004 **
84005 ** A NULL trace function means that no tracing is executes.  A non-NULL
84006 ** trace is a pointer to a function that is invoked at the start of each
84007 ** SQL statement.
84008 */
84009 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
84010   void *pOld;
84011   sqlite3_mutex_enter(db->mutex);
84012   pOld = db->pTraceArg;
84013   db->xTrace = xTrace;
84014   db->pTraceArg = pArg;
84015   sqlite3_mutex_leave(db->mutex);
84016   return pOld;
84017 }
84018 /*
84019 ** Register a profile function.  The pArg from the previously registered 
84020 ** profile function is returned.  
84021 **
84022 ** A NULL profile function means that no profiling is executes.  A non-NULL
84023 ** profile is a pointer to a function that is invoked at the conclusion of
84024 ** each SQL statement that is run.
84025 */
84026 SQLITE_API void *sqlite3_profile(
84027   sqlite3 *db,
84028   void (*xProfile)(void*,const char*,sqlite_uint64),
84029   void *pArg
84030 ){
84031   void *pOld;
84032   sqlite3_mutex_enter(db->mutex);
84033   pOld = db->pProfileArg;
84034   db->xProfile = xProfile;
84035   db->pProfileArg = pArg;
84036   sqlite3_mutex_leave(db->mutex);
84037   return pOld;
84038 }
84039 #endif /* SQLITE_OMIT_TRACE */
84040
84041 /*** EXPERIMENTAL ***
84042 **
84043 ** Register a function to be invoked when a transaction comments.
84044 ** If the invoked function returns non-zero, then the commit becomes a
84045 ** rollback.
84046 */
84047 SQLITE_API void *sqlite3_commit_hook(
84048   sqlite3 *db,              /* Attach the hook to this database */
84049   int (*xCallback)(void*),  /* Function to invoke on each commit */
84050   void *pArg                /* Argument to the function */
84051 ){
84052   void *pOld;
84053   sqlite3_mutex_enter(db->mutex);
84054   pOld = db->pCommitArg;
84055   db->xCommitCallback = xCallback;
84056   db->pCommitArg = pArg;
84057   sqlite3_mutex_leave(db->mutex);
84058   return pOld;
84059 }
84060
84061 /*
84062 ** Register a callback to be invoked each time a row is updated,
84063 ** inserted or deleted using this database connection.
84064 */
84065 SQLITE_API void *sqlite3_update_hook(
84066   sqlite3 *db,              /* Attach the hook to this database */
84067   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
84068   void *pArg                /* Argument to the function */
84069 ){
84070   void *pRet;
84071   sqlite3_mutex_enter(db->mutex);
84072   pRet = db->pUpdateArg;
84073   db->xUpdateCallback = xCallback;
84074   db->pUpdateArg = pArg;
84075   sqlite3_mutex_leave(db->mutex);
84076   return pRet;
84077 }
84078
84079 /*
84080 ** Register a callback to be invoked each time a transaction is rolled
84081 ** back by this database connection.
84082 */
84083 SQLITE_API void *sqlite3_rollback_hook(
84084   sqlite3 *db,              /* Attach the hook to this database */
84085   void (*xCallback)(void*), /* Callback function */
84086   void *pArg                /* Argument to the function */
84087 ){
84088   void *pRet;
84089   sqlite3_mutex_enter(db->mutex);
84090   pRet = db->pRollbackArg;
84091   db->xRollbackCallback = xCallback;
84092   db->pRollbackArg = pArg;
84093   sqlite3_mutex_leave(db->mutex);
84094   return pRet;
84095 }
84096
84097 /*
84098 ** This routine is called to create a connection to a database BTree
84099 ** driver.  If zFilename is the name of a file, then that file is
84100 ** opened and used.  If zFilename is the magic name ":memory:" then
84101 ** the database is stored in memory (and is thus forgotten as soon as
84102 ** the connection is closed.)  If zFilename is NULL then the database
84103 ** is a "virtual" database for transient use only and is deleted as
84104 ** soon as the connection is closed.
84105 **
84106 ** A virtual database can be either a disk file (that is automatically
84107 ** deleted when the file is closed) or it an be held entirely in memory,
84108 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
84109 ** db->temp_store variable, according to the following chart:
84110 **
84111 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
84112 **   -----------------     --------------     ------------------------------
84113 **   0                     any                file
84114 **   1                     1                  file
84115 **   1                     2                  memory
84116 **   1                     0                  file
84117 **   2                     1                  file
84118 **   2                     2                  memory
84119 **   2                     0                  memory
84120 **   3                     any                memory
84121 */
84122 SQLITE_PRIVATE int sqlite3BtreeFactory(
84123   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
84124   const char *zFilename,    /* Name of the file containing the BTree database */
84125   int omitJournal,          /* if TRUE then do not journal this file */
84126   int nCache,               /* How many pages in the page cache */
84127   int vfsFlags,             /* Flags passed through to vfsOpen */
84128   Btree **ppBtree           /* Pointer to new Btree object written here */
84129 ){
84130   int btFlags = 0;
84131   int rc;
84132   
84133   assert( sqlite3_mutex_held(db->mutex) );
84134   assert( ppBtree != 0);
84135   if( omitJournal ){
84136     btFlags |= BTREE_OMIT_JOURNAL;
84137   }
84138   if( db->flags & SQLITE_NoReadlock ){
84139     btFlags |= BTREE_NO_READLOCK;
84140   }
84141   if( zFilename==0 ){
84142 #if SQLITE_TEMP_STORE==0
84143     /* Do nothing */
84144 #endif
84145 #ifndef SQLITE_OMIT_MEMORYDB
84146 #if SQLITE_TEMP_STORE==1
84147     if( db->temp_store==2 ) zFilename = ":memory:";
84148 #endif
84149 #if SQLITE_TEMP_STORE==2
84150     if( db->temp_store!=1 ) zFilename = ":memory:";
84151 #endif
84152 #if SQLITE_TEMP_STORE==3
84153     zFilename = ":memory:";
84154 #endif
84155 #endif /* SQLITE_OMIT_MEMORYDB */
84156   }
84157
84158   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
84159     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
84160   }
84161   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
84162
84163   /* If the B-Tree was successfully opened, set the pager-cache size to the
84164   ** default value. Except, if the call to BtreeOpen() returned a handle
84165   ** open on an existing shared pager-cache, do not change the pager-cache 
84166   ** size.
84167   */
84168   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
84169     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
84170   }
84171   return rc;
84172 }
84173
84174 /*
84175 ** Return UTF-8 encoded English language explanation of the most recent
84176 ** error.
84177 */
84178 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
84179   const char *z;
84180   if( !db ){
84181     return sqlite3ErrStr(SQLITE_NOMEM);
84182   }
84183   if( !sqlite3SafetyCheckSickOrOk(db) ){
84184     return sqlite3ErrStr(SQLITE_MISUSE);
84185   }
84186   sqlite3_mutex_enter(db->mutex);
84187   assert( !db->mallocFailed );
84188   z = (char*)sqlite3_value_text(db->pErr);
84189   assert( !db->mallocFailed );
84190   if( z==0 ){
84191     z = sqlite3ErrStr(db->errCode);
84192   }
84193   sqlite3_mutex_leave(db->mutex);
84194   return z;
84195 }
84196
84197 #ifndef SQLITE_OMIT_UTF16
84198 /*
84199 ** Return UTF-16 encoded English language explanation of the most recent
84200 ** error.
84201 */
84202 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
84203   /* Because all the characters in the string are in the unicode
84204   ** range 0x00-0xFF, if we pad the big-endian string with a 
84205   ** zero byte, we can obtain the little-endian string with
84206   ** &big_endian[1].
84207   */
84208   static const char outOfMemBe[] = {
84209     0, 'o', 0, 'u', 0, 't', 0, ' ', 
84210     0, 'o', 0, 'f', 0, ' ', 
84211     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
84212   };
84213   static const char misuseBe [] = {
84214     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
84215     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
84216     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
84217     0, 'o', 0, 'u', 0, 't', 0, ' ', 
84218     0, 'o', 0, 'f', 0, ' ', 
84219     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
84220   };
84221
84222   const void *z;
84223   if( !db ){
84224     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
84225   }
84226   if( !sqlite3SafetyCheckSickOrOk(db) ){
84227     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
84228   }
84229   sqlite3_mutex_enter(db->mutex);
84230   assert( !db->mallocFailed );
84231   z = sqlite3_value_text16(db->pErr);
84232   if( z==0 ){
84233     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
84234          SQLITE_UTF8, SQLITE_STATIC);
84235     z = sqlite3_value_text16(db->pErr);
84236   }
84237   /* A malloc() may have failed within the call to sqlite3_value_text16()
84238   ** above. If this is the case, then the db->mallocFailed flag needs to
84239   ** be cleared before returning. Do this directly, instead of via
84240   ** sqlite3ApiExit(), to avoid setting the database handle error message.
84241   */
84242   db->mallocFailed = 0;
84243   sqlite3_mutex_leave(db->mutex);
84244   return z;
84245 }
84246 #endif /* SQLITE_OMIT_UTF16 */
84247
84248 /*
84249 ** Return the most recent error code generated by an SQLite routine. If NULL is
84250 ** passed to this function, we assume a malloc() failed during sqlite3_open().
84251 */
84252 SQLITE_API int sqlite3_errcode(sqlite3 *db){
84253   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
84254     return SQLITE_MISUSE;
84255   }
84256   if( !db || db->mallocFailed ){
84257     return SQLITE_NOMEM;
84258   }
84259   return db->errCode & db->errMask;
84260 }
84261
84262 /*
84263 ** Create a new collating function for database "db".  The name is zName
84264 ** and the encoding is enc.
84265 */
84266 static int createCollation(
84267   sqlite3* db, 
84268   const char *zName, 
84269   int enc, 
84270   void* pCtx,
84271   int(*xCompare)(void*,int,const void*,int,const void*),
84272   void(*xDel)(void*)
84273 ){
84274   CollSeq *pColl;
84275   int enc2;
84276   int nName;
84277   
84278   assert( sqlite3_mutex_held(db->mutex) );
84279
84280   /* If SQLITE_UTF16 is specified as the encoding type, transform this
84281   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
84282   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
84283   */
84284   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
84285   if( enc2==SQLITE_UTF16 ){
84286     enc2 = SQLITE_UTF16NATIVE;
84287   }
84288   if( (enc2&~3)!=0 ){
84289     return SQLITE_MISUSE;
84290   }
84291
84292   /* Check if this call is removing or replacing an existing collation 
84293   ** sequence. If so, and there are active VMs, return busy. If there
84294   ** are no active VMs, invalidate any pre-compiled statements.
84295   */
84296   nName = sqlite3Strlen(db, zName);
84297   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
84298   if( pColl && pColl->xCmp ){
84299     if( db->activeVdbeCnt ){
84300       sqlite3Error(db, SQLITE_BUSY, 
84301         "Unable to delete/modify collation sequence due to active statements");
84302       return SQLITE_BUSY;
84303     }
84304     sqlite3ExpirePreparedStatements(db);
84305
84306     /* If collation sequence pColl was created directly by a call to
84307     ** sqlite3_create_collation, and not generated by synthCollSeq(),
84308     ** then any copies made by synthCollSeq() need to be invalidated.
84309     ** Also, collation destructor - CollSeq.xDel() - function may need
84310     ** to be called.
84311     */ 
84312     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
84313       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
84314       int j;
84315       for(j=0; j<3; j++){
84316         CollSeq *p = &aColl[j];
84317         if( p->enc==pColl->enc ){
84318           if( p->xDel ){
84319             p->xDel(p->pUser);
84320           }
84321           p->xCmp = 0;
84322         }
84323       }
84324     }
84325   }
84326
84327   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
84328   if( pColl ){
84329     pColl->xCmp = xCompare;
84330     pColl->pUser = pCtx;
84331     pColl->xDel = xDel;
84332     pColl->enc = enc2 | (enc & SQLITE_UTF16_ALIGNED);
84333   }
84334   sqlite3Error(db, SQLITE_OK, 0);
84335   return SQLITE_OK;
84336 }
84337
84338
84339 /*
84340 ** This array defines hard upper bounds on limit values.  The
84341 ** initializer must be kept in sync with the SQLITE_LIMIT_*
84342 ** #defines in sqlite3.h.
84343 */
84344 static const int aHardLimit[] = {
84345   SQLITE_MAX_LENGTH,
84346   SQLITE_MAX_SQL_LENGTH,
84347   SQLITE_MAX_COLUMN,
84348   SQLITE_MAX_EXPR_DEPTH,
84349   SQLITE_MAX_COMPOUND_SELECT,
84350   SQLITE_MAX_VDBE_OP,
84351   SQLITE_MAX_FUNCTION_ARG,
84352   SQLITE_MAX_ATTACHED,
84353   SQLITE_MAX_LIKE_PATTERN_LENGTH,
84354   SQLITE_MAX_VARIABLE_NUMBER,
84355 };
84356
84357 /*
84358 ** Make sure the hard limits are set to reasonable values
84359 */
84360 #if SQLITE_MAX_LENGTH<100
84361 # error SQLITE_MAX_LENGTH must be at least 100
84362 #endif
84363 #if SQLITE_MAX_SQL_LENGTH<100
84364 # error SQLITE_MAX_SQL_LENGTH must be at least 100
84365 #endif
84366 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
84367 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
84368 #endif
84369 #if SQLITE_MAX_COMPOUND_SELECT<2
84370 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
84371 #endif
84372 #if SQLITE_MAX_VDBE_OP<40
84373 # error SQLITE_MAX_VDBE_OP must be at least 40
84374 #endif
84375 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
84376 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
84377 #endif
84378 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
84379 # error SQLITE_MAX_ATTACHED must be between 0 and 30
84380 #endif
84381 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
84382 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
84383 #endif
84384 #if SQLITE_MAX_VARIABLE_NUMBER<1
84385 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
84386 #endif
84387 #if SQLITE_MAX_COLUMN>32767
84388 # error SQLITE_MAX_COLUMN must not exceed 32767
84389 #endif
84390
84391
84392 /*
84393 ** Change the value of a limit.  Report the old value.
84394 ** If an invalid limit index is supplied, report -1.
84395 ** Make no changes but still report the old value if the
84396 ** new limit is negative.
84397 **
84398 ** A new lower limit does not shrink existing constructs.
84399 ** It merely prevents new constructs that exceed the limit
84400 ** from forming.
84401 */
84402 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
84403   int oldLimit;
84404   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
84405     return -1;
84406   }
84407   oldLimit = db->aLimit[limitId];
84408   if( newLimit>=0 ){
84409     if( newLimit>aHardLimit[limitId] ){
84410       newLimit = aHardLimit[limitId];
84411     }
84412     db->aLimit[limitId] = newLimit;
84413   }
84414   return oldLimit;
84415 }
84416
84417 /*
84418 ** This routine does the work of opening a database on behalf of
84419 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
84420 ** is UTF-8 encoded.
84421 */
84422 static int openDatabase(
84423   const char *zFilename, /* Database filename UTF-8 encoded */
84424   sqlite3 **ppDb,        /* OUT: Returned database handle */
84425   unsigned flags,        /* Operational flags */
84426   const char *zVfs       /* Name of the VFS to use */
84427 ){
84428   sqlite3 *db;
84429   int rc;
84430   CollSeq *pColl;
84431   int isThreadsafe;
84432
84433 #ifndef SQLITE_OMIT_AUTOINIT
84434   rc = sqlite3_initialize();
84435   if( rc ) return rc;
84436 #endif
84437
84438   if( sqlite3GlobalConfig.bCoreMutex==0 ){
84439     isThreadsafe = 0;
84440   }else if( flags & SQLITE_OPEN_NOMUTEX ){
84441     isThreadsafe = 0;
84442   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
84443     isThreadsafe = 1;
84444   }else{
84445     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
84446   }
84447
84448   /* Remove harmful bits from the flags parameter */
84449   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
84450                SQLITE_OPEN_MAIN_DB |
84451                SQLITE_OPEN_TEMP_DB | 
84452                SQLITE_OPEN_TRANSIENT_DB | 
84453                SQLITE_OPEN_MAIN_JOURNAL | 
84454                SQLITE_OPEN_TEMP_JOURNAL | 
84455                SQLITE_OPEN_SUBJOURNAL | 
84456                SQLITE_OPEN_MASTER_JOURNAL |
84457                SQLITE_OPEN_NOMUTEX |
84458                SQLITE_OPEN_FULLMUTEX
84459              );
84460
84461   /* Allocate the sqlite data structure */
84462   db = sqlite3MallocZero( sizeof(sqlite3) );
84463   if( db==0 ) goto opendb_out;
84464   if( isThreadsafe ){
84465     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
84466     if( db->mutex==0 ){
84467       sqlite3_free(db);
84468       db = 0;
84469       goto opendb_out;
84470     }
84471   }
84472   sqlite3_mutex_enter(db->mutex);
84473   db->errMask = 0xff;
84474   db->priorNewRowid = 0;
84475   db->nDb = 2;
84476   db->magic = SQLITE_MAGIC_BUSY;
84477   db->aDb = db->aDbStatic;
84478
84479   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
84480   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
84481   db->autoCommit = 1;
84482   db->nextAutovac = -1;
84483   db->nextPagesize = 0;
84484   db->flags |= SQLITE_ShortColNames
84485 #if SQLITE_DEFAULT_FILE_FORMAT<4
84486                  | SQLITE_LegacyFileFmt
84487 #endif
84488 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
84489                  | SQLITE_LoadExtension
84490 #endif
84491       ;
84492   sqlite3HashInit(&db->aCollSeq, 0);
84493 #ifndef SQLITE_OMIT_VIRTUALTABLE
84494   sqlite3HashInit(&db->aModule, 0);
84495 #endif
84496
84497   db->pVfs = sqlite3_vfs_find(zVfs);
84498   if( !db->pVfs ){
84499     rc = SQLITE_ERROR;
84500     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
84501     goto opendb_out;
84502   }
84503
84504   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
84505   ** and UTF-16, so add a version for each to avoid any unnecessary
84506   ** conversions. The only error that can occur here is a malloc() failure.
84507   */
84508   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
84509   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
84510   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
84511   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
84512   if( db->mallocFailed ){
84513     goto opendb_out;
84514   }
84515   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
84516   assert( db->pDfltColl!=0 );
84517
84518   /* Also add a UTF-8 case-insensitive collation sequence. */
84519   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
84520
84521   /* Set flags on the built-in collating sequences */
84522   db->pDfltColl->type = SQLITE_COLL_BINARY;
84523   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
84524   if( pColl ){
84525     pColl->type = SQLITE_COLL_NOCASE;
84526   }
84527
84528   /* Open the backend database driver */
84529   db->openFlags = flags;
84530   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
84531                            flags | SQLITE_OPEN_MAIN_DB,
84532                            &db->aDb[0].pBt);
84533   if( rc!=SQLITE_OK ){
84534     if( rc==SQLITE_IOERR_NOMEM ){
84535       rc = SQLITE_NOMEM;
84536     }
84537     sqlite3Error(db, rc, 0);
84538     goto opendb_out;
84539   }
84540   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
84541   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
84542
84543
84544   /* The default safety_level for the main database is 'full'; for the temp
84545   ** database it is 'NONE'. This matches the pager layer defaults.  
84546   */
84547   db->aDb[0].zName = "main";
84548   db->aDb[0].safety_level = 3;
84549 #ifndef SQLITE_OMIT_TEMPDB
84550   db->aDb[1].zName = "temp";
84551   db->aDb[1].safety_level = 1;
84552 #endif
84553
84554   db->magic = SQLITE_MAGIC_OPEN;
84555   if( db->mallocFailed ){
84556     goto opendb_out;
84557   }
84558
84559   /* Register all built-in functions, but do not attempt to read the
84560   ** database schema yet. This is delayed until the first time the database
84561   ** is accessed.
84562   */
84563   sqlite3Error(db, SQLITE_OK, 0);
84564   sqlite3RegisterBuiltinFunctions(db);
84565
84566   /* Load automatic extensions - extensions that have been registered
84567   ** using the sqlite3_automatic_extension() API.
84568   */
84569   (void)sqlite3AutoLoadExtensions(db);
84570   if( sqlite3_errcode(db)!=SQLITE_OK ){
84571     goto opendb_out;
84572   }
84573
84574 #ifdef SQLITE_ENABLE_FTS1
84575   if( !db->mallocFailed ){
84576     extern int sqlite3Fts1Init(sqlite3*);
84577     rc = sqlite3Fts1Init(db);
84578   }
84579 #endif
84580
84581 #ifdef SQLITE_ENABLE_FTS2
84582   if( !db->mallocFailed && rc==SQLITE_OK ){
84583     extern int sqlite3Fts2Init(sqlite3*);
84584     rc = sqlite3Fts2Init(db);
84585   }
84586 #endif
84587
84588 #ifdef SQLITE_ENABLE_FTS3
84589   if( !db->mallocFailed && rc==SQLITE_OK ){
84590     rc = sqlite3Fts3Init(db);
84591   }
84592 #endif
84593
84594 #ifdef SQLITE_ENABLE_ICU
84595   if( !db->mallocFailed && rc==SQLITE_OK ){
84596     rc = sqlite3IcuInit(db);
84597   }
84598 #endif
84599
84600 #ifdef SQLITE_ENABLE_RTREE
84601   if( !db->mallocFailed && rc==SQLITE_OK){
84602     rc = sqlite3RtreeInit(db);
84603   }
84604 #endif
84605
84606   sqlite3Error(db, rc, 0);
84607
84608   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
84609   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
84610   ** mode.  Doing nothing at all also makes NORMAL the default.
84611   */
84612 #ifdef SQLITE_DEFAULT_LOCKING_MODE
84613   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
84614   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
84615                           SQLITE_DEFAULT_LOCKING_MODE);
84616 #endif
84617
84618   /* Enable the lookaside-malloc subsystem */
84619   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
84620                         sqlite3GlobalConfig.nLookaside);
84621
84622 opendb_out:
84623   if( db ){
84624     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
84625     sqlite3_mutex_leave(db->mutex);
84626   }
84627   rc = sqlite3_errcode(db);
84628   if( rc==SQLITE_NOMEM ){
84629     sqlite3_close(db);
84630     db = 0;
84631   }else if( rc!=SQLITE_OK ){
84632     db->magic = SQLITE_MAGIC_SICK;
84633   }
84634   *ppDb = db;
84635   return sqlite3ApiExit(0, rc);
84636 }
84637
84638 /*
84639 ** Open a new database handle.
84640 */
84641 SQLITE_API int sqlite3_open(
84642   const char *zFilename, 
84643   sqlite3 **ppDb 
84644 ){
84645   return openDatabase(zFilename, ppDb,
84646                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
84647 }
84648 SQLITE_API int sqlite3_open_v2(
84649   const char *filename,   /* Database filename (UTF-8) */
84650   sqlite3 **ppDb,         /* OUT: SQLite db handle */
84651   int flags,              /* Flags */
84652   const char *zVfs        /* Name of VFS module to use */
84653 ){
84654   return openDatabase(filename, ppDb, flags, zVfs);
84655 }
84656
84657 #ifndef SQLITE_OMIT_UTF16
84658 /*
84659 ** Open a new database handle.
84660 */
84661 SQLITE_API int sqlite3_open16(
84662   const void *zFilename, 
84663   sqlite3 **ppDb
84664 ){
84665   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
84666   sqlite3_value *pVal;
84667   int rc;
84668
84669   assert( zFilename );
84670   assert( ppDb );
84671   *ppDb = 0;
84672 #ifndef SQLITE_OMIT_AUTOINIT
84673   rc = sqlite3_initialize();
84674   if( rc ) return rc;
84675 #endif
84676   pVal = sqlite3ValueNew(0);
84677   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
84678   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
84679   if( zFilename8 ){
84680     rc = openDatabase(zFilename8, ppDb,
84681                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
84682     assert( *ppDb || rc==SQLITE_NOMEM );
84683     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
84684       ENC(*ppDb) = SQLITE_UTF16NATIVE;
84685     }
84686   }else{
84687     rc = SQLITE_NOMEM;
84688   }
84689   sqlite3ValueFree(pVal);
84690
84691   return sqlite3ApiExit(0, rc);
84692 }
84693 #endif /* SQLITE_OMIT_UTF16 */
84694
84695 /*
84696 ** Register a new collation sequence with the database handle db.
84697 */
84698 SQLITE_API int sqlite3_create_collation(
84699   sqlite3* db, 
84700   const char *zName, 
84701   int enc, 
84702   void* pCtx,
84703   int(*xCompare)(void*,int,const void*,int,const void*)
84704 ){
84705   int rc;
84706   sqlite3_mutex_enter(db->mutex);
84707   assert( !db->mallocFailed );
84708   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
84709   rc = sqlite3ApiExit(db, rc);
84710   sqlite3_mutex_leave(db->mutex);
84711   return rc;
84712 }
84713
84714 /*
84715 ** Register a new collation sequence with the database handle db.
84716 */
84717 SQLITE_API int sqlite3_create_collation_v2(
84718   sqlite3* db, 
84719   const char *zName, 
84720   int enc, 
84721   void* pCtx,
84722   int(*xCompare)(void*,int,const void*,int,const void*),
84723   void(*xDel)(void*)
84724 ){
84725   int rc;
84726   sqlite3_mutex_enter(db->mutex);
84727   assert( !db->mallocFailed );
84728   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
84729   rc = sqlite3ApiExit(db, rc);
84730   sqlite3_mutex_leave(db->mutex);
84731   return rc;
84732 }
84733
84734 #ifndef SQLITE_OMIT_UTF16
84735 /*
84736 ** Register a new collation sequence with the database handle db.
84737 */
84738 SQLITE_API int sqlite3_create_collation16(
84739   sqlite3* db, 
84740   const void *zName,
84741   int enc, 
84742   void* pCtx,
84743   int(*xCompare)(void*,int,const void*,int,const void*)
84744 ){
84745   int rc = SQLITE_OK;
84746   char *zName8;
84747   sqlite3_mutex_enter(db->mutex);
84748   assert( !db->mallocFailed );
84749   zName8 = sqlite3Utf16to8(db, zName, -1);
84750   if( zName8 ){
84751     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
84752     sqlite3DbFree(db, zName8);
84753   }
84754   rc = sqlite3ApiExit(db, rc);
84755   sqlite3_mutex_leave(db->mutex);
84756   return rc;
84757 }
84758 #endif /* SQLITE_OMIT_UTF16 */
84759
84760 /*
84761 ** Register a collation sequence factory callback with the database handle
84762 ** db. Replace any previously installed collation sequence factory.
84763 */
84764 SQLITE_API int sqlite3_collation_needed(
84765   sqlite3 *db, 
84766   void *pCollNeededArg, 
84767   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
84768 ){
84769   sqlite3_mutex_enter(db->mutex);
84770   db->xCollNeeded = xCollNeeded;
84771   db->xCollNeeded16 = 0;
84772   db->pCollNeededArg = pCollNeededArg;
84773   sqlite3_mutex_leave(db->mutex);
84774   return SQLITE_OK;
84775 }
84776
84777 #ifndef SQLITE_OMIT_UTF16
84778 /*
84779 ** Register a collation sequence factory callback with the database handle
84780 ** db. Replace any previously installed collation sequence factory.
84781 */
84782 SQLITE_API int sqlite3_collation_needed16(
84783   sqlite3 *db, 
84784   void *pCollNeededArg, 
84785   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
84786 ){
84787   sqlite3_mutex_enter(db->mutex);
84788   db->xCollNeeded = 0;
84789   db->xCollNeeded16 = xCollNeeded16;
84790   db->pCollNeededArg = pCollNeededArg;
84791   sqlite3_mutex_leave(db->mutex);
84792   return SQLITE_OK;
84793 }
84794 #endif /* SQLITE_OMIT_UTF16 */
84795
84796 #ifndef SQLITE_OMIT_GLOBALRECOVER
84797 #ifndef SQLITE_OMIT_DEPRECATED
84798 /*
84799 ** This function is now an anachronism. It used to be used to recover from a
84800 ** malloc() failure, but SQLite now does this automatically.
84801 */
84802 SQLITE_API int sqlite3_global_recover(void){
84803   return SQLITE_OK;
84804 }
84805 #endif
84806 #endif
84807
84808 /*
84809 ** Test to see whether or not the database connection is in autocommit
84810 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
84811 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
84812 ** by the next COMMIT or ROLLBACK.
84813 **
84814 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
84815 */
84816 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
84817   return db->autoCommit;
84818 }
84819
84820 #ifdef SQLITE_DEBUG
84821 /*
84822 ** The following routine is subtituted for constant SQLITE_CORRUPT in
84823 ** debugging builds.  This provides a way to set a breakpoint for when
84824 ** corruption is first detected.
84825 */
84826 SQLITE_PRIVATE int sqlite3Corrupt(void){
84827   return SQLITE_CORRUPT;
84828 }
84829 #endif
84830
84831 #ifndef SQLITE_OMIT_DEPRECATED
84832 /*
84833 ** This is a convenience routine that makes sure that all thread-specific
84834 ** data for this thread has been deallocated.
84835 **
84836 ** SQLite no longer uses thread-specific data so this routine is now a
84837 ** no-op.  It is retained for historical compatibility.
84838 */
84839 SQLITE_API void sqlite3_thread_cleanup(void){
84840 }
84841 #endif
84842
84843 /*
84844 ** Return meta information about a specific column of a database table.
84845 ** See comment in sqlite3.h (sqlite.h.in) for details.
84846 */
84847 #ifdef SQLITE_ENABLE_COLUMN_METADATA
84848 SQLITE_API int sqlite3_table_column_metadata(
84849   sqlite3 *db,                /* Connection handle */
84850   const char *zDbName,        /* Database name or NULL */
84851   const char *zTableName,     /* Table name */
84852   const char *zColumnName,    /* Column name */
84853   char const **pzDataType,    /* OUTPUT: Declared data type */
84854   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
84855   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
84856   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
84857   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
84858 ){
84859   int rc;
84860   char *zErrMsg = 0;
84861   Table *pTab = 0;
84862   Column *pCol = 0;
84863   int iCol;
84864
84865   char const *zDataType = 0;
84866   char const *zCollSeq = 0;
84867   int notnull = 0;
84868   int primarykey = 0;
84869   int autoinc = 0;
84870
84871   /* Ensure the database schema has been loaded */
84872   sqlite3_mutex_enter(db->mutex);
84873   (void)sqlite3SafetyOn(db);
84874   sqlite3BtreeEnterAll(db);
84875   rc = sqlite3Init(db, &zErrMsg);
84876   sqlite3BtreeLeaveAll(db);
84877   if( SQLITE_OK!=rc ){
84878     goto error_out;
84879   }
84880
84881   /* Locate the table in question */
84882   pTab = sqlite3FindTable(db, zTableName, zDbName);
84883   if( !pTab || pTab->pSelect ){
84884     pTab = 0;
84885     goto error_out;
84886   }
84887
84888   /* Find the column for which info is requested */
84889   if( sqlite3IsRowid(zColumnName) ){
84890     iCol = pTab->iPKey;
84891     if( iCol>=0 ){
84892       pCol = &pTab->aCol[iCol];
84893     }
84894   }else{
84895     for(iCol=0; iCol<pTab->nCol; iCol++){
84896       pCol = &pTab->aCol[iCol];
84897       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
84898         break;
84899       }
84900     }
84901     if( iCol==pTab->nCol ){
84902       pTab = 0;
84903       goto error_out;
84904     }
84905   }
84906
84907   /* The following block stores the meta information that will be returned
84908   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
84909   ** and autoinc. At this point there are two possibilities:
84910   ** 
84911   **     1. The specified column name was rowid", "oid" or "_rowid_" 
84912   **        and there is no explicitly declared IPK column. 
84913   **
84914   **     2. The table is not a view and the column name identified an 
84915   **        explicitly declared column. Copy meta information from *pCol.
84916   */ 
84917   if( pCol ){
84918     zDataType = pCol->zType;
84919     zCollSeq = pCol->zColl;
84920     notnull = pCol->notNull!=0;
84921     primarykey  = pCol->isPrimKey!=0;
84922     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
84923   }else{
84924     zDataType = "INTEGER";
84925     primarykey = 1;
84926   }
84927   if( !zCollSeq ){
84928     zCollSeq = "BINARY";
84929   }
84930
84931 error_out:
84932   (void)sqlite3SafetyOff(db);
84933
84934   /* Whether the function call succeeded or failed, set the output parameters
84935   ** to whatever their local counterparts contain. If an error did occur,
84936   ** this has the effect of zeroing all output parameters.
84937   */
84938   if( pzDataType ) *pzDataType = zDataType;
84939   if( pzCollSeq ) *pzCollSeq = zCollSeq;
84940   if( pNotNull ) *pNotNull = notnull;
84941   if( pPrimaryKey ) *pPrimaryKey = primarykey;
84942   if( pAutoinc ) *pAutoinc = autoinc;
84943
84944   if( SQLITE_OK==rc && !pTab ){
84945     sqlite3DbFree(db, zErrMsg);
84946     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
84947         zColumnName);
84948     rc = SQLITE_ERROR;
84949   }
84950   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
84951   sqlite3DbFree(db, zErrMsg);
84952   rc = sqlite3ApiExit(db, rc);
84953   sqlite3_mutex_leave(db->mutex);
84954   return rc;
84955 }
84956 #endif
84957
84958 /*
84959 ** Sleep for a little while.  Return the amount of time slept.
84960 */
84961 SQLITE_API int sqlite3_sleep(int ms){
84962   sqlite3_vfs *pVfs;
84963   int rc;
84964   pVfs = sqlite3_vfs_find(0);
84965   if( pVfs==0 ) return 0;
84966
84967   /* This function works in milliseconds, but the underlying OsSleep() 
84968   ** API uses microseconds. Hence the 1000's.
84969   */
84970   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
84971   return rc;
84972 }
84973
84974 /*
84975 ** Enable or disable the extended result codes.
84976 */
84977 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
84978   sqlite3_mutex_enter(db->mutex);
84979   db->errMask = onoff ? 0xffffffff : 0xff;
84980   sqlite3_mutex_leave(db->mutex);
84981   return SQLITE_OK;
84982 }
84983
84984 /*
84985 ** Invoke the xFileControl method on a particular database.
84986 */
84987 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
84988   int rc = SQLITE_ERROR;
84989   int iDb;
84990   sqlite3_mutex_enter(db->mutex);
84991   if( zDbName==0 ){
84992     iDb = 0;
84993   }else{
84994     for(iDb=0; iDb<db->nDb; iDb++){
84995       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
84996     }
84997   }
84998   if( iDb<db->nDb ){
84999     Btree *pBtree = db->aDb[iDb].pBt;
85000     if( pBtree ){
85001       Pager *pPager;
85002       sqlite3_file *fd;
85003       sqlite3BtreeEnter(pBtree);
85004       pPager = sqlite3BtreePager(pBtree);
85005       assert( pPager!=0 );
85006       fd = sqlite3PagerFile(pPager);
85007       assert( fd!=0 );
85008       if( fd->pMethods ){
85009         rc = sqlite3OsFileControl(fd, op, pArg);
85010       }
85011       sqlite3BtreeLeave(pBtree);
85012     }
85013   }
85014   sqlite3_mutex_leave(db->mutex);
85015   return rc;   
85016 }
85017
85018 /*
85019 ** Interface to the testing logic.
85020 */
85021 SQLITE_API int sqlite3_test_control(int op, ...){
85022   int rc = 0;
85023 #ifndef SQLITE_OMIT_BUILTIN_TEST
85024   va_list ap;
85025   va_start(ap, op);
85026   switch( op ){
85027
85028     /*
85029     ** Save the current state of the PRNG.
85030     */
85031     case SQLITE_TESTCTRL_PRNG_SAVE: {
85032       sqlite3PrngSaveState();
85033       break;
85034     }
85035
85036     /*
85037     ** Restore the state of the PRNG to the last state saved using
85038     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
85039     ** this verb acts like PRNG_RESET.
85040     */
85041     case SQLITE_TESTCTRL_PRNG_RESTORE: {
85042       sqlite3PrngRestoreState();
85043       break;
85044     }
85045
85046     /*
85047     ** Reset the PRNG back to its uninitialized state.  The next call
85048     ** to sqlite3_randomness() will reseed the PRNG using a single call
85049     ** to the xRandomness method of the default VFS.
85050     */
85051     case SQLITE_TESTCTRL_PRNG_RESET: {
85052       sqlite3PrngResetState();
85053       break;
85054     }
85055
85056     /*
85057     **  sqlite3_test_control(BITVEC_TEST, size, program)
85058     **
85059     ** Run a test against a Bitvec object of size.  The program argument
85060     ** is an array of integers that defines the test.  Return -1 on a
85061     ** memory allocation error, 0 on success, or non-zero for an error.
85062     ** See the sqlite3BitvecBuiltinTest() for additional information.
85063     */
85064     case SQLITE_TESTCTRL_BITVEC_TEST: {
85065       int sz = va_arg(ap, int);
85066       int *aProg = va_arg(ap, int*);
85067       rc = sqlite3BitvecBuiltinTest(sz, aProg);
85068       break;
85069     }
85070
85071     /*
85072     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
85073     **
85074     ** Register hooks to call to indicate which malloc() failures 
85075     ** are benign.
85076     */
85077     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
85078       typedef void (*void_function)(void);
85079       void_function xBenignBegin;
85080       void_function xBenignEnd;
85081       xBenignBegin = va_arg(ap, void_function);
85082       xBenignEnd = va_arg(ap, void_function);
85083       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
85084       break;
85085     }
85086   }
85087   va_end(ap);
85088 #endif /* SQLITE_OMIT_BUILTIN_TEST */
85089   return rc;
85090 }
85091
85092 /************** End of main.c ************************************************/
85093 /************** Begin file fts3.c ********************************************/
85094 /*
85095 ** 2006 Oct 10
85096 **
85097 ** The author disclaims copyright to this source code.  In place of
85098 ** a legal notice, here is a blessing:
85099 **
85100 **    May you do good and not evil.
85101 **    May you find forgiveness for yourself and forgive others.
85102 **    May you share freely, never taking more than you give.
85103 **
85104 ******************************************************************************
85105 **
85106 ** This is an SQLite module implementing full-text search.
85107 */
85108
85109 /*
85110 ** The code in this file is only compiled if:
85111 **
85112 **     * The FTS3 module is being built as an extension
85113 **       (in which case SQLITE_CORE is not defined), or
85114 **
85115 **     * The FTS3 module is being built into the core of
85116 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
85117 */
85118
85119 /* TODO(shess) Consider exporting this comment to an HTML file or the
85120 ** wiki.
85121 */
85122 /* The full-text index is stored in a series of b+tree (-like)
85123 ** structures called segments which map terms to doclists.  The
85124 ** structures are like b+trees in layout, but are constructed from the
85125 ** bottom up in optimal fashion and are not updatable.  Since trees
85126 ** are built from the bottom up, things will be described from the
85127 ** bottom up.
85128 **
85129 **
85130 **** Varints ****
85131 ** The basic unit of encoding is a variable-length integer called a
85132 ** varint.  We encode variable-length integers in little-endian order
85133 ** using seven bits * per byte as follows:
85134 **
85135 ** KEY:
85136 **         A = 0xxxxxxx    7 bits of data and one flag bit
85137 **         B = 1xxxxxxx    7 bits of data and one flag bit
85138 **
85139 **  7 bits - A
85140 ** 14 bits - BA
85141 ** 21 bits - BBA
85142 ** and so on.
85143 **
85144 ** This is identical to how sqlite encodes varints (see util.c).
85145 **
85146 **
85147 **** Document lists ****
85148 ** A doclist (document list) holds a docid-sorted list of hits for a
85149 ** given term.  Doclists hold docids, and can optionally associate
85150 ** token positions and offsets with docids.
85151 **
85152 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
85153 **
85154 ** array {
85155 **   varint docid;
85156 **   array {                (position list for column 0)
85157 **     varint position;     (delta from previous position plus POS_BASE)
85158 **     varint startOffset;  (delta from previous startOffset)
85159 **     varint endOffset;    (delta from startOffset)
85160 **   }
85161 **   array {
85162 **     varint POS_COLUMN;   (marks start of position list for new column)
85163 **     varint column;       (index of new column)
85164 **     array {
85165 **       varint position;   (delta from previous position plus POS_BASE)
85166 **       varint startOffset;(delta from previous startOffset)
85167 **       varint endOffset;  (delta from startOffset)
85168 **     }
85169 **   }
85170 **   varint POS_END;        (marks end of positions for this document.
85171 ** }
85172 **
85173 ** Here, array { X } means zero or more occurrences of X, adjacent in
85174 ** memory.  A "position" is an index of a token in the token stream
85175 ** generated by the tokenizer, while an "offset" is a byte offset,
85176 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
85177 ** same logical place as the position element, and act as sentinals
85178 ** ending a position list array.
85179 **
85180 ** A DL_POSITIONS doclist omits the startOffset and endOffset
85181 ** information.  A DL_DOCIDS doclist omits both the position and
85182 ** offset information, becoming an array of varint-encoded docids.
85183 **
85184 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
85185 ** the type.  Due to how deletion is implemented in the segmentation
85186 ** system, on-disk doclists MUST store at least positions.
85187 **
85188 **
85189 **** Segment leaf nodes ****
85190 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
85191 ** nodes are written using LeafWriter, and read using LeafReader (to
85192 ** iterate through a single leaf node's data) and LeavesReader (to
85193 ** iterate through a segment's entire leaf layer).  Leaf nodes have
85194 ** the format:
85195 **
85196 ** varint iHeight;             (height from leaf level, always 0)
85197 ** varint nTerm;               (length of first term)
85198 ** char pTerm[nTerm];          (content of first term)
85199 ** varint nDoclist;            (length of term's associated doclist)
85200 ** char pDoclist[nDoclist];    (content of doclist)
85201 ** array {
85202 **                             (further terms are delta-encoded)
85203 **   varint nPrefix;           (length of prefix shared with previous term)
85204 **   varint nSuffix;           (length of unshared suffix)
85205 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
85206 **   varint nDoclist;          (length of term's associated doclist)
85207 **   char pDoclist[nDoclist];  (content of doclist)
85208 ** }
85209 **
85210 ** Here, array { X } means zero or more occurrences of X, adjacent in
85211 ** memory.
85212 **
85213 ** Leaf nodes are broken into blocks which are stored contiguously in
85214 ** the %_segments table in sorted order.  This means that when the end
85215 ** of a node is reached, the next term is in the node with the next
85216 ** greater node id.
85217 **
85218 ** New data is spilled to a new leaf node when the current node
85219 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
85220 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
85221 ** node (a leaf node with a single term and doclist).  The goal of
85222 ** these settings is to pack together groups of small doclists while
85223 ** making it efficient to directly access large doclists.  The
85224 ** assumption is that large doclists represent terms which are more
85225 ** likely to be query targets.
85226 **
85227 ** TODO(shess) It may be useful for blocking decisions to be more
85228 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
85229 ** node rather than splitting into 2k and .5k nodes.  My intuition is
85230 ** that this might extend through 2x or 4x the pagesize.
85231 **
85232 **
85233 **** Segment interior nodes ****
85234 ** Segment interior nodes store blockids for subtree nodes and terms
85235 ** to describe what data is stored by the each subtree.  Interior
85236 ** nodes are written using InteriorWriter, and read using
85237 ** InteriorReader.  InteriorWriters are created as needed when
85238 ** SegmentWriter creates new leaf nodes, or when an interior node
85239 ** itself grows too big and must be split.  The format of interior
85240 ** nodes:
85241 **
85242 ** varint iHeight;           (height from leaf level, always >0)
85243 ** varint iBlockid;          (block id of node's leftmost subtree)
85244 ** optional {
85245 **   varint nTerm;           (length of first term)
85246 **   char pTerm[nTerm];      (content of first term)
85247 **   array {
85248 **                                (further terms are delta-encoded)
85249 **     varint nPrefix;            (length of shared prefix with previous term)
85250 **     varint nSuffix;            (length of unshared suffix)
85251 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
85252 **   }
85253 ** }
85254 **
85255 ** Here, optional { X } means an optional element, while array { X }
85256 ** means zero or more occurrences of X, adjacent in memory.
85257 **
85258 ** An interior node encodes n terms separating n+1 subtrees.  The
85259 ** subtree blocks are contiguous, so only the first subtree's blockid
85260 ** is encoded.  The subtree at iBlockid will contain all terms less
85261 ** than the first term encoded (or all terms if no term is encoded).
85262 ** Otherwise, for terms greater than or equal to pTerm[i] but less
85263 ** than pTerm[i+1], the subtree for that term will be rooted at
85264 ** iBlockid+i.  Interior nodes only store enough term data to
85265 ** distinguish adjacent children (if the rightmost term of the left
85266 ** child is "something", and the leftmost term of the right child is
85267 ** "wicked", only "w" is stored).
85268 **
85269 ** New data is spilled to a new interior node at the same height when
85270 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
85271 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
85272 ** interior nodes and making the tree too skinny.  The interior nodes
85273 ** at a given height are naturally tracked by interior nodes at
85274 ** height+1, and so on.
85275 **
85276 **
85277 **** Segment directory ****
85278 ** The segment directory in table %_segdir stores meta-information for
85279 ** merging and deleting segments, and also the root node of the
85280 ** segment's tree.
85281 **
85282 ** The root node is the top node of the segment's tree after encoding
85283 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
85284 ** This could be either a leaf node or an interior node.  If the top
85285 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
85286 ** and a new root interior node is generated (which should always fit
85287 ** within ROOT_MAX because it only needs space for 2 varints, the
85288 ** height and the blockid of the previous root).
85289 **
85290 ** The meta-information in the segment directory is:
85291 **   level               - segment level (see below)
85292 **   idx                 - index within level
85293 **                       - (level,idx uniquely identify a segment)
85294 **   start_block         - first leaf node
85295 **   leaves_end_block    - last leaf node
85296 **   end_block           - last block (including interior nodes)
85297 **   root                - contents of root node
85298 **
85299 ** If the root node is a leaf node, then start_block,
85300 ** leaves_end_block, and end_block are all 0.
85301 **
85302 **
85303 **** Segment merging ****
85304 ** To amortize update costs, segments are groups into levels and
85305 ** merged in matches.  Each increase in level represents exponentially
85306 ** more documents.
85307 **
85308 ** New documents (actually, document updates) are tokenized and
85309 ** written individually (using LeafWriter) to a level 0 segment, with
85310 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
85311 ** level 0 segments are merged into a single level 1 segment.  Level 1
85312 ** is populated like level 0, and eventually MERGE_COUNT level 1
85313 ** segments are merged to a single level 2 segment (representing
85314 ** MERGE_COUNT^2 updates), and so on.
85315 **
85316 ** A segment merge traverses all segments at a given level in
85317 ** parallel, performing a straightforward sorted merge.  Since segment
85318 ** leaf nodes are written in to the %_segments table in order, this
85319 ** merge traverses the underlying sqlite disk structures efficiently.
85320 ** After the merge, all segment blocks from the merged level are
85321 ** deleted.
85322 **
85323 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
85324 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
85325 ** very similar performance numbers to 16 on insertion, though they're
85326 ** a tiny bit slower (perhaps due to more overhead in merge-time
85327 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
85328 ** 16, 2 about 66% slower than 16.
85329 **
85330 ** At query time, high MERGE_COUNT increases the number of segments
85331 ** which need to be scanned and merged.  For instance, with 100k docs
85332 ** inserted:
85333 **
85334 **    MERGE_COUNT   segments
85335 **       16           25
85336 **        8           12
85337 **        4           10
85338 **        2            6
85339 **
85340 ** This appears to have only a moderate impact on queries for very
85341 ** frequent terms (which are somewhat dominated by segment merge
85342 ** costs), and infrequent and non-existent terms still seem to be fast
85343 ** even with many segments.
85344 **
85345 ** TODO(shess) That said, it would be nice to have a better query-side
85346 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
85347 ** optimizations to things like doclist merging will swing the sweet
85348 ** spot around.
85349 **
85350 **
85351 **
85352 **** Handling of deletions and updates ****
85353 ** Since we're using a segmented structure, with no docid-oriented
85354 ** index into the term index, we clearly cannot simply update the term
85355 ** index when a document is deleted or updated.  For deletions, we
85356 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
85357 ** we simply write the new doclist.  Segment merges overwrite older
85358 ** data for a particular docid with newer data, so deletes or updates
85359 ** will eventually overtake the earlier data and knock it out.  The
85360 ** query logic likewise merges doclists so that newer data knocks out
85361 ** older data.
85362 **
85363 ** TODO(shess) Provide a VACUUM type operation to clear out all
85364 ** deletions and duplications.  This would basically be a forced merge
85365 ** into a single segment.
85366 */
85367
85368 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
85369
85370 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
85371 # define SQLITE_CORE 1
85372 #endif
85373
85374
85375 /************** Include fts3_hash.h in the middle of fts3.c ******************/
85376 /************** Begin file fts3_hash.h ***************************************/
85377 /*
85378 ** 2001 September 22
85379 **
85380 ** The author disclaims copyright to this source code.  In place of
85381 ** a legal notice, here is a blessing:
85382 **
85383 **    May you do good and not evil.
85384 **    May you find forgiveness for yourself and forgive others.
85385 **    May you share freely, never taking more than you give.
85386 **
85387 *************************************************************************
85388 ** This is the header file for the generic hash-table implemenation
85389 ** used in SQLite.  We've modified it slightly to serve as a standalone
85390 ** hash table implementation for the full-text indexing module.
85391 **
85392 */
85393 #ifndef _FTS3_HASH_H_
85394 #define _FTS3_HASH_H_
85395
85396 /* Forward declarations of structures. */
85397 typedef struct fts3Hash fts3Hash;
85398 typedef struct fts3HashElem fts3HashElem;
85399
85400 /* A complete hash table is an instance of the following structure.
85401 ** The internals of this structure are intended to be opaque -- client
85402 ** code should not attempt to access or modify the fields of this structure
85403 ** directly.  Change this structure only by using the routines below.
85404 ** However, many of the "procedures" and "functions" for modifying and
85405 ** accessing this structure are really macros, so we can't really make
85406 ** this structure opaque.
85407 */
85408 struct fts3Hash {
85409   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
85410   char copyKey;           /* True if copy of key made on insert */
85411   int count;              /* Number of entries in this table */
85412   fts3HashElem *first;    /* The first element of the array */
85413   int htsize;             /* Number of buckets in the hash table */
85414   struct _fts3ht {        /* the hash table */
85415     int count;               /* Number of entries with this hash */
85416     fts3HashElem *chain;     /* Pointer to first entry with this hash */
85417   } *ht;
85418 };
85419
85420 /* Each element in the hash table is an instance of the following 
85421 ** structure.  All elements are stored on a single doubly-linked list.
85422 **
85423 ** Again, this structure is intended to be opaque, but it can't really
85424 ** be opaque because it is used by macros.
85425 */
85426 struct fts3HashElem {
85427   fts3HashElem *next, *prev; /* Next and previous elements in the table */
85428   void *data;                /* Data associated with this element */
85429   void *pKey; int nKey;      /* Key associated with this element */
85430 };
85431
85432 /*
85433 ** There are 2 different modes of operation for a hash table:
85434 **
85435 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
85436 **                           (including the null-terminator, if any).  Case
85437 **                           is respected in comparisons.
85438 **
85439 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
85440 **                           memcmp() is used to compare keys.
85441 **
85442 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
85443 */
85444 #define FTS3_HASH_STRING    1
85445 #define FTS3_HASH_BINARY    2
85446
85447 /*
85448 ** Access routines.  To delete, insert a NULL pointer.
85449 */
85450 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
85451 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
85452 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
85453 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
85454
85455 /*
85456 ** Shorthand for the functions above
85457 */
85458 #define fts3HashInit   sqlite3Fts3HashInit
85459 #define fts3HashInsert sqlite3Fts3HashInsert
85460 #define fts3HashFind   sqlite3Fts3HashFind
85461 #define fts3HashClear  sqlite3Fts3HashClear
85462
85463 /*
85464 ** Macros for looping over all elements of a hash table.  The idiom is
85465 ** like this:
85466 **
85467 **   fts3Hash h;
85468 **   fts3HashElem *p;
85469 **   ...
85470 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
85471 **     SomeStructure *pData = fts3HashData(p);
85472 **     // do something with pData
85473 **   }
85474 */
85475 #define fts3HashFirst(H)  ((H)->first)
85476 #define fts3HashNext(E)   ((E)->next)
85477 #define fts3HashData(E)   ((E)->data)
85478 #define fts3HashKey(E)    ((E)->pKey)
85479 #define fts3HashKeysize(E) ((E)->nKey)
85480
85481 /*
85482 ** Number of entries in a hash table
85483 */
85484 #define fts3HashCount(H)  ((H)->count)
85485
85486 #endif /* _FTS3_HASH_H_ */
85487
85488 /************** End of fts3_hash.h *******************************************/
85489 /************** Continuing where we left off in fts3.c ***********************/
85490 /************** Include fts3_tokenizer.h in the middle of fts3.c *************/
85491 /************** Begin file fts3_tokenizer.h **********************************/
85492 /*
85493 ** 2006 July 10
85494 **
85495 ** The author disclaims copyright to this source code.
85496 **
85497 *************************************************************************
85498 ** Defines the interface to tokenizers used by fulltext-search.  There
85499 ** are three basic components:
85500 **
85501 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
85502 ** interface functions.  This is essentially the class structure for
85503 ** tokenizers.
85504 **
85505 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
85506 ** including customization information defined at creation time.
85507 **
85508 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
85509 ** tokens from a particular input.
85510 */
85511 #ifndef _FTS3_TOKENIZER_H_
85512 #define _FTS3_TOKENIZER_H_
85513
85514 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
85515 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
85516 ** we will need a way to register the API consistently.
85517 */
85518
85519 /*
85520 ** Structures used by the tokenizer interface. When a new tokenizer
85521 ** implementation is registered, the caller provides a pointer to
85522 ** an sqlite3_tokenizer_module containing pointers to the callback
85523 ** functions that make up an implementation.
85524 **
85525 ** When an fts3 table is created, it passes any arguments passed to
85526 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
85527 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
85528 ** implementation. The xCreate() function in turn returns an 
85529 ** sqlite3_tokenizer structure representing the specific tokenizer to
85530 ** be used for the fts3 table (customized by the tokenizer clause arguments).
85531 **
85532 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
85533 ** method is called. It returns an sqlite3_tokenizer_cursor object
85534 ** that may be used to tokenize a specific input buffer based on
85535 ** the tokenization rules supplied by a specific sqlite3_tokenizer
85536 ** object.
85537 */
85538 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
85539 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
85540 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
85541
85542 struct sqlite3_tokenizer_module {
85543
85544   /*
85545   ** Structure version. Should always be set to 0.
85546   */
85547   int iVersion;
85548
85549   /*
85550   ** Create a new tokenizer. The values in the argv[] array are the
85551   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
85552   ** TABLE statement that created the fts3 table. For example, if
85553   ** the following SQL is executed:
85554   **
85555   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
85556   **
85557   ** then argc is set to 2, and the argv[] array contains pointers
85558   ** to the strings "arg1" and "arg2".
85559   **
85560   ** This method should return either SQLITE_OK (0), or an SQLite error 
85561   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
85562   ** to point at the newly created tokenizer structure. The generic
85563   ** sqlite3_tokenizer.pModule variable should not be initialised by
85564   ** this callback. The caller will do so.
85565   */
85566   int (*xCreate)(
85567     int argc,                           /* Size of argv array */
85568     const char *const*argv,             /* Tokenizer argument strings */
85569     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
85570   );
85571
85572   /*
85573   ** Destroy an existing tokenizer. The fts3 module calls this method
85574   ** exactly once for each successful call to xCreate().
85575   */
85576   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
85577
85578   /*
85579   ** Create a tokenizer cursor to tokenize an input buffer. The caller
85580   ** is responsible for ensuring that the input buffer remains valid
85581   ** until the cursor is closed (using the xClose() method). 
85582   */
85583   int (*xOpen)(
85584     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
85585     const char *pInput, int nBytes,      /* Input buffer */
85586     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
85587   );
85588
85589   /*
85590   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
85591   ** method exactly once for each successful call to xOpen().
85592   */
85593   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
85594
85595   /*
85596   ** Retrieve the next token from the tokenizer cursor pCursor. This
85597   ** method should either return SQLITE_OK and set the values of the
85598   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
85599   ** the end of the buffer has been reached, or an SQLite error code.
85600   **
85601   ** *ppToken should be set to point at a buffer containing the 
85602   ** normalized version of the token (i.e. after any case-folding and/or
85603   ** stemming has been performed). *pnBytes should be set to the length
85604   ** of this buffer in bytes. The input text that generated the token is
85605   ** identified by the byte offsets returned in *piStartOffset and
85606   ** *piEndOffset.
85607   **
85608   ** The buffer *ppToken is set to point at is managed by the tokenizer
85609   ** implementation. It is only required to be valid until the next call
85610   ** to xNext() or xClose(). 
85611   */
85612   /* TODO(shess) current implementation requires pInput to be
85613   ** nul-terminated.  This should either be fixed, or pInput/nBytes
85614   ** should be converted to zInput.
85615   */
85616   int (*xNext)(
85617     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
85618     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
85619     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
85620     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
85621     int *piPosition      /* OUT: Number of tokens returned before this one */
85622   );
85623 };
85624
85625 struct sqlite3_tokenizer {
85626   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
85627   /* Tokenizer implementations will typically add additional fields */
85628 };
85629
85630 struct sqlite3_tokenizer_cursor {
85631   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
85632   /* Tokenizer implementations will typically add additional fields */
85633 };
85634
85635 #endif /* _FTS3_TOKENIZER_H_ */
85636
85637 /************** End of fts3_tokenizer.h **************************************/
85638 /************** Continuing where we left off in fts3.c ***********************/
85639 #ifndef SQLITE_CORE 
85640   SQLITE_EXTENSION_INIT1
85641 #endif
85642
85643
85644 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
85645 ** would be nice to order the file better, perhaps something along the
85646 ** lines of:
85647 **
85648 **  - utility functions
85649 **  - table setup functions
85650 **  - table update functions
85651 **  - table query functions
85652 **
85653 ** Put the query functions last because they're likely to reference
85654 ** typedefs or functions from the table update section.
85655 */
85656
85657 #if 0
85658 # define FTSTRACE(A)  printf A; fflush(stdout)
85659 #else
85660 # define FTSTRACE(A)
85661 #endif
85662
85663 /*
85664 ** Default span for NEAR operators.
85665 */
85666 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
85667
85668 /* It is not safe to call isspace(), tolower(), or isalnum() on
85669 ** hi-bit-set characters.  This is the same solution used in the
85670 ** tokenizer.
85671 */
85672 /* TODO(shess) The snippet-generation code should be using the
85673 ** tokenizer-generated tokens rather than doing its own local
85674 ** tokenization.
85675 */
85676 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
85677 static int safe_isspace(char c){
85678   return (c&0x80)==0 ? isspace(c) : 0;
85679 }
85680 static int safe_tolower(char c){
85681   return (c&0x80)==0 ? tolower(c) : c;
85682 }
85683 static int safe_isalnum(char c){
85684   return (c&0x80)==0 ? isalnum(c) : 0;
85685 }
85686
85687 typedef enum DocListType {
85688   DL_DOCIDS,              /* docids only */
85689   DL_POSITIONS,           /* docids + positions */
85690   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
85691 } DocListType;
85692
85693 /*
85694 ** By default, only positions and not offsets are stored in the doclists.
85695 ** To change this so that offsets are stored too, compile with
85696 **
85697 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
85698 **
85699 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
85700 ** into (no deletes or updates).
85701 */
85702 #ifndef DL_DEFAULT
85703 # define DL_DEFAULT DL_POSITIONS
85704 #endif
85705
85706 enum {
85707   POS_END = 0,        /* end of this position list */
85708   POS_COLUMN,         /* followed by new column number */
85709   POS_BASE
85710 };
85711
85712 /* MERGE_COUNT controls how often we merge segments (see comment at
85713 ** top of file).
85714 */
85715 #define MERGE_COUNT 16
85716
85717 /* utility functions */
85718
85719 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
85720 ** record to prevent errors of the form:
85721 **
85722 ** my_function(SomeType *b){
85723 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
85724 ** }
85725 */
85726 /* TODO(shess) Obvious candidates for a header file. */
85727 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
85728
85729 #ifndef NDEBUG
85730 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
85731 #else
85732 #  define SCRAMBLE(b)
85733 #endif
85734
85735 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
85736 #define VARINT_MAX 10
85737
85738 /* Write a 64-bit variable-length integer to memory starting at p[0].
85739  * The length of data written will be between 1 and VARINT_MAX bytes.
85740  * The number of bytes written is returned. */
85741 static int fts3PutVarint(char *p, sqlite_int64 v){
85742   unsigned char *q = (unsigned char *) p;
85743   sqlite_uint64 vu = v;
85744   do{
85745     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
85746     vu >>= 7;
85747   }while( vu!=0 );
85748   q[-1] &= 0x7f;  /* turn off high bit in final byte */
85749   assert( q - (unsigned char *)p <= VARINT_MAX );
85750   return (int) (q - (unsigned char *)p);
85751 }
85752
85753 /* Read a 64-bit variable-length integer from memory starting at p[0].
85754  * Return the number of bytes read, or 0 on error.
85755  * The value is stored in *v. */
85756 static int fts3GetVarint(const char *p, sqlite_int64 *v){
85757   const unsigned char *q = (const unsigned char *) p;
85758   sqlite_uint64 x = 0, y = 1;
85759   while( (*q & 0x80) == 0x80 ){
85760     x += y * (*q++ & 0x7f);
85761     y <<= 7;
85762     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
85763       assert( 0 );
85764       return 0;
85765     }
85766   }
85767   x += y * (*q++);
85768   *v = (sqlite_int64) x;
85769   return (int) (q - (unsigned char *)p);
85770 }
85771
85772 static int fts3GetVarint32(const char *p, int *pi){
85773  sqlite_int64 i;
85774  int ret = fts3GetVarint(p, &i);
85775  *pi = (int) i;
85776  assert( *pi==i );
85777  return ret;
85778 }
85779
85780 /*******************************************************************/
85781 /* DataBuffer is used to collect data into a buffer in piecemeal
85782 ** fashion.  It implements the usual distinction between amount of
85783 ** data currently stored (nData) and buffer capacity (nCapacity).
85784 **
85785 ** dataBufferInit - create a buffer with given initial capacity.
85786 ** dataBufferReset - forget buffer's data, retaining capacity.
85787 ** dataBufferDestroy - free buffer's data.
85788 ** dataBufferSwap - swap contents of two buffers.
85789 ** dataBufferExpand - expand capacity without adding data.
85790 ** dataBufferAppend - append data.
85791 ** dataBufferAppend2 - append two pieces of data at once.
85792 ** dataBufferReplace - replace buffer's data.
85793 */
85794 typedef struct DataBuffer {
85795   char *pData;          /* Pointer to malloc'ed buffer. */
85796   int nCapacity;        /* Size of pData buffer. */
85797   int nData;            /* End of data loaded into pData. */
85798 } DataBuffer;
85799
85800 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
85801   assert( nCapacity>=0 );
85802   pBuffer->nData = 0;
85803   pBuffer->nCapacity = nCapacity;
85804   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
85805 }
85806 static void dataBufferReset(DataBuffer *pBuffer){
85807   pBuffer->nData = 0;
85808 }
85809 static void dataBufferDestroy(DataBuffer *pBuffer){
85810   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
85811   SCRAMBLE(pBuffer);
85812 }
85813 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
85814   DataBuffer tmp = *pBuffer1;
85815   *pBuffer1 = *pBuffer2;
85816   *pBuffer2 = tmp;
85817 }
85818 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
85819   assert( nAddCapacity>0 );
85820   /* TODO(shess) Consider expanding more aggressively.  Note that the
85821   ** underlying malloc implementation may take care of such things for
85822   ** us already.
85823   */
85824   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
85825     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
85826     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
85827   }
85828 }
85829 static void dataBufferAppend(DataBuffer *pBuffer,
85830                              const char *pSource, int nSource){
85831   assert( nSource>0 && pSource!=NULL );
85832   dataBufferExpand(pBuffer, nSource);
85833   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
85834   pBuffer->nData += nSource;
85835 }
85836 static void dataBufferAppend2(DataBuffer *pBuffer,
85837                               const char *pSource1, int nSource1,
85838                               const char *pSource2, int nSource2){
85839   assert( nSource1>0 && pSource1!=NULL );
85840   assert( nSource2>0 && pSource2!=NULL );
85841   dataBufferExpand(pBuffer, nSource1+nSource2);
85842   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
85843   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
85844   pBuffer->nData += nSource1+nSource2;
85845 }
85846 static void dataBufferReplace(DataBuffer *pBuffer,
85847                               const char *pSource, int nSource){
85848   dataBufferReset(pBuffer);
85849   dataBufferAppend(pBuffer, pSource, nSource);
85850 }
85851
85852 /* StringBuffer is a null-terminated version of DataBuffer. */
85853 typedef struct StringBuffer {
85854   DataBuffer b;            /* Includes null terminator. */
85855 } StringBuffer;
85856
85857 static void initStringBuffer(StringBuffer *sb){
85858   dataBufferInit(&sb->b, 100);
85859   dataBufferReplace(&sb->b, "", 1);
85860 }
85861 static int stringBufferLength(StringBuffer *sb){
85862   return sb->b.nData-1;
85863 }
85864 static char *stringBufferData(StringBuffer *sb){
85865   return sb->b.pData;
85866 }
85867 static void stringBufferDestroy(StringBuffer *sb){
85868   dataBufferDestroy(&sb->b);
85869 }
85870
85871 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
85872   assert( sb->b.nData>0 );
85873   if( nFrom>0 ){
85874     sb->b.nData--;
85875     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
85876   }
85877 }
85878 static void append(StringBuffer *sb, const char *zFrom){
85879   nappend(sb, zFrom, strlen(zFrom));
85880 }
85881
85882 /* Append a list of strings separated by commas. */
85883 static void appendList(StringBuffer *sb, int nString, char **azString){
85884   int i;
85885   for(i=0; i<nString; ++i){
85886     if( i>0 ) append(sb, ", ");
85887     append(sb, azString[i]);
85888   }
85889 }
85890
85891 static int endsInWhiteSpace(StringBuffer *p){
85892   return stringBufferLength(p)>0 &&
85893     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
85894 }
85895
85896 /* If the StringBuffer ends in something other than white space, add a
85897 ** single space character to the end.
85898 */
85899 static void appendWhiteSpace(StringBuffer *p){
85900   if( stringBufferLength(p)==0 ) return;
85901   if( !endsInWhiteSpace(p) ) append(p, " ");
85902 }
85903
85904 /* Remove white space from the end of the StringBuffer */
85905 static void trimWhiteSpace(StringBuffer *p){
85906   while( endsInWhiteSpace(p) ){
85907     p->b.pData[--p->b.nData-1] = '\0';
85908   }
85909 }
85910
85911 /*******************************************************************/
85912 /* DLReader is used to read document elements from a doclist.  The
85913 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
85914 ** own the doclist buffer.
85915 **
85916 ** dlrAtEnd - true if there's no more data to read.
85917 ** dlrDocid - docid of current document.
85918 ** dlrDocData - doclist data for current document (including docid).
85919 ** dlrDocDataBytes - length of same.
85920 ** dlrAllDataBytes - length of all remaining data.
85921 ** dlrPosData - position data for current document.
85922 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
85923 ** dlrStep - step to current document.
85924 ** dlrInit - initial for doclist of given type against given data.
85925 ** dlrDestroy - clean up.
85926 **
85927 ** Expected usage is something like:
85928 **
85929 **   DLReader reader;
85930 **   dlrInit(&reader, pData, nData);
85931 **   while( !dlrAtEnd(&reader) ){
85932 **     // calls to dlrDocid() and kin.
85933 **     dlrStep(&reader);
85934 **   }
85935 **   dlrDestroy(&reader);
85936 */
85937 typedef struct DLReader {
85938   DocListType iType;
85939   const char *pData;
85940   int nData;
85941
85942   sqlite_int64 iDocid;
85943   int nElement;
85944 } DLReader;
85945
85946 static int dlrAtEnd(DLReader *pReader){
85947   assert( pReader->nData>=0 );
85948   return pReader->nData==0;
85949 }
85950 static sqlite_int64 dlrDocid(DLReader *pReader){
85951   assert( !dlrAtEnd(pReader) );
85952   return pReader->iDocid;
85953 }
85954 static const char *dlrDocData(DLReader *pReader){
85955   assert( !dlrAtEnd(pReader) );
85956   return pReader->pData;
85957 }
85958 static int dlrDocDataBytes(DLReader *pReader){
85959   assert( !dlrAtEnd(pReader) );
85960   return pReader->nElement;
85961 }
85962 static int dlrAllDataBytes(DLReader *pReader){
85963   assert( !dlrAtEnd(pReader) );
85964   return pReader->nData;
85965 }
85966 /* TODO(shess) Consider adding a field to track iDocid varint length
85967 ** to make these two functions faster.  This might matter (a tiny bit)
85968 ** for queries.
85969 */
85970 static const char *dlrPosData(DLReader *pReader){
85971   sqlite_int64 iDummy;
85972   int n = fts3GetVarint(pReader->pData, &iDummy);
85973   assert( !dlrAtEnd(pReader) );
85974   return pReader->pData+n;
85975 }
85976 static int dlrPosDataLen(DLReader *pReader){
85977   sqlite_int64 iDummy;
85978   int n = fts3GetVarint(pReader->pData, &iDummy);
85979   assert( !dlrAtEnd(pReader) );
85980   return pReader->nElement-n;
85981 }
85982 static void dlrStep(DLReader *pReader){
85983   assert( !dlrAtEnd(pReader) );
85984
85985   /* Skip past current doclist element. */
85986   assert( pReader->nElement<=pReader->nData );
85987   pReader->pData += pReader->nElement;
85988   pReader->nData -= pReader->nElement;
85989
85990   /* If there is more data, read the next doclist element. */
85991   if( pReader->nData!=0 ){
85992     sqlite_int64 iDocidDelta;
85993     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
85994     pReader->iDocid += iDocidDelta;
85995     if( pReader->iType>=DL_POSITIONS ){
85996       assert( n<pReader->nData );
85997       while( 1 ){
85998         n += fts3GetVarint32(pReader->pData+n, &iDummy);
85999         assert( n<=pReader->nData );
86000         if( iDummy==POS_END ) break;
86001         if( iDummy==POS_COLUMN ){
86002           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86003           assert( n<pReader->nData );
86004         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
86005           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86006           n += fts3GetVarint32(pReader->pData+n, &iDummy);
86007           assert( n<pReader->nData );
86008         }
86009       }
86010     }
86011     pReader->nElement = n;
86012     assert( pReader->nElement<=pReader->nData );
86013   }
86014 }
86015 static void dlrInit(DLReader *pReader, DocListType iType,
86016                     const char *pData, int nData){
86017   assert( pData!=NULL && nData!=0 );
86018   pReader->iType = iType;
86019   pReader->pData = pData;
86020   pReader->nData = nData;
86021   pReader->nElement = 0;
86022   pReader->iDocid = 0;
86023
86024   /* Load the first element's data.  There must be a first element. */
86025   dlrStep(pReader);
86026 }
86027 static void dlrDestroy(DLReader *pReader){
86028   SCRAMBLE(pReader);
86029 }
86030
86031 #ifndef NDEBUG
86032 /* Verify that the doclist can be validly decoded.  Also returns the
86033 ** last docid found because it is convenient in other assertions for
86034 ** DLWriter.
86035 */
86036 static void docListValidate(DocListType iType, const char *pData, int nData,
86037                             sqlite_int64 *pLastDocid){
86038   sqlite_int64 iPrevDocid = 0;
86039   assert( nData>0 );
86040   assert( pData!=0 );
86041   assert( pData+nData>pData );
86042   while( nData!=0 ){
86043     sqlite_int64 iDocidDelta;
86044     int n = fts3GetVarint(pData, &iDocidDelta);
86045     iPrevDocid += iDocidDelta;
86046     if( iType>DL_DOCIDS ){
86047       int iDummy;
86048       while( 1 ){
86049         n += fts3GetVarint32(pData+n, &iDummy);
86050         if( iDummy==POS_END ) break;
86051         if( iDummy==POS_COLUMN ){
86052           n += fts3GetVarint32(pData+n, &iDummy);
86053         }else if( iType>DL_POSITIONS ){
86054           n += fts3GetVarint32(pData+n, &iDummy);
86055           n += fts3GetVarint32(pData+n, &iDummy);
86056         }
86057         assert( n<=nData );
86058       }
86059     }
86060     assert( n<=nData );
86061     pData += n;
86062     nData -= n;
86063   }
86064   if( pLastDocid ) *pLastDocid = iPrevDocid;
86065 }
86066 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
86067 #else
86068 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
86069 #endif
86070
86071 /*******************************************************************/
86072 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
86073 ** always appends to the buffer and does not own it.
86074 **
86075 ** dlwInit - initialize to write a given type doclistto a buffer.
86076 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
86077 ** dlwAppend - append raw doclist data to buffer.
86078 ** dlwCopy - copy next doclist from reader to writer.
86079 ** dlwAdd - construct doclist element and append to buffer.
86080 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
86081 */
86082 typedef struct DLWriter {
86083   DocListType iType;
86084   DataBuffer *b;
86085   sqlite_int64 iPrevDocid;
86086 #ifndef NDEBUG
86087   int has_iPrevDocid;
86088 #endif
86089 } DLWriter;
86090
86091 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
86092   pWriter->b = b;
86093   pWriter->iType = iType;
86094   pWriter->iPrevDocid = 0;
86095 #ifndef NDEBUG
86096   pWriter->has_iPrevDocid = 0;
86097 #endif
86098 }
86099 static void dlwDestroy(DLWriter *pWriter){
86100   SCRAMBLE(pWriter);
86101 }
86102 /* iFirstDocid is the first docid in the doclist in pData.  It is
86103 ** needed because pData may point within a larger doclist, in which
86104 ** case the first item would be delta-encoded.
86105 **
86106 ** iLastDocid is the final docid in the doclist in pData.  It is
86107 ** needed to create the new iPrevDocid for future delta-encoding.  The
86108 ** code could decode the passed doclist to recreate iLastDocid, but
86109 ** the only current user (docListMerge) already has decoded this
86110 ** information.
86111 */
86112 /* TODO(shess) This has become just a helper for docListMerge.
86113 ** Consider a refactor to make this cleaner.
86114 */
86115 static void dlwAppend(DLWriter *pWriter,
86116                       const char *pData, int nData,
86117                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
86118   sqlite_int64 iDocid = 0;
86119   char c[VARINT_MAX];
86120   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
86121 #ifndef NDEBUG
86122   sqlite_int64 iLastDocidDelta;
86123 #endif
86124
86125   /* Recode the initial docid as delta from iPrevDocid. */
86126   nFirstOld = fts3GetVarint(pData, &iDocid);
86127   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
86128   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
86129
86130   /* Verify that the incoming doclist is valid AND that it ends with
86131   ** the expected docid.  This is essential because we'll trust this
86132   ** docid in future delta-encoding.
86133   */
86134   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
86135   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
86136
86137   /* Append recoded initial docid and everything else.  Rest of docids
86138   ** should have been delta-encoded from previous initial docid.
86139   */
86140   if( nFirstOld<nData ){
86141     dataBufferAppend2(pWriter->b, c, nFirstNew,
86142                       pData+nFirstOld, nData-nFirstOld);
86143   }else{
86144     dataBufferAppend(pWriter->b, c, nFirstNew);
86145   }
86146   pWriter->iPrevDocid = iLastDocid;
86147 }
86148 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
86149   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
86150             dlrDocid(pReader), dlrDocid(pReader));
86151 }
86152 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
86153   char c[VARINT_MAX];
86154   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
86155
86156   /* Docids must ascend. */
86157   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
86158   assert( pWriter->iType==DL_DOCIDS );
86159
86160   dataBufferAppend(pWriter->b, c, n);
86161   pWriter->iPrevDocid = iDocid;
86162 #ifndef NDEBUG
86163   pWriter->has_iPrevDocid = 1;
86164 #endif
86165 }
86166
86167 /*******************************************************************/
86168 /* PLReader is used to read data from a document's position list.  As
86169 ** the caller steps through the list, data is cached so that varints
86170 ** only need to be decoded once.
86171 **
86172 ** plrInit, plrDestroy - create/destroy a reader.
86173 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
86174 ** plrAtEnd - at end of stream, only call plrDestroy once true.
86175 ** plrStep - step to the next element.
86176 */
86177 typedef struct PLReader {
86178   /* These refer to the next position's data.  nData will reach 0 when
86179   ** reading the last position, so plrStep() signals EOF by setting
86180   ** pData to NULL.
86181   */
86182   const char *pData;
86183   int nData;
86184
86185   DocListType iType;
86186   int iColumn;         /* the last column read */
86187   int iPosition;       /* the last position read */
86188   int iStartOffset;    /* the last start offset read */
86189   int iEndOffset;      /* the last end offset read */
86190 } PLReader;
86191
86192 static int plrAtEnd(PLReader *pReader){
86193   return pReader->pData==NULL;
86194 }
86195 static int plrColumn(PLReader *pReader){
86196   assert( !plrAtEnd(pReader) );
86197   return pReader->iColumn;
86198 }
86199 static int plrPosition(PLReader *pReader){
86200   assert( !plrAtEnd(pReader) );
86201   return pReader->iPosition;
86202 }
86203 static int plrStartOffset(PLReader *pReader){
86204   assert( !plrAtEnd(pReader) );
86205   return pReader->iStartOffset;
86206 }
86207 static int plrEndOffset(PLReader *pReader){
86208   assert( !plrAtEnd(pReader) );
86209   return pReader->iEndOffset;
86210 }
86211 static void plrStep(PLReader *pReader){
86212   int i, n;
86213
86214   assert( !plrAtEnd(pReader) );
86215
86216   if( pReader->nData==0 ){
86217     pReader->pData = NULL;
86218     return;
86219   }
86220
86221   n = fts3GetVarint32(pReader->pData, &i);
86222   if( i==POS_COLUMN ){
86223     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
86224     pReader->iPosition = 0;
86225     pReader->iStartOffset = 0;
86226     n += fts3GetVarint32(pReader->pData+n, &i);
86227   }
86228   /* Should never see adjacent column changes. */
86229   assert( i!=POS_COLUMN );
86230
86231   if( i==POS_END ){
86232     pReader->nData = 0;
86233     pReader->pData = NULL;
86234     return;
86235   }
86236
86237   pReader->iPosition += i-POS_BASE;
86238   if( pReader->iType==DL_POSITIONS_OFFSETS ){
86239     n += fts3GetVarint32(pReader->pData+n, &i);
86240     pReader->iStartOffset += i;
86241     n += fts3GetVarint32(pReader->pData+n, &i);
86242     pReader->iEndOffset = pReader->iStartOffset+i;
86243   }
86244   assert( n<=pReader->nData );
86245   pReader->pData += n;
86246   pReader->nData -= n;
86247 }
86248
86249 static void plrInit(PLReader *pReader, DLReader *pDLReader){
86250   pReader->pData = dlrPosData(pDLReader);
86251   pReader->nData = dlrPosDataLen(pDLReader);
86252   pReader->iType = pDLReader->iType;
86253   pReader->iColumn = 0;
86254   pReader->iPosition = 0;
86255   pReader->iStartOffset = 0;
86256   pReader->iEndOffset = 0;
86257   plrStep(pReader);
86258 }
86259 static void plrDestroy(PLReader *pReader){
86260   SCRAMBLE(pReader);
86261 }
86262
86263 /*******************************************************************/
86264 /* PLWriter is used in constructing a document's position list.  As a
86265 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
86266 ** PLWriter writes to the associated DLWriter's buffer.
86267 **
86268 ** plwInit - init for writing a document's poslist.
86269 ** plwDestroy - clear a writer.
86270 ** plwAdd - append position and offset information.
86271 ** plwCopy - copy next position's data from reader to writer.
86272 ** plwTerminate - add any necessary doclist terminator.
86273 **
86274 ** Calling plwAdd() after plwTerminate() may result in a corrupt
86275 ** doclist.
86276 */
86277 /* TODO(shess) Until we've written the second item, we can cache the
86278 ** first item's information.  Then we'd have three states:
86279 **
86280 ** - initialized with docid, no positions.
86281 ** - docid and one position.
86282 ** - docid and multiple positions.
86283 **
86284 ** Only the last state needs to actually write to dlw->b, which would
86285 ** be an improvement in the DLCollector case.
86286 */
86287 typedef struct PLWriter {
86288   DLWriter *dlw;
86289
86290   int iColumn;    /* the last column written */
86291   int iPos;       /* the last position written */
86292   int iOffset;    /* the last start offset written */
86293 } PLWriter;
86294
86295 /* TODO(shess) In the case where the parent is reading these values
86296 ** from a PLReader, we could optimize to a copy if that PLReader has
86297 ** the same type as pWriter.
86298 */
86299 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
86300                    int iStartOffset, int iEndOffset){
86301   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
86302   ** iStartOffsetDelta, and iEndOffsetDelta.
86303   */
86304   char c[5*VARINT_MAX];
86305   int n = 0;
86306
86307   /* Ban plwAdd() after plwTerminate(). */
86308   assert( pWriter->iPos!=-1 );
86309
86310   if( pWriter->dlw->iType==DL_DOCIDS ) return;
86311
86312   if( iColumn!=pWriter->iColumn ){
86313     n += fts3PutVarint(c+n, POS_COLUMN);
86314     n += fts3PutVarint(c+n, iColumn);
86315     pWriter->iColumn = iColumn;
86316     pWriter->iPos = 0;
86317     pWriter->iOffset = 0;
86318   }
86319   assert( iPos>=pWriter->iPos );
86320   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
86321   pWriter->iPos = iPos;
86322   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
86323     assert( iStartOffset>=pWriter->iOffset );
86324     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
86325     pWriter->iOffset = iStartOffset;
86326     assert( iEndOffset>=iStartOffset );
86327     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
86328   }
86329   dataBufferAppend(pWriter->dlw->b, c, n);
86330 }
86331 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
86332   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
86333          plrStartOffset(pReader), plrEndOffset(pReader));
86334 }
86335 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
86336   char c[VARINT_MAX];
86337   int n;
86338
86339   pWriter->dlw = dlw;
86340
86341   /* Docids must ascend. */
86342   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
86343   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
86344   dataBufferAppend(pWriter->dlw->b, c, n);
86345   pWriter->dlw->iPrevDocid = iDocid;
86346 #ifndef NDEBUG
86347   pWriter->dlw->has_iPrevDocid = 1;
86348 #endif
86349
86350   pWriter->iColumn = 0;
86351   pWriter->iPos = 0;
86352   pWriter->iOffset = 0;
86353 }
86354 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
86355 ** then plwDestroy() would no longer be just a destructor, it would
86356 ** also be doing work, which isn't consistent with the overall idiom.
86357 ** Another option would be for plwAdd() to always append any necessary
86358 ** terminator, so that the output is always correct.  But that would
86359 ** add incremental work to the common case with the only benefit being
86360 ** API elegance.  Punt for now.
86361 */
86362 static void plwTerminate(PLWriter *pWriter){
86363   if( pWriter->dlw->iType>DL_DOCIDS ){
86364     char c[VARINT_MAX];
86365     int n = fts3PutVarint(c, POS_END);
86366     dataBufferAppend(pWriter->dlw->b, c, n);
86367   }
86368 #ifndef NDEBUG
86369   /* Mark as terminated for assert in plwAdd(). */
86370   pWriter->iPos = -1;
86371 #endif
86372 }
86373 static void plwDestroy(PLWriter *pWriter){
86374   SCRAMBLE(pWriter);
86375 }
86376
86377 /*******************************************************************/
86378 /* DLCollector wraps PLWriter and DLWriter to provide a
86379 ** dynamically-allocated doclist area to use during tokenization.
86380 **
86381 ** dlcNew - malloc up and initialize a collector.
86382 ** dlcDelete - destroy a collector and all contained items.
86383 ** dlcAddPos - append position and offset information.
86384 ** dlcAddDoclist - add the collected doclist to the given buffer.
86385 ** dlcNext - terminate the current document and open another.
86386 */
86387 typedef struct DLCollector {
86388   DataBuffer b;
86389   DLWriter dlw;
86390   PLWriter plw;
86391 } DLCollector;
86392
86393 /* TODO(shess) This could also be done by calling plwTerminate() and
86394 ** dataBufferAppend().  I tried that, expecting nominal performance
86395 ** differences, but it seemed to pretty reliably be worth 1% to code
86396 ** it this way.  I suspect it is the incremental malloc overhead (some
86397 ** percentage of the plwTerminate() calls will cause a realloc), so
86398 ** this might be worth revisiting if the DataBuffer implementation
86399 ** changes.
86400 */
86401 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
86402   if( pCollector->dlw.iType>DL_DOCIDS ){
86403     char c[VARINT_MAX];
86404     int n = fts3PutVarint(c, POS_END);
86405     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
86406   }else{
86407     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
86408   }
86409 }
86410 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
86411   plwTerminate(&pCollector->plw);
86412   plwDestroy(&pCollector->plw);
86413   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
86414 }
86415 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
86416                       int iStartOffset, int iEndOffset){
86417   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
86418 }
86419
86420 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
86421   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
86422   dataBufferInit(&pCollector->b, 0);
86423   dlwInit(&pCollector->dlw, iType, &pCollector->b);
86424   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
86425   return pCollector;
86426 }
86427 static void dlcDelete(DLCollector *pCollector){
86428   plwDestroy(&pCollector->plw);
86429   dlwDestroy(&pCollector->dlw);
86430   dataBufferDestroy(&pCollector->b);
86431   SCRAMBLE(pCollector);
86432   sqlite3_free(pCollector);
86433 }
86434
86435
86436 /* Copy the doclist data of iType in pData/nData into *out, trimming
86437 ** unnecessary data as we go.  Only columns matching iColumn are
86438 ** copied, all columns copied if iColumn is -1.  Elements with no
86439 ** matching columns are dropped.  The output is an iOutType doclist.
86440 */
86441 /* NOTE(shess) This code is only valid after all doclists are merged.
86442 ** If this is run before merges, then doclist items which represent
86443 ** deletion will be trimmed, and will thus not effect a deletion
86444 ** during the merge.
86445 */
86446 static void docListTrim(DocListType iType, const char *pData, int nData,
86447                         int iColumn, DocListType iOutType, DataBuffer *out){
86448   DLReader dlReader;
86449   DLWriter dlWriter;
86450
86451   assert( iOutType<=iType );
86452
86453   dlrInit(&dlReader, iType, pData, nData);
86454   dlwInit(&dlWriter, iOutType, out);
86455
86456   while( !dlrAtEnd(&dlReader) ){
86457     PLReader plReader;
86458     PLWriter plWriter;
86459     int match = 0;
86460
86461     plrInit(&plReader, &dlReader);
86462
86463     while( !plrAtEnd(&plReader) ){
86464       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
86465         if( !match ){
86466           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
86467           match = 1;
86468         }
86469         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
86470                plrStartOffset(&plReader), plrEndOffset(&plReader));
86471       }
86472       plrStep(&plReader);
86473     }
86474     if( match ){
86475       plwTerminate(&plWriter);
86476       plwDestroy(&plWriter);
86477     }
86478
86479     plrDestroy(&plReader);
86480     dlrStep(&dlReader);
86481   }
86482   dlwDestroy(&dlWriter);
86483   dlrDestroy(&dlReader);
86484 }
86485
86486 /* Used by docListMerge() to keep doclists in the ascending order by
86487 ** docid, then ascending order by age (so the newest comes first).
86488 */
86489 typedef struct OrderedDLReader {
86490   DLReader *pReader;
86491
86492   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
86493   ** age (which we do), then we could use pReader comparisons to break
86494   ** ties.
86495   */
86496   int idx;
86497 } OrderedDLReader;
86498
86499 /* Order eof to end, then by docid asc, idx desc. */
86500 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
86501   if( dlrAtEnd(r1->pReader) ){
86502     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
86503     return 1;                              /* Only r1 atEnd(). */
86504   }
86505   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
86506
86507   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
86508   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
86509
86510   /* Descending on idx. */
86511   return r2->idx-r1->idx;
86512 }
86513
86514 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
86515 ** p[1..n-1] is already sorted.
86516 */
86517 /* TODO(shess) Is this frequent enough to warrant a binary search?
86518 ** Before implementing that, instrument the code to check.  In most
86519 ** current usage, I expect that p[0] will be less than p[1] a very
86520 ** high proportion of the time.
86521 */
86522 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
86523   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
86524     OrderedDLReader tmp = p[0];
86525     p[0] = p[1];
86526     p[1] = tmp;
86527     n--;
86528     p++;
86529   }
86530 }
86531
86532 /* Given an array of doclist readers, merge their doclist elements
86533 ** into out in sorted order (by docid), dropping elements from older
86534 ** readers when there is a duplicate docid.  pReaders is assumed to be
86535 ** ordered by age, oldest first.
86536 */
86537 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
86538 ** be fixed.
86539 */
86540 static void docListMerge(DataBuffer *out,
86541                          DLReader *pReaders, int nReaders){
86542   OrderedDLReader readers[MERGE_COUNT];
86543   DLWriter writer;
86544   int i, n;
86545   const char *pStart = 0;
86546   int nStart = 0;
86547   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
86548
86549   assert( nReaders>0 );
86550   if( nReaders==1 ){
86551     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
86552     return;
86553   }
86554
86555   assert( nReaders<=MERGE_COUNT );
86556   n = 0;
86557   for(i=0; i<nReaders; i++){
86558     assert( pReaders[i].iType==pReaders[0].iType );
86559     readers[i].pReader = pReaders+i;
86560     readers[i].idx = i;
86561     n += dlrAllDataBytes(&pReaders[i]);
86562   }
86563   /* Conservatively size output to sum of inputs.  Output should end
86564   ** up strictly smaller than input.
86565   */
86566   dataBufferExpand(out, n);
86567
86568   /* Get the readers into sorted order. */
86569   while( i-->0 ){
86570     orderedDLReaderReorder(readers+i, nReaders-i);
86571   }
86572
86573   dlwInit(&writer, pReaders[0].iType, out);
86574   while( !dlrAtEnd(readers[0].pReader) ){
86575     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
86576
86577     /* If this is a continuation of the current buffer to copy, extend
86578     ** that buffer.  memcpy() seems to be more efficient if it has a
86579     ** lots of data to copy.
86580     */
86581     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
86582       nStart += dlrDocDataBytes(readers[0].pReader);
86583     }else{
86584       if( pStart!=0 ){
86585         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
86586       }
86587       pStart = dlrDocData(readers[0].pReader);
86588       nStart = dlrDocDataBytes(readers[0].pReader);
86589       iFirstDocid = iDocid;
86590     }
86591     iLastDocid = iDocid;
86592     dlrStep(readers[0].pReader);
86593
86594     /* Drop all of the older elements with the same docid. */
86595     for(i=1; i<nReaders &&
86596              !dlrAtEnd(readers[i].pReader) &&
86597              dlrDocid(readers[i].pReader)==iDocid; i++){
86598       dlrStep(readers[i].pReader);
86599     }
86600
86601     /* Get the readers back into order. */
86602     while( i-->0 ){
86603       orderedDLReaderReorder(readers+i, nReaders-i);
86604     }
86605   }
86606
86607   /* Copy over any remaining elements. */
86608   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
86609   dlwDestroy(&writer);
86610 }
86611
86612 /* Helper function for posListUnion().  Compares the current position
86613 ** between left and right, returning as standard C idiom of <0 if
86614 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
86615 ** compares greater.
86616 */
86617 static int posListCmp(PLReader *pLeft, PLReader *pRight){
86618   assert( pLeft->iType==pRight->iType );
86619   if( pLeft->iType==DL_DOCIDS ) return 0;
86620
86621   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
86622   if( plrAtEnd(pRight) ) return -1;
86623
86624   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
86625   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
86626
86627   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
86628   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
86629   if( pLeft->iType==DL_POSITIONS ) return 0;
86630
86631   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
86632   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
86633
86634   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
86635   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
86636
86637   return 0;
86638 }
86639
86640 /* Write the union of position lists in pLeft and pRight to pOut.
86641 ** "Union" in this case meaning "All unique position tuples".  Should
86642 ** work with any doclist type, though both inputs and the output
86643 ** should be the same type.
86644 */
86645 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
86646   PLReader left, right;
86647   PLWriter writer;
86648
86649   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
86650   assert( pLeft->iType==pRight->iType );
86651   assert( pLeft->iType==pOut->iType );
86652
86653   plrInit(&left, pLeft);
86654   plrInit(&right, pRight);
86655   plwInit(&writer, pOut, dlrDocid(pLeft));
86656
86657   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
86658     int c = posListCmp(&left, &right);
86659     if( c<0 ){
86660       plwCopy(&writer, &left);
86661       plrStep(&left);
86662     }else if( c>0 ){
86663       plwCopy(&writer, &right);
86664       plrStep(&right);
86665     }else{
86666       plwCopy(&writer, &left);
86667       plrStep(&left);
86668       plrStep(&right);
86669     }
86670   }
86671
86672   plwTerminate(&writer);
86673   plwDestroy(&writer);
86674   plrDestroy(&left);
86675   plrDestroy(&right);
86676 }
86677
86678 /* Write the union of doclists in pLeft and pRight to pOut.  For
86679 ** docids in common between the inputs, the union of the position
86680 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
86681 */
86682 static void docListUnion(
86683   const char *pLeft, int nLeft,
86684   const char *pRight, int nRight,
86685   DataBuffer *pOut      /* Write the combined doclist here */
86686 ){
86687   DLReader left, right;
86688   DLWriter writer;
86689
86690   if( nLeft==0 ){
86691     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
86692     return;
86693   }
86694   if( nRight==0 ){
86695     dataBufferAppend(pOut, pLeft, nLeft);
86696     return;
86697   }
86698
86699   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
86700   dlrInit(&right, DL_DEFAULT, pRight, nRight);
86701   dlwInit(&writer, DL_DEFAULT, pOut);
86702
86703   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
86704     if( dlrAtEnd(&right) ){
86705       dlwCopy(&writer, &left);
86706       dlrStep(&left);
86707     }else if( dlrAtEnd(&left) ){
86708       dlwCopy(&writer, &right);
86709       dlrStep(&right);
86710     }else if( dlrDocid(&left)<dlrDocid(&right) ){
86711       dlwCopy(&writer, &left);
86712       dlrStep(&left);
86713     }else if( dlrDocid(&left)>dlrDocid(&right) ){
86714       dlwCopy(&writer, &right);
86715       dlrStep(&right);
86716     }else{
86717       posListUnion(&left, &right, &writer);
86718       dlrStep(&left);
86719       dlrStep(&right);
86720     }
86721   }
86722
86723   dlrDestroy(&left);
86724   dlrDestroy(&right);
86725   dlwDestroy(&writer);
86726 }
86727
86728 /* 
86729 ** This function is used as part of the implementation of phrase and
86730 ** NEAR matching.
86731 **
86732 ** pLeft and pRight are DLReaders positioned to the same docid in
86733 ** lists of type DL_POSITION. This function writes an entry to the
86734 ** DLWriter pOut for each position in pRight that is less than
86735 ** (nNear+1) greater (but not equal to or smaller) than a position 
86736 ** in pLeft. For example, if nNear is 0, and the positions contained
86737 ** by pLeft and pRight are:
86738 **
86739 **    pLeft:  5 10 15 20
86740 **    pRight: 6  9 17 21
86741 **
86742 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
86743 ** then a positionids "6" and "21" are also added to pOut.
86744 **
86745 ** If boolean argument isSaveLeft is true, then positionids are copied
86746 ** from pLeft instead of pRight. In the example above, the positions "5"
86747 ** and "20" would be added instead of "6" and "21".
86748 */
86749 static void posListPhraseMerge(
86750   DLReader *pLeft, 
86751   DLReader *pRight,
86752   int nNear,
86753   int isSaveLeft,
86754   DLWriter *pOut
86755 ){
86756   PLReader left, right;
86757   PLWriter writer;
86758   int match = 0;
86759
86760   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
86761   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
86762
86763   plrInit(&left, pLeft);
86764   plrInit(&right, pRight);
86765
86766   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
86767     if( plrColumn(&left)<plrColumn(&right) ){
86768       plrStep(&left);
86769     }else if( plrColumn(&left)>plrColumn(&right) ){
86770       plrStep(&right);
86771     }else if( plrPosition(&left)>=plrPosition(&right) ){
86772       plrStep(&right);
86773     }else{
86774       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
86775         if( !match ){
86776           plwInit(&writer, pOut, dlrDocid(pLeft));
86777           match = 1;
86778         }
86779         if( !isSaveLeft ){
86780           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
86781         }else{
86782           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
86783         }
86784         plrStep(&right);
86785       }else{
86786         plrStep(&left);
86787       }
86788     }
86789   }
86790
86791   if( match ){
86792     plwTerminate(&writer);
86793     plwDestroy(&writer);
86794   }
86795
86796   plrDestroy(&left);
86797   plrDestroy(&right);
86798 }
86799
86800 /*
86801 ** Compare the values pointed to by the PLReaders passed as arguments. 
86802 ** Return -1 if the value pointed to by pLeft is considered less than
86803 ** the value pointed to by pRight, +1 if it is considered greater
86804 ** than it, or 0 if it is equal. i.e.
86805 **
86806 **     (*pLeft - *pRight)
86807 **
86808 ** A PLReader that is in the EOF condition is considered greater than
86809 ** any other. If neither argument is in EOF state, the return value of
86810 ** plrColumn() is used. If the plrColumn() values are equal, the
86811 ** comparison is on the basis of plrPosition().
86812 */
86813 static int plrCompare(PLReader *pLeft, PLReader *pRight){
86814   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
86815
86816   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
86817     return (plrAtEnd(pRight) ? -1 : 1);
86818   }
86819   if( plrColumn(pLeft)!=plrColumn(pRight) ){
86820     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
86821   }
86822   if( plrPosition(pLeft)!=plrPosition(pRight) ){
86823     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
86824   }
86825   return 0;
86826 }
86827
86828 /* We have two doclists with positions:  pLeft and pRight. Depending
86829 ** on the value of the nNear parameter, perform either a phrase
86830 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
86831 ** and write the results into pOut.
86832 **
86833 ** A phrase intersection means that two documents only match
86834 ** if pLeft.iPos+1==pRight.iPos.
86835 **
86836 ** A NEAR intersection means that two documents only match if 
86837 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
86838 **
86839 ** If a NEAR intersection is requested, then the nPhrase argument should
86840 ** be passed the number of tokens in the two operands to the NEAR operator
86841 ** combined. For example:
86842 **
86843 **       Query syntax               nPhrase
86844 **      ------------------------------------
86845 **       "A B C" NEAR "D E"         5
86846 **       A NEAR B                   2
86847 **
86848 ** iType controls the type of data written to pOut.  If iType is
86849 ** DL_POSITIONS, the positions are those from pRight.
86850 */
86851 static void docListPhraseMerge(
86852   const char *pLeft, int nLeft,
86853   const char *pRight, int nRight,
86854   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
86855   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
86856   DocListType iType,    /* Type of doclist to write to pOut */
86857   DataBuffer *pOut      /* Write the combined doclist here */
86858 ){
86859   DLReader left, right;
86860   DLWriter writer;
86861
86862   if( nLeft==0 || nRight==0 ) return;
86863
86864   assert( iType!=DL_POSITIONS_OFFSETS );
86865
86866   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
86867   dlrInit(&right, DL_POSITIONS, pRight, nRight);
86868   dlwInit(&writer, iType, pOut);
86869
86870   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
86871     if( dlrDocid(&left)<dlrDocid(&right) ){
86872       dlrStep(&left);
86873     }else if( dlrDocid(&right)<dlrDocid(&left) ){
86874       dlrStep(&right);
86875     }else{
86876       if( nNear==0 ){
86877         posListPhraseMerge(&left, &right, 0, 0, &writer);
86878       }else{
86879         /* This case occurs when two terms (simple terms or phrases) are
86880          * connected by a NEAR operator, span (nNear+1). i.e.
86881          *
86882          *     '"terrible company" NEAR widget'
86883          */
86884         DataBuffer one = {0, 0, 0};
86885         DataBuffer two = {0, 0, 0};
86886
86887         DLWriter dlwriter2;
86888         DLReader dr1 = {0, 0, 0, 0, 0}; 
86889         DLReader dr2 = {0, 0, 0, 0, 0};
86890
86891         dlwInit(&dlwriter2, iType, &one);
86892         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
86893         dlwInit(&dlwriter2, iType, &two);
86894         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
86895
86896         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
86897         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
86898
86899         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
86900           PLReader pr1 = {0};
86901           PLReader pr2 = {0};
86902
86903           PLWriter plwriter;
86904           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
86905
86906           if( one.nData ) plrInit(&pr1, &dr1);
86907           if( two.nData ) plrInit(&pr2, &dr2);
86908           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
86909             int iCompare = plrCompare(&pr1, &pr2);
86910             switch( iCompare ){
86911               case -1:
86912                 plwCopy(&plwriter, &pr1);
86913                 plrStep(&pr1);
86914                 break;
86915               case 1:
86916                 plwCopy(&plwriter, &pr2);
86917                 plrStep(&pr2);
86918                 break;
86919               case 0:
86920                 plwCopy(&plwriter, &pr1);
86921                 plrStep(&pr1);
86922                 plrStep(&pr2);
86923                 break;
86924             }
86925           }
86926           plwTerminate(&plwriter);
86927         }
86928         dataBufferDestroy(&one);
86929         dataBufferDestroy(&two);
86930       }
86931       dlrStep(&left);
86932       dlrStep(&right);
86933     }
86934   }
86935
86936   dlrDestroy(&left);
86937   dlrDestroy(&right);
86938   dlwDestroy(&writer);
86939 }
86940
86941 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
86942 ** Write the intersection of these two doclists into pOut as a
86943 ** DL_DOCIDS doclist.
86944 */
86945 static void docListAndMerge(
86946   const char *pLeft, int nLeft,
86947   const char *pRight, int nRight,
86948   DataBuffer *pOut      /* Write the combined doclist here */
86949 ){
86950   DLReader left, right;
86951   DLWriter writer;
86952
86953   if( nLeft==0 || nRight==0 ) return;
86954
86955   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
86956   dlrInit(&right, DL_DOCIDS, pRight, nRight);
86957   dlwInit(&writer, DL_DOCIDS, pOut);
86958
86959   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
86960     if( dlrDocid(&left)<dlrDocid(&right) ){
86961       dlrStep(&left);
86962     }else if( dlrDocid(&right)<dlrDocid(&left) ){
86963       dlrStep(&right);
86964     }else{
86965       dlwAdd(&writer, dlrDocid(&left));
86966       dlrStep(&left);
86967       dlrStep(&right);
86968     }
86969   }
86970
86971   dlrDestroy(&left);
86972   dlrDestroy(&right);
86973   dlwDestroy(&writer);
86974 }
86975
86976 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
86977 ** Write the union of these two doclists into pOut as a
86978 ** DL_DOCIDS doclist.
86979 */
86980 static void docListOrMerge(
86981   const char *pLeft, int nLeft,
86982   const char *pRight, int nRight,
86983   DataBuffer *pOut      /* Write the combined doclist here */
86984 ){
86985   DLReader left, right;
86986   DLWriter writer;
86987
86988   if( nLeft==0 ){
86989     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
86990     return;
86991   }
86992   if( nRight==0 ){
86993     dataBufferAppend(pOut, pLeft, nLeft);
86994     return;
86995   }
86996
86997   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
86998   dlrInit(&right, DL_DOCIDS, pRight, nRight);
86999   dlwInit(&writer, DL_DOCIDS, pOut);
87000
87001   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
87002     if( dlrAtEnd(&right) ){
87003       dlwAdd(&writer, dlrDocid(&left));
87004       dlrStep(&left);
87005     }else if( dlrAtEnd(&left) ){
87006       dlwAdd(&writer, dlrDocid(&right));
87007       dlrStep(&right);
87008     }else if( dlrDocid(&left)<dlrDocid(&right) ){
87009       dlwAdd(&writer, dlrDocid(&left));
87010       dlrStep(&left);
87011     }else if( dlrDocid(&right)<dlrDocid(&left) ){
87012       dlwAdd(&writer, dlrDocid(&right));
87013       dlrStep(&right);
87014     }else{
87015       dlwAdd(&writer, dlrDocid(&left));
87016       dlrStep(&left);
87017       dlrStep(&right);
87018     }
87019   }
87020
87021   dlrDestroy(&left);
87022   dlrDestroy(&right);
87023   dlwDestroy(&writer);
87024 }
87025
87026 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
87027 ** Write into pOut as DL_DOCIDS doclist containing all documents that
87028 ** occur in pLeft but not in pRight.
87029 */
87030 static void docListExceptMerge(
87031   const char *pLeft, int nLeft,
87032   const char *pRight, int nRight,
87033   DataBuffer *pOut      /* Write the combined doclist here */
87034 ){
87035   DLReader left, right;
87036   DLWriter writer;
87037
87038   if( nLeft==0 ) return;
87039   if( nRight==0 ){
87040     dataBufferAppend(pOut, pLeft, nLeft);
87041     return;
87042   }
87043
87044   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
87045   dlrInit(&right, DL_DOCIDS, pRight, nRight);
87046   dlwInit(&writer, DL_DOCIDS, pOut);
87047
87048   while( !dlrAtEnd(&left) ){
87049     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
87050       dlrStep(&right);
87051     }
87052     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
87053       dlwAdd(&writer, dlrDocid(&left));
87054     }
87055     dlrStep(&left);
87056   }
87057
87058   dlrDestroy(&left);
87059   dlrDestroy(&right);
87060   dlwDestroy(&writer);
87061 }
87062
87063 static char *string_dup_n(const char *s, int n){
87064   char *str = sqlite3_malloc(n + 1);
87065   memcpy(str, s, n);
87066   str[n] = '\0';
87067   return str;
87068 }
87069
87070 /* Duplicate a string; the caller must free() the returned string.
87071  * (We don't use strdup() since it is not part of the standard C library and
87072  * may not be available everywhere.) */
87073 static char *string_dup(const char *s){
87074   return string_dup_n(s, strlen(s));
87075 }
87076
87077 /* Format a string, replacing each occurrence of the % character with
87078  * zDb.zName.  This may be more convenient than sqlite_mprintf()
87079  * when one string is used repeatedly in a format string.
87080  * The caller must free() the returned string. */
87081 static char *string_format(const char *zFormat,
87082                            const char *zDb, const char *zName){
87083   const char *p;
87084   size_t len = 0;
87085   size_t nDb = strlen(zDb);
87086   size_t nName = strlen(zName);
87087   size_t nFullTableName = nDb+1+nName;
87088   char *result;
87089   char *r;
87090
87091   /* first compute length needed */
87092   for(p = zFormat ; *p ; ++p){
87093     len += (*p=='%' ? nFullTableName : 1);
87094   }
87095   len += 1;  /* for null terminator */
87096
87097   r = result = sqlite3_malloc(len);
87098   for(p = zFormat; *p; ++p){
87099     if( *p=='%' ){
87100       memcpy(r, zDb, nDb);
87101       r += nDb;
87102       *r++ = '.';
87103       memcpy(r, zName, nName);
87104       r += nName;
87105     } else {
87106       *r++ = *p;
87107     }
87108   }
87109   *r++ = '\0';
87110   assert( r == result + len );
87111   return result;
87112 }
87113
87114 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
87115                     const char *zFormat){
87116   char *zCommand = string_format(zFormat, zDb, zName);
87117   int rc;
87118   FTSTRACE(("FTS3 sql: %s\n", zCommand));
87119   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
87120   sqlite3_free(zCommand);
87121   return rc;
87122 }
87123
87124 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
87125                        sqlite3_stmt **ppStmt, const char *zFormat){
87126   char *zCommand = string_format(zFormat, zDb, zName);
87127   int rc;
87128   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
87129   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
87130   sqlite3_free(zCommand);
87131   return rc;
87132 }
87133
87134 /* end utility functions */
87135
87136 /* Forward reference */
87137 typedef struct fulltext_vtab fulltext_vtab;
87138
87139 /* A single term in a query is represented by an instances of
87140 ** the following structure. Each word which may match against
87141 ** document content is a term. Operators, like NEAR or OR, are
87142 ** not terms. Query terms are organized as a flat list stored
87143 ** in the Query.pTerms array.
87144 **
87145 ** If the QueryTerm.nPhrase variable is non-zero, then the QueryTerm
87146 ** is the first in a contiguous string of terms that are either part
87147 ** of the same phrase, or connected by the NEAR operator.
87148 **
87149 ** If the QueryTerm.nNear variable is non-zero, then the token is followed 
87150 ** by a NEAR operator with span set to (nNear-1). For example, the 
87151 ** following query:
87152 **
87153 ** The QueryTerm.iPhrase variable stores the index of the token within
87154 ** its phrase, indexed starting at 1, or 1 if the token is not part 
87155 ** of any phrase.
87156 **
87157 ** For example, the data structure used to represent the following query:
87158 **
87159 **     ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"'
87160 **
87161 ** is:
87162 **
87163 **     {nPhrase=4, iPhrase=1, nNear=6, pTerm="sqlite"},
87164 **     {nPhrase=0, iPhrase=1, nNear=3, pTerm="google"},
87165 **     {nPhrase=0, iPhrase=1, nNear=0, pTerm="search"},
87166 **     {nPhrase=0, iPhrase=2, nNear=0, pTerm="engine"},
87167 **
87168 ** compiling the FTS3 syntax to Query structures is done by the parseQuery()
87169 ** function.
87170 */
87171 typedef struct QueryTerm {
87172   short int nPhrase; /* How many following terms are part of the same phrase */
87173   short int iPhrase; /* This is the i-th term of a phrase. */
87174   short int iColumn; /* Column of the index that must match this term */
87175   short int nNear;   /* term followed by a NEAR operator with span=(nNear-1) */
87176   signed char isOr;  /* this term is preceded by "OR" */
87177   signed char isNot; /* this term is preceded by "-" */
87178   signed char isPrefix; /* this term is followed by "*" */
87179   char *pTerm;       /* text of the term.  '\000' terminated.  malloced */
87180   int nTerm;         /* Number of bytes in pTerm[] */
87181 } QueryTerm;
87182
87183
87184 /* A query string is parsed into a Query structure.
87185  *
87186  * We could, in theory, allow query strings to be complicated
87187  * nested expressions with precedence determined by parentheses.
87188  * But none of the major search engines do this.  (Perhaps the
87189  * feeling is that an parenthesized expression is two complex of
87190  * an idea for the average user to grasp.)  Taking our lead from
87191  * the major search engines, we will allow queries to be a list
87192  * of terms (with an implied AND operator) or phrases in double-quotes,
87193  * with a single optional "-" before each non-phrase term to designate
87194  * negation and an optional OR connector.
87195  *
87196  * OR binds more tightly than the implied AND, which is what the
87197  * major search engines seem to do.  So, for example:
87198  * 
87199  *    [one two OR three]     ==>    one AND (two OR three)
87200  *    [one OR two three]     ==>    (one OR two) AND three
87201  *
87202  * A "-" before a term matches all entries that lack that term.
87203  * The "-" must occur immediately before the term with in intervening
87204  * space.  This is how the search engines do it.
87205  *
87206  * A NOT term cannot be the right-hand operand of an OR.  If this
87207  * occurs in the query string, the NOT is ignored:
87208  *
87209  *    [one OR -two]          ==>    one OR two
87210  *
87211  */
87212 typedef struct Query {
87213   fulltext_vtab *pFts;  /* The full text index */
87214   int nTerms;           /* Number of terms in the query */
87215   QueryTerm *pTerms;    /* Array of terms.  Space obtained from malloc() */
87216   int nextIsOr;         /* Set the isOr flag on the next inserted term */
87217   int nextIsNear;       /* Set the isOr flag on the next inserted term */
87218   int nextColumn;       /* Next word parsed must be in this column */
87219   int dfltColumn;       /* The default column */
87220 } Query;
87221
87222
87223 /*
87224 ** An instance of the following structure keeps track of generated
87225 ** matching-word offset information and snippets.
87226 */
87227 typedef struct Snippet {
87228   int nMatch;     /* Total number of matches */
87229   int nAlloc;     /* Space allocated for aMatch[] */
87230   struct snippetMatch { /* One entry for each matching term */
87231     char snStatus;       /* Status flag for use while constructing snippets */
87232     short int iCol;      /* The column that contains the match */
87233     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
87234     int iToken;          /* The index of the matching document token */
87235     short int nByte;     /* Number of bytes in the term */
87236     int iStart;          /* The offset to the first character of the term */
87237   } *aMatch;      /* Points to space obtained from malloc */
87238   char *zOffset;  /* Text rendering of aMatch[] */
87239   int nOffset;    /* strlen(zOffset) */
87240   char *zSnippet; /* Snippet text */
87241   int nSnippet;   /* strlen(zSnippet) */
87242 } Snippet;
87243
87244
87245 typedef enum QueryType {
87246   QUERY_GENERIC,   /* table scan */
87247   QUERY_DOCID,     /* lookup by docid */
87248   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
87249 } QueryType;
87250
87251 typedef enum fulltext_statement {
87252   CONTENT_INSERT_STMT,
87253   CONTENT_SELECT_STMT,
87254   CONTENT_UPDATE_STMT,
87255   CONTENT_DELETE_STMT,
87256   CONTENT_EXISTS_STMT,
87257
87258   BLOCK_INSERT_STMT,
87259   BLOCK_SELECT_STMT,
87260   BLOCK_DELETE_STMT,
87261   BLOCK_DELETE_ALL_STMT,
87262
87263   SEGDIR_MAX_INDEX_STMT,
87264   SEGDIR_SET_STMT,
87265   SEGDIR_SELECT_LEVEL_STMT,
87266   SEGDIR_SPAN_STMT,
87267   SEGDIR_DELETE_STMT,
87268   SEGDIR_SELECT_SEGMENT_STMT,
87269   SEGDIR_SELECT_ALL_STMT,
87270   SEGDIR_DELETE_ALL_STMT,
87271   SEGDIR_COUNT_STMT,
87272
87273   MAX_STMT                     /* Always at end! */
87274 } fulltext_statement;
87275
87276 /* These must exactly match the enum above. */
87277 /* TODO(shess): Is there some risk that a statement will be used in two
87278 ** cursors at once, e.g.  if a query joins a virtual table to itself?
87279 ** If so perhaps we should move some of these to the cursor object.
87280 */
87281 static const char *const fulltext_zStatement[MAX_STMT] = {
87282   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
87283   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
87284   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
87285   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
87286   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
87287
87288   /* BLOCK_INSERT */
87289   "insert into %_segments (blockid, block) values (null, ?)",
87290   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
87291   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
87292   /* BLOCK_DELETE_ALL */ "delete from %_segments",
87293
87294   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
87295   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
87296   /* SEGDIR_SELECT_LEVEL */
87297   "select start_block, leaves_end_block, root from %_segdir "
87298   " where level = ? order by idx",
87299   /* SEGDIR_SPAN */
87300   "select min(start_block), max(end_block) from %_segdir "
87301   " where level = ? and start_block <> 0",
87302   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
87303
87304   /* NOTE(shess): The first three results of the following two
87305   ** statements must match.
87306   */
87307   /* SEGDIR_SELECT_SEGMENT */
87308   "select start_block, leaves_end_block, root from %_segdir "
87309   " where level = ? and idx = ?",
87310   /* SEGDIR_SELECT_ALL */
87311   "select start_block, leaves_end_block, root from %_segdir "
87312   " order by level desc, idx asc",
87313   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
87314   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
87315 };
87316
87317 /*
87318 ** A connection to a fulltext index is an instance of the following
87319 ** structure.  The xCreate and xConnect methods create an instance
87320 ** of this structure and xDestroy and xDisconnect free that instance.
87321 ** All other methods receive a pointer to the structure as one of their
87322 ** arguments.
87323 */
87324 struct fulltext_vtab {
87325   sqlite3_vtab base;               /* Base class used by SQLite core */
87326   sqlite3 *db;                     /* The database connection */
87327   const char *zDb;                 /* logical database name */
87328   const char *zName;               /* virtual table name */
87329   int nColumn;                     /* number of columns in virtual table */
87330   char **azColumn;                 /* column names.  malloced */
87331   char **azContentColumn;          /* column names in content table; malloced */
87332   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
87333
87334   /* Precompiled statements which we keep as long as the table is
87335   ** open.
87336   */
87337   sqlite3_stmt *pFulltextStatements[MAX_STMT];
87338
87339   /* Precompiled statements used for segment merges.  We run a
87340   ** separate select across the leaf level of each tree being merged.
87341   */
87342   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
87343   /* The statement used to prepare pLeafSelectStmts. */
87344 #define LEAF_SELECT \
87345   "select block from %_segments where blockid between ? and ? order by blockid"
87346
87347   /* These buffer pending index updates during transactions.
87348   ** nPendingData estimates the memory size of the pending data.  It
87349   ** doesn't include the hash-bucket overhead, nor any malloc
87350   ** overhead.  When nPendingData exceeds kPendingThreshold, the
87351   ** buffer is flushed even before the transaction closes.
87352   ** pendingTerms stores the data, and is only valid when nPendingData
87353   ** is >=0 (nPendingData<0 means pendingTerms has not been
87354   ** initialized).  iPrevDocid is the last docid written, used to make
87355   ** certain we're inserting in sorted order.
87356   */
87357   int nPendingData;
87358 #define kPendingThreshold (1*1024*1024)
87359   sqlite_int64 iPrevDocid;
87360   fts3Hash pendingTerms;
87361 };
87362
87363 /*
87364 ** When the core wants to do a query, it create a cursor using a
87365 ** call to xOpen.  This structure is an instance of a cursor.  It
87366 ** is destroyed by xClose.
87367 */
87368 typedef struct fulltext_cursor {
87369   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
87370   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
87371   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
87372   int eof;                         /* True if at End Of Results */
87373   Query q;                         /* Parsed query string */
87374   Snippet snippet;                 /* Cached snippet for the current row */
87375   int iColumn;                     /* Column being searched */
87376   DataBuffer result;               /* Doclist results from fulltextQuery */
87377   DLReader reader;                 /* Result reader if result not empty */
87378 } fulltext_cursor;
87379
87380 static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
87381   return (fulltext_vtab *) c->base.pVtab;
87382 }
87383
87384 static const sqlite3_module fts3Module;   /* forward declaration */
87385
87386 /* Return a dynamically generated statement of the form
87387  *   insert into %_content (docid, ...) values (?, ...)
87388  */
87389 static const char *contentInsertStatement(fulltext_vtab *v){
87390   StringBuffer sb;
87391   int i;
87392
87393   initStringBuffer(&sb);
87394   append(&sb, "insert into %_content (docid, ");
87395   appendList(&sb, v->nColumn, v->azContentColumn);
87396   append(&sb, ") values (?");
87397   for(i=0; i<v->nColumn; ++i)
87398     append(&sb, ", ?");
87399   append(&sb, ")");
87400   return stringBufferData(&sb);
87401 }
87402
87403 /* Return a dynamically generated statement of the form
87404  *   select <content columns> from %_content where docid = ?
87405  */
87406 static const char *contentSelectStatement(fulltext_vtab *v){
87407   StringBuffer sb;
87408   initStringBuffer(&sb);
87409   append(&sb, "SELECT ");
87410   appendList(&sb, v->nColumn, v->azContentColumn);
87411   append(&sb, " FROM %_content WHERE docid = ?");
87412   return stringBufferData(&sb);
87413 }
87414
87415 /* Return a dynamically generated statement of the form
87416  *   update %_content set [col_0] = ?, [col_1] = ?, ...
87417  *                    where docid = ?
87418  */
87419 static const char *contentUpdateStatement(fulltext_vtab *v){
87420   StringBuffer sb;
87421   int i;
87422
87423   initStringBuffer(&sb);
87424   append(&sb, "update %_content set ");
87425   for(i=0; i<v->nColumn; ++i) {
87426     if( i>0 ){
87427       append(&sb, ", ");
87428     }
87429     append(&sb, v->azContentColumn[i]);
87430     append(&sb, " = ?");
87431   }
87432   append(&sb, " where docid = ?");
87433   return stringBufferData(&sb);
87434 }
87435
87436 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
87437 ** If the indicated statement has never been prepared, it is prepared
87438 ** and cached, otherwise the cached version is reset.
87439 */
87440 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
87441                              sqlite3_stmt **ppStmt){
87442   assert( iStmt<MAX_STMT );
87443   if( v->pFulltextStatements[iStmt]==NULL ){
87444     const char *zStmt;
87445     int rc;
87446     switch( iStmt ){
87447       case CONTENT_INSERT_STMT:
87448         zStmt = contentInsertStatement(v); break;
87449       case CONTENT_SELECT_STMT:
87450         zStmt = contentSelectStatement(v); break;
87451       case CONTENT_UPDATE_STMT:
87452         zStmt = contentUpdateStatement(v); break;
87453       default:
87454         zStmt = fulltext_zStatement[iStmt];
87455     }
87456     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
87457                          zStmt);
87458     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
87459     if( rc!=SQLITE_OK ) return rc;
87460   } else {
87461     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
87462     if( rc!=SQLITE_OK ) return rc;
87463   }
87464
87465   *ppStmt = v->pFulltextStatements[iStmt];
87466   return SQLITE_OK;
87467 }
87468
87469 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
87470 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
87471 ** where we expect no results.
87472 */
87473 static int sql_single_step(sqlite3_stmt *s){
87474   int rc = sqlite3_step(s);
87475   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
87476 }
87477
87478 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
87479 ** statements.  idx -1 is a special case for an uncached version of
87480 ** the statement (used in the optimize implementation).
87481 */
87482 /* TODO(shess) Write version for generic statements and then share
87483 ** that between the cached-statement functions.
87484 */
87485 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
87486                                   sqlite3_stmt **ppStmt){
87487   assert( idx>=-1 && idx<MERGE_COUNT );
87488   if( idx==-1 ){
87489     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
87490   }else if( v->pLeafSelectStmts[idx]==NULL ){
87491     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
87492                          LEAF_SELECT);
87493     if( rc!=SQLITE_OK ) return rc;
87494   }else{
87495     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
87496     if( rc!=SQLITE_OK ) return rc;
87497   }
87498
87499   *ppStmt = v->pLeafSelectStmts[idx];
87500   return SQLITE_OK;
87501 }
87502
87503 /* insert into %_content (docid, ...) values ([docid], [pValues])
87504 ** If the docid contains SQL NULL, then a unique docid will be
87505 ** generated.
87506 */
87507 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
87508                           sqlite3_value **pValues){
87509   sqlite3_stmt *s;
87510   int i;
87511   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
87512   if( rc!=SQLITE_OK ) return rc;
87513
87514   rc = sqlite3_bind_value(s, 1, docid);
87515   if( rc!=SQLITE_OK ) return rc;
87516
87517   for(i=0; i<v->nColumn; ++i){
87518     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
87519     if( rc!=SQLITE_OK ) return rc;
87520   }
87521
87522   return sql_single_step(s);
87523 }
87524
87525 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
87526  *                  where docid = [iDocid] */
87527 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
87528                           sqlite_int64 iDocid){
87529   sqlite3_stmt *s;
87530   int i;
87531   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
87532   if( rc!=SQLITE_OK ) return rc;
87533
87534   for(i=0; i<v->nColumn; ++i){
87535     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
87536     if( rc!=SQLITE_OK ) return rc;
87537   }
87538
87539   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
87540   if( rc!=SQLITE_OK ) return rc;
87541
87542   return sql_single_step(s);
87543 }
87544
87545 static void freeStringArray(int nString, const char **pString){
87546   int i;
87547
87548   for (i=0 ; i < nString ; ++i) {
87549     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
87550   }
87551   sqlite3_free((void *) pString);
87552 }
87553
87554 /* select * from %_content where docid = [iDocid]
87555  * The caller must delete the returned array and all strings in it.
87556  * null fields will be NULL in the returned array.
87557  *
87558  * TODO: Perhaps we should return pointer/length strings here for consistency
87559  * with other code which uses pointer/length. */
87560 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
87561                           const char ***pValues){
87562   sqlite3_stmt *s;
87563   const char **values;
87564   int i;
87565   int rc;
87566
87567   *pValues = NULL;
87568
87569   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
87570   if( rc!=SQLITE_OK ) return rc;
87571
87572   rc = sqlite3_bind_int64(s, 1, iDocid);
87573   if( rc!=SQLITE_OK ) return rc;
87574
87575   rc = sqlite3_step(s);
87576   if( rc!=SQLITE_ROW ) return rc;
87577
87578   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
87579   for(i=0; i<v->nColumn; ++i){
87580     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
87581       values[i] = NULL;
87582     }else{
87583       values[i] = string_dup((char*)sqlite3_column_text(s, i));
87584     }
87585   }
87586
87587   /* We expect only one row.  We must execute another sqlite3_step()
87588    * to complete the iteration; otherwise the table will remain locked. */
87589   rc = sqlite3_step(s);
87590   if( rc==SQLITE_DONE ){
87591     *pValues = values;
87592     return SQLITE_OK;
87593   }
87594
87595   freeStringArray(v->nColumn, values);
87596   return rc;
87597 }
87598
87599 /* delete from %_content where docid = [iDocid ] */
87600 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
87601   sqlite3_stmt *s;
87602   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
87603   if( rc!=SQLITE_OK ) return rc;
87604
87605   rc = sqlite3_bind_int64(s, 1, iDocid);
87606   if( rc!=SQLITE_OK ) return rc;
87607
87608   return sql_single_step(s);
87609 }
87610
87611 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
87612 ** no rows exist, and any error in case of failure.
87613 */
87614 static int content_exists(fulltext_vtab *v){
87615   sqlite3_stmt *s;
87616   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
87617   if( rc!=SQLITE_OK ) return rc;
87618
87619   rc = sqlite3_step(s);
87620   if( rc!=SQLITE_ROW ) return rc;
87621
87622   /* We expect only one row.  We must execute another sqlite3_step()
87623    * to complete the iteration; otherwise the table will remain locked. */
87624   rc = sqlite3_step(s);
87625   if( rc==SQLITE_DONE ) return SQLITE_ROW;
87626   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87627   return rc;
87628 }
87629
87630 /* insert into %_segments values ([pData])
87631 **   returns assigned blockid in *piBlockid
87632 */
87633 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
87634                         sqlite_int64 *piBlockid){
87635   sqlite3_stmt *s;
87636   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
87637   if( rc!=SQLITE_OK ) return rc;
87638
87639   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
87640   if( rc!=SQLITE_OK ) return rc;
87641
87642   rc = sqlite3_step(s);
87643   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87644   if( rc!=SQLITE_DONE ) return rc;
87645
87646   /* blockid column is an alias for rowid. */
87647   *piBlockid = sqlite3_last_insert_rowid(v->db);
87648   return SQLITE_OK;
87649 }
87650
87651 /* delete from %_segments
87652 **   where blockid between [iStartBlockid] and [iEndBlockid]
87653 **
87654 ** Deletes the range of blocks, inclusive, used to delete the blocks
87655 ** which form a segment.
87656 */
87657 static int block_delete(fulltext_vtab *v,
87658                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
87659   sqlite3_stmt *s;
87660   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
87661   if( rc!=SQLITE_OK ) return rc;
87662
87663   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
87664   if( rc!=SQLITE_OK ) return rc;
87665
87666   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
87667   if( rc!=SQLITE_OK ) return rc;
87668
87669   return sql_single_step(s);
87670 }
87671
87672 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
87673 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
87674 ** iLevel.  Otherwise returns an error.
87675 */
87676 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
87677   sqlite3_stmt *s;
87678   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
87679   if( rc!=SQLITE_OK ) return rc;
87680
87681   rc = sqlite3_bind_int(s, 1, iLevel);
87682   if( rc!=SQLITE_OK ) return rc;
87683
87684   rc = sqlite3_step(s);
87685   /* Should always get at least one row due to how max() works. */
87686   if( rc==SQLITE_DONE ) return SQLITE_DONE;
87687   if( rc!=SQLITE_ROW ) return rc;
87688
87689   /* NULL means that there were no inputs to max(). */
87690   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
87691     rc = sqlite3_step(s);
87692     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87693     return rc;
87694   }
87695
87696   *pidx = sqlite3_column_int(s, 0);
87697
87698   /* We expect only one row.  We must execute another sqlite3_step()
87699    * to complete the iteration; otherwise the table will remain locked. */
87700   rc = sqlite3_step(s);
87701   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87702   if( rc!=SQLITE_DONE ) return rc;
87703   return SQLITE_ROW;
87704 }
87705
87706 /* insert into %_segdir values (
87707 **   [iLevel], [idx],
87708 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
87709 **   [pRootData]
87710 ** )
87711 */
87712 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
87713                       sqlite_int64 iStartBlockid,
87714                       sqlite_int64 iLeavesEndBlockid,
87715                       sqlite_int64 iEndBlockid,
87716                       const char *pRootData, int nRootData){
87717   sqlite3_stmt *s;
87718   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
87719   if( rc!=SQLITE_OK ) return rc;
87720
87721   rc = sqlite3_bind_int(s, 1, iLevel);
87722   if( rc!=SQLITE_OK ) return rc;
87723
87724   rc = sqlite3_bind_int(s, 2, idx);
87725   if( rc!=SQLITE_OK ) return rc;
87726
87727   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
87728   if( rc!=SQLITE_OK ) return rc;
87729
87730   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
87731   if( rc!=SQLITE_OK ) return rc;
87732
87733   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
87734   if( rc!=SQLITE_OK ) return rc;
87735
87736   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
87737   if( rc!=SQLITE_OK ) return rc;
87738
87739   return sql_single_step(s);
87740 }
87741
87742 /* Queries %_segdir for the block span of the segments in level
87743 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
87744 ** SQLITE_ROW if there are blocks, else an error.
87745 */
87746 static int segdir_span(fulltext_vtab *v, int iLevel,
87747                        sqlite_int64 *piStartBlockid,
87748                        sqlite_int64 *piEndBlockid){
87749   sqlite3_stmt *s;
87750   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
87751   if( rc!=SQLITE_OK ) return rc;
87752
87753   rc = sqlite3_bind_int(s, 1, iLevel);
87754   if( rc!=SQLITE_OK ) return rc;
87755
87756   rc = sqlite3_step(s);
87757   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
87758   if( rc!=SQLITE_ROW ) return rc;
87759
87760   /* This happens if all segments at this level are entirely inline. */
87761   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
87762     /* We expect only one row.  We must execute another sqlite3_step()
87763      * to complete the iteration; otherwise the table will remain locked. */
87764     int rc2 = sqlite3_step(s);
87765     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
87766     return rc2;
87767   }
87768
87769   *piStartBlockid = sqlite3_column_int64(s, 0);
87770   *piEndBlockid = sqlite3_column_int64(s, 1);
87771
87772   /* We expect only one row.  We must execute another sqlite3_step()
87773    * to complete the iteration; otherwise the table will remain locked. */
87774   rc = sqlite3_step(s);
87775   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87776   if( rc!=SQLITE_DONE ) return rc;
87777   return SQLITE_ROW;
87778 }
87779
87780 /* Delete the segment blocks and segment directory records for all
87781 ** segments at iLevel.
87782 */
87783 static int segdir_delete(fulltext_vtab *v, int iLevel){
87784   sqlite3_stmt *s;
87785   sqlite_int64 iStartBlockid, iEndBlockid;
87786   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
87787   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
87788
87789   if( rc==SQLITE_ROW ){
87790     rc = block_delete(v, iStartBlockid, iEndBlockid);
87791     if( rc!=SQLITE_OK ) return rc;
87792   }
87793
87794   /* Delete the segment directory itself. */
87795   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
87796   if( rc!=SQLITE_OK ) return rc;
87797
87798   rc = sqlite3_bind_int64(s, 1, iLevel);
87799   if( rc!=SQLITE_OK ) return rc;
87800
87801   return sql_single_step(s);
87802 }
87803
87804 /* Delete entire fts index, SQLITE_OK on success, relevant error on
87805 ** failure.
87806 */
87807 static int segdir_delete_all(fulltext_vtab *v){
87808   sqlite3_stmt *s;
87809   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
87810   if( rc!=SQLITE_OK ) return rc;
87811
87812   rc = sql_single_step(s);
87813   if( rc!=SQLITE_OK ) return rc;
87814
87815   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
87816   if( rc!=SQLITE_OK ) return rc;
87817
87818   return sql_single_step(s);
87819 }
87820
87821 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
87822 ** %_segdir and *piMaxLevel set to the highest level which has a
87823 ** segment.  Otherwise returns the SQLite error which caused failure.
87824 */
87825 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
87826   sqlite3_stmt *s;
87827   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
87828   if( rc!=SQLITE_OK ) return rc;
87829
87830   rc = sqlite3_step(s);
87831   /* TODO(shess): This case should not be possible?  Should stronger
87832   ** measures be taken if it happens?
87833   */
87834   if( rc==SQLITE_DONE ){
87835     *pnSegments = 0;
87836     *piMaxLevel = 0;
87837     return SQLITE_OK;
87838   }
87839   if( rc!=SQLITE_ROW ) return rc;
87840
87841   *pnSegments = sqlite3_column_int(s, 0);
87842   *piMaxLevel = sqlite3_column_int(s, 1);
87843
87844   /* We expect only one row.  We must execute another sqlite3_step()
87845    * to complete the iteration; otherwise the table will remain locked. */
87846   rc = sqlite3_step(s);
87847   if( rc==SQLITE_DONE ) return SQLITE_OK;
87848   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
87849   return rc;
87850 }
87851
87852 /* TODO(shess) clearPendingTerms() is far down the file because
87853 ** writeZeroSegment() is far down the file because LeafWriter is far
87854 ** down the file.  Consider refactoring the code to move the non-vtab
87855 ** code above the vtab code so that we don't need this forward
87856 ** reference.
87857 */
87858 static int clearPendingTerms(fulltext_vtab *v);
87859
87860 /*
87861 ** Free the memory used to contain a fulltext_vtab structure.
87862 */
87863 static void fulltext_vtab_destroy(fulltext_vtab *v){
87864   int iStmt, i;
87865
87866   FTSTRACE(("FTS3 Destroy %p\n", v));
87867   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
87868     if( v->pFulltextStatements[iStmt]!=NULL ){
87869       sqlite3_finalize(v->pFulltextStatements[iStmt]);
87870       v->pFulltextStatements[iStmt] = NULL;
87871     }
87872   }
87873
87874   for( i=0; i<MERGE_COUNT; i++ ){
87875     if( v->pLeafSelectStmts[i]!=NULL ){
87876       sqlite3_finalize(v->pLeafSelectStmts[i]);
87877       v->pLeafSelectStmts[i] = NULL;
87878     }
87879   }
87880
87881   if( v->pTokenizer!=NULL ){
87882     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
87883     v->pTokenizer = NULL;
87884   }
87885
87886   clearPendingTerms(v);
87887
87888   sqlite3_free(v->azColumn);
87889   for(i = 0; i < v->nColumn; ++i) {
87890     sqlite3_free(v->azContentColumn[i]);
87891   }
87892   sqlite3_free(v->azContentColumn);
87893   sqlite3_free(v);
87894 }
87895
87896 /*
87897 ** Token types for parsing the arguments to xConnect or xCreate.
87898 */
87899 #define TOKEN_EOF         0    /* End of file */
87900 #define TOKEN_SPACE       1    /* Any kind of whitespace */
87901 #define TOKEN_ID          2    /* An identifier */
87902 #define TOKEN_STRING      3    /* A string literal */
87903 #define TOKEN_PUNCT       4    /* A single punctuation character */
87904
87905 /*
87906 ** If X is a character that can be used in an identifier then
87907 ** ftsIdChar(X) will be true.  Otherwise it is false.
87908 **
87909 ** For ASCII, any character with the high-order bit set is
87910 ** allowed in an identifier.  For 7-bit characters, 
87911 ** isFtsIdChar[X] must be 1.
87912 **
87913 ** Ticket #1066.  the SQL standard does not allow '$' in the
87914 ** middle of identfiers.  But many SQL implementations do. 
87915 ** SQLite will allow '$' in identifiers for compatibility.
87916 ** But the feature is undocumented.
87917 */
87918 static const char isFtsIdChar[] = {
87919 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
87920     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
87921     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
87922     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
87923     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
87924     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
87925     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
87926 };
87927 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
87928
87929
87930 /*
87931 ** Return the length of the token that begins at z[0]. 
87932 ** Store the token type in *tokenType before returning.
87933 */
87934 static int ftsGetToken(const char *z, int *tokenType){
87935   int i, c;
87936   switch( *z ){
87937     case 0: {
87938       *tokenType = TOKEN_EOF;
87939       return 0;
87940     }
87941     case ' ': case '\t': case '\n': case '\f': case '\r': {
87942       for(i=1; safe_isspace(z[i]); i++){}
87943       *tokenType = TOKEN_SPACE;
87944       return i;
87945     }
87946     case '`':
87947     case '\'':
87948     case '"': {
87949       int delim = z[0];
87950       for(i=1; (c=z[i])!=0; i++){
87951         if( c==delim ){
87952           if( z[i+1]==delim ){
87953             i++;
87954           }else{
87955             break;
87956           }
87957         }
87958       }
87959       *tokenType = TOKEN_STRING;
87960       return i + (c!=0);
87961     }
87962     case '[': {
87963       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
87964       *tokenType = TOKEN_ID;
87965       return i;
87966     }
87967     default: {
87968       if( !ftsIdChar(*z) ){
87969         break;
87970       }
87971       for(i=1; ftsIdChar(z[i]); i++){}
87972       *tokenType = TOKEN_ID;
87973       return i;
87974     }
87975   }
87976   *tokenType = TOKEN_PUNCT;
87977   return 1;
87978 }
87979
87980 /*
87981 ** A token extracted from a string is an instance of the following
87982 ** structure.
87983 */
87984 typedef struct FtsToken {
87985   const char *z;       /* Pointer to token text.  Not '\000' terminated */
87986   short int n;         /* Length of the token text in bytes. */
87987 } FtsToken;
87988
87989 /*
87990 ** Given a input string (which is really one of the argv[] parameters
87991 ** passed into xConnect or xCreate) split the string up into tokens.
87992 ** Return an array of pointers to '\000' terminated strings, one string
87993 ** for each non-whitespace token.
87994 **
87995 ** The returned array is terminated by a single NULL pointer.
87996 **
87997 ** Space to hold the returned array is obtained from a single
87998 ** malloc and should be freed by passing the return value to free().
87999 ** The individual strings within the token list are all a part of
88000 ** the single memory allocation and will all be freed at once.
88001 */
88002 static char **tokenizeString(const char *z, int *pnToken){
88003   int nToken = 0;
88004   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
88005   int n = 1;
88006   int e, i;
88007   int totalSize = 0;
88008   char **azToken;
88009   char *zCopy;
88010   while( n>0 ){
88011     n = ftsGetToken(z, &e);
88012     if( e!=TOKEN_SPACE ){
88013       aToken[nToken].z = z;
88014       aToken[nToken].n = n;
88015       nToken++;
88016       totalSize += n+1;
88017     }
88018     z += n;
88019   }
88020   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
88021   zCopy = (char*)&azToken[nToken];
88022   nToken--;
88023   for(i=0; i<nToken; i++){
88024     azToken[i] = zCopy;
88025     n = aToken[i].n;
88026     memcpy(zCopy, aToken[i].z, n);
88027     zCopy[n] = 0;
88028     zCopy += n+1;
88029   }
88030   azToken[nToken] = 0;
88031   sqlite3_free(aToken);
88032   *pnToken = nToken;
88033   return azToken;
88034 }
88035
88036 /*
88037 ** Convert an SQL-style quoted string into a normal string by removing
88038 ** the quote characters.  The conversion is done in-place.  If the
88039 ** input does not begin with a quote character, then this routine
88040 ** is a no-op.
88041 **
88042 ** Examples:
88043 **
88044 **     "abc"   becomes   abc
88045 **     'xyz'   becomes   xyz
88046 **     [pqr]   becomes   pqr
88047 **     `mno`   becomes   mno
88048 */
88049 static void dequoteString(char *z){
88050   int quote;
88051   int i, j;
88052   if( z==0 ) return;
88053   quote = z[0];
88054   switch( quote ){
88055     case '\'':  break;
88056     case '"':   break;
88057     case '`':   break;                /* For MySQL compatibility */
88058     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
88059     default:    return;
88060   }
88061   for(i=1, j=0; z[i]; i++){
88062     if( z[i]==quote ){
88063       if( z[i+1]==quote ){
88064         z[j++] = quote;
88065         i++;
88066       }else{
88067         z[j++] = 0;
88068         break;
88069       }
88070     }else{
88071       z[j++] = z[i];
88072     }
88073   }
88074 }
88075
88076 /*
88077 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
88078 ** token and all punctuation tokens.  Remove the quotes from
88079 ** around string literal tokens.
88080 **
88081 ** Example:
88082 **
88083 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
88084 **     output:     chinese simplifed mixed
88085 **
88086 ** Another example:
88087 **
88088 **     input:      delimiters ( '[' , ']' , '...' )
88089 **     output:     [ ] ...
88090 */
88091 static void tokenListToIdList(char **azIn){
88092   int i, j;
88093   if( azIn ){
88094     for(i=0, j=-1; azIn[i]; i++){
88095       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
88096         dequoteString(azIn[i]);
88097         if( j>=0 ){
88098           azIn[j] = azIn[i];
88099         }
88100         j++;
88101       }
88102     }
88103     azIn[j] = 0;
88104   }
88105 }
88106
88107
88108 /*
88109 ** Find the first alphanumeric token in the string zIn.  Null-terminate
88110 ** this token.  Remove any quotation marks.  And return a pointer to
88111 ** the result.
88112 */
88113 static char *firstToken(char *zIn, char **pzTail){
88114   int n, ttype;
88115   while(1){
88116     n = ftsGetToken(zIn, &ttype);
88117     if( ttype==TOKEN_SPACE ){
88118       zIn += n;
88119     }else if( ttype==TOKEN_EOF ){
88120       *pzTail = zIn;
88121       return 0;
88122     }else{
88123       zIn[n] = 0;
88124       *pzTail = &zIn[1];
88125       dequoteString(zIn);
88126       return zIn;
88127     }
88128   }
88129   /*NOTREACHED*/
88130 }
88131
88132 /* Return true if...
88133 **
88134 **   *  s begins with the string t, ignoring case
88135 **   *  s is longer than t
88136 **   *  The first character of s beyond t is not a alphanumeric
88137 ** 
88138 ** Ignore leading space in *s.
88139 **
88140 ** To put it another way, return true if the first token of
88141 ** s[] is t[].
88142 */
88143 static int startsWith(const char *s, const char *t){
88144   while( safe_isspace(*s) ){ s++; }
88145   while( *t ){
88146     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
88147   }
88148   return *s!='_' && !safe_isalnum(*s);
88149 }
88150
88151 /*
88152 ** An instance of this structure defines the "spec" of a
88153 ** full text index.  This structure is populated by parseSpec
88154 ** and use by fulltextConnect and fulltextCreate.
88155 */
88156 typedef struct TableSpec {
88157   const char *zDb;         /* Logical database name */
88158   const char *zName;       /* Name of the full-text index */
88159   int nColumn;             /* Number of columns to be indexed */
88160   char **azColumn;         /* Original names of columns to be indexed */
88161   char **azContentColumn;  /* Column names for %_content */
88162   char **azTokenizer;      /* Name of tokenizer and its arguments */
88163 } TableSpec;
88164
88165 /*
88166 ** Reclaim all of the memory used by a TableSpec
88167 */
88168 static void clearTableSpec(TableSpec *p) {
88169   sqlite3_free(p->azColumn);
88170   sqlite3_free(p->azContentColumn);
88171   sqlite3_free(p->azTokenizer);
88172 }
88173
88174 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
88175  *
88176  * CREATE VIRTUAL TABLE email
88177  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
88178  *
88179  * We return parsed information in a TableSpec structure.
88180  * 
88181  */
88182 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
88183                      char**pzErr){
88184   int i, n;
88185   char *z, *zDummy;
88186   char **azArg;
88187   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
88188
88189   assert( argc>=3 );
88190   /* Current interface:
88191   ** argv[0] - module name
88192   ** argv[1] - database name
88193   ** argv[2] - table name
88194   ** argv[3..] - columns, optionally followed by tokenizer specification
88195   **             and snippet delimiters specification.
88196   */
88197
88198   /* Make a copy of the complete argv[][] array in a single allocation.
88199   ** The argv[][] array is read-only and transient.  We can write to the
88200   ** copy in order to modify things and the copy is persistent.
88201   */
88202   CLEAR(pSpec);
88203   for(i=n=0; i<argc; i++){
88204     n += strlen(argv[i]) + 1;
88205   }
88206   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
88207   if( azArg==0 ){
88208     return SQLITE_NOMEM;
88209   }
88210   z = (char*)&azArg[argc];
88211   for(i=0; i<argc; i++){
88212     azArg[i] = z;
88213     strcpy(z, argv[i]);
88214     z += strlen(z)+1;
88215   }
88216
88217   /* Identify the column names and the tokenizer and delimiter arguments
88218   ** in the argv[][] array.
88219   */
88220   pSpec->zDb = azArg[1];
88221   pSpec->zName = azArg[2];
88222   pSpec->nColumn = 0;
88223   pSpec->azColumn = azArg;
88224   zTokenizer = "tokenize simple";
88225   for(i=3; i<argc; ++i){
88226     if( startsWith(azArg[i],"tokenize") ){
88227       zTokenizer = azArg[i];
88228     }else{
88229       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
88230       pSpec->nColumn++;
88231     }
88232   }
88233   if( pSpec->nColumn==0 ){
88234     azArg[0] = "content";
88235     pSpec->nColumn = 1;
88236   }
88237
88238   /*
88239   ** Construct the list of content column names.
88240   **
88241   ** Each content column name will be of the form cNNAAAA
88242   ** where NN is the column number and AAAA is the sanitized
88243   ** column name.  "sanitized" means that special characters are
88244   ** converted to "_".  The cNN prefix guarantees that all column
88245   ** names are unique.
88246   **
88247   ** The AAAA suffix is not strictly necessary.  It is included
88248   ** for the convenience of people who might examine the generated
88249   ** %_content table and wonder what the columns are used for.
88250   */
88251   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
88252   if( pSpec->azContentColumn==0 ){
88253     clearTableSpec(pSpec);
88254     return SQLITE_NOMEM;
88255   }
88256   for(i=0; i<pSpec->nColumn; i++){
88257     char *p;
88258     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
88259     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
88260       if( !safe_isalnum(*p) ) *p = '_';
88261     }
88262   }
88263
88264   /*
88265   ** Parse the tokenizer specification string.
88266   */
88267   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
88268   tokenListToIdList(pSpec->azTokenizer);
88269
88270   return SQLITE_OK;
88271 }
88272
88273 /*
88274 ** Generate a CREATE TABLE statement that describes the schema of
88275 ** the virtual table.  Return a pointer to this schema string.
88276 **
88277 ** Space is obtained from sqlite3_mprintf() and should be freed
88278 ** using sqlite3_free().
88279 */
88280 static char *fulltextSchema(
88281   int nColumn,                  /* Number of columns */
88282   const char *const* azColumn,  /* List of columns */
88283   const char *zTableName        /* Name of the table */
88284 ){
88285   int i;
88286   char *zSchema, *zNext;
88287   const char *zSep = "(";
88288   zSchema = sqlite3_mprintf("CREATE TABLE x");
88289   for(i=0; i<nColumn; i++){
88290     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
88291     sqlite3_free(zSchema);
88292     zSchema = zNext;
88293     zSep = ",";
88294   }
88295   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
88296   sqlite3_free(zSchema);
88297   zSchema = zNext;
88298   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
88299   sqlite3_free(zSchema);
88300   return zNext;
88301 }
88302
88303 /*
88304 ** Build a new sqlite3_vtab structure that will describe the
88305 ** fulltext index defined by spec.
88306 */
88307 static int constructVtab(
88308   sqlite3 *db,              /* The SQLite database connection */
88309   fts3Hash *pHash,          /* Hash table containing tokenizers */
88310   TableSpec *spec,          /* Parsed spec information from parseSpec() */
88311   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
88312   char **pzErr              /* Write any error message here */
88313 ){
88314   int rc;
88315   int n;
88316   fulltext_vtab *v = 0;
88317   const sqlite3_tokenizer_module *m = NULL;
88318   char *schema;
88319
88320   char const *zTok;         /* Name of tokenizer to use for this fts table */
88321   int nTok;                 /* Length of zTok, including nul terminator */
88322
88323   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
88324   if( v==0 ) return SQLITE_NOMEM;
88325   CLEAR(v);
88326   /* sqlite will initialize v->base */
88327   v->db = db;
88328   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
88329   v->zName = spec->zName;   /* Freed when azColumn is freed */
88330   v->nColumn = spec->nColumn;
88331   v->azContentColumn = spec->azContentColumn;
88332   spec->azContentColumn = 0;
88333   v->azColumn = spec->azColumn;
88334   spec->azColumn = 0;
88335
88336   if( spec->azTokenizer==0 ){
88337     return SQLITE_NOMEM;
88338   }
88339
88340   zTok = spec->azTokenizer[0]; 
88341   if( !zTok ){
88342     zTok = "simple";
88343   }
88344   nTok = strlen(zTok)+1;
88345
88346   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
88347   if( !m ){
88348     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
88349     rc = SQLITE_ERROR;
88350     goto err;
88351   }
88352
88353   for(n=0; spec->azTokenizer[n]; n++){}
88354   if( n ){
88355     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
88356                     &v->pTokenizer);
88357   }else{
88358     rc = m->xCreate(0, 0, &v->pTokenizer);
88359   }
88360   if( rc!=SQLITE_OK ) goto err;
88361   v->pTokenizer->pModule = m;
88362
88363   /* TODO: verify the existence of backing tables foo_content, foo_term */
88364
88365   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
88366                           spec->zName);
88367   rc = sqlite3_declare_vtab(db, schema);
88368   sqlite3_free(schema);
88369   if( rc!=SQLITE_OK ) goto err;
88370
88371   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
88372
88373   /* Indicate that the buffer is not live. */
88374   v->nPendingData = -1;
88375
88376   *ppVTab = &v->base;
88377   FTSTRACE(("FTS3 Connect %p\n", v));
88378
88379   return rc;
88380
88381 err:
88382   fulltext_vtab_destroy(v);
88383   return rc;
88384 }
88385
88386 static int fulltextConnect(
88387   sqlite3 *db,
88388   void *pAux,
88389   int argc, const char *const*argv,
88390   sqlite3_vtab **ppVTab,
88391   char **pzErr
88392 ){
88393   TableSpec spec;
88394   int rc = parseSpec(&spec, argc, argv, pzErr);
88395   if( rc!=SQLITE_OK ) return rc;
88396
88397   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
88398   clearTableSpec(&spec);
88399   return rc;
88400 }
88401
88402 /* The %_content table holds the text of each document, with
88403 ** the docid column exposed as the SQLite rowid for the table.
88404 */
88405 /* TODO(shess) This comment needs elaboration to match the updated
88406 ** code.  Work it into the top-of-file comment at that time.
88407 */
88408 static int fulltextCreate(sqlite3 *db, void *pAux,
88409                           int argc, const char * const *argv,
88410                           sqlite3_vtab **ppVTab, char **pzErr){
88411   int rc;
88412   TableSpec spec;
88413   StringBuffer schema;
88414   FTSTRACE(("FTS3 Create\n"));
88415
88416   rc = parseSpec(&spec, argc, argv, pzErr);
88417   if( rc!=SQLITE_OK ) return rc;
88418
88419   initStringBuffer(&schema);
88420   append(&schema, "CREATE TABLE %_content(");
88421   append(&schema, "  docid INTEGER PRIMARY KEY,");
88422   appendList(&schema, spec.nColumn, spec.azContentColumn);
88423   append(&schema, ")");
88424   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
88425   stringBufferDestroy(&schema);
88426   if( rc!=SQLITE_OK ) goto out;
88427
88428   rc = sql_exec(db, spec.zDb, spec.zName,
88429                 "create table %_segments("
88430                 "  blockid INTEGER PRIMARY KEY,"
88431                 "  block blob"
88432                 ");"
88433                 );
88434   if( rc!=SQLITE_OK ) goto out;
88435
88436   rc = sql_exec(db, spec.zDb, spec.zName,
88437                 "create table %_segdir("
88438                 "  level integer,"
88439                 "  idx integer,"
88440                 "  start_block integer,"
88441                 "  leaves_end_block integer,"
88442                 "  end_block integer,"
88443                 "  root blob,"
88444                 "  primary key(level, idx)"
88445                 ");");
88446   if( rc!=SQLITE_OK ) goto out;
88447
88448   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
88449
88450 out:
88451   clearTableSpec(&spec);
88452   return rc;
88453 }
88454
88455 /* Decide how to handle an SQL query. */
88456 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
88457   fulltext_vtab *v = (fulltext_vtab *)pVTab;
88458   int i;
88459   FTSTRACE(("FTS3 BestIndex\n"));
88460
88461   for(i=0; i<pInfo->nConstraint; ++i){
88462     const struct sqlite3_index_constraint *pConstraint;
88463     pConstraint = &pInfo->aConstraint[i];
88464     if( pConstraint->usable ) {
88465       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
88466           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
88467         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
88468         FTSTRACE(("FTS3 QUERY_DOCID\n"));
88469       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
88470                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
88471         /* full-text search */
88472         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
88473         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
88474       } else continue;
88475
88476       pInfo->aConstraintUsage[i].argvIndex = 1;
88477       pInfo->aConstraintUsage[i].omit = 1;
88478
88479       /* An arbitrary value for now.
88480        * TODO: Perhaps docid matches should be considered cheaper than
88481        * full-text searches. */
88482       pInfo->estimatedCost = 1.0;   
88483
88484       return SQLITE_OK;
88485     }
88486   }
88487   pInfo->idxNum = QUERY_GENERIC;
88488   return SQLITE_OK;
88489 }
88490
88491 static int fulltextDisconnect(sqlite3_vtab *pVTab){
88492   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
88493   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
88494   return SQLITE_OK;
88495 }
88496
88497 static int fulltextDestroy(sqlite3_vtab *pVTab){
88498   fulltext_vtab *v = (fulltext_vtab *)pVTab;
88499   int rc;
88500
88501   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
88502   rc = sql_exec(v->db, v->zDb, v->zName,
88503                 "drop table if exists %_content;"
88504                 "drop table if exists %_segments;"
88505                 "drop table if exists %_segdir;"
88506                 );
88507   if( rc!=SQLITE_OK ) return rc;
88508
88509   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
88510   return SQLITE_OK;
88511 }
88512
88513 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
88514   fulltext_cursor *c;
88515
88516   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
88517   if( c ){
88518     memset(c, 0, sizeof(fulltext_cursor));
88519     /* sqlite will initialize c->base */
88520     *ppCursor = &c->base;
88521     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
88522     return SQLITE_OK;
88523   }else{
88524     return SQLITE_NOMEM;
88525   }
88526 }
88527
88528
88529 /* Free all of the dynamically allocated memory held by *q
88530 */
88531 static void queryClear(Query *q){
88532   int i;
88533   for(i = 0; i < q->nTerms; ++i){
88534     sqlite3_free(q->pTerms[i].pTerm);
88535   }
88536   sqlite3_free(q->pTerms);
88537   CLEAR(q);
88538 }
88539
88540 /* Free all of the dynamically allocated memory held by the
88541 ** Snippet
88542 */
88543 static void snippetClear(Snippet *p){
88544   sqlite3_free(p->aMatch);
88545   sqlite3_free(p->zOffset);
88546   sqlite3_free(p->zSnippet);
88547   CLEAR(p);
88548 }
88549 /*
88550 ** Append a single entry to the p->aMatch[] log.
88551 */
88552 static void snippetAppendMatch(
88553   Snippet *p,               /* Append the entry to this snippet */
88554   int iCol, int iTerm,      /* The column and query term */
88555   int iToken,               /* Matching token in document */
88556   int iStart, int nByte     /* Offset and size of the match */
88557 ){
88558   int i;
88559   struct snippetMatch *pMatch;
88560   if( p->nMatch+1>=p->nAlloc ){
88561     p->nAlloc = p->nAlloc*2 + 10;
88562     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
88563     if( p->aMatch==0 ){
88564       p->nMatch = 0;
88565       p->nAlloc = 0;
88566       return;
88567     }
88568   }
88569   i = p->nMatch++;
88570   pMatch = &p->aMatch[i];
88571   pMatch->iCol = iCol;
88572   pMatch->iTerm = iTerm;
88573   pMatch->iToken = iToken;
88574   pMatch->iStart = iStart;
88575   pMatch->nByte = nByte;
88576 }
88577
88578 /*
88579 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
88580 */
88581 #define FTS3_ROTOR_SZ   (32)
88582 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
88583
88584 /*
88585 ** Add entries to pSnippet->aMatch[] for every match that occurs against
88586 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
88587 */
88588 static void snippetOffsetsOfColumn(
88589   Query *pQuery,
88590   Snippet *pSnippet,
88591   int iColumn,
88592   const char *zDoc,
88593   int nDoc
88594 ){
88595   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
88596   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
88597   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
88598   fulltext_vtab *pVtab;                /* The full text index */
88599   int nColumn;                         /* Number of columns in the index */
88600   const QueryTerm *aTerm;              /* Query string terms */
88601   int nTerm;                           /* Number of query string terms */  
88602   int i, j;                            /* Loop counters */
88603   int rc;                              /* Return code */
88604   unsigned int match, prevMatch;       /* Phrase search bitmasks */
88605   const char *zToken;                  /* Next token from the tokenizer */
88606   int nToken;                          /* Size of zToken */
88607   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
88608
88609   /* The following variables keep a circular buffer of the last
88610   ** few tokens */
88611   unsigned int iRotor = 0;             /* Index of current token */
88612   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
88613   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
88614
88615   pVtab = pQuery->pFts;
88616   nColumn = pVtab->nColumn;
88617   pTokenizer = pVtab->pTokenizer;
88618   pTModule = pTokenizer->pModule;
88619   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
88620   if( rc ) return;
88621   pTCursor->pTokenizer = pTokenizer;
88622   aTerm = pQuery->pTerms;
88623   nTerm = pQuery->nTerms;
88624   if( nTerm>=FTS3_ROTOR_SZ ){
88625     nTerm = FTS3_ROTOR_SZ - 1;
88626   }
88627   prevMatch = 0;
88628   while(1){
88629     rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
88630     if( rc ) break;
88631     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
88632     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
88633     match = 0;
88634     for(i=0; i<nTerm; i++){
88635       int iCol;
88636       iCol = aTerm[i].iColumn;
88637       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
88638       if( aTerm[i].nTerm>nToken ) continue;
88639       if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
88640       assert( aTerm[i].nTerm<=nToken );
88641       if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
88642       if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
88643       match |= 1<<i;
88644       if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
88645         for(j=aTerm[i].iPhrase-1; j>=0; j--){
88646           int k = (iRotor-j) & FTS3_ROTOR_MASK;
88647           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
88648                 iRotorBegin[k], iRotorLen[k]);
88649         }
88650       }
88651     }
88652     prevMatch = match<<1;
88653     iRotor++;
88654   }
88655   pTModule->xClose(pTCursor);  
88656 }
88657
88658 /*
88659 ** Remove entries from the pSnippet structure to account for the NEAR
88660 ** operator. When this is called, pSnippet contains the list of token 
88661 ** offsets produced by treating all NEAR operators as AND operators.
88662 ** This function removes any entries that should not be present after
88663 ** accounting for the NEAR restriction. For example, if the queried
88664 ** document is:
88665 **
88666 **     "A B C D E A"
88667 **
88668 ** and the query is:
88669 ** 
88670 **     A NEAR/0 E
88671 **
88672 ** then when this function is called the Snippet contains token offsets
88673 ** 0, 4 and 5. This function removes the "0" entry (because the first A
88674 ** is not near enough to an E).
88675 */
88676 static void trimSnippetOffsetsForNear(Query *pQuery, Snippet *pSnippet){
88677   int ii;
88678   int iDir = 1;
88679
88680   while(iDir>-2) {
88681     assert( iDir==1 || iDir==-1 );
88682     for(ii=0; ii<pSnippet->nMatch; ii++){
88683       int jj;
88684       int nNear;
88685       struct snippetMatch *pMatch = &pSnippet->aMatch[ii];
88686       QueryTerm *pQueryTerm = &pQuery->pTerms[pMatch->iTerm];
88687
88688       if( (pMatch->iTerm+iDir)<0 
88689        || (pMatch->iTerm+iDir)>=pQuery->nTerms
88690       ){
88691         continue;
88692       }
88693      
88694       nNear = pQueryTerm->nNear;
88695       if( iDir<0 ){
88696         nNear = pQueryTerm[-1].nNear;
88697       }
88698   
88699       if( pMatch->iTerm>=0 && nNear ){
88700         int isOk = 0;
88701         int iNextTerm = pMatch->iTerm+iDir;
88702         int iPrevTerm = iNextTerm;
88703
88704         int iEndToken;
88705         int iStartToken;
88706
88707         if( iDir<0 ){
88708           int nPhrase = 1;
88709           iStartToken = pMatch->iToken;
88710           while( (pMatch->iTerm+nPhrase)<pQuery->nTerms 
88711               && pQuery->pTerms[pMatch->iTerm+nPhrase].iPhrase>1 
88712           ){
88713             nPhrase++;
88714           }
88715           iEndToken = iStartToken + nPhrase - 1;
88716         }else{
88717           iEndToken   = pMatch->iToken;
88718           iStartToken = pMatch->iToken+1-pQueryTerm->iPhrase;
88719         }
88720
88721         while( pQuery->pTerms[iNextTerm].iPhrase>1 ){
88722           iNextTerm--;
88723         }
88724         while( (iPrevTerm+1)<pQuery->nTerms && 
88725                pQuery->pTerms[iPrevTerm+1].iPhrase>1 
88726         ){
88727           iPrevTerm++;
88728         }
88729   
88730         for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
88731           struct snippetMatch *p = &pSnippet->aMatch[jj];
88732           if( p->iCol==pMatch->iCol && ((
88733                p->iTerm==iNextTerm && 
88734                p->iToken>iEndToken && 
88735                p->iToken<=iEndToken+nNear
88736           ) || (
88737                p->iTerm==iPrevTerm && 
88738                p->iToken<iStartToken && 
88739                p->iToken>=iStartToken-nNear
88740           ))){
88741             isOk = 1;
88742           }
88743         }
88744         if( !isOk ){
88745           for(jj=1-pQueryTerm->iPhrase; jj<=0; jj++){
88746             pMatch[jj].iTerm = -1;
88747           }
88748           ii = -1;
88749           iDir = 1;
88750         }
88751       }
88752     }
88753     iDir -= 2;
88754   }
88755 }
88756
88757 /*
88758 ** Compute all offsets for the current row of the query.  
88759 ** If the offsets have already been computed, this routine is a no-op.
88760 */
88761 static void snippetAllOffsets(fulltext_cursor *p){
88762   int nColumn;
88763   int iColumn, i;
88764   int iFirst, iLast;
88765   fulltext_vtab *pFts;
88766
88767   if( p->snippet.nMatch ) return;
88768   if( p->q.nTerms==0 ) return;
88769   pFts = p->q.pFts;
88770   nColumn = pFts->nColumn;
88771   iColumn = (p->iCursorType - QUERY_FULLTEXT);
88772   if( iColumn<0 || iColumn>=nColumn ){
88773     iFirst = 0;
88774     iLast = nColumn-1;
88775   }else{
88776     iFirst = iColumn;
88777     iLast = iColumn;
88778   }
88779   for(i=iFirst; i<=iLast; i++){
88780     const char *zDoc;
88781     int nDoc;
88782     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
88783     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
88784     snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
88785   }
88786
88787   trimSnippetOffsetsForNear(&p->q, &p->snippet);
88788 }
88789
88790 /*
88791 ** Convert the information in the aMatch[] array of the snippet
88792 ** into the string zOffset[0..nOffset-1].
88793 */
88794 static void snippetOffsetText(Snippet *p){
88795   int i;
88796   int cnt = 0;
88797   StringBuffer sb;
88798   char zBuf[200];
88799   if( p->zOffset ) return;
88800   initStringBuffer(&sb);
88801   for(i=0; i<p->nMatch; i++){
88802     struct snippetMatch *pMatch = &p->aMatch[i];
88803     if( pMatch->iTerm>=0 ){
88804       /* If snippetMatch.iTerm is less than 0, then the match was 
88805       ** discarded as part of processing the NEAR operator (see the 
88806       ** trimSnippetOffsetsForNear() function for details). Ignore 
88807       ** it in this case
88808       */
88809       zBuf[0] = ' ';
88810       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
88811           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
88812       append(&sb, zBuf);
88813       cnt++;
88814     }
88815   }
88816   p->zOffset = stringBufferData(&sb);
88817   p->nOffset = stringBufferLength(&sb);
88818 }
88819
88820 /*
88821 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
88822 ** of matching words some of which might be in zDoc.  zDoc is column
88823 ** number iCol.
88824 **
88825 ** iBreak is suggested spot in zDoc where we could begin or end an
88826 ** excerpt.  Return a value similar to iBreak but possibly adjusted
88827 ** to be a little left or right so that the break point is better.
88828 */
88829 static int wordBoundary(
88830   int iBreak,                   /* The suggested break point */
88831   const char *zDoc,             /* Document text */
88832   int nDoc,                     /* Number of bytes in zDoc[] */
88833   struct snippetMatch *aMatch,  /* Matching words */
88834   int nMatch,                   /* Number of entries in aMatch[] */
88835   int iCol                      /* The column number for zDoc[] */
88836 ){
88837   int i;
88838   if( iBreak<=10 ){
88839     return 0;
88840   }
88841   if( iBreak>=nDoc-10 ){
88842     return nDoc;
88843   }
88844   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
88845   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
88846   if( i<nMatch ){
88847     if( aMatch[i].iStart<iBreak+10 ){
88848       return aMatch[i].iStart;
88849     }
88850     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
88851       return aMatch[i-1].iStart;
88852     }
88853   }
88854   for(i=1; i<=10; i++){
88855     if( safe_isspace(zDoc[iBreak-i]) ){
88856       return iBreak - i + 1;
88857     }
88858     if( safe_isspace(zDoc[iBreak+i]) ){
88859       return iBreak + i + 1;
88860     }
88861   }
88862   return iBreak;
88863 }
88864
88865
88866
88867 /*
88868 ** Allowed values for Snippet.aMatch[].snStatus
88869 */
88870 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
88871 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
88872
88873 /*
88874 ** Generate the text of a snippet.
88875 */
88876 static void snippetText(
88877   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
88878   const char *zStartMark,     /* Markup to appear before each match */
88879   const char *zEndMark,       /* Markup to appear after each match */
88880   const char *zEllipsis       /* Ellipsis mark */
88881 ){
88882   int i, j;
88883   struct snippetMatch *aMatch;
88884   int nMatch;
88885   int nDesired;
88886   StringBuffer sb;
88887   int tailCol;
88888   int tailOffset;
88889   int iCol;
88890   int nDoc;
88891   const char *zDoc;
88892   int iStart, iEnd;
88893   int tailEllipsis = 0;
88894   int iMatch;
88895   
88896
88897   sqlite3_free(pCursor->snippet.zSnippet);
88898   pCursor->snippet.zSnippet = 0;
88899   aMatch = pCursor->snippet.aMatch;
88900   nMatch = pCursor->snippet.nMatch;
88901   initStringBuffer(&sb);
88902
88903   for(i=0; i<nMatch; i++){
88904     aMatch[i].snStatus = SNIPPET_IGNORE;
88905   }
88906   nDesired = 0;
88907   for(i=0; i<pCursor->q.nTerms; i++){
88908     for(j=0; j<nMatch; j++){
88909       if( aMatch[j].iTerm==i ){
88910         aMatch[j].snStatus = SNIPPET_DESIRED;
88911         nDesired++;
88912         break;
88913       }
88914     }
88915   }
88916
88917   iMatch = 0;
88918   tailCol = -1;
88919   tailOffset = 0;
88920   for(i=0; i<nMatch && nDesired>0; i++){
88921     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
88922     nDesired--;
88923     iCol = aMatch[i].iCol;
88924     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
88925     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
88926     iStart = aMatch[i].iStart - 40;
88927     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
88928     if( iStart<=10 ){
88929       iStart = 0;
88930     }
88931     if( iCol==tailCol && iStart<=tailOffset+20 ){
88932       iStart = tailOffset;
88933     }
88934     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
88935       trimWhiteSpace(&sb);
88936       appendWhiteSpace(&sb);
88937       append(&sb, zEllipsis);
88938       appendWhiteSpace(&sb);
88939     }
88940     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
88941     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
88942     if( iEnd>=nDoc-10 ){
88943       iEnd = nDoc;
88944       tailEllipsis = 0;
88945     }else{
88946       tailEllipsis = 1;
88947     }
88948     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
88949     while( iStart<iEnd ){
88950       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
88951              && aMatch[iMatch].iCol<=iCol ){
88952         iMatch++;
88953       }
88954       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
88955              && aMatch[iMatch].iCol==iCol ){
88956         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
88957         iStart = aMatch[iMatch].iStart;
88958         append(&sb, zStartMark);
88959         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
88960         append(&sb, zEndMark);
88961         iStart += aMatch[iMatch].nByte;
88962         for(j=iMatch+1; j<nMatch; j++){
88963           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
88964               && aMatch[j].snStatus==SNIPPET_DESIRED ){
88965             nDesired--;
88966             aMatch[j].snStatus = SNIPPET_IGNORE;
88967           }
88968         }
88969       }else{
88970         nappend(&sb, &zDoc[iStart], iEnd - iStart);
88971         iStart = iEnd;
88972       }
88973     }
88974     tailCol = iCol;
88975     tailOffset = iEnd;
88976   }
88977   trimWhiteSpace(&sb);
88978   if( tailEllipsis ){
88979     appendWhiteSpace(&sb);
88980     append(&sb, zEllipsis);
88981   }
88982   pCursor->snippet.zSnippet = stringBufferData(&sb);
88983   pCursor->snippet.nSnippet = stringBufferLength(&sb);
88984 }
88985
88986
88987 /*
88988 ** Close the cursor.  For additional information see the documentation
88989 ** on the xClose method of the virtual table interface.
88990 */
88991 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
88992   fulltext_cursor *c = (fulltext_cursor *) pCursor;
88993   FTSTRACE(("FTS3 Close %p\n", c));
88994   sqlite3_finalize(c->pStmt);
88995   queryClear(&c->q);
88996   snippetClear(&c->snippet);
88997   if( c->result.nData!=0 ) dlrDestroy(&c->reader);
88998   dataBufferDestroy(&c->result);
88999   sqlite3_free(c);
89000   return SQLITE_OK;
89001 }
89002
89003 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
89004   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89005   int rc;
89006
89007   FTSTRACE(("FTS3 Next %p\n", pCursor));
89008   snippetClear(&c->snippet);
89009   if( c->iCursorType < QUERY_FULLTEXT ){
89010     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
89011     rc = sqlite3_step(c->pStmt);
89012     switch( rc ){
89013       case SQLITE_ROW:
89014         c->eof = 0;
89015         return SQLITE_OK;
89016       case SQLITE_DONE:
89017         c->eof = 1;
89018         return SQLITE_OK;
89019       default:
89020         c->eof = 1;
89021         return rc;
89022     }
89023   } else {  /* full-text query */
89024     rc = sqlite3_reset(c->pStmt);
89025     if( rc!=SQLITE_OK ) return rc;
89026
89027     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
89028       c->eof = 1;
89029       return SQLITE_OK;
89030     }
89031     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
89032     dlrStep(&c->reader);
89033     if( rc!=SQLITE_OK ) return rc;
89034     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
89035     rc = sqlite3_step(c->pStmt);
89036     if( rc==SQLITE_ROW ){   /* the case we expect */
89037       c->eof = 0;
89038       return SQLITE_OK;
89039     }
89040     /* an error occurred; abort */
89041     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
89042   }
89043 }
89044
89045
89046 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
89047 ** another file, term_select() could be pushed above
89048 ** docListOfTerm().
89049 */
89050 static int termSelect(fulltext_vtab *v, int iColumn,
89051                       const char *pTerm, int nTerm, int isPrefix,
89052                       DocListType iType, DataBuffer *out);
89053
89054 /* Return a DocList corresponding to the query term *pTerm.  If *pTerm
89055 ** is the first term of a phrase query, go ahead and evaluate the phrase
89056 ** query and return the doclist for the entire phrase query.
89057 **
89058 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
89059 ** overwritten.
89060 */
89061 static int docListOfTerm(
89062   fulltext_vtab *v,    /* The full text index */
89063   int iColumn,         /* column to restrict to.  No restriction if >=nColumn */
89064   QueryTerm *pQTerm,   /* Term we are looking for, or 1st term of a phrase */
89065   DataBuffer *pResult  /* Write the result here */
89066 ){
89067   DataBuffer left, right, new;
89068   int i, rc;
89069
89070   /* No phrase search if no position info. */
89071   assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
89072
89073   /* This code should never be called with buffered updates. */
89074   assert( v->nPendingData<0 );
89075
89076   dataBufferInit(&left, 0);
89077   rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
89078                   (0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS), &left);
89079   if( rc ) return rc;
89080   for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
89081     /* If this token is connected to the next by a NEAR operator, and
89082     ** the next token is the start of a phrase, then set nPhraseRight
89083     ** to the number of tokens in the phrase. Otherwise leave it at 1.
89084     */
89085     int nPhraseRight = 1;
89086     while( (i+nPhraseRight)<=pQTerm->nPhrase 
89087         && pQTerm[i+nPhraseRight].nNear==0 
89088     ){
89089       nPhraseRight++;
89090     }
89091
89092     dataBufferInit(&right, 0);
89093     rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
89094                     pQTerm[i].isPrefix, DL_POSITIONS, &right);
89095     if( rc ){
89096       dataBufferDestroy(&left);
89097       return rc;
89098     }
89099     dataBufferInit(&new, 0);
89100     docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
89101                        pQTerm[i-1].nNear, pQTerm[i-1].iPhrase + nPhraseRight,
89102                        ((i<pQTerm->nPhrase) ? DL_POSITIONS : DL_DOCIDS),
89103                        &new);
89104     dataBufferDestroy(&left);
89105     dataBufferDestroy(&right);
89106     left = new;
89107   }
89108   *pResult = left;
89109   return SQLITE_OK;
89110 }
89111
89112 /* Add a new term pTerm[0..nTerm-1] to the query *q.
89113 */
89114 static void queryAdd(Query *q, const char *pTerm, int nTerm){
89115   QueryTerm *t;
89116   ++q->nTerms;
89117   q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
89118   if( q->pTerms==0 ){
89119     q->nTerms = 0;
89120     return;
89121   }
89122   t = &q->pTerms[q->nTerms - 1];
89123   CLEAR(t);
89124   t->pTerm = sqlite3_malloc(nTerm+1);
89125   memcpy(t->pTerm, pTerm, nTerm);
89126   t->pTerm[nTerm] = 0;
89127   t->nTerm = nTerm;
89128   t->isOr = q->nextIsOr;
89129   t->isPrefix = 0;
89130   q->nextIsOr = 0;
89131   t->iColumn = q->nextColumn;
89132   q->nextColumn = q->dfltColumn;
89133 }
89134
89135 /*
89136 ** Check to see if the string zToken[0...nToken-1] matches any
89137 ** column name in the virtual table.   If it does,
89138 ** return the zero-indexed column number.  If not, return -1.
89139 */
89140 static int checkColumnSpecifier(
89141   fulltext_vtab *pVtab,    /* The virtual table */
89142   const char *zToken,      /* Text of the token */
89143   int nToken               /* Number of characters in the token */
89144 ){
89145   int i;
89146   for(i=0; i<pVtab->nColumn; i++){
89147     if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
89148         && pVtab->azColumn[i][nToken]==0 ){
89149       return i;
89150     }
89151   }
89152   return -1;
89153 }
89154
89155 /*
89156 ** Parse the text at zSegment[0..nSegment-1].  Add additional terms
89157 ** to the query being assemblied in pQuery.
89158 **
89159 ** inPhrase is true if zSegment[0..nSegement-1] is contained within
89160 ** double-quotes.  If inPhrase is true, then the first term
89161 ** is marked with the number of terms in the phrase less one and
89162 ** OR and "-" syntax is ignored.  If inPhrase is false, then every
89163 ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
89164 */
89165 static int tokenizeSegment(
89166   sqlite3_tokenizer *pTokenizer,          /* The tokenizer to use */
89167   const char *zSegment, int nSegment,     /* Query expression being parsed */
89168   int inPhrase,                           /* True if within "..." */
89169   Query *pQuery                           /* Append results here */
89170 ){
89171   const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
89172   sqlite3_tokenizer_cursor *pCursor;
89173   int firstIndex = pQuery->nTerms;
89174   int iCol;
89175   int nTerm = 1;
89176   
89177   int rc = pModule->xOpen(pTokenizer, zSegment, nSegment, &pCursor);
89178   if( rc!=SQLITE_OK ) return rc;
89179   pCursor->pTokenizer = pTokenizer;
89180
89181   while( 1 ){
89182     const char *zToken;
89183     int nToken, iBegin, iEnd, iPos;
89184
89185     rc = pModule->xNext(pCursor,
89186                         &zToken, &nToken,
89187                         &iBegin, &iEnd, &iPos);
89188     if( rc!=SQLITE_OK ) break;
89189     if( !inPhrase &&
89190         zSegment[iEnd]==':' &&
89191          (iCol = checkColumnSpecifier(pQuery->pFts, zToken, nToken))>=0 ){
89192       pQuery->nextColumn = iCol;
89193       continue;
89194     }
89195     if( !inPhrase && pQuery->nTerms>0 && nToken==2 
89196      && zSegment[iBegin+0]=='O'
89197      && zSegment[iBegin+1]=='R' 
89198     ){
89199       pQuery->nextIsOr = 1;
89200       continue;
89201     }
89202     if( !inPhrase && pQuery->nTerms>0 && !pQuery->nextIsOr && nToken==4 
89203       && memcmp(&zSegment[iBegin], "NEAR", 4)==0
89204     ){
89205       QueryTerm *pTerm = &pQuery->pTerms[pQuery->nTerms-1];
89206       if( (iBegin+6)<nSegment 
89207        && zSegment[iBegin+4] == '/'
89208        && isdigit(zSegment[iBegin+5])
89209       ){
89210         int k;
89211         pTerm->nNear = 0;
89212         for(k=5; (iBegin+k)<=nSegment && isdigit(zSegment[iBegin+k]); k++){
89213           pTerm->nNear = pTerm->nNear*10 + (zSegment[iBegin+k] - '0');
89214         }
89215         pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
89216       } else {
89217         pTerm->nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
89218       }
89219       pTerm->nNear++;
89220       continue;
89221     }
89222
89223     queryAdd(pQuery, zToken, nToken);
89224     if( !inPhrase && iBegin>0 && zSegment[iBegin-1]=='-' ){
89225       pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
89226     }
89227     if( iEnd<nSegment && zSegment[iEnd]=='*' ){
89228       pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
89229     }
89230     pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
89231     if( inPhrase ){
89232       nTerm++;
89233     }
89234   }
89235
89236   if( inPhrase && pQuery->nTerms>firstIndex ){
89237     pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
89238   }
89239
89240   return pModule->xClose(pCursor);
89241 }
89242
89243 /* Parse a query string, yielding a Query object pQuery.
89244 **
89245 ** The calling function will need to queryClear() to clean up
89246 ** the dynamically allocated memory held by pQuery.
89247 */
89248 static int parseQuery(
89249   fulltext_vtab *v,        /* The fulltext index */
89250   const char *zInput,      /* Input text of the query string */
89251   int nInput,              /* Size of the input text */
89252   int dfltColumn,          /* Default column of the index to match against */
89253   Query *pQuery            /* Write the parse results here. */
89254 ){
89255   int iInput, inPhrase = 0;
89256   int ii;
89257   QueryTerm *aTerm;
89258
89259   if( zInput==0 ) nInput = 0;
89260   if( nInput<0 ) nInput = strlen(zInput);
89261   pQuery->nTerms = 0;
89262   pQuery->pTerms = NULL;
89263   pQuery->nextIsOr = 0;
89264   pQuery->nextColumn = dfltColumn;
89265   pQuery->dfltColumn = dfltColumn;
89266   pQuery->pFts = v;
89267
89268   for(iInput=0; iInput<nInput; ++iInput){
89269     int i;
89270     for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
89271     if( i>iInput ){
89272       tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
89273                        pQuery);
89274     }
89275     iInput = i;
89276     if( i<nInput ){
89277       assert( zInput[i]=='"' );
89278       inPhrase = !inPhrase;
89279     }
89280   }
89281
89282   if( inPhrase ){
89283     /* unmatched quote */
89284     queryClear(pQuery);
89285     return SQLITE_ERROR;
89286   }
89287
89288   /* Modify the values of the QueryTerm.nPhrase variables to account for
89289   ** the NEAR operator. For the purposes of QueryTerm.nPhrase, phrases
89290   ** and tokens connected by the NEAR operator are handled as a single
89291   ** phrase. See comments above the QueryTerm structure for details.
89292   */
89293   aTerm = pQuery->pTerms;
89294   for(ii=0; ii<pQuery->nTerms; ii++){
89295     if( aTerm[ii].nNear || aTerm[ii].nPhrase ){
89296       while (aTerm[ii+aTerm[ii].nPhrase].nNear) {
89297         aTerm[ii].nPhrase += (1 + aTerm[ii+aTerm[ii].nPhrase+1].nPhrase);
89298       }
89299     }
89300   }
89301
89302   return SQLITE_OK;
89303 }
89304
89305 /* TODO(shess) Refactor the code to remove this forward decl. */
89306 static int flushPendingTerms(fulltext_vtab *v);
89307
89308 /* Perform a full-text query using the search expression in
89309 ** zInput[0..nInput-1].  Return a list of matching documents
89310 ** in pResult.
89311 **
89312 ** Queries must match column iColumn.  Or if iColumn>=nColumn
89313 ** they are allowed to match against any column.
89314 */
89315 static int fulltextQuery(
89316   fulltext_vtab *v,      /* The full text index */
89317   int iColumn,           /* Match against this column by default */
89318   const char *zInput,    /* The query string */
89319   int nInput,            /* Number of bytes in zInput[] */
89320   DataBuffer *pResult,   /* Write the result doclist here */
89321   Query *pQuery          /* Put parsed query string here */
89322 ){
89323   int i, iNext, rc;
89324   DataBuffer left, right, or, new;
89325   int nNot = 0;
89326   QueryTerm *aTerm;
89327
89328   /* TODO(shess) Instead of flushing pendingTerms, we could query for
89329   ** the relevant term and merge the doclist into what we receive from
89330   ** the database.  Wait and see if this is a common issue, first.
89331   **
89332   ** A good reason not to flush is to not generate update-related
89333   ** error codes from here.
89334   */
89335
89336   /* Flush any buffered updates before executing the query. */
89337   rc = flushPendingTerms(v);
89338   if( rc!=SQLITE_OK ) return rc;
89339
89340   /* TODO(shess) I think that the queryClear() calls below are not
89341   ** necessary, because fulltextClose() already clears the query.
89342   */
89343   rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
89344   if( rc!=SQLITE_OK ) return rc;
89345
89346   /* Empty or NULL queries return no results. */
89347   if( pQuery->nTerms==0 ){
89348     dataBufferInit(pResult, 0);
89349     return SQLITE_OK;
89350   }
89351
89352   /* Merge AND terms. */
89353   /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
89354   aTerm = pQuery->pTerms;
89355   for(i = 0; i<pQuery->nTerms; i=iNext){
89356     if( aTerm[i].isNot ){
89357       /* Handle all NOT terms in a separate pass */
89358       nNot++;
89359       iNext = i + aTerm[i].nPhrase+1;
89360       continue;
89361     }
89362     iNext = i + aTerm[i].nPhrase + 1;
89363     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
89364     if( rc ){
89365       if( i!=nNot ) dataBufferDestroy(&left);
89366       queryClear(pQuery);
89367       return rc;
89368     }
89369     while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
89370       rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
89371       iNext += aTerm[iNext].nPhrase + 1;
89372       if( rc ){
89373         if( i!=nNot ) dataBufferDestroy(&left);
89374         dataBufferDestroy(&right);
89375         queryClear(pQuery);
89376         return rc;
89377       }
89378       dataBufferInit(&new, 0);
89379       docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
89380       dataBufferDestroy(&right);
89381       dataBufferDestroy(&or);
89382       right = new;
89383     }
89384     if( i==nNot ){           /* first term processed. */
89385       left = right;
89386     }else{
89387       dataBufferInit(&new, 0);
89388       docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
89389       dataBufferDestroy(&right);
89390       dataBufferDestroy(&left);
89391       left = new;
89392     }
89393   }
89394
89395   if( nNot==pQuery->nTerms ){
89396     /* We do not yet know how to handle a query of only NOT terms */
89397     return SQLITE_ERROR;
89398   }
89399
89400   /* Do the EXCEPT terms */
89401   for(i=0; i<pQuery->nTerms;  i += aTerm[i].nPhrase + 1){
89402     if( !aTerm[i].isNot ) continue;
89403     rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
89404     if( rc ){
89405       queryClear(pQuery);
89406       dataBufferDestroy(&left);
89407       return rc;
89408     }
89409     dataBufferInit(&new, 0);
89410     docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
89411     dataBufferDestroy(&right);
89412     dataBufferDestroy(&left);
89413     left = new;
89414   }
89415
89416   *pResult = left;
89417   return rc;
89418 }
89419
89420 /*
89421 ** This is the xFilter interface for the virtual table.  See
89422 ** the virtual table xFilter method documentation for additional
89423 ** information.
89424 **
89425 ** If idxNum==QUERY_GENERIC then do a full table scan against
89426 ** the %_content table.
89427 **
89428 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
89429 ** in the %_content table.
89430 **
89431 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
89432 ** column on the left-hand side of the MATCH operator is column
89433 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
89434 ** side of the MATCH operator.
89435 */
89436 /* TODO(shess) Upgrade the cursor initialization and destruction to
89437 ** account for fulltextFilter() being called multiple times on the
89438 ** same cursor.  The current solution is very fragile.  Apply fix to
89439 ** fts3 as appropriate.
89440 */
89441 static int fulltextFilter(
89442   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
89443   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
89444   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
89445 ){
89446   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89447   fulltext_vtab *v = cursor_vtab(c);
89448   int rc;
89449
89450   FTSTRACE(("FTS3 Filter %p\n",pCursor));
89451
89452   /* If the cursor has a statement that was not prepared according to
89453   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
89454   ** given cursor will have the same idxNum , but in this case it's
89455   ** easy to be safe.
89456   */
89457   if( c->pStmt && c->iCursorType!=idxNum ){
89458     sqlite3_finalize(c->pStmt);
89459     c->pStmt = NULL;
89460   }
89461
89462   /* Get a fresh statement appropriate to idxNum. */
89463   /* TODO(shess): Add a prepared-statement cache in the vt structure.
89464   ** The cache must handle multiple open cursors.  Easier to cache the
89465   ** statement variants at the vt to reduce malloc/realloc/free here.
89466   ** Or we could have a StringBuffer variant which allowed stack
89467   ** construction for small values.
89468   */
89469   if( !c->pStmt ){
89470     StringBuffer sb;
89471     initStringBuffer(&sb);
89472     append(&sb, "SELECT docid, ");
89473     appendList(&sb, v->nColumn, v->azContentColumn);
89474     append(&sb, " FROM %_content");
89475     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
89476     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
89477                      stringBufferData(&sb));
89478     stringBufferDestroy(&sb);
89479     if( rc!=SQLITE_OK ) return rc;
89480     c->iCursorType = idxNum;
89481   }else{
89482     sqlite3_reset(c->pStmt);
89483     assert( c->iCursorType==idxNum );
89484   }
89485
89486   switch( idxNum ){
89487     case QUERY_GENERIC:
89488       break;
89489
89490     case QUERY_DOCID:
89491       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
89492       if( rc!=SQLITE_OK ) return rc;
89493       break;
89494
89495     default:   /* full-text search */
89496     {
89497       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
89498       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
89499       assert( argc==1 );
89500       queryClear(&c->q);
89501       if( c->result.nData!=0 ){
89502         /* This case happens if the same cursor is used repeatedly. */
89503         dlrDestroy(&c->reader);
89504         dataBufferReset(&c->result);
89505       }else{
89506         dataBufferInit(&c->result, 0);
89507       }
89508       rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
89509       if( rc!=SQLITE_OK ) return rc;
89510       if( c->result.nData!=0 ){
89511         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
89512       }
89513       break;
89514     }
89515   }
89516
89517   return fulltextNext(pCursor);
89518 }
89519
89520 /* This is the xEof method of the virtual table.  The SQLite core
89521 ** calls this routine to find out if it has reached the end of
89522 ** a query's results set.
89523 */
89524 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
89525   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89526   return c->eof;
89527 }
89528
89529 /* This is the xColumn method of the virtual table.  The SQLite
89530 ** core calls this method during a query when it needs the value
89531 ** of a column from the virtual table.  This method needs to use
89532 ** one of the sqlite3_result_*() routines to store the requested
89533 ** value back in the pContext.
89534 */
89535 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
89536                           sqlite3_context *pContext, int idxCol){
89537   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89538   fulltext_vtab *v = cursor_vtab(c);
89539
89540   if( idxCol<v->nColumn ){
89541     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
89542     sqlite3_result_value(pContext, pVal);
89543   }else if( idxCol==v->nColumn ){
89544     /* The extra column whose name is the same as the table.
89545     ** Return a blob which is a pointer to the cursor
89546     */
89547     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
89548   }else if( idxCol==v->nColumn+1 ){
89549     /* The docid column, which is an alias for rowid. */
89550     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
89551     sqlite3_result_value(pContext, pVal);
89552   }
89553   return SQLITE_OK;
89554 }
89555
89556 /* This is the xRowid method.  The SQLite core calls this routine to
89557 ** retrieve the rowid for the current row of the result set.  fts3
89558 ** exposes %_content.docid as the rowid for the virtual table.  The
89559 ** rowid should be written to *pRowid.
89560 */
89561 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
89562   fulltext_cursor *c = (fulltext_cursor *) pCursor;
89563
89564   *pRowid = sqlite3_column_int64(c->pStmt, 0);
89565   return SQLITE_OK;
89566 }
89567
89568 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
89569 ** we also store positions and offsets in the hash table using that
89570 ** column number.
89571 */
89572 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
89573                       const char *zText, int iColumn){
89574   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
89575   sqlite3_tokenizer_cursor *pCursor;
89576   const char *pToken;
89577   int nTokenBytes;
89578   int iStartOffset, iEndOffset, iPosition;
89579   int rc;
89580
89581   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
89582   if( rc!=SQLITE_OK ) return rc;
89583
89584   pCursor->pTokenizer = pTokenizer;
89585   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
89586                                                    &pToken, &nTokenBytes,
89587                                                    &iStartOffset, &iEndOffset,
89588                                                    &iPosition)) ){
89589     DLCollector *p;
89590     int nData;                   /* Size of doclist before our update. */
89591
89592     /* Positions can't be negative; we use -1 as a terminator
89593      * internally.  Token can't be NULL or empty. */
89594     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
89595       rc = SQLITE_ERROR;
89596       break;
89597     }
89598
89599     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
89600     if( p==NULL ){
89601       nData = 0;
89602       p = dlcNew(iDocid, DL_DEFAULT);
89603       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
89604
89605       /* Overhead for our hash table entry, the key, and the value. */
89606       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
89607     }else{
89608       nData = p->b.nData;
89609       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
89610     }
89611     if( iColumn>=0 ){
89612       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
89613     }
89614
89615     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
89616     v->nPendingData += p->b.nData-nData;
89617   }
89618
89619   /* TODO(shess) Check return?  Should this be able to cause errors at
89620   ** this point?  Actually, same question about sqlite3_finalize(),
89621   ** though one could argue that failure there means that the data is
89622   ** not durable.  *ponder*
89623   */
89624   pTokenizer->pModule->xClose(pCursor);
89625   if( SQLITE_DONE == rc ) return SQLITE_OK;
89626   return rc;
89627 }
89628
89629 /* Add doclists for all terms in [pValues] to pendingTerms table. */
89630 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
89631                        sqlite3_value **pValues){
89632   int i;
89633   for(i = 0; i < v->nColumn ; ++i){
89634     char *zText = (char*)sqlite3_value_text(pValues[i]);
89635     int rc = buildTerms(v, iDocid, zText, i);
89636     if( rc!=SQLITE_OK ) return rc;
89637   }
89638   return SQLITE_OK;
89639 }
89640
89641 /* Add empty doclists for all terms in the given row's content to
89642 ** pendingTerms.
89643 */
89644 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
89645   const char **pValues;
89646   int i, rc;
89647
89648   /* TODO(shess) Should we allow such tables at all? */
89649   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
89650
89651   rc = content_select(v, iDocid, &pValues);
89652   if( rc!=SQLITE_OK ) return rc;
89653
89654   for(i = 0 ; i < v->nColumn; ++i) {
89655     rc = buildTerms(v, iDocid, pValues[i], -1);
89656     if( rc!=SQLITE_OK ) break;
89657   }
89658
89659   freeStringArray(v->nColumn, pValues);
89660   return SQLITE_OK;
89661 }
89662
89663 /* TODO(shess) Refactor the code to remove this forward decl. */
89664 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
89665
89666 /* Insert a row into the %_content table; set *piDocid to be the ID of the
89667 ** new row.  Add doclists for terms to pendingTerms.
89668 */
89669 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
89670                         sqlite3_value **pValues, sqlite_int64 *piDocid){
89671   int rc;
89672
89673   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
89674   if( rc!=SQLITE_OK ) return rc;
89675
89676   /* docid column is an alias for rowid. */
89677   *piDocid = sqlite3_last_insert_rowid(v->db);
89678   rc = initPendingTerms(v, *piDocid);
89679   if( rc!=SQLITE_OK ) return rc;
89680
89681   return insertTerms(v, *piDocid, pValues);
89682 }
89683
89684 /* Delete a row from the %_content table; add empty doclists for terms
89685 ** to pendingTerms.
89686 */
89687 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
89688   int rc = initPendingTerms(v, iRow);
89689   if( rc!=SQLITE_OK ) return rc;
89690
89691   rc = deleteTerms(v, iRow);
89692   if( rc!=SQLITE_OK ) return rc;
89693
89694   return content_delete(v, iRow);  /* execute an SQL DELETE */
89695 }
89696
89697 /* Update a row in the %_content table; add delete doclists to
89698 ** pendingTerms for old terms not in the new data, add insert doclists
89699 ** to pendingTerms for terms in the new data.
89700 */
89701 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
89702                         sqlite3_value **pValues){
89703   int rc = initPendingTerms(v, iRow);
89704   if( rc!=SQLITE_OK ) return rc;
89705
89706   /* Generate an empty doclist for each term that previously appeared in this
89707    * row. */
89708   rc = deleteTerms(v, iRow);
89709   if( rc!=SQLITE_OK ) return rc;
89710
89711   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
89712   if( rc!=SQLITE_OK ) return rc;
89713
89714   /* Now add positions for terms which appear in the updated row. */
89715   return insertTerms(v, iRow, pValues);
89716 }
89717
89718 /*******************************************************************/
89719 /* InteriorWriter is used to collect terms and block references into
89720 ** interior nodes in %_segments.  See commentary at top of file for
89721 ** format.
89722 */
89723
89724 /* How large interior nodes can grow. */
89725 #define INTERIOR_MAX 2048
89726
89727 /* Minimum number of terms per interior node (except the root). This
89728 ** prevents large terms from making the tree too skinny - must be >0
89729 ** so that the tree always makes progress.  Note that the min tree
89730 ** fanout will be INTERIOR_MIN_TERMS+1.
89731 */
89732 #define INTERIOR_MIN_TERMS 7
89733 #if INTERIOR_MIN_TERMS<1
89734 # error INTERIOR_MIN_TERMS must be greater than 0.
89735 #endif
89736
89737 /* ROOT_MAX controls how much data is stored inline in the segment
89738 ** directory.
89739 */
89740 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
89741 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
89742 ** can both see it, but if the caller passed it in, we wouldn't even
89743 ** need a define.
89744 */
89745 #define ROOT_MAX 1024
89746 #if ROOT_MAX<VARINT_MAX*2
89747 # error ROOT_MAX must have enough space for a header.
89748 #endif
89749
89750 /* InteriorBlock stores a linked-list of interior blocks while a lower
89751 ** layer is being constructed.
89752 */
89753 typedef struct InteriorBlock {
89754   DataBuffer term;           /* Leftmost term in block's subtree. */
89755   DataBuffer data;           /* Accumulated data for the block. */
89756   struct InteriorBlock *next;
89757 } InteriorBlock;
89758
89759 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
89760                                        const char *pTerm, int nTerm){
89761   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
89762   char c[VARINT_MAX+VARINT_MAX];
89763   int n;
89764
89765   if( block ){
89766     memset(block, 0, sizeof(*block));
89767     dataBufferInit(&block->term, 0);
89768     dataBufferReplace(&block->term, pTerm, nTerm);
89769
89770     n = fts3PutVarint(c, iHeight);
89771     n += fts3PutVarint(c+n, iChildBlock);
89772     dataBufferInit(&block->data, INTERIOR_MAX);
89773     dataBufferReplace(&block->data, c, n);
89774   }
89775   return block;
89776 }
89777
89778 #ifndef NDEBUG
89779 /* Verify that the data is readable as an interior node. */
89780 static void interiorBlockValidate(InteriorBlock *pBlock){
89781   const char *pData = pBlock->data.pData;
89782   int nData = pBlock->data.nData;
89783   int n, iDummy;
89784   sqlite_int64 iBlockid;
89785
89786   assert( nData>0 );
89787   assert( pData!=0 );
89788   assert( pData+nData>pData );
89789
89790   /* Must lead with height of node as a varint(n), n>0 */
89791   n = fts3GetVarint32(pData, &iDummy);
89792   assert( n>0 );
89793   assert( iDummy>0 );
89794   assert( n<nData );
89795   pData += n;
89796   nData -= n;
89797
89798   /* Must contain iBlockid. */
89799   n = fts3GetVarint(pData, &iBlockid);
89800   assert( n>0 );
89801   assert( n<=nData );
89802   pData += n;
89803   nData -= n;
89804
89805   /* Zero or more terms of positive length */
89806   if( nData!=0 ){
89807     /* First term is not delta-encoded. */
89808     n = fts3GetVarint32(pData, &iDummy);
89809     assert( n>0 );
89810     assert( iDummy>0 );
89811     assert( n+iDummy>0);
89812     assert( n+iDummy<=nData );
89813     pData += n+iDummy;
89814     nData -= n+iDummy;
89815
89816     /* Following terms delta-encoded. */
89817     while( nData!=0 ){
89818       /* Length of shared prefix. */
89819       n = fts3GetVarint32(pData, &iDummy);
89820       assert( n>0 );
89821       assert( iDummy>=0 );
89822       assert( n<nData );
89823       pData += n;
89824       nData -= n;
89825
89826       /* Length and data of distinct suffix. */
89827       n = fts3GetVarint32(pData, &iDummy);
89828       assert( n>0 );
89829       assert( iDummy>0 );
89830       assert( n+iDummy>0);
89831       assert( n+iDummy<=nData );
89832       pData += n+iDummy;
89833       nData -= n+iDummy;
89834     }
89835   }
89836 }
89837 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
89838 #else
89839 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
89840 #endif
89841
89842 typedef struct InteriorWriter {
89843   int iHeight;                   /* from 0 at leaves. */
89844   InteriorBlock *first, *last;
89845   struct InteriorWriter *parentWriter;
89846
89847   DataBuffer term;               /* Last term written to block "last". */
89848   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
89849 #ifndef NDEBUG
89850   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
89851 #endif
89852 } InteriorWriter;
89853
89854 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
89855 ** term in the tree.  iChildBlock is the leftmost child block at the
89856 ** next level down the tree.
89857 */
89858 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
89859                                sqlite_int64 iChildBlock,
89860                                InteriorWriter *pWriter){
89861   InteriorBlock *block;
89862   assert( iHeight>0 );
89863   CLEAR(pWriter);
89864
89865   pWriter->iHeight = iHeight;
89866   pWriter->iOpeningChildBlock = iChildBlock;
89867 #ifndef NDEBUG
89868   pWriter->iLastChildBlock = iChildBlock;
89869 #endif
89870   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
89871   pWriter->last = pWriter->first = block;
89872   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89873   dataBufferInit(&pWriter->term, 0);
89874 }
89875
89876 /* Append the child node rooted at iChildBlock to the interior node,
89877 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
89878 */
89879 static void interiorWriterAppend(InteriorWriter *pWriter,
89880                                  const char *pTerm, int nTerm,
89881                                  sqlite_int64 iChildBlock){
89882   char c[VARINT_MAX+VARINT_MAX];
89883   int n, nPrefix = 0;
89884
89885   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89886
89887   /* The first term written into an interior node is actually
89888   ** associated with the second child added (the first child was added
89889   ** in interiorWriterInit, or in the if clause at the bottom of this
89890   ** function).  That term gets encoded straight up, with nPrefix left
89891   ** at 0.
89892   */
89893   if( pWriter->term.nData==0 ){
89894     n = fts3PutVarint(c, nTerm);
89895   }else{
89896     while( nPrefix<pWriter->term.nData &&
89897            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
89898       nPrefix++;
89899     }
89900
89901     n = fts3PutVarint(c, nPrefix);
89902     n += fts3PutVarint(c+n, nTerm-nPrefix);
89903   }
89904
89905 #ifndef NDEBUG
89906   pWriter->iLastChildBlock++;
89907 #endif
89908   assert( pWriter->iLastChildBlock==iChildBlock );
89909
89910   /* Overflow to a new block if the new term makes the current block
89911   ** too big, and the current block already has enough terms.
89912   */
89913   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
89914       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
89915     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
89916                                            pTerm, nTerm);
89917     pWriter->last = pWriter->last->next;
89918     pWriter->iOpeningChildBlock = iChildBlock;
89919     dataBufferReset(&pWriter->term);
89920   }else{
89921     dataBufferAppend2(&pWriter->last->data, c, n,
89922                       pTerm+nPrefix, nTerm-nPrefix);
89923     dataBufferReplace(&pWriter->term, pTerm, nTerm);
89924   }
89925   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
89926 }
89927
89928 /* Free the space used by pWriter, including the linked-list of
89929 ** InteriorBlocks, and parentWriter, if present.
89930 */
89931 static int interiorWriterDestroy(InteriorWriter *pWriter){
89932   InteriorBlock *block = pWriter->first;
89933
89934   while( block!=NULL ){
89935     InteriorBlock *b = block;
89936     block = block->next;
89937     dataBufferDestroy(&b->term);
89938     dataBufferDestroy(&b->data);
89939     sqlite3_free(b);
89940   }
89941   if( pWriter->parentWriter!=NULL ){
89942     interiorWriterDestroy(pWriter->parentWriter);
89943     sqlite3_free(pWriter->parentWriter);
89944   }
89945   dataBufferDestroy(&pWriter->term);
89946   SCRAMBLE(pWriter);
89947   return SQLITE_OK;
89948 }
89949
89950 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
89951 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
89952 ** pWriter to %_segments, building a new layer of interior nodes, and
89953 ** recursively ask for their root into.
89954 */
89955 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
89956                                   char **ppRootInfo, int *pnRootInfo,
89957                                   sqlite_int64 *piEndBlockid){
89958   InteriorBlock *block = pWriter->first;
89959   sqlite_int64 iBlockid = 0;
89960   int rc;
89961
89962   /* If we can fit the segment inline */
89963   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
89964     *ppRootInfo = block->data.pData;
89965     *pnRootInfo = block->data.nData;
89966     return SQLITE_OK;
89967   }
89968
89969   /* Flush the first block to %_segments, and create a new level of
89970   ** interior node.
89971   */
89972   ASSERT_VALID_INTERIOR_BLOCK(block);
89973   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
89974   if( rc!=SQLITE_OK ) return rc;
89975   *piEndBlockid = iBlockid;
89976
89977   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
89978   interiorWriterInit(pWriter->iHeight+1,
89979                      block->term.pData, block->term.nData,
89980                      iBlockid, pWriter->parentWriter);
89981
89982   /* Flush additional blocks and append to the higher interior
89983   ** node.
89984   */
89985   for(block=block->next; block!=NULL; block=block->next){
89986     ASSERT_VALID_INTERIOR_BLOCK(block);
89987     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
89988     if( rc!=SQLITE_OK ) return rc;
89989     *piEndBlockid = iBlockid;
89990
89991     interiorWriterAppend(pWriter->parentWriter,
89992                          block->term.pData, block->term.nData, iBlockid);
89993   }
89994
89995   /* Parent node gets the chance to be the root. */
89996   return interiorWriterRootInfo(v, pWriter->parentWriter,
89997                                 ppRootInfo, pnRootInfo, piEndBlockid);
89998 }
89999
90000 /****************************************************************/
90001 /* InteriorReader is used to read off the data from an interior node
90002 ** (see comment at top of file for the format).
90003 */
90004 typedef struct InteriorReader {
90005   const char *pData;
90006   int nData;
90007
90008   DataBuffer term;          /* previous term, for decoding term delta. */
90009
90010   sqlite_int64 iBlockid;
90011 } InteriorReader;
90012
90013 static void interiorReaderDestroy(InteriorReader *pReader){
90014   dataBufferDestroy(&pReader->term);
90015   SCRAMBLE(pReader);
90016 }
90017
90018 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
90019 ** and the blob is empty or otherwise contains suspect data?
90020 */
90021 static void interiorReaderInit(const char *pData, int nData,
90022                                InteriorReader *pReader){
90023   int n, nTerm;
90024
90025   /* Require at least the leading flag byte */
90026   assert( nData>0 );
90027   assert( pData[0]!='\0' );
90028
90029   CLEAR(pReader);
90030
90031   /* Decode the base blockid, and set the cursor to the first term. */
90032   n = fts3GetVarint(pData+1, &pReader->iBlockid);
90033   assert( 1+n<=nData );
90034   pReader->pData = pData+1+n;
90035   pReader->nData = nData-(1+n);
90036
90037   /* A single-child interior node (such as when a leaf node was too
90038   ** large for the segment directory) won't have any terms.
90039   ** Otherwise, decode the first term.
90040   */
90041   if( pReader->nData==0 ){
90042     dataBufferInit(&pReader->term, 0);
90043   }else{
90044     n = fts3GetVarint32(pReader->pData, &nTerm);
90045     dataBufferInit(&pReader->term, nTerm);
90046     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
90047     assert( n+nTerm<=pReader->nData );
90048     pReader->pData += n+nTerm;
90049     pReader->nData -= n+nTerm;
90050   }
90051 }
90052
90053 static int interiorReaderAtEnd(InteriorReader *pReader){
90054   return pReader->term.nData==0;
90055 }
90056
90057 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
90058   return pReader->iBlockid;
90059 }
90060
90061 static int interiorReaderTermBytes(InteriorReader *pReader){
90062   assert( !interiorReaderAtEnd(pReader) );
90063   return pReader->term.nData;
90064 }
90065 static const char *interiorReaderTerm(InteriorReader *pReader){
90066   assert( !interiorReaderAtEnd(pReader) );
90067   return pReader->term.pData;
90068 }
90069
90070 /* Step forward to the next term in the node. */
90071 static void interiorReaderStep(InteriorReader *pReader){
90072   assert( !interiorReaderAtEnd(pReader) );
90073
90074   /* If the last term has been read, signal eof, else construct the
90075   ** next term.
90076   */
90077   if( pReader->nData==0 ){
90078     dataBufferReset(&pReader->term);
90079   }else{
90080     int n, nPrefix, nSuffix;
90081
90082     n = fts3GetVarint32(pReader->pData, &nPrefix);
90083     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
90084
90085     /* Truncate the current term and append suffix data. */
90086     pReader->term.nData = nPrefix;
90087     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
90088
90089     assert( n+nSuffix<=pReader->nData );
90090     pReader->pData += n+nSuffix;
90091     pReader->nData -= n+nSuffix;
90092   }
90093   pReader->iBlockid++;
90094 }
90095
90096 /* Compare the current term to pTerm[nTerm], returning strcmp-style
90097 ** results.  If isPrefix, equality means equal through nTerm bytes.
90098 */
90099 static int interiorReaderTermCmp(InteriorReader *pReader,
90100                                  const char *pTerm, int nTerm, int isPrefix){
90101   const char *pReaderTerm = interiorReaderTerm(pReader);
90102   int nReaderTerm = interiorReaderTermBytes(pReader);
90103   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
90104
90105   if( n==0 ){
90106     if( nReaderTerm>0 ) return -1;
90107     if( nTerm>0 ) return 1;
90108     return 0;
90109   }
90110
90111   c = memcmp(pReaderTerm, pTerm, n);
90112   if( c!=0 ) return c;
90113   if( isPrefix && n==nTerm ) return 0;
90114   return nReaderTerm - nTerm;
90115 }
90116
90117 /****************************************************************/
90118 /* LeafWriter is used to collect terms and associated doclist data
90119 ** into leaf blocks in %_segments (see top of file for format info).
90120 ** Expected usage is:
90121 **
90122 ** LeafWriter writer;
90123 ** leafWriterInit(0, 0, &writer);
90124 ** while( sorted_terms_left_to_process ){
90125 **   // data is doclist data for that term.
90126 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
90127 **   if( rc!=SQLITE_OK ) goto err;
90128 ** }
90129 ** rc = leafWriterFinalize(v, &writer);
90130 **err:
90131 ** leafWriterDestroy(&writer);
90132 ** return rc;
90133 **
90134 ** leafWriterStep() may write a collected leaf out to %_segments.
90135 ** leafWriterFinalize() finishes writing any buffered data and stores
90136 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
90137 ** InteriorWriters allocated as part of writing this segment.
90138 **
90139 ** TODO(shess) Document leafWriterStepMerge().
90140 */
90141
90142 /* Put terms with data this big in their own block. */
90143 #define STANDALONE_MIN 1024
90144
90145 /* Keep leaf blocks below this size. */
90146 #define LEAF_MAX 2048
90147
90148 typedef struct LeafWriter {
90149   int iLevel;
90150   int idx;
90151   sqlite_int64 iStartBlockid;     /* needed to create the root info */
90152   sqlite_int64 iEndBlockid;       /* when we're done writing. */
90153
90154   DataBuffer term;                /* previous encoded term */
90155   DataBuffer data;                /* encoding buffer */
90156
90157   /* bytes of first term in the current node which distinguishes that
90158   ** term from the last term of the previous node.
90159   */
90160   int nTermDistinct;
90161
90162   InteriorWriter parentWriter;    /* if we overflow */
90163   int has_parent;
90164 } LeafWriter;
90165
90166 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
90167   CLEAR(pWriter);
90168   pWriter->iLevel = iLevel;
90169   pWriter->idx = idx;
90170
90171   dataBufferInit(&pWriter->term, 32);
90172
90173   /* Start out with a reasonably sized block, though it can grow. */
90174   dataBufferInit(&pWriter->data, LEAF_MAX);
90175 }
90176
90177 #ifndef NDEBUG
90178 /* Verify that the data is readable as a leaf node. */
90179 static void leafNodeValidate(const char *pData, int nData){
90180   int n, iDummy;
90181
90182   if( nData==0 ) return;
90183   assert( nData>0 );
90184   assert( pData!=0 );
90185   assert( pData+nData>pData );
90186
90187   /* Must lead with a varint(0) */
90188   n = fts3GetVarint32(pData, &iDummy);
90189   assert( iDummy==0 );
90190   assert( n>0 );
90191   assert( n<nData );
90192   pData += n;
90193   nData -= n;
90194
90195   /* Leading term length and data must fit in buffer. */
90196   n = fts3GetVarint32(pData, &iDummy);
90197   assert( n>0 );
90198   assert( iDummy>0 );
90199   assert( n+iDummy>0 );
90200   assert( n+iDummy<nData );
90201   pData += n+iDummy;
90202   nData -= n+iDummy;
90203
90204   /* Leading term's doclist length and data must fit. */
90205   n = fts3GetVarint32(pData, &iDummy);
90206   assert( n>0 );
90207   assert( iDummy>0 );
90208   assert( n+iDummy>0 );
90209   assert( n+iDummy<=nData );
90210   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
90211   pData += n+iDummy;
90212   nData -= n+iDummy;
90213
90214   /* Verify that trailing terms and doclists also are readable. */
90215   while( nData!=0 ){
90216     n = fts3GetVarint32(pData, &iDummy);
90217     assert( n>0 );
90218     assert( iDummy>=0 );
90219     assert( n<nData );
90220     pData += n;
90221     nData -= n;
90222     n = fts3GetVarint32(pData, &iDummy);
90223     assert( n>0 );
90224     assert( iDummy>0 );
90225     assert( n+iDummy>0 );
90226     assert( n+iDummy<nData );
90227     pData += n+iDummy;
90228     nData -= n+iDummy;
90229
90230     n = fts3GetVarint32(pData, &iDummy);
90231     assert( n>0 );
90232     assert( iDummy>0 );
90233     assert( n+iDummy>0 );
90234     assert( n+iDummy<=nData );
90235     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
90236     pData += n+iDummy;
90237     nData -= n+iDummy;
90238   }
90239 }
90240 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
90241 #else
90242 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
90243 #endif
90244
90245 /* Flush the current leaf node to %_segments, and adding the resulting
90246 ** blockid and the starting term to the interior node which will
90247 ** contain it.
90248 */
90249 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
90250                                    int iData, int nData){
90251   sqlite_int64 iBlockid = 0;
90252   const char *pStartingTerm;
90253   int nStartingTerm, rc, n;
90254
90255   /* Must have the leading varint(0) flag, plus at least some
90256   ** valid-looking data.
90257   */
90258   assert( nData>2 );
90259   assert( iData>=0 );
90260   assert( iData+nData<=pWriter->data.nData );
90261   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
90262
90263   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
90264   if( rc!=SQLITE_OK ) return rc;
90265   assert( iBlockid!=0 );
90266
90267   /* Reconstruct the first term in the leaf for purposes of building
90268   ** the interior node.
90269   */
90270   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
90271   pStartingTerm = pWriter->data.pData+iData+1+n;
90272   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
90273   assert( pWriter->nTermDistinct>0 );
90274   assert( pWriter->nTermDistinct<=nStartingTerm );
90275   nStartingTerm = pWriter->nTermDistinct;
90276
90277   if( pWriter->has_parent ){
90278     interiorWriterAppend(&pWriter->parentWriter,
90279                          pStartingTerm, nStartingTerm, iBlockid);
90280   }else{
90281     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
90282                        &pWriter->parentWriter);
90283     pWriter->has_parent = 1;
90284   }
90285
90286   /* Track the span of this segment's leaf nodes. */
90287   if( pWriter->iEndBlockid==0 ){
90288     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
90289   }else{
90290     pWriter->iEndBlockid++;
90291     assert( iBlockid==pWriter->iEndBlockid );
90292   }
90293
90294   return SQLITE_OK;
90295 }
90296 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
90297   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
90298   if( rc!=SQLITE_OK ) return rc;
90299
90300   /* Re-initialize the output buffer. */
90301   dataBufferReset(&pWriter->data);
90302
90303   return SQLITE_OK;
90304 }
90305
90306 /* Fetch the root info for the segment.  If the entire leaf fits
90307 ** within ROOT_MAX, then it will be returned directly, otherwise it
90308 ** will be flushed and the root info will be returned from the
90309 ** interior node.  *piEndBlockid is set to the blockid of the last
90310 ** interior or leaf node written to disk (0 if none are written at
90311 ** all).
90312 */
90313 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
90314                               char **ppRootInfo, int *pnRootInfo,
90315                               sqlite_int64 *piEndBlockid){
90316   /* we can fit the segment entirely inline */
90317   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
90318     *ppRootInfo = pWriter->data.pData;
90319     *pnRootInfo = pWriter->data.nData;
90320     *piEndBlockid = 0;
90321     return SQLITE_OK;
90322   }
90323
90324   /* Flush remaining leaf data. */
90325   if( pWriter->data.nData>0 ){
90326     int rc = leafWriterFlush(v, pWriter);
90327     if( rc!=SQLITE_OK ) return rc;
90328   }
90329
90330   /* We must have flushed a leaf at some point. */
90331   assert( pWriter->has_parent );
90332
90333   /* Tenatively set the end leaf blockid as the end blockid.  If the
90334   ** interior node can be returned inline, this will be the final
90335   ** blockid, otherwise it will be overwritten by
90336   ** interiorWriterRootInfo().
90337   */
90338   *piEndBlockid = pWriter->iEndBlockid;
90339
90340   return interiorWriterRootInfo(v, &pWriter->parentWriter,
90341                                 ppRootInfo, pnRootInfo, piEndBlockid);
90342 }
90343
90344 /* Collect the rootInfo data and store it into the segment directory.
90345 ** This has the effect of flushing the segment's leaf data to
90346 ** %_segments, and also flushing any interior nodes to %_segments.
90347 */
90348 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
90349   sqlite_int64 iEndBlockid;
90350   char *pRootInfo;
90351   int rc, nRootInfo;
90352
90353   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
90354   if( rc!=SQLITE_OK ) return rc;
90355
90356   /* Don't bother storing an entirely empty segment. */
90357   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
90358
90359   return segdir_set(v, pWriter->iLevel, pWriter->idx,
90360                     pWriter->iStartBlockid, pWriter->iEndBlockid,
90361                     iEndBlockid, pRootInfo, nRootInfo);
90362 }
90363
90364 static void leafWriterDestroy(LeafWriter *pWriter){
90365   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
90366   dataBufferDestroy(&pWriter->term);
90367   dataBufferDestroy(&pWriter->data);
90368 }
90369
90370 /* Encode a term into the leafWriter, delta-encoding as appropriate.
90371 ** Returns the length of the new term which distinguishes it from the
90372 ** previous term, which can be used to set nTermDistinct when a node
90373 ** boundary is crossed.
90374 */
90375 static int leafWriterEncodeTerm(LeafWriter *pWriter,
90376                                 const char *pTerm, int nTerm){
90377   char c[VARINT_MAX+VARINT_MAX];
90378   int n, nPrefix = 0;
90379
90380   assert( nTerm>0 );
90381   while( nPrefix<pWriter->term.nData &&
90382          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
90383     nPrefix++;
90384     /* Failing this implies that the terms weren't in order. */
90385     assert( nPrefix<nTerm );
90386   }
90387
90388   if( pWriter->data.nData==0 ){
90389     /* Encode the node header and leading term as:
90390     **  varint(0)
90391     **  varint(nTerm)
90392     **  char pTerm[nTerm]
90393     */
90394     n = fts3PutVarint(c, '\0');
90395     n += fts3PutVarint(c+n, nTerm);
90396     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
90397   }else{
90398     /* Delta-encode the term as:
90399     **  varint(nPrefix)
90400     **  varint(nSuffix)
90401     **  char pTermSuffix[nSuffix]
90402     */
90403     n = fts3PutVarint(c, nPrefix);
90404     n += fts3PutVarint(c+n, nTerm-nPrefix);
90405     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
90406   }
90407   dataBufferReplace(&pWriter->term, pTerm, nTerm);
90408
90409   return nPrefix+1;
90410 }
90411
90412 /* Used to avoid a memmove when a large amount of doclist data is in
90413 ** the buffer.  This constructs a node and term header before
90414 ** iDoclistData and flushes the resulting complete node using
90415 ** leafWriterInternalFlush().
90416 */
90417 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
90418                                  const char *pTerm, int nTerm,
90419                                  int iDoclistData){
90420   char c[VARINT_MAX+VARINT_MAX];
90421   int iData, n = fts3PutVarint(c, 0);
90422   n += fts3PutVarint(c+n, nTerm);
90423
90424   /* There should always be room for the header.  Even if pTerm shared
90425   ** a substantial prefix with the previous term, the entire prefix
90426   ** could be constructed from earlier data in the doclist, so there
90427   ** should be room.
90428   */
90429   assert( iDoclistData>=n+nTerm );
90430
90431   iData = iDoclistData-(n+nTerm);
90432   memcpy(pWriter->data.pData+iData, c, n);
90433   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
90434
90435   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
90436 }
90437
90438 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
90439 ** %_segments.
90440 */
90441 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
90442                                const char *pTerm, int nTerm,
90443                                DLReader *pReaders, int nReaders){
90444   char c[VARINT_MAX+VARINT_MAX];
90445   int iTermData = pWriter->data.nData, iDoclistData;
90446   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
90447
90448   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
90449   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
90450
90451   /* Remember nTermDistinct if opening a new node. */
90452   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
90453
90454   iDoclistData = pWriter->data.nData;
90455
90456   /* Estimate the length of the merged doclist so we can leave space
90457   ** to encode it.
90458   */
90459   for(i=0, nData=0; i<nReaders; i++){
90460     nData += dlrAllDataBytes(&pReaders[i]);
90461   }
90462   n = fts3PutVarint(c, nData);
90463   dataBufferAppend(&pWriter->data, c, n);
90464
90465   docListMerge(&pWriter->data, pReaders, nReaders);
90466   ASSERT_VALID_DOCLIST(DL_DEFAULT,
90467                        pWriter->data.pData+iDoclistData+n,
90468                        pWriter->data.nData-iDoclistData-n, NULL);
90469
90470   /* The actual amount of doclist data at this point could be smaller
90471   ** than the length we encoded.  Additionally, the space required to
90472   ** encode this length could be smaller.  For small doclists, this is
90473   ** not a big deal, we can just use memmove() to adjust things.
90474   */
90475   nActualData = pWriter->data.nData-(iDoclistData+n);
90476   nActual = fts3PutVarint(c, nActualData);
90477   assert( nActualData<=nData );
90478   assert( nActual<=n );
90479
90480   /* If the new doclist is big enough for force a standalone leaf
90481   ** node, we can immediately flush it inline without doing the
90482   ** memmove().
90483   */
90484   /* TODO(shess) This test matches leafWriterStep(), which does this
90485   ** test before it knows the cost to varint-encode the term and
90486   ** doclist lengths.  At some point, change to
90487   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
90488   */
90489   if( nTerm+nActualData>STANDALONE_MIN ){
90490     /* Push leaf node from before this term. */
90491     if( iTermData>0 ){
90492       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
90493       if( rc!=SQLITE_OK ) return rc;
90494
90495       pWriter->nTermDistinct = nTermDistinct;
90496     }
90497
90498     /* Fix the encoded doclist length. */
90499     iDoclistData += n - nActual;
90500     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
90501
90502     /* Push the standalone leaf node. */
90503     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
90504     if( rc!=SQLITE_OK ) return rc;
90505
90506     /* Leave the node empty. */
90507     dataBufferReset(&pWriter->data);
90508
90509     return rc;
90510   }
90511
90512   /* At this point, we know that the doclist was small, so do the
90513   ** memmove if indicated.
90514   */
90515   if( nActual<n ){
90516     memmove(pWriter->data.pData+iDoclistData+nActual,
90517             pWriter->data.pData+iDoclistData+n,
90518             pWriter->data.nData-(iDoclistData+n));
90519     pWriter->data.nData -= n-nActual;
90520   }
90521
90522   /* Replace written length with actual length. */
90523   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
90524
90525   /* If the node is too large, break things up. */
90526   /* TODO(shess) This test matches leafWriterStep(), which does this
90527   ** test before it knows the cost to varint-encode the term and
90528   ** doclist lengths.  At some point, change to
90529   ** pWriter->data.nData>LEAF_MAX.
90530   */
90531   if( iTermData+nTerm+nActualData>LEAF_MAX ){
90532     /* Flush out the leading data as a node */
90533     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
90534     if( rc!=SQLITE_OK ) return rc;
90535
90536     pWriter->nTermDistinct = nTermDistinct;
90537
90538     /* Rebuild header using the current term */
90539     n = fts3PutVarint(pWriter->data.pData, 0);
90540     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
90541     memcpy(pWriter->data.pData+n, pTerm, nTerm);
90542     n += nTerm;
90543
90544     /* There should always be room, because the previous encoding
90545     ** included all data necessary to construct the term.
90546     */
90547     assert( n<iDoclistData );
90548     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
90549     ** following memcpy() is safe (as opposed to needing a memmove).
90550     */
90551     assert( 2*STANDALONE_MIN<=LEAF_MAX );
90552     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
90553     memcpy(pWriter->data.pData+n,
90554            pWriter->data.pData+iDoclistData,
90555            pWriter->data.nData-iDoclistData);
90556     pWriter->data.nData -= iDoclistData-n;
90557   }
90558   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
90559
90560   return SQLITE_OK;
90561 }
90562
90563 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
90564 ** %_segments.
90565 */
90566 /* TODO(shess) Revise writeZeroSegment() so that doclists are
90567 ** constructed directly in pWriter->data.
90568 */
90569 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
90570                           const char *pTerm, int nTerm,
90571                           const char *pData, int nData){
90572   int rc;
90573   DLReader reader;
90574
90575   dlrInit(&reader, DL_DEFAULT, pData, nData);
90576   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
90577   dlrDestroy(&reader);
90578
90579   return rc;
90580 }
90581
90582
90583 /****************************************************************/
90584 /* LeafReader is used to iterate over an individual leaf node. */
90585 typedef struct LeafReader {
90586   DataBuffer term;          /* copy of current term. */
90587
90588   const char *pData;        /* data for current term. */
90589   int nData;
90590 } LeafReader;
90591
90592 static void leafReaderDestroy(LeafReader *pReader){
90593   dataBufferDestroy(&pReader->term);
90594   SCRAMBLE(pReader);
90595 }
90596
90597 static int leafReaderAtEnd(LeafReader *pReader){
90598   return pReader->nData<=0;
90599 }
90600
90601 /* Access the current term. */
90602 static int leafReaderTermBytes(LeafReader *pReader){
90603   return pReader->term.nData;
90604 }
90605 static const char *leafReaderTerm(LeafReader *pReader){
90606   assert( pReader->term.nData>0 );
90607   return pReader->term.pData;
90608 }
90609
90610 /* Access the doclist data for the current term. */
90611 static int leafReaderDataBytes(LeafReader *pReader){
90612   int nData;
90613   assert( pReader->term.nData>0 );
90614   fts3GetVarint32(pReader->pData, &nData);
90615   return nData;
90616 }
90617 static const char *leafReaderData(LeafReader *pReader){
90618   int n, nData;
90619   assert( pReader->term.nData>0 );
90620   n = fts3GetVarint32(pReader->pData, &nData);
90621   return pReader->pData+n;
90622 }
90623
90624 static void leafReaderInit(const char *pData, int nData,
90625                            LeafReader *pReader){
90626   int nTerm, n;
90627
90628   assert( nData>0 );
90629   assert( pData[0]=='\0' );
90630
90631   CLEAR(pReader);
90632
90633   /* Read the first term, skipping the header byte. */
90634   n = fts3GetVarint32(pData+1, &nTerm);
90635   dataBufferInit(&pReader->term, nTerm);
90636   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
90637
90638   /* Position after the first term. */
90639   assert( 1+n+nTerm<nData );
90640   pReader->pData = pData+1+n+nTerm;
90641   pReader->nData = nData-1-n-nTerm;
90642 }
90643
90644 /* Step the reader forward to the next term. */
90645 static void leafReaderStep(LeafReader *pReader){
90646   int n, nData, nPrefix, nSuffix;
90647   assert( !leafReaderAtEnd(pReader) );
90648
90649   /* Skip previous entry's data block. */
90650   n = fts3GetVarint32(pReader->pData, &nData);
90651   assert( n+nData<=pReader->nData );
90652   pReader->pData += n+nData;
90653   pReader->nData -= n+nData;
90654
90655   if( !leafReaderAtEnd(pReader) ){
90656     /* Construct the new term using a prefix from the old term plus a
90657     ** suffix from the leaf data.
90658     */
90659     n = fts3GetVarint32(pReader->pData, &nPrefix);
90660     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
90661     assert( n+nSuffix<pReader->nData );
90662     pReader->term.nData = nPrefix;
90663     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
90664
90665     pReader->pData += n+nSuffix;
90666     pReader->nData -= n+nSuffix;
90667   }
90668 }
90669
90670 /* strcmp-style comparison of pReader's current term against pTerm.
90671 ** If isPrefix, equality means equal through nTerm bytes.
90672 */
90673 static int leafReaderTermCmp(LeafReader *pReader,
90674                              const char *pTerm, int nTerm, int isPrefix){
90675   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
90676   if( n==0 ){
90677     if( pReader->term.nData>0 ) return -1;
90678     if(nTerm>0 ) return 1;
90679     return 0;
90680   }
90681
90682   c = memcmp(pReader->term.pData, pTerm, n);
90683   if( c!=0 ) return c;
90684   if( isPrefix && n==nTerm ) return 0;
90685   return pReader->term.nData - nTerm;
90686 }
90687
90688
90689 /****************************************************************/
90690 /* LeavesReader wraps LeafReader to allow iterating over the entire
90691 ** leaf layer of the tree.
90692 */
90693 typedef struct LeavesReader {
90694   int idx;                  /* Index within the segment. */
90695
90696   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
90697   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
90698
90699   LeafReader leafReader;    /* reader for the current leaf. */
90700   DataBuffer rootData;      /* root data for inline. */
90701 } LeavesReader;
90702
90703 /* Access the current term. */
90704 static int leavesReaderTermBytes(LeavesReader *pReader){
90705   assert( !pReader->eof );
90706   return leafReaderTermBytes(&pReader->leafReader);
90707 }
90708 static const char *leavesReaderTerm(LeavesReader *pReader){
90709   assert( !pReader->eof );
90710   return leafReaderTerm(&pReader->leafReader);
90711 }
90712
90713 /* Access the doclist data for the current term. */
90714 static int leavesReaderDataBytes(LeavesReader *pReader){
90715   assert( !pReader->eof );
90716   return leafReaderDataBytes(&pReader->leafReader);
90717 }
90718 static const char *leavesReaderData(LeavesReader *pReader){
90719   assert( !pReader->eof );
90720   return leafReaderData(&pReader->leafReader);
90721 }
90722
90723 static int leavesReaderAtEnd(LeavesReader *pReader){
90724   return pReader->eof;
90725 }
90726
90727 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
90728 ** leaving the statement handle open, which locks the table.
90729 */
90730 /* TODO(shess) This "solution" is not satisfactory.  Really, there
90731 ** should be check-in function for all statement handles which
90732 ** arranges to call sqlite3_reset().  This most likely will require
90733 ** modification to control flow all over the place, though, so for now
90734 ** just punt.
90735 **
90736 ** Note the the current system assumes that segment merges will run to
90737 ** completion, which is why this particular probably hasn't arisen in
90738 ** this case.  Probably a brittle assumption.
90739 */
90740 static int leavesReaderReset(LeavesReader *pReader){
90741   return sqlite3_reset(pReader->pStmt);
90742 }
90743
90744 static void leavesReaderDestroy(LeavesReader *pReader){
90745   /* If idx is -1, that means we're using a non-cached statement
90746   ** handle in the optimize() case, so we need to release it.
90747   */
90748   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
90749     sqlite3_finalize(pReader->pStmt);
90750   }
90751   leafReaderDestroy(&pReader->leafReader);
90752   dataBufferDestroy(&pReader->rootData);
90753   SCRAMBLE(pReader);
90754 }
90755
90756 /* Initialize pReader with the given root data (if iStartBlockid==0
90757 ** the leaf data was entirely contained in the root), or from the
90758 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
90759 */
90760 static int leavesReaderInit(fulltext_vtab *v,
90761                             int idx,
90762                             sqlite_int64 iStartBlockid,
90763                             sqlite_int64 iEndBlockid,
90764                             const char *pRootData, int nRootData,
90765                             LeavesReader *pReader){
90766   CLEAR(pReader);
90767   pReader->idx = idx;
90768
90769   dataBufferInit(&pReader->rootData, 0);
90770   if( iStartBlockid==0 ){
90771     /* Entire leaf level fit in root data. */
90772     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
90773     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
90774                    &pReader->leafReader);
90775   }else{
90776     sqlite3_stmt *s;
90777     int rc = sql_get_leaf_statement(v, idx, &s);
90778     if( rc!=SQLITE_OK ) return rc;
90779
90780     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
90781     if( rc!=SQLITE_OK ) return rc;
90782
90783     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
90784     if( rc!=SQLITE_OK ) return rc;
90785
90786     rc = sqlite3_step(s);
90787     if( rc==SQLITE_DONE ){
90788       pReader->eof = 1;
90789       return SQLITE_OK;
90790     }
90791     if( rc!=SQLITE_ROW ) return rc;
90792
90793     pReader->pStmt = s;
90794     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
90795                    sqlite3_column_bytes(pReader->pStmt, 0),
90796                    &pReader->leafReader);
90797   }
90798   return SQLITE_OK;
90799 }
90800
90801 /* Step the current leaf forward to the next term.  If we reach the
90802 ** end of the current leaf, step forward to the next leaf block.
90803 */
90804 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
90805   assert( !leavesReaderAtEnd(pReader) );
90806   leafReaderStep(&pReader->leafReader);
90807
90808   if( leafReaderAtEnd(&pReader->leafReader) ){
90809     int rc;
90810     if( pReader->rootData.pData ){
90811       pReader->eof = 1;
90812       return SQLITE_OK;
90813     }
90814     rc = sqlite3_step(pReader->pStmt);
90815     if( rc!=SQLITE_ROW ){
90816       pReader->eof = 1;
90817       return rc==SQLITE_DONE ? SQLITE_OK : rc;
90818     }
90819     leafReaderDestroy(&pReader->leafReader);
90820     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
90821                    sqlite3_column_bytes(pReader->pStmt, 0),
90822                    &pReader->leafReader);
90823   }
90824   return SQLITE_OK;
90825 }
90826
90827 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
90828 ** always sort to the end.
90829 */
90830 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
90831   if( leavesReaderAtEnd(lr1) ){
90832     if( leavesReaderAtEnd(lr2) ) return 0;
90833     return 1;
90834   }
90835   if( leavesReaderAtEnd(lr2) ) return -1;
90836
90837   return leafReaderTermCmp(&lr1->leafReader,
90838                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
90839                            0);
90840 }
90841
90842 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
90843 ** so that older segments sort before newer segments.
90844 */
90845 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
90846   int c = leavesReaderTermCmp(lr1, lr2);
90847   if( c!=0 ) return c;
90848   return lr1->idx-lr2->idx;
90849 }
90850
90851 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
90852 ** sorted position.
90853 */
90854 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
90855   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
90856     LeavesReader tmp = pLr[0];
90857     pLr[0] = pLr[1];
90858     pLr[1] = tmp;
90859     nLr--;
90860     pLr++;
90861   }
90862 }
90863
90864 /* Initializes pReaders with the segments from level iLevel, returning
90865 ** the number of segments in *piReaders.  Leaves pReaders in sorted
90866 ** order.
90867 */
90868 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
90869                              LeavesReader *pReaders, int *piReaders){
90870   sqlite3_stmt *s;
90871   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
90872   if( rc!=SQLITE_OK ) return rc;
90873
90874   rc = sqlite3_bind_int(s, 1, iLevel);
90875   if( rc!=SQLITE_OK ) return rc;
90876
90877   i = 0;
90878   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
90879     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
90880     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
90881     const char *pRootData = sqlite3_column_blob(s, 2);
90882     int nRootData = sqlite3_column_bytes(s, 2);
90883
90884     assert( i<MERGE_COUNT );
90885     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
90886                           &pReaders[i]);
90887     if( rc!=SQLITE_OK ) break;
90888
90889     i++;
90890   }
90891   if( rc!=SQLITE_DONE ){
90892     while( i-->0 ){
90893       leavesReaderDestroy(&pReaders[i]);
90894     }
90895     return rc;
90896   }
90897
90898   *piReaders = i;
90899
90900   /* Leave our results sorted by term, then age. */
90901   while( i-- ){
90902     leavesReaderReorder(pReaders+i, *piReaders-i);
90903   }
90904   return SQLITE_OK;
90905 }
90906
90907 /* Merge doclists from pReaders[nReaders] into a single doclist, which
90908 ** is written to pWriter.  Assumes pReaders is ordered oldest to
90909 ** newest.
90910 */
90911 /* TODO(shess) Consider putting this inline in segmentMerge(). */
90912 static int leavesReadersMerge(fulltext_vtab *v,
90913                               LeavesReader *pReaders, int nReaders,
90914                               LeafWriter *pWriter){
90915   DLReader dlReaders[MERGE_COUNT];
90916   const char *pTerm = leavesReaderTerm(pReaders);
90917   int i, nTerm = leavesReaderTermBytes(pReaders);
90918
90919   assert( nReaders<=MERGE_COUNT );
90920
90921   for(i=0; i<nReaders; i++){
90922     dlrInit(&dlReaders[i], DL_DEFAULT,
90923             leavesReaderData(pReaders+i),
90924             leavesReaderDataBytes(pReaders+i));
90925   }
90926
90927   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
90928 }
90929
90930 /* Forward ref due to mutual recursion with segdirNextIndex(). */
90931 static int segmentMerge(fulltext_vtab *v, int iLevel);
90932
90933 /* Put the next available index at iLevel into *pidx.  If iLevel
90934 ** already has MERGE_COUNT segments, they are merged to a higher
90935 ** level to make room.
90936 */
90937 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
90938   int rc = segdir_max_index(v, iLevel, pidx);
90939   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
90940     *pidx = 0;
90941   }else if( rc==SQLITE_ROW ){
90942     if( *pidx==(MERGE_COUNT-1) ){
90943       rc = segmentMerge(v, iLevel);
90944       if( rc!=SQLITE_OK ) return rc;
90945       *pidx = 0;
90946     }else{
90947       (*pidx)++;
90948     }
90949   }else{
90950     return rc;
90951   }
90952   return SQLITE_OK;
90953 }
90954
90955 /* Merge MERGE_COUNT segments at iLevel into a new segment at
90956 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
90957 ** merged to make room.
90958 */
90959 static int segmentMerge(fulltext_vtab *v, int iLevel){
90960   LeafWriter writer;
90961   LeavesReader lrs[MERGE_COUNT];
90962   int i, rc, idx = 0;
90963
90964   /* Determine the next available segment index at the next level,
90965   ** merging as necessary.
90966   */
90967   rc = segdirNextIndex(v, iLevel+1, &idx);
90968   if( rc!=SQLITE_OK ) return rc;
90969
90970   /* TODO(shess) This assumes that we'll always see exactly
90971   ** MERGE_COUNT segments to merge at a given level.  That will be
90972   ** broken if we allow the developer to request preemptive or
90973   ** deferred merging.
90974   */
90975   memset(&lrs, '\0', sizeof(lrs));
90976   rc = leavesReadersInit(v, iLevel, lrs, &i);
90977   if( rc!=SQLITE_OK ) return rc;
90978   assert( i==MERGE_COUNT );
90979
90980   leafWriterInit(iLevel+1, idx, &writer);
90981
90982   /* Since leavesReaderReorder() pushes readers at eof to the end,
90983   ** when the first reader is empty, all will be empty.
90984   */
90985   while( !leavesReaderAtEnd(lrs) ){
90986     /* Figure out how many readers share their next term. */
90987     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
90988       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
90989     }
90990
90991     rc = leavesReadersMerge(v, lrs, i, &writer);
90992     if( rc!=SQLITE_OK ) goto err;
90993
90994     /* Step forward those that were merged. */
90995     while( i-->0 ){
90996       rc = leavesReaderStep(v, lrs+i);
90997       if( rc!=SQLITE_OK ) goto err;
90998
90999       /* Reorder by term, then by age. */
91000       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
91001     }
91002   }
91003
91004   for(i=0; i<MERGE_COUNT; i++){
91005     leavesReaderDestroy(&lrs[i]);
91006   }
91007
91008   rc = leafWriterFinalize(v, &writer);
91009   leafWriterDestroy(&writer);
91010   if( rc!=SQLITE_OK ) return rc;
91011
91012   /* Delete the merged segment data. */
91013   return segdir_delete(v, iLevel);
91014
91015  err:
91016   for(i=0; i<MERGE_COUNT; i++){
91017     leavesReaderDestroy(&lrs[i]);
91018   }
91019   leafWriterDestroy(&writer);
91020   return rc;
91021 }
91022
91023 /* Accumulate the union of *acc and *pData into *acc. */
91024 static void docListAccumulateUnion(DataBuffer *acc,
91025                                    const char *pData, int nData) {
91026   DataBuffer tmp = *acc;
91027   dataBufferInit(acc, tmp.nData+nData);
91028   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
91029   dataBufferDestroy(&tmp);
91030 }
91031
91032 /* TODO(shess) It might be interesting to explore different merge
91033 ** strategies, here.  For instance, since this is a sorted merge, we
91034 ** could easily merge many doclists in parallel.  With some
91035 ** comprehension of the storage format, we could merge all of the
91036 ** doclists within a leaf node directly from the leaf node's storage.
91037 ** It may be worthwhile to merge smaller doclists before larger
91038 ** doclists, since they can be traversed more quickly - but the
91039 ** results may have less overlap, making them more expensive in a
91040 ** different way.
91041 */
91042
91043 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
91044 ** *out (any doclists with duplicate docids overwrite those in *out).
91045 ** Internal function for loadSegmentLeaf().
91046 */
91047 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
91048                                 const char *pTerm, int nTerm, int isPrefix,
91049                                 DataBuffer *out){
91050   /* doclist data is accumulated into pBuffers similar to how one does
91051   ** increment in binary arithmetic.  If index 0 is empty, the data is
91052   ** stored there.  If there is data there, it is merged and the
91053   ** results carried into position 1, with further merge-and-carry
91054   ** until an empty position is found.
91055   */
91056   DataBuffer *pBuffers = NULL;
91057   int nBuffers = 0, nMaxBuffers = 0, rc;
91058
91059   assert( nTerm>0 );
91060
91061   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
91062       rc=leavesReaderStep(v, pReader)){
91063     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
91064     ** already taken to compare the terms of two LeavesReaders.  Think
91065     ** on a better name.  [Meanwhile, break encapsulation rather than
91066     ** use a confusing name.]
91067     */
91068     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
91069     if( c>0 ) break;      /* Past any possible matches. */
91070     if( c==0 ){
91071       const char *pData = leavesReaderData(pReader);
91072       int iBuffer, nData = leavesReaderDataBytes(pReader);
91073
91074       /* Find the first empty buffer. */
91075       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
91076         if( 0==pBuffers[iBuffer].nData ) break;
91077       }
91078
91079       /* Out of buffers, add an empty one. */
91080       if( iBuffer==nBuffers ){
91081         if( nBuffers==nMaxBuffers ){
91082           DataBuffer *p;
91083           nMaxBuffers += 20;
91084
91085           /* Manual realloc so we can handle NULL appropriately. */
91086           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
91087           if( p==NULL ){
91088             rc = SQLITE_NOMEM;
91089             break;
91090           }
91091
91092           if( nBuffers>0 ){
91093             assert(pBuffers!=NULL);
91094             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
91095             sqlite3_free(pBuffers);
91096           }
91097           pBuffers = p;
91098         }
91099         dataBufferInit(&(pBuffers[nBuffers]), 0);
91100         nBuffers++;
91101       }
91102
91103       /* At this point, must have an empty at iBuffer. */
91104       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
91105
91106       /* If empty was first buffer, no need for merge logic. */
91107       if( iBuffer==0 ){
91108         dataBufferReplace(&(pBuffers[0]), pData, nData);
91109       }else{
91110         /* pAcc is the empty buffer the merged data will end up in. */
91111         DataBuffer *pAcc = &(pBuffers[iBuffer]);
91112         DataBuffer *p = &(pBuffers[0]);
91113
91114         /* Handle position 0 specially to avoid need to prime pAcc
91115         ** with pData/nData.
91116         */
91117         dataBufferSwap(p, pAcc);
91118         docListAccumulateUnion(pAcc, pData, nData);
91119
91120         /* Accumulate remaining doclists into pAcc. */
91121         for(++p; p<pAcc; ++p){
91122           docListAccumulateUnion(pAcc, p->pData, p->nData);
91123
91124           /* dataBufferReset() could allow a large doclist to blow up
91125           ** our memory requirements.
91126           */
91127           if( p->nCapacity<1024 ){
91128             dataBufferReset(p);
91129           }else{
91130             dataBufferDestroy(p);
91131             dataBufferInit(p, 0);
91132           }
91133         }
91134       }
91135     }
91136   }
91137
91138   /* Union all the doclists together into *out. */
91139   /* TODO(shess) What if *out is big?  Sigh. */
91140   if( rc==SQLITE_OK && nBuffers>0 ){
91141     int iBuffer;
91142     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
91143       if( pBuffers[iBuffer].nData>0 ){
91144         if( out->nData==0 ){
91145           dataBufferSwap(out, &(pBuffers[iBuffer]));
91146         }else{
91147           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
91148                                  pBuffers[iBuffer].nData);
91149         }
91150       }
91151     }
91152   }
91153
91154   while( nBuffers-- ){
91155     dataBufferDestroy(&(pBuffers[nBuffers]));
91156   }
91157   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
91158
91159   return rc;
91160 }
91161
91162 /* Call loadSegmentLeavesInt() with pData/nData as input. */
91163 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
91164                            const char *pTerm, int nTerm, int isPrefix,
91165                            DataBuffer *out){
91166   LeavesReader reader;
91167   int rc;
91168
91169   assert( nData>1 );
91170   assert( *pData=='\0' );
91171   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
91172   if( rc!=SQLITE_OK ) return rc;
91173
91174   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
91175   leavesReaderReset(&reader);
91176   leavesReaderDestroy(&reader);
91177   return rc;
91178 }
91179
91180 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
91181 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
91182 ** out.
91183 */
91184 static int loadSegmentLeaves(fulltext_vtab *v,
91185                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
91186                              const char *pTerm, int nTerm, int isPrefix,
91187                              DataBuffer *out){
91188   int rc;
91189   LeavesReader reader;
91190
91191   assert( iStartLeaf<=iEndLeaf );
91192   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
91193   if( rc!=SQLITE_OK ) return rc;
91194
91195   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
91196   leavesReaderReset(&reader);
91197   leavesReaderDestroy(&reader);
91198   return rc;
91199 }
91200
91201 /* Taking pData/nData as an interior node, find the sequence of child
91202 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
91203 ** interior node terms logically come between the blocks, so there is
91204 ** one more blockid than there are terms (that block contains terms >=
91205 ** the last interior-node term).
91206 */
91207 /* TODO(shess) The calling code may already know that the end child is
91208 ** not worth calculating, because the end may be in a later sibling
91209 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
91210 ** it is not worthwhile.
91211 */
91212 static void getChildrenContaining(const char *pData, int nData,
91213                                   const char *pTerm, int nTerm, int isPrefix,
91214                                   sqlite_int64 *piStartChild,
91215                                   sqlite_int64 *piEndChild){
91216   InteriorReader reader;
91217
91218   assert( nData>1 );
91219   assert( *pData!='\0' );
91220   interiorReaderInit(pData, nData, &reader);
91221
91222   /* Scan for the first child which could contain pTerm/nTerm. */
91223   while( !interiorReaderAtEnd(&reader) ){
91224     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
91225     interiorReaderStep(&reader);
91226   }
91227   *piStartChild = interiorReaderCurrentBlockid(&reader);
91228
91229   /* Keep scanning to find a term greater than our term, using prefix
91230   ** comparison if indicated.  If isPrefix is false, this will be the
91231   ** same blockid as the starting block.
91232   */
91233   while( !interiorReaderAtEnd(&reader) ){
91234     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
91235     interiorReaderStep(&reader);
91236   }
91237   *piEndChild = interiorReaderCurrentBlockid(&reader);
91238
91239   interiorReaderDestroy(&reader);
91240
91241   /* Children must ascend, and if !prefix, both must be the same. */
91242   assert( *piEndChild>=*piStartChild );
91243   assert( isPrefix || *piStartChild==*piEndChild );
91244 }
91245
91246 /* Read block at iBlockid and pass it with other params to
91247 ** getChildrenContaining().
91248 */
91249 static int loadAndGetChildrenContaining(
91250   fulltext_vtab *v,
91251   sqlite_int64 iBlockid,
91252   const char *pTerm, int nTerm, int isPrefix,
91253   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
91254 ){
91255   sqlite3_stmt *s = NULL;
91256   int rc;
91257
91258   assert( iBlockid!=0 );
91259   assert( pTerm!=NULL );
91260   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
91261   assert( piStartChild!=NULL );
91262   assert( piEndChild!=NULL );
91263
91264   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
91265   if( rc!=SQLITE_OK ) return rc;
91266
91267   rc = sqlite3_bind_int64(s, 1, iBlockid);
91268   if( rc!=SQLITE_OK ) return rc;
91269
91270   rc = sqlite3_step(s);
91271   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
91272   if( rc!=SQLITE_ROW ) return rc;
91273
91274   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
91275                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
91276
91277   /* We expect only one row.  We must execute another sqlite3_step()
91278    * to complete the iteration; otherwise the table will remain
91279    * locked. */
91280   rc = sqlite3_step(s);
91281   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
91282   if( rc!=SQLITE_DONE ) return rc;
91283
91284   return SQLITE_OK;
91285 }
91286
91287 /* Traverse the tree represented by pData[nData] looking for
91288 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
91289 ** loadSegment() to make error-handling cleaner.
91290 */
91291 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
91292                           sqlite_int64 iLeavesEnd,
91293                           const char *pTerm, int nTerm, int isPrefix,
91294                           DataBuffer *out){
91295   /* Special case where root is a leaf. */
91296   if( *pData=='\0' ){
91297     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
91298   }else{
91299     int rc;
91300     sqlite_int64 iStartChild, iEndChild;
91301
91302     /* Process pData as an interior node, then loop down the tree
91303     ** until we find the set of leaf nodes to scan for the term.
91304     */
91305     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
91306                           &iStartChild, &iEndChild);
91307     while( iStartChild>iLeavesEnd ){
91308       sqlite_int64 iNextStart, iNextEnd;
91309       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
91310                                         &iNextStart, &iNextEnd);
91311       if( rc!=SQLITE_OK ) return rc;
91312
91313       /* If we've branched, follow the end branch, too. */
91314       if( iStartChild!=iEndChild ){
91315         sqlite_int64 iDummy;
91316         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
91317                                           &iDummy, &iNextEnd);
91318         if( rc!=SQLITE_OK ) return rc;
91319       }
91320
91321       assert( iNextStart<=iNextEnd );
91322       iStartChild = iNextStart;
91323       iEndChild = iNextEnd;
91324     }
91325     assert( iStartChild<=iLeavesEnd );
91326     assert( iEndChild<=iLeavesEnd );
91327
91328     /* Scan through the leaf segments for doclists. */
91329     return loadSegmentLeaves(v, iStartChild, iEndChild,
91330                              pTerm, nTerm, isPrefix, out);
91331   }
91332 }
91333
91334 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
91335 ** merge its doclist over *out (any duplicate doclists read from the
91336 ** segment rooted at pData will overwrite those in *out).
91337 */
91338 /* TODO(shess) Consider changing this to determine the depth of the
91339 ** leaves using either the first characters of interior nodes (when
91340 ** ==1, we're one level above the leaves), or the first character of
91341 ** the root (which will describe the height of the tree directly).
91342 ** Either feels somewhat tricky to me.
91343 */
91344 /* TODO(shess) The current merge is likely to be slow for large
91345 ** doclists (though it should process from newest/smallest to
91346 ** oldest/largest, so it may not be that bad).  It might be useful to
91347 ** modify things to allow for N-way merging.  This could either be
91348 ** within a segment, with pairwise merges across segments, or across
91349 ** all segments at once.
91350 */
91351 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
91352                        sqlite_int64 iLeavesEnd,
91353                        const char *pTerm, int nTerm, int isPrefix,
91354                        DataBuffer *out){
91355   DataBuffer result;
91356   int rc;
91357
91358   assert( nData>1 );
91359
91360   /* This code should never be called with buffered updates. */
91361   assert( v->nPendingData<0 );
91362
91363   dataBufferInit(&result, 0);
91364   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
91365                       pTerm, nTerm, isPrefix, &result);
91366   if( rc==SQLITE_OK && result.nData>0 ){
91367     if( out->nData==0 ){
91368       DataBuffer tmp = *out;
91369       *out = result;
91370       result = tmp;
91371     }else{
91372       DataBuffer merged;
91373       DLReader readers[2];
91374
91375       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
91376       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
91377       dataBufferInit(&merged, out->nData+result.nData);
91378       docListMerge(&merged, readers, 2);
91379       dataBufferDestroy(out);
91380       *out = merged;
91381       dlrDestroy(&readers[0]);
91382       dlrDestroy(&readers[1]);
91383     }
91384   }
91385   dataBufferDestroy(&result);
91386   return rc;
91387 }
91388
91389 /* Scan the database and merge together the posting lists for the term
91390 ** into *out.
91391 */
91392 static int termSelect(fulltext_vtab *v, int iColumn,
91393                       const char *pTerm, int nTerm, int isPrefix,
91394                       DocListType iType, DataBuffer *out){
91395   DataBuffer doclist;
91396   sqlite3_stmt *s;
91397   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
91398   if( rc!=SQLITE_OK ) return rc;
91399
91400   /* This code should never be called with buffered updates. */
91401   assert( v->nPendingData<0 );
91402
91403   dataBufferInit(&doclist, 0);
91404
91405   /* Traverse the segments from oldest to newest so that newer doclist
91406   ** elements for given docids overwrite older elements.
91407   */
91408   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
91409     const char *pData = sqlite3_column_blob(s, 2);
91410     const int nData = sqlite3_column_bytes(s, 2);
91411     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
91412     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
91413                      &doclist);
91414     if( rc!=SQLITE_OK ) goto err;
91415   }
91416   if( rc==SQLITE_DONE ){
91417     if( doclist.nData!=0 ){
91418       /* TODO(shess) The old term_select_all() code applied the column
91419       ** restrict as we merged segments, leading to smaller buffers.
91420       ** This is probably worthwhile to bring back, once the new storage
91421       ** system is checked in.
91422       */
91423       if( iColumn==v->nColumn) iColumn = -1;
91424       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
91425                   iColumn, iType, out);
91426     }
91427     rc = SQLITE_OK;
91428   }
91429
91430  err:
91431   dataBufferDestroy(&doclist);
91432   return rc;
91433 }
91434
91435 /****************************************************************/
91436 /* Used to hold hashtable data for sorting. */
91437 typedef struct TermData {
91438   const char *pTerm;
91439   int nTerm;
91440   DLCollector *pCollector;
91441 } TermData;
91442
91443 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
91444 ** for equal, >0 for greater-than).
91445 */
91446 static int termDataCmp(const void *av, const void *bv){
91447   const TermData *a = (const TermData *)av;
91448   const TermData *b = (const TermData *)bv;
91449   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
91450   int c = memcmp(a->pTerm, b->pTerm, n);
91451   if( c!=0 ) return c;
91452   return a->nTerm-b->nTerm;
91453 }
91454
91455 /* Order pTerms data by term, then write a new level 0 segment using
91456 ** LeafWriter.
91457 */
91458 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
91459   fts3HashElem *e;
91460   int idx, rc, i, n;
91461   TermData *pData;
91462   LeafWriter writer;
91463   DataBuffer dl;
91464
91465   /* Determine the next index at level 0, merging as necessary. */
91466   rc = segdirNextIndex(v, 0, &idx);
91467   if( rc!=SQLITE_OK ) return rc;
91468
91469   n = fts3HashCount(pTerms);
91470   pData = sqlite3_malloc(n*sizeof(TermData));
91471
91472   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
91473     assert( i<n );
91474     pData[i].pTerm = fts3HashKey(e);
91475     pData[i].nTerm = fts3HashKeysize(e);
91476     pData[i].pCollector = fts3HashData(e);
91477   }
91478   assert( i==n );
91479
91480   /* TODO(shess) Should we allow user-defined collation sequences,
91481   ** here?  I think we only need that once we support prefix searches.
91482   */
91483   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
91484
91485   /* TODO(shess) Refactor so that we can write directly to the segment
91486   ** DataBuffer, as happens for segment merges.
91487   */
91488   leafWriterInit(0, idx, &writer);
91489   dataBufferInit(&dl, 0);
91490   for(i=0; i<n; i++){
91491     dataBufferReset(&dl);
91492     dlcAddDoclist(pData[i].pCollector, &dl);
91493     rc = leafWriterStep(v, &writer,
91494                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
91495     if( rc!=SQLITE_OK ) goto err;
91496   }
91497   rc = leafWriterFinalize(v, &writer);
91498
91499  err:
91500   dataBufferDestroy(&dl);
91501   sqlite3_free(pData);
91502   leafWriterDestroy(&writer);
91503   return rc;
91504 }
91505
91506 /* If pendingTerms has data, free it. */
91507 static int clearPendingTerms(fulltext_vtab *v){
91508   if( v->nPendingData>=0 ){
91509     fts3HashElem *e;
91510     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
91511       dlcDelete(fts3HashData(e));
91512     }
91513     fts3HashClear(&v->pendingTerms);
91514     v->nPendingData = -1;
91515   }
91516   return SQLITE_OK;
91517 }
91518
91519 /* If pendingTerms has data, flush it to a level-zero segment, and
91520 ** free it.
91521 */
91522 static int flushPendingTerms(fulltext_vtab *v){
91523   if( v->nPendingData>=0 ){
91524     int rc = writeZeroSegment(v, &v->pendingTerms);
91525     if( rc==SQLITE_OK ) clearPendingTerms(v);
91526     return rc;
91527   }
91528   return SQLITE_OK;
91529 }
91530
91531 /* If pendingTerms is "too big", or docid is out of order, flush it.
91532 ** Regardless, be certain that pendingTerms is initialized for use.
91533 */
91534 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
91535   /* TODO(shess) Explore whether partially flushing the buffer on
91536   ** forced-flush would provide better performance.  I suspect that if
91537   ** we ordered the doclists by size and flushed the largest until the
91538   ** buffer was half empty, that would let the less frequent terms
91539   ** generate longer doclists.
91540   */
91541   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
91542     int rc = flushPendingTerms(v);
91543     if( rc!=SQLITE_OK ) return rc;
91544   }
91545   if( v->nPendingData<0 ){
91546     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
91547     v->nPendingData = 0;
91548   }
91549   v->iPrevDocid = iDocid;
91550   return SQLITE_OK;
91551 }
91552
91553 /* This function implements the xUpdate callback; it is the top-level entry
91554  * point for inserting, deleting or updating a row in a full-text table. */
91555 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
91556                           sqlite_int64 *pRowid){
91557   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91558   int rc;
91559
91560   FTSTRACE(("FTS3 Update %p\n", pVtab));
91561
91562   if( nArg<2 ){
91563     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
91564     if( rc==SQLITE_OK ){
91565       /* If we just deleted the last row in the table, clear out the
91566       ** index data.
91567       */
91568       rc = content_exists(v);
91569       if( rc==SQLITE_ROW ){
91570         rc = SQLITE_OK;
91571       }else if( rc==SQLITE_DONE ){
91572         /* Clear the pending terms so we don't flush a useless level-0
91573         ** segment when the transaction closes.
91574         */
91575         rc = clearPendingTerms(v);
91576         if( rc==SQLITE_OK ){
91577           rc = segdir_delete_all(v);
91578         }
91579       }
91580     }
91581   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
91582     /* An update:
91583      * ppArg[0] = old rowid
91584      * ppArg[1] = new rowid
91585      * ppArg[2..2+v->nColumn-1] = values
91586      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
91587      * ppArg[2+v->nColumn+1] = value for docid
91588      */
91589     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
91590     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
91591         sqlite3_value_int64(ppArg[1]) != rowid ){
91592       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
91593     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
91594               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
91595       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
91596     }else{
91597       assert( nArg==2+v->nColumn+2);
91598       rc = index_update(v, rowid, &ppArg[2]);
91599     }
91600   } else {
91601     /* An insert:
91602      * ppArg[1] = requested rowid
91603      * ppArg[2..2+v->nColumn-1] = values
91604      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
91605      * ppArg[2+v->nColumn+1] = value for docid
91606      */
91607     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
91608     assert( nArg==2+v->nColumn+2);
91609     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
91610         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
91611       /* TODO(shess) Consider allowing this to work if the values are
91612       ** identical.  I'm inclined to discourage that usage, though,
91613       ** given that both rowid and docid are special columns.  Better
91614       ** would be to define one or the other as the default winner,
91615       ** but should it be fts3-centric (docid) or SQLite-centric
91616       ** (rowid)?
91617       */
91618       rc = SQLITE_ERROR;
91619     }else{
91620       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
91621         pRequestDocid = ppArg[1];
91622       }
91623       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
91624     }
91625   }
91626
91627   return rc;
91628 }
91629
91630 static int fulltextSync(sqlite3_vtab *pVtab){
91631   FTSTRACE(("FTS3 xSync()\n"));
91632   return flushPendingTerms((fulltext_vtab *)pVtab);
91633 }
91634
91635 static int fulltextBegin(sqlite3_vtab *pVtab){
91636   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91637   FTSTRACE(("FTS3 xBegin()\n"));
91638
91639   /* Any buffered updates should have been cleared by the previous
91640   ** transaction.
91641   */
91642   assert( v->nPendingData<0 );
91643   return clearPendingTerms(v);
91644 }
91645
91646 static int fulltextCommit(sqlite3_vtab *pVtab){
91647   fulltext_vtab *v = (fulltext_vtab *) pVtab;
91648   FTSTRACE(("FTS3 xCommit()\n"));
91649
91650   /* Buffered updates should have been cleared by fulltextSync(). */
91651   assert( v->nPendingData<0 );
91652   return clearPendingTerms(v);
91653 }
91654
91655 static int fulltextRollback(sqlite3_vtab *pVtab){
91656   FTSTRACE(("FTS3 xRollback()\n"));
91657   return clearPendingTerms((fulltext_vtab *)pVtab);
91658 }
91659
91660 /*
91661 ** Implementation of the snippet() function for FTS3
91662 */
91663 static void snippetFunc(
91664   sqlite3_context *pContext,
91665   int argc,
91666   sqlite3_value **argv
91667 ){
91668   fulltext_cursor *pCursor;
91669   if( argc<1 ) return;
91670   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91671       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91672     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
91673   }else{
91674     const char *zStart = "<b>";
91675     const char *zEnd = "</b>";
91676     const char *zEllipsis = "<b>...</b>";
91677     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91678     if( argc>=2 ){
91679       zStart = (const char*)sqlite3_value_text(argv[1]);
91680       if( argc>=3 ){
91681         zEnd = (const char*)sqlite3_value_text(argv[2]);
91682         if( argc>=4 ){
91683           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
91684         }
91685       }
91686     }
91687     snippetAllOffsets(pCursor);
91688     snippetText(pCursor, zStart, zEnd, zEllipsis);
91689     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
91690                         pCursor->snippet.nSnippet, SQLITE_STATIC);
91691   }
91692 }
91693
91694 /*
91695 ** Implementation of the offsets() function for FTS3
91696 */
91697 static void snippetOffsetsFunc(
91698   sqlite3_context *pContext,
91699   int argc,
91700   sqlite3_value **argv
91701 ){
91702   fulltext_cursor *pCursor;
91703   if( argc<1 ) return;
91704   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91705       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91706     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
91707   }else{
91708     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91709     snippetAllOffsets(pCursor);
91710     snippetOffsetText(&pCursor->snippet);
91711     sqlite3_result_text(pContext,
91712                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
91713                         SQLITE_STATIC);
91714   }
91715 }
91716
91717 /* OptLeavesReader is nearly identical to LeavesReader, except that
91718 ** where LeavesReader is geared towards the merging of complete
91719 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
91720 ** is geared towards implementation of the optimize() function, and
91721 ** can merge all segments simultaneously.  This version may be
91722 ** somewhat less efficient than LeavesReader because it merges into an
91723 ** accumulator rather than doing an N-way merge, but since segment
91724 ** size grows exponentially (so segment count logrithmically) this is
91725 ** probably not an immediate problem.
91726 */
91727 /* TODO(shess): Prove that assertion, or extend the merge code to
91728 ** merge tree fashion (like the prefix-searching code does).
91729 */
91730 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
91731 ** merged with little or no loss of performance for LeavesReader.  The
91732 ** merged code would need to handle >MERGE_COUNT segments, and would
91733 ** also need to be able to optionally optimize away deletes.
91734 */
91735 typedef struct OptLeavesReader {
91736   /* Segment number, to order readers by age. */
91737   int segment;
91738   LeavesReader reader;
91739 } OptLeavesReader;
91740
91741 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
91742   return leavesReaderAtEnd(&pReader->reader);
91743 }
91744 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
91745   return leavesReaderTermBytes(&pReader->reader);
91746 }
91747 static const char *optLeavesReaderData(OptLeavesReader *pReader){
91748   return leavesReaderData(&pReader->reader);
91749 }
91750 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
91751   return leavesReaderDataBytes(&pReader->reader);
91752 }
91753 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
91754   return leavesReaderTerm(&pReader->reader);
91755 }
91756 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
91757   return leavesReaderStep(v, &pReader->reader);
91758 }
91759 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
91760   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
91761 }
91762 /* Order by term ascending, segment ascending (oldest to newest), with
91763 ** exhausted readers to the end.
91764 */
91765 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
91766   int c = optLeavesReaderTermCmp(lr1, lr2);
91767   if( c!=0 ) return c;
91768   return lr1->segment-lr2->segment;
91769 }
91770 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
91771 ** pLr[1..nLr-1] is already sorted.
91772 */
91773 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
91774   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
91775     OptLeavesReader tmp = pLr[0];
91776     pLr[0] = pLr[1];
91777     pLr[1] = tmp;
91778     nLr--;
91779     pLr++;
91780   }
91781 }
91782
91783 /* optimize() helper function.  Put the readers in order and iterate
91784 ** through them, merging doclists for matching terms into pWriter.
91785 ** Returns SQLITE_OK on success, or the SQLite error code which
91786 ** prevented success.
91787 */
91788 static int optimizeInternal(fulltext_vtab *v,
91789                             OptLeavesReader *readers, int nReaders,
91790                             LeafWriter *pWriter){
91791   int i, rc = SQLITE_OK;
91792   DataBuffer doclist, merged, tmp;
91793
91794   /* Order the readers. */
91795   i = nReaders;
91796   while( i-- > 0 ){
91797     optLeavesReaderReorder(&readers[i], nReaders-i);
91798   }
91799
91800   dataBufferInit(&doclist, LEAF_MAX);
91801   dataBufferInit(&merged, LEAF_MAX);
91802
91803   /* Exhausted readers bubble to the end, so when the first reader is
91804   ** at eof, all are at eof.
91805   */
91806   while( !optLeavesReaderAtEnd(&readers[0]) ){
91807
91808     /* Figure out how many readers share the next term. */
91809     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
91810       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
91811     }
91812
91813     /* Special-case for no merge. */
91814     if( i==1 ){
91815       /* Trim deletions from the doclist. */
91816       dataBufferReset(&merged);
91817       docListTrim(DL_DEFAULT,
91818                   optLeavesReaderData(&readers[0]),
91819                   optLeavesReaderDataBytes(&readers[0]),
91820                   -1, DL_DEFAULT, &merged);
91821     }else{
91822       DLReader dlReaders[MERGE_COUNT];
91823       int iReader, nReaders;
91824
91825       /* Prime the pipeline with the first reader's doclist.  After
91826       ** one pass index 0 will reference the accumulated doclist.
91827       */
91828       dlrInit(&dlReaders[0], DL_DEFAULT,
91829               optLeavesReaderData(&readers[0]),
91830               optLeavesReaderDataBytes(&readers[0]));
91831       iReader = 1;
91832
91833       assert( iReader<i );  /* Must execute the loop at least once. */
91834       while( iReader<i ){
91835         /* Merge 16 inputs per pass. */
91836         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
91837              iReader++, nReaders++ ){
91838           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
91839                   optLeavesReaderData(&readers[iReader]),
91840                   optLeavesReaderDataBytes(&readers[iReader]));
91841         }
91842
91843         /* Merge doclists and swap result into accumulator. */
91844         dataBufferReset(&merged);
91845         docListMerge(&merged, dlReaders, nReaders);
91846         tmp = merged;
91847         merged = doclist;
91848         doclist = tmp;
91849
91850         while( nReaders-- > 0 ){
91851           dlrDestroy(&dlReaders[nReaders]);
91852         }
91853
91854         /* Accumulated doclist to reader 0 for next pass. */
91855         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
91856       }
91857
91858       /* Destroy reader that was left in the pipeline. */
91859       dlrDestroy(&dlReaders[0]);
91860
91861       /* Trim deletions from the doclist. */
91862       dataBufferReset(&merged);
91863       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
91864                   -1, DL_DEFAULT, &merged);
91865     }
91866
91867     /* Only pass doclists with hits (skip if all hits deleted). */
91868     if( merged.nData>0 ){
91869       rc = leafWriterStep(v, pWriter,
91870                           optLeavesReaderTerm(&readers[0]),
91871                           optLeavesReaderTermBytes(&readers[0]),
91872                           merged.pData, merged.nData);
91873       if( rc!=SQLITE_OK ) goto err;
91874     }
91875
91876     /* Step merged readers to next term and reorder. */
91877     while( i-- > 0 ){
91878       rc = optLeavesReaderStep(v, &readers[i]);
91879       if( rc!=SQLITE_OK ) goto err;
91880
91881       optLeavesReaderReorder(&readers[i], nReaders-i);
91882     }
91883   }
91884
91885  err:
91886   dataBufferDestroy(&doclist);
91887   dataBufferDestroy(&merged);
91888   return rc;
91889 }
91890
91891 /* Implement optimize() function for FTS3.  optimize(t) merges all
91892 ** segments in the fts index into a single segment.  't' is the magic
91893 ** table-named column.
91894 */
91895 static void optimizeFunc(sqlite3_context *pContext,
91896                          int argc, sqlite3_value **argv){
91897   fulltext_cursor *pCursor;
91898   if( argc>1 ){
91899     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
91900   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
91901             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
91902     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
91903   }else{
91904     fulltext_vtab *v;
91905     int i, rc, iMaxLevel;
91906     OptLeavesReader *readers;
91907     int nReaders;
91908     LeafWriter writer;
91909     sqlite3_stmt *s;
91910
91911     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
91912     v = cursor_vtab(pCursor);
91913
91914     /* Flush any buffered updates before optimizing. */
91915     rc = flushPendingTerms(v);
91916     if( rc!=SQLITE_OK ) goto err;
91917
91918     rc = segdir_count(v, &nReaders, &iMaxLevel);
91919     if( rc!=SQLITE_OK ) goto err;
91920     if( nReaders==0 || nReaders==1 ){
91921       sqlite3_result_text(pContext, "Index already optimal", -1,
91922                           SQLITE_STATIC);
91923       return;
91924     }
91925
91926     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
91927     if( rc!=SQLITE_OK ) goto err;
91928
91929     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
91930     if( readers==NULL ) goto err;
91931
91932     /* Note that there will already be a segment at this position
91933     ** until we call segdir_delete() on iMaxLevel.
91934     */
91935     leafWriterInit(iMaxLevel, 0, &writer);
91936
91937     i = 0;
91938     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
91939       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
91940       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
91941       const char *pRootData = sqlite3_column_blob(s, 2);
91942       int nRootData = sqlite3_column_bytes(s, 2);
91943
91944       assert( i<nReaders );
91945       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
91946                             &readers[i].reader);
91947       if( rc!=SQLITE_OK ) break;
91948
91949       readers[i].segment = i;
91950       i++;
91951     }
91952
91953     /* If we managed to succesfully read them all, optimize them. */
91954     if( rc==SQLITE_DONE ){
91955       assert( i==nReaders );
91956       rc = optimizeInternal(v, readers, nReaders, &writer);
91957     }
91958
91959     while( i-- > 0 ){
91960       leavesReaderDestroy(&readers[i].reader);
91961     }
91962     sqlite3_free(readers);
91963
91964     /* If we've successfully gotten to here, delete the old segments
91965     ** and flush the interior structure of the new segment.
91966     */
91967     if( rc==SQLITE_OK ){
91968       for( i=0; i<=iMaxLevel; i++ ){
91969         rc = segdir_delete(v, i);
91970         if( rc!=SQLITE_OK ) break;
91971       }
91972
91973       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
91974     }
91975
91976     leafWriterDestroy(&writer);
91977
91978     if( rc!=SQLITE_OK ) goto err;
91979
91980     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
91981     return;
91982
91983     /* TODO(shess): Error-handling needs to be improved along the
91984     ** lines of the dump_ functions.
91985     */
91986  err:
91987     {
91988       char buf[512];
91989       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
91990                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
91991       sqlite3_result_error(pContext, buf, -1);
91992     }
91993   }
91994 }
91995
91996 #ifdef SQLITE_TEST
91997 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
91998 ** pull the error from the context's db handle.
91999 */
92000 static void generateError(sqlite3_context *pContext,
92001                           const char *prefix, const char *msg){
92002   char buf[512];
92003   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
92004   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
92005   sqlite3_result_error(pContext, buf, -1);
92006 }
92007
92008 /* Helper function to collect the set of terms in the segment into
92009 ** pTerms.  The segment is defined by the leaf nodes between
92010 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
92011 ** pRootData if iStartBlockid is 0 (in which case the entire segment
92012 ** fit in a leaf).
92013 */
92014 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
92015                                fts3Hash *pTerms){
92016   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
92017   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
92018   const char *pRootData = sqlite3_column_blob(s, 2);
92019   const int nRootData = sqlite3_column_bytes(s, 2);
92020   LeavesReader reader;
92021   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
92022                             pRootData, nRootData, &reader);
92023   if( rc!=SQLITE_OK ) return rc;
92024
92025   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
92026     const char *pTerm = leavesReaderTerm(&reader);
92027     const int nTerm = leavesReaderTermBytes(&reader);
92028     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
92029     void *newValue = (void *)((char *)oldValue+1);
92030
92031     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
92032     ** the data value passed is returned in case of malloc failure.
92033     */
92034     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
92035       rc = SQLITE_NOMEM;
92036     }else{
92037       rc = leavesReaderStep(v, &reader);
92038     }
92039   }
92040
92041   leavesReaderDestroy(&reader);
92042   return rc;
92043 }
92044
92045 /* Helper function to build the result string for dump_terms(). */
92046 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
92047   int iTerm, nTerms, nResultBytes, iByte;
92048   char *result;
92049   TermData *pData;
92050   fts3HashElem *e;
92051
92052   /* Iterate pTerms to generate an array of terms in pData for
92053   ** sorting.
92054   */
92055   nTerms = fts3HashCount(pTerms);
92056   assert( nTerms>0 );
92057   pData = sqlite3_malloc(nTerms*sizeof(TermData));
92058   if( pData==NULL ) return SQLITE_NOMEM;
92059
92060   nResultBytes = 0;
92061   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
92062     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
92063     assert( iTerm<nTerms );
92064     pData[iTerm].pTerm = fts3HashKey(e);
92065     pData[iTerm].nTerm = fts3HashKeysize(e);
92066     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
92067   }
92068   assert( iTerm==nTerms );
92069
92070   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
92071   result = sqlite3_malloc(nResultBytes);
92072   if( result==NULL ){
92073     sqlite3_free(pData);
92074     return SQLITE_NOMEM;
92075   }
92076
92077   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
92078
92079   /* Read the terms in order to build the result. */
92080   iByte = 0;
92081   for(iTerm=0; iTerm<nTerms; ++iTerm){
92082     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
92083     iByte += pData[iTerm].nTerm;
92084     result[iByte++] = ' ';
92085   }
92086   assert( iByte==nResultBytes );
92087   assert( result[nResultBytes-1]==' ' );
92088   result[nResultBytes-1] = '\0';
92089
92090   /* Passes away ownership of result. */
92091   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
92092   sqlite3_free(pData);
92093   return SQLITE_OK;
92094 }
92095
92096 /* Implements dump_terms() for use in inspecting the fts3 index from
92097 ** tests.  TEXT result containing the ordered list of terms joined by
92098 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
92099 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
92100 ** all terms in the index.  In both cases t is the fts table's magic
92101 ** table-named column.
92102 */
92103 static void dumpTermsFunc(
92104   sqlite3_context *pContext,
92105   int argc, sqlite3_value **argv
92106 ){
92107   fulltext_cursor *pCursor;
92108   if( argc!=3 && argc!=1 ){
92109     generateError(pContext, "dump_terms", "incorrect arguments");
92110   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
92111             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
92112     generateError(pContext, "dump_terms", "illegal first argument");
92113   }else{
92114     fulltext_vtab *v;
92115     fts3Hash terms;
92116     sqlite3_stmt *s = NULL;
92117     int rc;
92118
92119     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
92120     v = cursor_vtab(pCursor);
92121
92122     /* If passed only the cursor column, get all segments.  Otherwise
92123     ** get the segment described by the following two arguments.
92124     */
92125     if( argc==1 ){
92126       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
92127     }else{
92128       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
92129       if( rc==SQLITE_OK ){
92130         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
92131         if( rc==SQLITE_OK ){
92132           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
92133         }
92134       }
92135     }
92136
92137     if( rc!=SQLITE_OK ){
92138       generateError(pContext, "dump_terms", NULL);
92139       return;
92140     }
92141
92142     /* Collect the terms for each segment. */
92143     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
92144     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
92145       rc = collectSegmentTerms(v, s, &terms);
92146       if( rc!=SQLITE_OK ) break;
92147     }
92148
92149     if( rc!=SQLITE_DONE ){
92150       sqlite3_reset(s);
92151       generateError(pContext, "dump_terms", NULL);
92152     }else{
92153       const int nTerms = fts3HashCount(&terms);
92154       if( nTerms>0 ){
92155         rc = generateTermsResult(pContext, &terms);
92156         if( rc==SQLITE_NOMEM ){
92157           generateError(pContext, "dump_terms", "out of memory");
92158         }else{
92159           assert( rc==SQLITE_OK );
92160         }
92161       }else if( argc==3 ){
92162         /* The specific segment asked for could not be found. */
92163         generateError(pContext, "dump_terms", "segment not found");
92164       }else{
92165         /* No segments found. */
92166         /* TODO(shess): It should be impossible to reach this.  This
92167         ** case can only happen for an empty table, in which case
92168         ** SQLite has no rows to call this function on.
92169         */
92170         sqlite3_result_null(pContext);
92171       }
92172     }
92173     sqlite3Fts3HashClear(&terms);
92174   }
92175 }
92176
92177 /* Expand the DL_DEFAULT doclist in pData into a text result in
92178 ** pContext.
92179 */
92180 static void createDoclistResult(sqlite3_context *pContext,
92181                                 const char *pData, int nData){
92182   DataBuffer dump;
92183   DLReader dlReader;
92184
92185   assert( pData!=NULL && nData>0 );
92186
92187   dataBufferInit(&dump, 0);
92188   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
92189   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
92190     char buf[256];
92191     PLReader plReader;
92192
92193     plrInit(&plReader, &dlReader);
92194     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
92195       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
92196       dataBufferAppend(&dump, buf, strlen(buf));
92197     }else{
92198       int iColumn = plrColumn(&plReader);
92199
92200       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
92201                        dlrDocid(&dlReader), iColumn);
92202       dataBufferAppend(&dump, buf, strlen(buf));
92203
92204       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
92205         if( plrColumn(&plReader)!=iColumn ){
92206           iColumn = plrColumn(&plReader);
92207           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
92208           assert( dump.nData>0 );
92209           dump.nData--;                     /* Overwrite trailing space. */
92210           assert( dump.pData[dump.nData]==' ');
92211           dataBufferAppend(&dump, buf, strlen(buf));
92212         }
92213         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
92214           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
92215                            plrPosition(&plReader),
92216                            plrStartOffset(&plReader), plrEndOffset(&plReader));
92217         }else if( DL_DEFAULT==DL_POSITIONS ){
92218           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
92219         }else{
92220           assert( NULL=="Unhandled DL_DEFAULT value");
92221         }
92222         dataBufferAppend(&dump, buf, strlen(buf));
92223       }
92224       plrDestroy(&plReader);
92225
92226       assert( dump.nData>0 );
92227       dump.nData--;                     /* Overwrite trailing space. */
92228       assert( dump.pData[dump.nData]==' ');
92229       dataBufferAppend(&dump, "]] ", 3);
92230     }
92231   }
92232   dlrDestroy(&dlReader);
92233
92234   assert( dump.nData>0 );
92235   dump.nData--;                     /* Overwrite trailing space. */
92236   assert( dump.pData[dump.nData]==' ');
92237   dump.pData[dump.nData] = '\0';
92238   assert( dump.nData>0 );
92239
92240   /* Passes ownership of dump's buffer to pContext. */
92241   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
92242   dump.pData = NULL;
92243   dump.nData = dump.nCapacity = 0;
92244 }
92245
92246 /* Implements dump_doclist() for use in inspecting the fts3 index from
92247 ** tests.  TEXT result containing a string representation of the
92248 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
92249 ** dumps the doclist for term from the segment specified by level, idx
92250 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
92251 ** doclist for the term across all segments.  The per-segment doclist
92252 ** can contain deletions, while the full-index doclist will not
92253 ** (deletions are omitted).
92254 **
92255 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
92256 **
92257 ** DL_DOCIDS: [1] [3] [7]
92258 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
92259 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
92260 **
92261 ** In each case the number after the outer '[' is the docid.  In the
92262 ** latter two cases, the number before the inner '[' is the column
92263 ** associated with the values within.  For DL_POSITIONS the numbers
92264 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
92265 ** position, the start offset, and the end offset.
92266 */
92267 static void dumpDoclistFunc(
92268   sqlite3_context *pContext,
92269   int argc, sqlite3_value **argv
92270 ){
92271   fulltext_cursor *pCursor;
92272   if( argc!=2 && argc!=4 ){
92273     generateError(pContext, "dump_doclist", "incorrect arguments");
92274   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
92275             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
92276     generateError(pContext, "dump_doclist", "illegal first argument");
92277   }else if( sqlite3_value_text(argv[1])==NULL ||
92278             sqlite3_value_text(argv[1])[0]=='\0' ){
92279     generateError(pContext, "dump_doclist", "empty second argument");
92280   }else{
92281     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
92282     const int nTerm = strlen(pTerm);
92283     fulltext_vtab *v;
92284     int rc;
92285     DataBuffer doclist;
92286
92287     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
92288     v = cursor_vtab(pCursor);
92289
92290     dataBufferInit(&doclist, 0);
92291
92292     /* termSelect() yields the same logical doclist that queries are
92293     ** run against.
92294     */
92295     if( argc==2 ){
92296       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
92297     }else{
92298       sqlite3_stmt *s = NULL;
92299
92300       /* Get our specific segment's information. */
92301       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
92302       if( rc==SQLITE_OK ){
92303         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
92304         if( rc==SQLITE_OK ){
92305           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
92306         }
92307       }
92308
92309       if( rc==SQLITE_OK ){
92310         rc = sqlite3_step(s);
92311
92312         if( rc==SQLITE_DONE ){
92313           dataBufferDestroy(&doclist);
92314           generateError(pContext, "dump_doclist", "segment not found");
92315           return;
92316         }
92317
92318         /* Found a segment, load it into doclist. */
92319         if( rc==SQLITE_ROW ){
92320           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
92321           const char *pData = sqlite3_column_blob(s, 2);
92322           const int nData = sqlite3_column_bytes(s, 2);
92323
92324           /* loadSegment() is used by termSelect() to load each
92325           ** segment's data.
92326           */
92327           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
92328                            &doclist);
92329           if( rc==SQLITE_OK ){
92330             rc = sqlite3_step(s);
92331
92332             /* Should not have more than one matching segment. */
92333             if( rc!=SQLITE_DONE ){
92334               sqlite3_reset(s);
92335               dataBufferDestroy(&doclist);
92336               generateError(pContext, "dump_doclist", "invalid segdir");
92337               return;
92338             }
92339             rc = SQLITE_OK;
92340           }
92341         }
92342       }
92343
92344       sqlite3_reset(s);
92345     }
92346
92347     if( rc==SQLITE_OK ){
92348       if( doclist.nData>0 ){
92349         createDoclistResult(pContext, doclist.pData, doclist.nData);
92350       }else{
92351         /* TODO(shess): This can happen if the term is not present, or
92352         ** if all instances of the term have been deleted and this is
92353         ** an all-index dump.  It may be interesting to distinguish
92354         ** these cases.
92355         */
92356         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
92357       }
92358     }else if( rc==SQLITE_NOMEM ){
92359       /* Handle out-of-memory cases specially because if they are
92360       ** generated in fts3 code they may not be reflected in the db
92361       ** handle.
92362       */
92363       /* TODO(shess): Handle this more comprehensively.
92364       ** sqlite3ErrStr() has what I need, but is internal.
92365       */
92366       generateError(pContext, "dump_doclist", "out of memory");
92367     }else{
92368       generateError(pContext, "dump_doclist", NULL);
92369     }
92370
92371     dataBufferDestroy(&doclist);
92372   }
92373 }
92374 #endif
92375
92376 /*
92377 ** This routine implements the xFindFunction method for the FTS3
92378 ** virtual table.
92379 */
92380 static int fulltextFindFunction(
92381   sqlite3_vtab *pVtab,
92382   int nArg,
92383   const char *zName,
92384   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
92385   void **ppArg
92386 ){
92387   if( strcmp(zName,"snippet")==0 ){
92388     *pxFunc = snippetFunc;
92389     return 1;
92390   }else if( strcmp(zName,"offsets")==0 ){
92391     *pxFunc = snippetOffsetsFunc;
92392     return 1;
92393   }else if( strcmp(zName,"optimize")==0 ){
92394     *pxFunc = optimizeFunc;
92395     return 1;
92396 #ifdef SQLITE_TEST
92397     /* NOTE(shess): These functions are present only for testing
92398     ** purposes.  No particular effort is made to optimize their
92399     ** execution or how they build their results.
92400     */
92401   }else if( strcmp(zName,"dump_terms")==0 ){
92402     /* fprintf(stderr, "Found dump_terms\n"); */
92403     *pxFunc = dumpTermsFunc;
92404     return 1;
92405   }else if( strcmp(zName,"dump_doclist")==0 ){
92406     /* fprintf(stderr, "Found dump_doclist\n"); */
92407     *pxFunc = dumpDoclistFunc;
92408     return 1;
92409 #endif
92410   }
92411   return 0;
92412 }
92413
92414 /*
92415 ** Rename an fts3 table.
92416 */
92417 static int fulltextRename(
92418   sqlite3_vtab *pVtab,
92419   const char *zName
92420 ){
92421   fulltext_vtab *p = (fulltext_vtab *)pVtab;
92422   int rc = SQLITE_NOMEM;
92423   char *zSql = sqlite3_mprintf(
92424     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
92425     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
92426     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
92427     , p->zDb, p->zName, zName 
92428     , p->zDb, p->zName, zName 
92429     , p->zDb, p->zName, zName
92430   );
92431   if( zSql ){
92432     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
92433     sqlite3_free(zSql);
92434   }
92435   return rc;
92436 }
92437
92438 static const sqlite3_module fts3Module = {
92439   /* iVersion      */ 0,
92440   /* xCreate       */ fulltextCreate,
92441   /* xConnect      */ fulltextConnect,
92442   /* xBestIndex    */ fulltextBestIndex,
92443   /* xDisconnect   */ fulltextDisconnect,
92444   /* xDestroy      */ fulltextDestroy,
92445   /* xOpen         */ fulltextOpen,
92446   /* xClose        */ fulltextClose,
92447   /* xFilter       */ fulltextFilter,
92448   /* xNext         */ fulltextNext,
92449   /* xEof          */ fulltextEof,
92450   /* xColumn       */ fulltextColumn,
92451   /* xRowid        */ fulltextRowid,
92452   /* xUpdate       */ fulltextUpdate,
92453   /* xBegin        */ fulltextBegin,
92454   /* xSync         */ fulltextSync,
92455   /* xCommit       */ fulltextCommit,
92456   /* xRollback     */ fulltextRollback,
92457   /* xFindFunction */ fulltextFindFunction,
92458   /* xRename */       fulltextRename,
92459 };
92460
92461 static void hashDestroy(void *p){
92462   fts3Hash *pHash = (fts3Hash *)p;
92463   sqlite3Fts3HashClear(pHash);
92464   sqlite3_free(pHash);
92465 }
92466
92467 /*
92468 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
92469 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
92470 ** two forward declarations are for functions declared in these files
92471 ** used to retrieve the respective implementations.
92472 **
92473 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
92474 ** to by the argument to point a the "simple" tokenizer implementation.
92475 ** Function ...PorterTokenizerModule() sets *pModule to point to the
92476 ** porter tokenizer/stemmer implementation.
92477 */
92478 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92479 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92480 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
92481
92482 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
92483
92484 /*
92485 ** Initialise the fts3 extension. If this extension is built as part
92486 ** of the sqlite library, then this function is called directly by
92487 ** SQLite. If fts3 is built as a dynamically loadable extension, this
92488 ** function is called by the sqlite3_extension_init() entry point.
92489 */
92490 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
92491   int rc = SQLITE_OK;
92492   fts3Hash *pHash = 0;
92493   const sqlite3_tokenizer_module *pSimple = 0;
92494   const sqlite3_tokenizer_module *pPorter = 0;
92495   const sqlite3_tokenizer_module *pIcu = 0;
92496
92497   sqlite3Fts3SimpleTokenizerModule(&pSimple);
92498   sqlite3Fts3PorterTokenizerModule(&pPorter);
92499 #ifdef SQLITE_ENABLE_ICU
92500   sqlite3Fts3IcuTokenizerModule(&pIcu);
92501 #endif
92502
92503   /* Allocate and initialise the hash-table used to store tokenizers. */
92504   pHash = sqlite3_malloc(sizeof(fts3Hash));
92505   if( !pHash ){
92506     rc = SQLITE_NOMEM;
92507   }else{
92508     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
92509   }
92510
92511   /* Load the built-in tokenizers into the hash table */
92512   if( rc==SQLITE_OK ){
92513     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
92514      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
92515      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
92516     ){
92517       rc = SQLITE_NOMEM;
92518     }
92519   }
92520
92521   /* Create the virtual table wrapper around the hash-table and overload 
92522   ** the two scalar functions. If this is successful, register the
92523   ** module with sqlite.
92524   */
92525   if( SQLITE_OK==rc 
92526    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
92527    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
92528    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
92529    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
92530 #ifdef SQLITE_TEST
92531    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
92532    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
92533 #endif
92534   ){
92535     return sqlite3_create_module_v2(
92536         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
92537     );
92538   }
92539
92540   /* An error has occured. Delete the hash table and return the error code. */
92541   assert( rc!=SQLITE_OK );
92542   if( pHash ){
92543     sqlite3Fts3HashClear(pHash);
92544     sqlite3_free(pHash);
92545   }
92546   return rc;
92547 }
92548
92549 #if !SQLITE_CORE
92550 SQLITE_API int sqlite3_extension_init(
92551   sqlite3 *db, 
92552   char **pzErrMsg,
92553   const sqlite3_api_routines *pApi
92554 ){
92555   SQLITE_EXTENSION_INIT2(pApi)
92556   return sqlite3Fts3Init(db);
92557 }
92558 #endif
92559
92560 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
92561
92562 /************** End of fts3.c ************************************************/
92563 /************** Begin file fts3_hash.c ***************************************/
92564 /*
92565 ** 2001 September 22
92566 **
92567 ** The author disclaims copyright to this source code.  In place of
92568 ** a legal notice, here is a blessing:
92569 **
92570 **    May you do good and not evil.
92571 **    May you find forgiveness for yourself and forgive others.
92572 **    May you share freely, never taking more than you give.
92573 **
92574 *************************************************************************
92575 ** This is the implementation of generic hash-tables used in SQLite.
92576 ** We've modified it slightly to serve as a standalone hash table
92577 ** implementation for the full-text indexing module.
92578 */
92579
92580 /*
92581 ** The code in this file is only compiled if:
92582 **
92583 **     * The FTS3 module is being built as an extension
92584 **       (in which case SQLITE_CORE is not defined), or
92585 **
92586 **     * The FTS3 module is being built into the core of
92587 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
92588 */
92589 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
92590
92591
92592
92593 /*
92594 ** Malloc and Free functions
92595 */
92596 static void *fts3HashMalloc(int n){
92597   void *p = sqlite3_malloc(n);
92598   if( p ){
92599     memset(p, 0, n);
92600   }
92601   return p;
92602 }
92603 static void fts3HashFree(void *p){
92604   sqlite3_free(p);
92605 }
92606
92607 /* Turn bulk memory into a hash table object by initializing the
92608 ** fields of the Hash structure.
92609 **
92610 ** "pNew" is a pointer to the hash table that is to be initialized.
92611 ** keyClass is one of the constants 
92612 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
92613 ** determines what kind of key the hash table will use.  "copyKey" is
92614 ** true if the hash table should make its own private copy of keys and
92615 ** false if it should just use the supplied pointer.
92616 */
92617 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
92618   assert( pNew!=0 );
92619   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
92620   pNew->keyClass = keyClass;
92621   pNew->copyKey = copyKey;
92622   pNew->first = 0;
92623   pNew->count = 0;
92624   pNew->htsize = 0;
92625   pNew->ht = 0;
92626 }
92627
92628 /* Remove all entries from a hash table.  Reclaim all memory.
92629 ** Call this routine to delete a hash table or to reset a hash table
92630 ** to the empty state.
92631 */
92632 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
92633   fts3HashElem *elem;         /* For looping over all elements of the table */
92634
92635   assert( pH!=0 );
92636   elem = pH->first;
92637   pH->first = 0;
92638   fts3HashFree(pH->ht);
92639   pH->ht = 0;
92640   pH->htsize = 0;
92641   while( elem ){
92642     fts3HashElem *next_elem = elem->next;
92643     if( pH->copyKey && elem->pKey ){
92644       fts3HashFree(elem->pKey);
92645     }
92646     fts3HashFree(elem);
92647     elem = next_elem;
92648   }
92649   pH->count = 0;
92650 }
92651
92652 /*
92653 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
92654 */
92655 static int fts3StrHash(const void *pKey, int nKey){
92656   const char *z = (const char *)pKey;
92657   int h = 0;
92658   if( nKey<=0 ) nKey = (int) strlen(z);
92659   while( nKey > 0  ){
92660     h = (h<<3) ^ h ^ *z++;
92661     nKey--;
92662   }
92663   return h & 0x7fffffff;
92664 }
92665 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
92666   if( n1!=n2 ) return 1;
92667   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
92668 }
92669
92670 /*
92671 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
92672 */
92673 static int fts3BinHash(const void *pKey, int nKey){
92674   int h = 0;
92675   const char *z = (const char *)pKey;
92676   while( nKey-- > 0 ){
92677     h = (h<<3) ^ h ^ *(z++);
92678   }
92679   return h & 0x7fffffff;
92680 }
92681 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
92682   if( n1!=n2 ) return 1;
92683   return memcmp(pKey1,pKey2,n1);
92684 }
92685
92686 /*
92687 ** Return a pointer to the appropriate hash function given the key class.
92688 **
92689 ** The C syntax in this function definition may be unfamilar to some 
92690 ** programmers, so we provide the following additional explanation:
92691 **
92692 ** The name of the function is "ftsHashFunction".  The function takes a
92693 ** single parameter "keyClass".  The return value of ftsHashFunction()
92694 ** is a pointer to another function.  Specifically, the return value
92695 ** of ftsHashFunction() is a pointer to a function that takes two parameters
92696 ** with types "const void*" and "int" and returns an "int".
92697 */
92698 static int (*ftsHashFunction(int keyClass))(const void*,int){
92699   if( keyClass==FTS3_HASH_STRING ){
92700     return &fts3StrHash;
92701   }else{
92702     assert( keyClass==FTS3_HASH_BINARY );
92703     return &fts3BinHash;
92704   }
92705 }
92706
92707 /*
92708 ** Return a pointer to the appropriate hash function given the key class.
92709 **
92710 ** For help in interpreted the obscure C code in the function definition,
92711 ** see the header comment on the previous function.
92712 */
92713 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
92714   if( keyClass==FTS3_HASH_STRING ){
92715     return &fts3StrCompare;
92716   }else{
92717     assert( keyClass==FTS3_HASH_BINARY );
92718     return &fts3BinCompare;
92719   }
92720 }
92721
92722 /* Link an element into the hash table
92723 */
92724 static void fts3HashInsertElement(
92725   fts3Hash *pH,            /* The complete hash table */
92726   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
92727   fts3HashElem *pNew       /* The element to be inserted */
92728 ){
92729   fts3HashElem *pHead;     /* First element already in pEntry */
92730   pHead = pEntry->chain;
92731   if( pHead ){
92732     pNew->next = pHead;
92733     pNew->prev = pHead->prev;
92734     if( pHead->prev ){ pHead->prev->next = pNew; }
92735     else             { pH->first = pNew; }
92736     pHead->prev = pNew;
92737   }else{
92738     pNew->next = pH->first;
92739     if( pH->first ){ pH->first->prev = pNew; }
92740     pNew->prev = 0;
92741     pH->first = pNew;
92742   }
92743   pEntry->count++;
92744   pEntry->chain = pNew;
92745 }
92746
92747
92748 /* Resize the hash table so that it cantains "new_size" buckets.
92749 ** "new_size" must be a power of 2.  The hash table might fail 
92750 ** to resize if sqliteMalloc() fails.
92751 */
92752 static void fts3Rehash(fts3Hash *pH, int new_size){
92753   struct _fts3ht *new_ht;          /* The new hash table */
92754   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
92755   int (*xHash)(const void*,int);   /* The hash function */
92756
92757   assert( (new_size & (new_size-1))==0 );
92758   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
92759   if( new_ht==0 ) return;
92760   fts3HashFree(pH->ht);
92761   pH->ht = new_ht;
92762   pH->htsize = new_size;
92763   xHash = ftsHashFunction(pH->keyClass);
92764   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
92765     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
92766     next_elem = elem->next;
92767     fts3HashInsertElement(pH, &new_ht[h], elem);
92768   }
92769 }
92770
92771 /* This function (for internal use only) locates an element in an
92772 ** hash table that matches the given key.  The hash for this key has
92773 ** already been computed and is passed as the 4th parameter.
92774 */
92775 static fts3HashElem *fts3FindElementByHash(
92776   const fts3Hash *pH, /* The pH to be searched */
92777   const void *pKey,   /* The key we are searching for */
92778   int nKey,
92779   int h               /* The hash for this key. */
92780 ){
92781   fts3HashElem *elem;            /* Used to loop thru the element list */
92782   int count;                     /* Number of elements left to test */
92783   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
92784
92785   if( pH->ht ){
92786     struct _fts3ht *pEntry = &pH->ht[h];
92787     elem = pEntry->chain;
92788     count = pEntry->count;
92789     xCompare = ftsCompareFunction(pH->keyClass);
92790     while( count-- && elem ){
92791       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
92792         return elem;
92793       }
92794       elem = elem->next;
92795     }
92796   }
92797   return 0;
92798 }
92799
92800 /* Remove a single entry from the hash table given a pointer to that
92801 ** element and a hash on the element's key.
92802 */
92803 static void fts3RemoveElementByHash(
92804   fts3Hash *pH,         /* The pH containing "elem" */
92805   fts3HashElem* elem,   /* The element to be removed from the pH */
92806   int h                 /* Hash value for the element */
92807 ){
92808   struct _fts3ht *pEntry;
92809   if( elem->prev ){
92810     elem->prev->next = elem->next; 
92811   }else{
92812     pH->first = elem->next;
92813   }
92814   if( elem->next ){
92815     elem->next->prev = elem->prev;
92816   }
92817   pEntry = &pH->ht[h];
92818   if( pEntry->chain==elem ){
92819     pEntry->chain = elem->next;
92820   }
92821   pEntry->count--;
92822   if( pEntry->count<=0 ){
92823     pEntry->chain = 0;
92824   }
92825   if( pH->copyKey && elem->pKey ){
92826     fts3HashFree(elem->pKey);
92827   }
92828   fts3HashFree( elem );
92829   pH->count--;
92830   if( pH->count<=0 ){
92831     assert( pH->first==0 );
92832     assert( pH->count==0 );
92833     fts3HashClear(pH);
92834   }
92835 }
92836
92837 /* Attempt to locate an element of the hash table pH with a key
92838 ** that matches pKey,nKey.  Return the data for this element if it is
92839 ** found, or NULL if there is no match.
92840 */
92841 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
92842   int h;                 /* A hash on key */
92843   fts3HashElem *elem;    /* The element that matches key */
92844   int (*xHash)(const void*,int);  /* The hash function */
92845
92846   if( pH==0 || pH->ht==0 ) return 0;
92847   xHash = ftsHashFunction(pH->keyClass);
92848   assert( xHash!=0 );
92849   h = (*xHash)(pKey,nKey);
92850   assert( (pH->htsize & (pH->htsize-1))==0 );
92851   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
92852   return elem ? elem->data : 0;
92853 }
92854
92855 /* Insert an element into the hash table pH.  The key is pKey,nKey
92856 ** and the data is "data".
92857 **
92858 ** If no element exists with a matching key, then a new
92859 ** element is created.  A copy of the key is made if the copyKey
92860 ** flag is set.  NULL is returned.
92861 **
92862 ** If another element already exists with the same key, then the
92863 ** new data replaces the old data and the old data is returned.
92864 ** The key is not copied in this instance.  If a malloc fails, then
92865 ** the new data is returned and the hash table is unchanged.
92866 **
92867 ** If the "data" parameter to this function is NULL, then the
92868 ** element corresponding to "key" is removed from the hash table.
92869 */
92870 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
92871   fts3Hash *pH,        /* The hash table to insert into */
92872   const void *pKey,    /* The key */
92873   int nKey,            /* Number of bytes in the key */
92874   void *data           /* The data */
92875 ){
92876   int hraw;                 /* Raw hash value of the key */
92877   int h;                    /* the hash of the key modulo hash table size */
92878   fts3HashElem *elem;       /* Used to loop thru the element list */
92879   fts3HashElem *new_elem;   /* New element added to the pH */
92880   int (*xHash)(const void*,int);  /* The hash function */
92881
92882   assert( pH!=0 );
92883   xHash = ftsHashFunction(pH->keyClass);
92884   assert( xHash!=0 );
92885   hraw = (*xHash)(pKey, nKey);
92886   assert( (pH->htsize & (pH->htsize-1))==0 );
92887   h = hraw & (pH->htsize-1);
92888   elem = fts3FindElementByHash(pH,pKey,nKey,h);
92889   if( elem ){
92890     void *old_data = elem->data;
92891     if( data==0 ){
92892       fts3RemoveElementByHash(pH,elem,h);
92893     }else{
92894       elem->data = data;
92895     }
92896     return old_data;
92897   }
92898   if( data==0 ) return 0;
92899   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
92900   if( new_elem==0 ) return data;
92901   if( pH->copyKey && pKey!=0 ){
92902     new_elem->pKey = fts3HashMalloc( nKey );
92903     if( new_elem->pKey==0 ){
92904       fts3HashFree(new_elem);
92905       return data;
92906     }
92907     memcpy((void*)new_elem->pKey, pKey, nKey);
92908   }else{
92909     new_elem->pKey = (void*)pKey;
92910   }
92911   new_elem->nKey = nKey;
92912   pH->count++;
92913   if( pH->htsize==0 ){
92914     fts3Rehash(pH,8);
92915     if( pH->htsize==0 ){
92916       pH->count = 0;
92917       fts3HashFree(new_elem);
92918       return data;
92919     }
92920   }
92921   if( pH->count > pH->htsize ){
92922     fts3Rehash(pH,pH->htsize*2);
92923   }
92924   assert( pH->htsize>0 );
92925   assert( (pH->htsize & (pH->htsize-1))==0 );
92926   h = hraw & (pH->htsize-1);
92927   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
92928   new_elem->data = data;
92929   return 0;
92930 }
92931
92932 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
92933
92934 /************** End of fts3_hash.c *******************************************/
92935 /************** Begin file fts3_porter.c *************************************/
92936 /*
92937 ** 2006 September 30
92938 **
92939 ** The author disclaims copyright to this source code.  In place of
92940 ** a legal notice, here is a blessing:
92941 **
92942 **    May you do good and not evil.
92943 **    May you find forgiveness for yourself and forgive others.
92944 **    May you share freely, never taking more than you give.
92945 **
92946 *************************************************************************
92947 ** Implementation of the full-text-search tokenizer that implements
92948 ** a Porter stemmer.
92949 */
92950
92951 /*
92952 ** The code in this file is only compiled if:
92953 **
92954 **     * The FTS3 module is being built as an extension
92955 **       (in which case SQLITE_CORE is not defined), or
92956 **
92957 **     * The FTS3 module is being built into the core of
92958 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
92959 */
92960 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
92961
92962
92963
92964
92965 /*
92966 ** Class derived from sqlite3_tokenizer
92967 */
92968 typedef struct porter_tokenizer {
92969   sqlite3_tokenizer base;      /* Base class */
92970 } porter_tokenizer;
92971
92972 /*
92973 ** Class derived from sqlit3_tokenizer_cursor
92974 */
92975 typedef struct porter_tokenizer_cursor {
92976   sqlite3_tokenizer_cursor base;
92977   const char *zInput;          /* input we are tokenizing */
92978   int nInput;                  /* size of the input */
92979   int iOffset;                 /* current position in zInput */
92980   int iToken;                  /* index of next token to be returned */
92981   char *zToken;                /* storage for current token */
92982   int nAllocated;              /* space allocated to zToken buffer */
92983 } porter_tokenizer_cursor;
92984
92985
92986 /* Forward declaration */
92987 static const sqlite3_tokenizer_module porterTokenizerModule;
92988
92989
92990 /*
92991 ** Create a new tokenizer instance.
92992 */
92993 static int porterCreate(
92994   int argc, const char * const *argv,
92995   sqlite3_tokenizer **ppTokenizer
92996 ){
92997   porter_tokenizer *t;
92998   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
92999   if( t==NULL ) return SQLITE_NOMEM;
93000   memset(t, 0, sizeof(*t));
93001   *ppTokenizer = &t->base;
93002   return SQLITE_OK;
93003 }
93004
93005 /*
93006 ** Destroy a tokenizer
93007 */
93008 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
93009   sqlite3_free(pTokenizer);
93010   return SQLITE_OK;
93011 }
93012
93013 /*
93014 ** Prepare to begin tokenizing a particular string.  The input
93015 ** string to be tokenized is zInput[0..nInput-1].  A cursor
93016 ** used to incrementally tokenize this string is returned in 
93017 ** *ppCursor.
93018 */
93019 static int porterOpen(
93020   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
93021   const char *zInput, int nInput,        /* String to be tokenized */
93022   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
93023 ){
93024   porter_tokenizer_cursor *c;
93025
93026   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
93027   if( c==NULL ) return SQLITE_NOMEM;
93028
93029   c->zInput = zInput;
93030   if( zInput==0 ){
93031     c->nInput = 0;
93032   }else if( nInput<0 ){
93033     c->nInput = (int)strlen(zInput);
93034   }else{
93035     c->nInput = nInput;
93036   }
93037   c->iOffset = 0;                 /* start tokenizing at the beginning */
93038   c->iToken = 0;
93039   c->zToken = NULL;               /* no space allocated, yet. */
93040   c->nAllocated = 0;
93041
93042   *ppCursor = &c->base;
93043   return SQLITE_OK;
93044 }
93045
93046 /*
93047 ** Close a tokenization cursor previously opened by a call to
93048 ** porterOpen() above.
93049 */
93050 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
93051   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
93052   sqlite3_free(c->zToken);
93053   sqlite3_free(c);
93054   return SQLITE_OK;
93055 }
93056 /*
93057 ** Vowel or consonant
93058 */
93059 static const char cType[] = {
93060    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
93061    1, 1, 1, 2, 1
93062 };
93063
93064 /*
93065 ** isConsonant() and isVowel() determine if their first character in
93066 ** the string they point to is a consonant or a vowel, according
93067 ** to Porter ruls.  
93068 **
93069 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
93070 ** 'Y' is a consonant unless it follows another consonant,
93071 ** in which case it is a vowel.
93072 **
93073 ** In these routine, the letters are in reverse order.  So the 'y' rule
93074 ** is that 'y' is a consonant unless it is followed by another
93075 ** consonent.
93076 */
93077 static int isVowel(const char*);
93078 static int isConsonant(const char *z){
93079   int j;
93080   char x = *z;
93081   if( x==0 ) return 0;
93082   assert( x>='a' && x<='z' );
93083   j = cType[x-'a'];
93084   if( j<2 ) return j;
93085   return z[1]==0 || isVowel(z + 1);
93086 }
93087 static int isVowel(const char *z){
93088   int j;
93089   char x = *z;
93090   if( x==0 ) return 0;
93091   assert( x>='a' && x<='z' );
93092   j = cType[x-'a'];
93093   if( j<2 ) return 1-j;
93094   return isConsonant(z + 1);
93095 }
93096
93097 /*
93098 ** Let any sequence of one or more vowels be represented by V and let
93099 ** C be sequence of one or more consonants.  Then every word can be
93100 ** represented as:
93101 **
93102 **           [C] (VC){m} [V]
93103 **
93104 ** In prose:  A word is an optional consonant followed by zero or
93105 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
93106 ** number of vowel consonant pairs.  This routine computes the value
93107 ** of m for the first i bytes of a word.
93108 **
93109 ** Return true if the m-value for z is 1 or more.  In other words,
93110 ** return true if z contains at least one vowel that is followed
93111 ** by a consonant.
93112 **
93113 ** In this routine z[] is in reverse order.  So we are really looking
93114 ** for an instance of of a consonant followed by a vowel.
93115 */
93116 static int m_gt_0(const char *z){
93117   while( isVowel(z) ){ z++; }
93118   if( *z==0 ) return 0;
93119   while( isConsonant(z) ){ z++; }
93120   return *z!=0;
93121 }
93122
93123 /* Like mgt0 above except we are looking for a value of m which is
93124 ** exactly 1
93125 */
93126 static int m_eq_1(const char *z){
93127   while( isVowel(z) ){ z++; }
93128   if( *z==0 ) return 0;
93129   while( isConsonant(z) ){ z++; }
93130   if( *z==0 ) return 0;
93131   while( isVowel(z) ){ z++; }
93132   if( *z==0 ) return 1;
93133   while( isConsonant(z) ){ z++; }
93134   return *z==0;
93135 }
93136
93137 /* Like mgt0 above except we are looking for a value of m>1 instead
93138 ** or m>0
93139 */
93140 static int m_gt_1(const char *z){
93141   while( isVowel(z) ){ z++; }
93142   if( *z==0 ) return 0;
93143   while( isConsonant(z) ){ z++; }
93144   if( *z==0 ) return 0;
93145   while( isVowel(z) ){ z++; }
93146   if( *z==0 ) return 0;
93147   while( isConsonant(z) ){ z++; }
93148   return *z!=0;
93149 }
93150
93151 /*
93152 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
93153 */
93154 static int hasVowel(const char *z){
93155   while( isConsonant(z) ){ z++; }
93156   return *z!=0;
93157 }
93158
93159 /*
93160 ** Return TRUE if the word ends in a double consonant.
93161 **
93162 ** The text is reversed here. So we are really looking at
93163 ** the first two characters of z[].
93164 */
93165 static int doubleConsonant(const char *z){
93166   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
93167 }
93168
93169 /*
93170 ** Return TRUE if the word ends with three letters which
93171 ** are consonant-vowel-consonent and where the final consonant
93172 ** is not 'w', 'x', or 'y'.
93173 **
93174 ** The word is reversed here.  So we are really checking the
93175 ** first three letters and the first one cannot be in [wxy].
93176 */
93177 static int star_oh(const char *z){
93178   return
93179     z[0]!=0 && isConsonant(z) &&
93180     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
93181     z[1]!=0 && isVowel(z+1) &&
93182     z[2]!=0 && isConsonant(z+2);
93183 }
93184
93185 /*
93186 ** If the word ends with zFrom and xCond() is true for the stem
93187 ** of the word that preceeds the zFrom ending, then change the 
93188 ** ending to zTo.
93189 **
93190 ** The input word *pz and zFrom are both in reverse order.  zTo
93191 ** is in normal order. 
93192 **
93193 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
93194 ** match.  Not that TRUE is returned even if xCond() fails and
93195 ** no substitution occurs.
93196 */
93197 static int stem(
93198   char **pz,             /* The word being stemmed (Reversed) */
93199   const char *zFrom,     /* If the ending matches this... (Reversed) */
93200   const char *zTo,       /* ... change the ending to this (not reversed) */
93201   int (*xCond)(const char*)   /* Condition that must be true */
93202 ){
93203   char *z = *pz;
93204   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
93205   if( *zFrom!=0 ) return 0;
93206   if( xCond && !xCond(z) ) return 1;
93207   while( *zTo ){
93208     *(--z) = *(zTo++);
93209   }
93210   *pz = z;
93211   return 1;
93212 }
93213
93214 /*
93215 ** This is the fallback stemmer used when the porter stemmer is
93216 ** inappropriate.  The input word is copied into the output with
93217 ** US-ASCII case folding.  If the input word is too long (more
93218 ** than 20 bytes if it contains no digits or more than 6 bytes if
93219 ** it contains digits) then word is truncated to 20 or 6 bytes
93220 ** by taking 10 or 3 bytes from the beginning and end.
93221 */
93222 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
93223   int i, mx, j;
93224   int hasDigit = 0;
93225   for(i=0; i<nIn; i++){
93226     int c = zIn[i];
93227     if( c>='A' && c<='Z' ){
93228       zOut[i] = c - 'A' + 'a';
93229     }else{
93230       if( c>='0' && c<='9' ) hasDigit = 1;
93231       zOut[i] = c;
93232     }
93233   }
93234   mx = hasDigit ? 3 : 10;
93235   if( nIn>mx*2 ){
93236     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
93237       zOut[j] = zOut[i];
93238     }
93239     i = j;
93240   }
93241   zOut[i] = 0;
93242   *pnOut = i;
93243 }
93244
93245
93246 /*
93247 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
93248 ** zOut is at least big enough to hold nIn bytes.  Write the actual
93249 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
93250 **
93251 ** Any upper-case characters in the US-ASCII character set ([A-Z])
93252 ** are converted to lower case.  Upper-case UTF characters are
93253 ** unchanged.
93254 **
93255 ** Words that are longer than about 20 bytes are stemmed by retaining
93256 ** a few bytes from the beginning and the end of the word.  If the
93257 ** word contains digits, 3 bytes are taken from the beginning and
93258 ** 3 bytes from the end.  For long words without digits, 10 bytes
93259 ** are taken from each end.  US-ASCII case folding still applies.
93260 ** 
93261 ** If the input word contains not digits but does characters not 
93262 ** in [a-zA-Z] then no stemming is attempted and this routine just 
93263 ** copies the input into the input into the output with US-ASCII
93264 ** case folding.
93265 **
93266 ** Stemming never increases the length of the word.  So there is
93267 ** no chance of overflowing the zOut buffer.
93268 */
93269 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
93270   int i, j, c;
93271   char zReverse[28];
93272   char *z, *z2;
93273   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
93274     /* The word is too big or too small for the porter stemmer.
93275     ** Fallback to the copy stemmer */
93276     copy_stemmer(zIn, nIn, zOut, pnOut);
93277     return;
93278   }
93279   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
93280     c = zIn[i];
93281     if( c>='A' && c<='Z' ){
93282       zReverse[j] = c + 'a' - 'A';
93283     }else if( c>='a' && c<='z' ){
93284       zReverse[j] = c;
93285     }else{
93286       /* The use of a character not in [a-zA-Z] means that we fallback
93287       ** to the copy stemmer */
93288       copy_stemmer(zIn, nIn, zOut, pnOut);
93289       return;
93290     }
93291   }
93292   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
93293   z = &zReverse[j+1];
93294
93295
93296   /* Step 1a */
93297   if( z[0]=='s' ){
93298     if(
93299      !stem(&z, "sess", "ss", 0) &&
93300      !stem(&z, "sei", "i", 0)  &&
93301      !stem(&z, "ss", "ss", 0)
93302     ){
93303       z++;
93304     }
93305   }
93306
93307   /* Step 1b */  
93308   z2 = z;
93309   if( stem(&z, "dee", "ee", m_gt_0) ){
93310     /* Do nothing.  The work was all in the test */
93311   }else if( 
93312      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
93313       && z!=z2
93314   ){
93315      if( stem(&z, "ta", "ate", 0) ||
93316          stem(&z, "lb", "ble", 0) ||
93317          stem(&z, "zi", "ize", 0) ){
93318        /* Do nothing.  The work was all in the test */
93319      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
93320        z++;
93321      }else if( m_eq_1(z) && star_oh(z) ){
93322        *(--z) = 'e';
93323      }
93324   }
93325
93326   /* Step 1c */
93327   if( z[0]=='y' && hasVowel(z+1) ){
93328     z[0] = 'i';
93329   }
93330
93331   /* Step 2 */
93332   switch( z[1] ){
93333    case 'a':
93334      stem(&z, "lanoita", "ate", m_gt_0) ||
93335      stem(&z, "lanoit", "tion", m_gt_0);
93336      break;
93337    case 'c':
93338      stem(&z, "icne", "ence", m_gt_0) ||
93339      stem(&z, "icna", "ance", m_gt_0);
93340      break;
93341    case 'e':
93342      stem(&z, "rezi", "ize", m_gt_0);
93343      break;
93344    case 'g':
93345      stem(&z, "igol", "log", m_gt_0);
93346      break;
93347    case 'l':
93348      stem(&z, "ilb", "ble", m_gt_0) ||
93349      stem(&z, "illa", "al", m_gt_0) ||
93350      stem(&z, "iltne", "ent", m_gt_0) ||
93351      stem(&z, "ile", "e", m_gt_0) ||
93352      stem(&z, "ilsuo", "ous", m_gt_0);
93353      break;
93354    case 'o':
93355      stem(&z, "noitazi", "ize", m_gt_0) ||
93356      stem(&z, "noita", "ate", m_gt_0) ||
93357      stem(&z, "rota", "ate", m_gt_0);
93358      break;
93359    case 's':
93360      stem(&z, "msila", "al", m_gt_0) ||
93361      stem(&z, "ssenevi", "ive", m_gt_0) ||
93362      stem(&z, "ssenluf", "ful", m_gt_0) ||
93363      stem(&z, "ssensuo", "ous", m_gt_0);
93364      break;
93365    case 't':
93366      stem(&z, "itila", "al", m_gt_0) ||
93367      stem(&z, "itivi", "ive", m_gt_0) ||
93368      stem(&z, "itilib", "ble", m_gt_0);
93369      break;
93370   }
93371
93372   /* Step 3 */
93373   switch( z[0] ){
93374    case 'e':
93375      stem(&z, "etaci", "ic", m_gt_0) ||
93376      stem(&z, "evita", "", m_gt_0)   ||
93377      stem(&z, "ezila", "al", m_gt_0);
93378      break;
93379    case 'i':
93380      stem(&z, "itici", "ic", m_gt_0);
93381      break;
93382    case 'l':
93383      stem(&z, "laci", "ic", m_gt_0) ||
93384      stem(&z, "luf", "", m_gt_0);
93385      break;
93386    case 's':
93387      stem(&z, "ssen", "", m_gt_0);
93388      break;
93389   }
93390
93391   /* Step 4 */
93392   switch( z[1] ){
93393    case 'a':
93394      if( z[0]=='l' && m_gt_1(z+2) ){
93395        z += 2;
93396      }
93397      break;
93398    case 'c':
93399      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
93400        z += 4;
93401      }
93402      break;
93403    case 'e':
93404      if( z[0]=='r' && m_gt_1(z+2) ){
93405        z += 2;
93406      }
93407      break;
93408    case 'i':
93409      if( z[0]=='c' && m_gt_1(z+2) ){
93410        z += 2;
93411      }
93412      break;
93413    case 'l':
93414      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
93415        z += 4;
93416      }
93417      break;
93418    case 'n':
93419      if( z[0]=='t' ){
93420        if( z[2]=='a' ){
93421          if( m_gt_1(z+3) ){
93422            z += 3;
93423          }
93424        }else if( z[2]=='e' ){
93425          stem(&z, "tneme", "", m_gt_1) ||
93426          stem(&z, "tnem", "", m_gt_1) ||
93427          stem(&z, "tne", "", m_gt_1);
93428        }
93429      }
93430      break;
93431    case 'o':
93432      if( z[0]=='u' ){
93433        if( m_gt_1(z+2) ){
93434          z += 2;
93435        }
93436      }else if( z[3]=='s' || z[3]=='t' ){
93437        stem(&z, "noi", "", m_gt_1);
93438      }
93439      break;
93440    case 's':
93441      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
93442        z += 3;
93443      }
93444      break;
93445    case 't':
93446      stem(&z, "eta", "", m_gt_1) ||
93447      stem(&z, "iti", "", m_gt_1);
93448      break;
93449    case 'u':
93450      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
93451        z += 3;
93452      }
93453      break;
93454    case 'v':
93455    case 'z':
93456      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
93457        z += 3;
93458      }
93459      break;
93460   }
93461
93462   /* Step 5a */
93463   if( z[0]=='e' ){
93464     if( m_gt_1(z+1) ){
93465       z++;
93466     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
93467       z++;
93468     }
93469   }
93470
93471   /* Step 5b */
93472   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
93473     z++;
93474   }
93475
93476   /* z[] is now the stemmed word in reverse order.  Flip it back
93477   ** around into forward order and return.
93478   */
93479   *pnOut = i = strlen(z);
93480   zOut[i] = 0;
93481   while( *z ){
93482     zOut[--i] = *(z++);
93483   }
93484 }
93485
93486 /*
93487 ** Characters that can be part of a token.  We assume any character
93488 ** whose value is greater than 0x80 (any UTF character) can be
93489 ** part of a token.  In other words, delimiters all must have
93490 ** values of 0x7f or lower.
93491 */
93492 static const char porterIdChar[] = {
93493 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
93494     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
93495     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
93496     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
93497     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
93498     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
93499 };
93500 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
93501
93502 /*
93503 ** Extract the next token from a tokenization cursor.  The cursor must
93504 ** have been opened by a prior call to porterOpen().
93505 */
93506 static int porterNext(
93507   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
93508   const char **pzToken,               /* OUT: *pzToken is the token text */
93509   int *pnBytes,                       /* OUT: Number of bytes in token */
93510   int *piStartOffset,                 /* OUT: Starting offset of token */
93511   int *piEndOffset,                   /* OUT: Ending offset of token */
93512   int *piPosition                     /* OUT: Position integer of token */
93513 ){
93514   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
93515   const char *z = c->zInput;
93516
93517   while( c->iOffset<c->nInput ){
93518     int iStartOffset, ch;
93519
93520     /* Scan past delimiter characters */
93521     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
93522       c->iOffset++;
93523     }
93524
93525     /* Count non-delimiter characters. */
93526     iStartOffset = c->iOffset;
93527     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
93528       c->iOffset++;
93529     }
93530
93531     if( c->iOffset>iStartOffset ){
93532       int n = c->iOffset-iStartOffset;
93533       if( n>c->nAllocated ){
93534         c->nAllocated = n+20;
93535         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
93536         if( c->zToken==NULL ) return SQLITE_NOMEM;
93537       }
93538       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
93539       *pzToken = c->zToken;
93540       *piStartOffset = iStartOffset;
93541       *piEndOffset = c->iOffset;
93542       *piPosition = c->iToken++;
93543       return SQLITE_OK;
93544     }
93545   }
93546   return SQLITE_DONE;
93547 }
93548
93549 /*
93550 ** The set of routines that implement the porter-stemmer tokenizer
93551 */
93552 static const sqlite3_tokenizer_module porterTokenizerModule = {
93553   0,
93554   porterCreate,
93555   porterDestroy,
93556   porterOpen,
93557   porterClose,
93558   porterNext,
93559 };
93560
93561 /*
93562 ** Allocate a new porter tokenizer.  Return a pointer to the new
93563 ** tokenizer in *ppModule
93564 */
93565 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
93566   sqlite3_tokenizer_module const**ppModule
93567 ){
93568   *ppModule = &porterTokenizerModule;
93569 }
93570
93571 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93572
93573 /************** End of fts3_porter.c *****************************************/
93574 /************** Begin file fts3_tokenizer.c **********************************/
93575 /*
93576 ** 2007 June 22
93577 **
93578 ** The author disclaims copyright to this source code.  In place of
93579 ** a legal notice, here is a blessing:
93580 **
93581 **    May you do good and not evil.
93582 **    May you find forgiveness for yourself and forgive others.
93583 **    May you share freely, never taking more than you give.
93584 **
93585 ******************************************************************************
93586 **
93587 ** This is part of an SQLite module implementing full-text search.
93588 ** This particular file implements the generic tokenizer interface.
93589 */
93590
93591 /*
93592 ** The code in this file is only compiled if:
93593 **
93594 **     * The FTS3 module is being built as an extension
93595 **       (in which case SQLITE_CORE is not defined), or
93596 **
93597 **     * The FTS3 module is being built into the core of
93598 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93599 */
93600 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93601
93602 #ifndef SQLITE_CORE
93603   SQLITE_EXTENSION_INIT1
93604 #endif
93605
93606
93607 /*
93608 ** Implementation of the SQL scalar function for accessing the underlying 
93609 ** hash table. This function may be called as follows:
93610 **
93611 **   SELECT <function-name>(<key-name>);
93612 **   SELECT <function-name>(<key-name>, <pointer>);
93613 **
93614 ** where <function-name> is the name passed as the second argument
93615 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
93616 **
93617 ** If the <pointer> argument is specified, it must be a blob value
93618 ** containing a pointer to be stored as the hash data corresponding
93619 ** to the string <key-name>. If <pointer> is not specified, then
93620 ** the string <key-name> must already exist in the has table. Otherwise,
93621 ** an error is returned.
93622 **
93623 ** Whether or not the <pointer> argument is specified, the value returned
93624 ** is a blob containing the pointer stored as the hash data corresponding
93625 ** to string <key-name> (after the hash-table is updated, if applicable).
93626 */
93627 static void scalarFunc(
93628   sqlite3_context *context,
93629   int argc,
93630   sqlite3_value **argv
93631 ){
93632   fts3Hash *pHash;
93633   void *pPtr = 0;
93634   const unsigned char *zName;
93635   int nName;
93636
93637   assert( argc==1 || argc==2 );
93638
93639   pHash = (fts3Hash *)sqlite3_user_data(context);
93640
93641   zName = sqlite3_value_text(argv[0]);
93642   nName = sqlite3_value_bytes(argv[0])+1;
93643
93644   if( argc==2 ){
93645     void *pOld;
93646     int n = sqlite3_value_bytes(argv[1]);
93647     if( n!=sizeof(pPtr) ){
93648       sqlite3_result_error(context, "argument type mismatch", -1);
93649       return;
93650     }
93651     pPtr = *(void **)sqlite3_value_blob(argv[1]);
93652     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
93653     if( pOld==pPtr ){
93654       sqlite3_result_error(context, "out of memory", -1);
93655       return;
93656     }
93657   }else{
93658     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
93659     if( !pPtr ){
93660       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
93661       sqlite3_result_error(context, zErr, -1);
93662       sqlite3_free(zErr);
93663       return;
93664     }
93665   }
93666
93667   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
93668 }
93669
93670 #ifdef SQLITE_TEST
93671
93672
93673 /*
93674 ** Implementation of a special SQL scalar function for testing tokenizers 
93675 ** designed to be used in concert with the Tcl testing framework. This
93676 ** function must be called with two arguments:
93677 **
93678 **   SELECT <function-name>(<key-name>, <input-string>);
93679 **   SELECT <function-name>(<key-name>, <pointer>);
93680 **
93681 ** where <function-name> is the name passed as the second argument
93682 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
93683 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
93684 **
93685 ** The return value is a string that may be interpreted as a Tcl
93686 ** list. For each token in the <input-string>, three elements are
93687 ** added to the returned list. The first is the token position, the 
93688 ** second is the token text (folded, stemmed, etc.) and the third is the
93689 ** substring of <input-string> associated with the token. For example, 
93690 ** using the built-in "simple" tokenizer:
93691 **
93692 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
93693 **
93694 ** will return the string:
93695 **
93696 **   "{0 i I 1 dont don't 2 see see 3 how how}"
93697 **   
93698 */
93699 static void testFunc(
93700   sqlite3_context *context,
93701   int argc,
93702   sqlite3_value **argv
93703 ){
93704   fts3Hash *pHash;
93705   sqlite3_tokenizer_module *p;
93706   sqlite3_tokenizer *pTokenizer = 0;
93707   sqlite3_tokenizer_cursor *pCsr = 0;
93708
93709   const char *zErr = 0;
93710
93711   const char *zName;
93712   int nName;
93713   const char *zInput;
93714   int nInput;
93715
93716   const char *zArg = 0;
93717
93718   const char *zToken;
93719   int nToken;
93720   int iStart;
93721   int iEnd;
93722   int iPos;
93723
93724   Tcl_Obj *pRet;
93725
93726   assert( argc==2 || argc==3 );
93727
93728   nName = sqlite3_value_bytes(argv[0]);
93729   zName = (const char *)sqlite3_value_text(argv[0]);
93730   nInput = sqlite3_value_bytes(argv[argc-1]);
93731   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
93732
93733   if( argc==3 ){
93734     zArg = (const char *)sqlite3_value_text(argv[1]);
93735   }
93736
93737   pHash = (fts3Hash *)sqlite3_user_data(context);
93738   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
93739
93740   if( !p ){
93741     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
93742     sqlite3_result_error(context, zErr, -1);
93743     sqlite3_free(zErr);
93744     return;
93745   }
93746
93747   pRet = Tcl_NewObj();
93748   Tcl_IncrRefCount(pRet);
93749
93750   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
93751     zErr = "error in xCreate()";
93752     goto finish;
93753   }
93754   pTokenizer->pModule = p;
93755   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
93756     zErr = "error in xOpen()";
93757     goto finish;
93758   }
93759   pCsr->pTokenizer = pTokenizer;
93760
93761   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
93762     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
93763     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
93764     zToken = &zInput[iStart];
93765     nToken = iEnd-iStart;
93766     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
93767   }
93768
93769   if( SQLITE_OK!=p->xClose(pCsr) ){
93770     zErr = "error in xClose()";
93771     goto finish;
93772   }
93773   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
93774     zErr = "error in xDestroy()";
93775     goto finish;
93776   }
93777
93778 finish:
93779   if( zErr ){
93780     sqlite3_result_error(context, zErr, -1);
93781   }else{
93782     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
93783   }
93784   Tcl_DecrRefCount(pRet);
93785 }
93786
93787 static
93788 int registerTokenizer(
93789   sqlite3 *db, 
93790   char *zName, 
93791   const sqlite3_tokenizer_module *p
93792 ){
93793   int rc;
93794   sqlite3_stmt *pStmt;
93795   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
93796
93797   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
93798   if( rc!=SQLITE_OK ){
93799     return rc;
93800   }
93801
93802   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
93803   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
93804   sqlite3_step(pStmt);
93805
93806   return sqlite3_finalize(pStmt);
93807 }
93808
93809 static
93810 int queryTokenizer(
93811   sqlite3 *db, 
93812   char *zName,  
93813   const sqlite3_tokenizer_module **pp
93814 ){
93815   int rc;
93816   sqlite3_stmt *pStmt;
93817   const char zSql[] = "SELECT fts3_tokenizer(?)";
93818
93819   *pp = 0;
93820   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
93821   if( rc!=SQLITE_OK ){
93822     return rc;
93823   }
93824
93825   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
93826   if( SQLITE_ROW==sqlite3_step(pStmt) ){
93827     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
93828       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
93829     }
93830   }
93831
93832   return sqlite3_finalize(pStmt);
93833 }
93834
93835 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
93836
93837 /*
93838 ** Implementation of the scalar function fts3_tokenizer_internal_test().
93839 ** This function is used for testing only, it is not included in the
93840 ** build unless SQLITE_TEST is defined.
93841 **
93842 ** The purpose of this is to test that the fts3_tokenizer() function
93843 ** can be used as designed by the C-code in the queryTokenizer and
93844 ** registerTokenizer() functions above. These two functions are repeated
93845 ** in the README.tokenizer file as an example, so it is important to
93846 ** test them.
93847 **
93848 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
93849 ** function with no arguments. An assert() will fail if a problem is
93850 ** detected. i.e.:
93851 **
93852 **     SELECT fts3_tokenizer_internal_test();
93853 **
93854 */
93855 static void intTestFunc(
93856   sqlite3_context *context,
93857   int argc,
93858   sqlite3_value **argv
93859 ){
93860   int rc;
93861   const sqlite3_tokenizer_module *p1;
93862   const sqlite3_tokenizer_module *p2;
93863   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
93864
93865   /* Test the query function */
93866   sqlite3Fts3SimpleTokenizerModule(&p1);
93867   rc = queryTokenizer(db, "simple", &p2);
93868   assert( rc==SQLITE_OK );
93869   assert( p1==p2 );
93870   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
93871   assert( rc==SQLITE_ERROR );
93872   assert( p2==0 );
93873   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
93874
93875   /* Test the storage function */
93876   rc = registerTokenizer(db, "nosuchtokenizer", p1);
93877   assert( rc==SQLITE_OK );
93878   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
93879   assert( rc==SQLITE_OK );
93880   assert( p2==p1 );
93881
93882   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
93883 }
93884
93885 #endif
93886
93887 /*
93888 ** Set up SQL objects in database db used to access the contents of
93889 ** the hash table pointed to by argument pHash. The hash table must
93890 ** been initialised to use string keys, and to take a private copy 
93891 ** of the key when a value is inserted. i.e. by a call similar to:
93892 **
93893 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
93894 **
93895 ** This function adds a scalar function (see header comment above
93896 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
93897 ** defined at compilation time, a temporary virtual table (see header 
93898 ** comment above struct HashTableVtab) to the database schema. Both 
93899 ** provide read/write access to the contents of *pHash.
93900 **
93901 ** The third argument to this function, zName, is used as the name
93902 ** of both the scalar and, if created, the virtual table.
93903 */
93904 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
93905   sqlite3 *db, 
93906   fts3Hash *pHash, 
93907   const char *zName
93908 ){
93909   int rc = SQLITE_OK;
93910   void *p = (void *)pHash;
93911   const int any = SQLITE_ANY;
93912   char *zTest = 0;
93913   char *zTest2 = 0;
93914
93915 #ifdef SQLITE_TEST
93916   void *pdb = (void *)db;
93917   zTest = sqlite3_mprintf("%s_test", zName);
93918   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
93919   if( !zTest || !zTest2 ){
93920     rc = SQLITE_NOMEM;
93921   }
93922 #endif
93923
93924   if( rc!=SQLITE_OK
93925    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
93926    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
93927 #ifdef SQLITE_TEST
93928    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
93929    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
93930    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
93931 #endif
93932   );
93933
93934   sqlite3_free(zTest);
93935   sqlite3_free(zTest2);
93936   return rc;
93937 }
93938
93939 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
93940
93941 /************** End of fts3_tokenizer.c **************************************/
93942 /************** Begin file fts3_tokenizer1.c *********************************/
93943 /*
93944 ** 2006 Oct 10
93945 **
93946 ** The author disclaims copyright to this source code.  In place of
93947 ** a legal notice, here is a blessing:
93948 **
93949 **    May you do good and not evil.
93950 **    May you find forgiveness for yourself and forgive others.
93951 **    May you share freely, never taking more than you give.
93952 **
93953 ******************************************************************************
93954 **
93955 ** Implementation of the "simple" full-text-search tokenizer.
93956 */
93957
93958 /*
93959 ** The code in this file is only compiled if:
93960 **
93961 **     * The FTS3 module is being built as an extension
93962 **       (in which case SQLITE_CORE is not defined), or
93963 **
93964 **     * The FTS3 module is being built into the core of
93965 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
93966 */
93967 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
93968
93969
93970
93971
93972 typedef struct simple_tokenizer {
93973   sqlite3_tokenizer base;
93974   char delim[128];             /* flag ASCII delimiters */
93975 } simple_tokenizer;
93976
93977 typedef struct simple_tokenizer_cursor {
93978   sqlite3_tokenizer_cursor base;
93979   const char *pInput;          /* input we are tokenizing */
93980   int nBytes;                  /* size of the input */
93981   int iOffset;                 /* current position in pInput */
93982   int iToken;                  /* index of next token to be returned */
93983   char *pToken;                /* storage for current token */
93984   int nTokenAllocated;         /* space allocated to zToken buffer */
93985 } simple_tokenizer_cursor;
93986
93987
93988 /* Forward declaration */
93989 static const sqlite3_tokenizer_module simpleTokenizerModule;
93990
93991 static int simpleDelim(simple_tokenizer *t, unsigned char c){
93992   return c<0x80 && t->delim[c];
93993 }
93994
93995 /*
93996 ** Create a new tokenizer instance.
93997 */
93998 static int simpleCreate(
93999   int argc, const char * const *argv,
94000   sqlite3_tokenizer **ppTokenizer
94001 ){
94002   simple_tokenizer *t;
94003
94004   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
94005   if( t==NULL ) return SQLITE_NOMEM;
94006   memset(t, 0, sizeof(*t));
94007
94008   /* TODO(shess) Delimiters need to remain the same from run to run,
94009   ** else we need to reindex.  One solution would be a meta-table to
94010   ** track such information in the database, then we'd only want this
94011   ** information on the initial create.
94012   */
94013   if( argc>1 ){
94014     int i, n = strlen(argv[1]);
94015     for(i=0; i<n; i++){
94016       unsigned char ch = argv[1][i];
94017       /* We explicitly don't support UTF-8 delimiters for now. */
94018       if( ch>=0x80 ){
94019         sqlite3_free(t);
94020         return SQLITE_ERROR;
94021       }
94022       t->delim[ch] = 1;
94023     }
94024   } else {
94025     /* Mark non-alphanumeric ASCII characters as delimiters */
94026     int i;
94027     for(i=1; i<0x80; i++){
94028       t->delim[i] = !isalnum(i);
94029     }
94030   }
94031
94032   *ppTokenizer = &t->base;
94033   return SQLITE_OK;
94034 }
94035
94036 /*
94037 ** Destroy a tokenizer
94038 */
94039 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
94040   sqlite3_free(pTokenizer);
94041   return SQLITE_OK;
94042 }
94043
94044 /*
94045 ** Prepare to begin tokenizing a particular string.  The input
94046 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
94047 ** used to incrementally tokenize this string is returned in 
94048 ** *ppCursor.
94049 */
94050 static int simpleOpen(
94051   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
94052   const char *pInput, int nBytes,        /* String to be tokenized */
94053   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
94054 ){
94055   simple_tokenizer_cursor *c;
94056
94057   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
94058   if( c==NULL ) return SQLITE_NOMEM;
94059
94060   c->pInput = pInput;
94061   if( pInput==0 ){
94062     c->nBytes = 0;
94063   }else if( nBytes<0 ){
94064     c->nBytes = (int)strlen(pInput);
94065   }else{
94066     c->nBytes = nBytes;
94067   }
94068   c->iOffset = 0;                 /* start tokenizing at the beginning */
94069   c->iToken = 0;
94070   c->pToken = NULL;               /* no space allocated, yet. */
94071   c->nTokenAllocated = 0;
94072
94073   *ppCursor = &c->base;
94074   return SQLITE_OK;
94075 }
94076
94077 /*
94078 ** Close a tokenization cursor previously opened by a call to
94079 ** simpleOpen() above.
94080 */
94081 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
94082   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
94083   sqlite3_free(c->pToken);
94084   sqlite3_free(c);
94085   return SQLITE_OK;
94086 }
94087
94088 /*
94089 ** Extract the next token from a tokenization cursor.  The cursor must
94090 ** have been opened by a prior call to simpleOpen().
94091 */
94092 static int simpleNext(
94093   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
94094   const char **ppToken,               /* OUT: *ppToken is the token text */
94095   int *pnBytes,                       /* OUT: Number of bytes in token */
94096   int *piStartOffset,                 /* OUT: Starting offset of token */
94097   int *piEndOffset,                   /* OUT: Ending offset of token */
94098   int *piPosition                     /* OUT: Position integer of token */
94099 ){
94100   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
94101   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
94102   unsigned char *p = (unsigned char *)c->pInput;
94103
94104   while( c->iOffset<c->nBytes ){
94105     int iStartOffset;
94106
94107     /* Scan past delimiter characters */
94108     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
94109       c->iOffset++;
94110     }
94111
94112     /* Count non-delimiter characters. */
94113     iStartOffset = c->iOffset;
94114     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
94115       c->iOffset++;
94116     }
94117
94118     if( c->iOffset>iStartOffset ){
94119       int i, n = c->iOffset-iStartOffset;
94120       if( n>c->nTokenAllocated ){
94121         c->nTokenAllocated = n+20;
94122         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
94123         if( c->pToken==NULL ) return SQLITE_NOMEM;
94124       }
94125       for(i=0; i<n; i++){
94126         /* TODO(shess) This needs expansion to handle UTF-8
94127         ** case-insensitivity.
94128         */
94129         unsigned char ch = p[iStartOffset+i];
94130         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
94131       }
94132       *ppToken = c->pToken;
94133       *pnBytes = n;
94134       *piStartOffset = iStartOffset;
94135       *piEndOffset = c->iOffset;
94136       *piPosition = c->iToken++;
94137
94138       return SQLITE_OK;
94139     }
94140   }
94141   return SQLITE_DONE;
94142 }
94143
94144 /*
94145 ** The set of routines that implement the simple tokenizer
94146 */
94147 static const sqlite3_tokenizer_module simpleTokenizerModule = {
94148   0,
94149   simpleCreate,
94150   simpleDestroy,
94151   simpleOpen,
94152   simpleClose,
94153   simpleNext,
94154 };
94155
94156 /*
94157 ** Allocate a new simple tokenizer.  Return a pointer to the new
94158 ** tokenizer in *ppModule
94159 */
94160 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
94161   sqlite3_tokenizer_module const**ppModule
94162 ){
94163   *ppModule = &simpleTokenizerModule;
94164 }
94165
94166 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
94167
94168 /************** End of fts3_tokenizer1.c *************************************/
94169 /************** Begin file rtree.c *******************************************/
94170 /*
94171 ** 2001 September 15
94172 **
94173 ** The author disclaims copyright to this source code.  In place of
94174 ** a legal notice, here is a blessing:
94175 **
94176 **    May you do good and not evil.
94177 **    May you find forgiveness for yourself and forgive others.
94178 **    May you share freely, never taking more than you give.
94179 **
94180 *************************************************************************
94181 ** This file contains code for implementations of the r-tree and r*-tree
94182 ** algorithms packaged as an SQLite virtual table module.
94183 **
94184 ** $Id: rtree.c,v 1.9 2008/09/08 11:07:03 danielk1977 Exp $
94185 */
94186
94187 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
94188
94189 /*
94190 ** This file contains an implementation of a couple of different variants
94191 ** of the r-tree algorithm. See the README file for further details. The 
94192 ** same data-structure is used for all, but the algorithms for insert and
94193 ** delete operations vary. The variants used are selected at compile time 
94194 ** by defining the following symbols:
94195 */
94196
94197 /* Either, both or none of the following may be set to activate 
94198 ** r*tree variant algorithms.
94199 */
94200 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
94201 #define VARIANT_RSTARTREE_REINSERT      1
94202
94203 /* 
94204 ** Exactly one of the following must be set to 1.
94205 */
94206 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
94207 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
94208 #define VARIANT_RSTARTREE_SPLIT         1
94209
94210 #define VARIANT_GUTTMAN_SPLIT \
94211         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
94212
94213 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
94214   #define PickNext QuadraticPickNext
94215   #define PickSeeds QuadraticPickSeeds
94216   #define AssignCells splitNodeGuttman
94217 #endif
94218 #if VARIANT_GUTTMAN_LINEAR_SPLIT
94219   #define PickNext LinearPickNext
94220   #define PickSeeds LinearPickSeeds
94221   #define AssignCells splitNodeGuttman
94222 #endif
94223 #if VARIANT_RSTARTREE_SPLIT
94224   #define AssignCells splitNodeStartree
94225 #endif
94226
94227
94228 #ifndef SQLITE_CORE
94229   SQLITE_EXTENSION_INIT1
94230 #else
94231 #endif
94232
94233
94234 #ifndef SQLITE_AMALGAMATION
94235 typedef sqlite3_int64 i64;
94236 typedef unsigned char u8;
94237 typedef unsigned int u32;
94238 #endif
94239
94240 typedef struct Rtree Rtree;
94241 typedef struct RtreeCursor RtreeCursor;
94242 typedef struct RtreeNode RtreeNode;
94243 typedef struct RtreeCell RtreeCell;
94244 typedef struct RtreeConstraint RtreeConstraint;
94245 typedef union RtreeCoord RtreeCoord;
94246
94247 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
94248 #define RTREE_MAX_DIMENSIONS 5
94249
94250 /* Size of hash table Rtree.aHash. This hash table is not expected to
94251 ** ever contain very many entries, so a fixed number of buckets is 
94252 ** used.
94253 */
94254 #define HASHSIZE 128
94255
94256 /* 
94257 ** An rtree virtual-table object.
94258 */
94259 struct Rtree {
94260   sqlite3_vtab base;
94261   sqlite3 *db;                /* Host database connection */
94262   int iNodeSize;              /* Size in bytes of each node in the node table */
94263   int nDim;                   /* Number of dimensions */
94264   int nBytesPerCell;          /* Bytes consumed per cell */
94265   int iDepth;                 /* Current depth of the r-tree structure */
94266   char *zDb;                  /* Name of database containing r-tree table */
94267   char *zName;                /* Name of r-tree table */ 
94268   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
94269   int nBusy;                  /* Current number of users of this structure */
94270
94271   /* List of nodes removed during a CondenseTree operation. List is
94272   ** linked together via the pointer normally used for hash chains -
94273   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
94274   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
94275   */
94276   RtreeNode *pDeleted;
94277   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
94278
94279   /* Statements to read/write/delete a record from xxx_node */
94280   sqlite3_stmt *pReadNode;
94281   sqlite3_stmt *pWriteNode;
94282   sqlite3_stmt *pDeleteNode;
94283
94284   /* Statements to read/write/delete a record from xxx_rowid */
94285   sqlite3_stmt *pReadRowid;
94286   sqlite3_stmt *pWriteRowid;
94287   sqlite3_stmt *pDeleteRowid;
94288
94289   /* Statements to read/write/delete a record from xxx_parent */
94290   sqlite3_stmt *pReadParent;
94291   sqlite3_stmt *pWriteParent;
94292   sqlite3_stmt *pDeleteParent;
94293
94294   int eCoordType;
94295 };
94296
94297 /* Possible values for eCoordType: */
94298 #define RTREE_COORD_REAL32 0
94299 #define RTREE_COORD_INT32  1
94300
94301 /*
94302 ** The minimum number of cells allowed for a node is a third of the 
94303 ** maximum. In Gutman's notation:
94304 **
94305 **     m = M/3
94306 **
94307 ** If an R*-tree "Reinsert" operation is required, the same number of
94308 ** cells are removed from the overfull node and reinserted into the tree.
94309 */
94310 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
94311 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
94312 #define RTREE_MAXCELLS 51
94313
94314 /* 
94315 ** An rtree cursor object.
94316 */
94317 struct RtreeCursor {
94318   sqlite3_vtab_cursor base;
94319   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
94320   int iCell;                        /* Index of current cell in pNode */
94321   int iStrategy;                    /* Copy of idxNum search parameter */
94322   int nConstraint;                  /* Number of entries in aConstraint */
94323   RtreeConstraint *aConstraint;     /* Search constraints. */
94324 };
94325
94326 union RtreeCoord {
94327   float f;
94328   int i;
94329 };
94330
94331 /*
94332 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
94333 ** formatted as a double. This macro assumes that local variable pRtree points
94334 ** to the Rtree structure associated with the RtreeCoord.
94335 */
94336 #define DCOORD(coord) (                           \
94337   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
94338     ((double)coord.f) :                           \
94339     ((double)coord.i)                             \
94340 )
94341
94342 /*
94343 ** A search constraint.
94344 */
94345 struct RtreeConstraint {
94346   int iCoord;                       /* Index of constrained coordinate */
94347   int op;                           /* Constraining operation */
94348   double rValue;                    /* Constraint value. */
94349 };
94350
94351 /* Possible values for RtreeConstraint.op */
94352 #define RTREE_EQ 0x41
94353 #define RTREE_LE 0x42
94354 #define RTREE_LT 0x43
94355 #define RTREE_GE 0x44
94356 #define RTREE_GT 0x45
94357
94358 /* 
94359 ** An rtree structure node.
94360 **
94361 ** Data format (RtreeNode.zData):
94362 **
94363 **   1. If the node is the root node (node 1), then the first 2 bytes
94364 **      of the node contain the tree depth as a big-endian integer.
94365 **      For non-root nodes, the first 2 bytes are left unused.
94366 **
94367 **   2. The next 2 bytes contain the number of entries currently 
94368 **      stored in the node.
94369 **
94370 **   3. The remainder of the node contains the node entries. Each entry
94371 **      consists of a single 8-byte integer followed by an even number
94372 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
94373 **      of a record. For internal nodes it is the node number of a
94374 **      child page.
94375 */
94376 struct RtreeNode {
94377   RtreeNode *pParent;               /* Parent node */
94378   i64 iNode;
94379   int nRef;
94380   int isDirty;
94381   u8 *zData;
94382   RtreeNode *pNext;                 /* Next node in this hash chain */
94383 };
94384 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
94385
94386 /* 
94387 ** Structure to store a deserialized rtree record.
94388 */
94389 struct RtreeCell {
94390   i64 iRowid;
94391   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
94392 };
94393
94394 #define MAX(x,y) ((x) < (y) ? (y) : (x))
94395 #define MIN(x,y) ((x) > (y) ? (y) : (x))
94396
94397 /*
94398 ** Functions to deserialize a 16 bit integer, 32 bit real number and
94399 ** 64 bit integer. The deserialized value is returned.
94400 */
94401 static int readInt16(u8 *p){
94402   return (p[0]<<8) + p[1];
94403 }
94404 static void readCoord(u8 *p, RtreeCoord *pCoord){
94405   u32 i = (
94406     (((u32)p[0]) << 24) + 
94407     (((u32)p[1]) << 16) + 
94408     (((u32)p[2]) <<  8) + 
94409     (((u32)p[3]) <<  0)
94410   );
94411   *(u32 *)pCoord = i;
94412 }
94413 static i64 readInt64(u8 *p){
94414   return (
94415     (((i64)p[0]) << 56) + 
94416     (((i64)p[1]) << 48) + 
94417     (((i64)p[2]) << 40) + 
94418     (((i64)p[3]) << 32) + 
94419     (((i64)p[4]) << 24) + 
94420     (((i64)p[5]) << 16) + 
94421     (((i64)p[6]) <<  8) + 
94422     (((i64)p[7]) <<  0)
94423   );
94424 }
94425
94426 /*
94427 ** Functions to serialize a 16 bit integer, 32 bit real number and
94428 ** 64 bit integer. The value returned is the number of bytes written
94429 ** to the argument buffer (always 2, 4 and 8 respectively).
94430 */
94431 static int writeInt16(u8 *p, int i){
94432   p[0] = (i>> 8)&0xFF;
94433   p[1] = (i>> 0)&0xFF;
94434   return 2;
94435 }
94436 static int writeCoord(u8 *p, RtreeCoord *pCoord){
94437   u32 i;
94438   assert( sizeof(RtreeCoord)==4 );
94439   assert( sizeof(u32)==4 );
94440   i = *(u32 *)pCoord;
94441   p[0] = (i>>24)&0xFF;
94442   p[1] = (i>>16)&0xFF;
94443   p[2] = (i>> 8)&0xFF;
94444   p[3] = (i>> 0)&0xFF;
94445   return 4;
94446 }
94447 static int writeInt64(u8 *p, i64 i){
94448   p[0] = (i>>56)&0xFF;
94449   p[1] = (i>>48)&0xFF;
94450   p[2] = (i>>40)&0xFF;
94451   p[3] = (i>>32)&0xFF;
94452   p[4] = (i>>24)&0xFF;
94453   p[5] = (i>>16)&0xFF;
94454   p[6] = (i>> 8)&0xFF;
94455   p[7] = (i>> 0)&0xFF;
94456   return 8;
94457 }
94458
94459 /*
94460 ** Increment the reference count of node p.
94461 */
94462 static void nodeReference(RtreeNode *p){
94463   if( p ){
94464     p->nRef++;
94465   }
94466 }
94467
94468 /*
94469 ** Clear the content of node p (set all bytes to 0x00).
94470 */
94471 static void nodeZero(Rtree *pRtree, RtreeNode *p){
94472   if( p ){
94473     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
94474     p->isDirty = 1;
94475   }
94476 }
94477
94478 /*
94479 ** Given a node number iNode, return the corresponding key to use
94480 ** in the Rtree.aHash table.
94481 */
94482 static int nodeHash(i64 iNode){
94483   return (
94484     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
94485     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
94486   ) % HASHSIZE;
94487 }
94488
94489 /*
94490 ** Search the node hash table for node iNode. If found, return a pointer
94491 ** to it. Otherwise, return 0.
94492 */
94493 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
94494   RtreeNode *p;
94495   assert( iNode!=0 );
94496   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
94497   return p;
94498 }
94499
94500 /*
94501 ** Add node pNode to the node hash table.
94502 */
94503 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
94504   if( pNode ){
94505     int iHash;
94506     assert( pNode->pNext==0 );
94507     iHash = nodeHash(pNode->iNode);
94508     pNode->pNext = pRtree->aHash[iHash];
94509     pRtree->aHash[iHash] = pNode;
94510   }
94511 }
94512
94513 /*
94514 ** Remove node pNode from the node hash table.
94515 */
94516 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
94517   RtreeNode **pp;
94518   if( pNode->iNode!=0 ){
94519     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
94520     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
94521     *pp = pNode->pNext;
94522     pNode->pNext = 0;
94523   }
94524 }
94525
94526 /*
94527 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
94528 ** indicating that node has not yet been assigned a node number. It is
94529 ** assigned a node number when nodeWrite() is called to write the
94530 ** node contents out to the database.
94531 */
94532 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
94533   RtreeNode *pNode;
94534   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
94535   if( pNode ){
94536     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
94537     pNode->zData = (u8 *)&pNode[1];
94538     pNode->nRef = 1;
94539     pNode->pParent = pParent;
94540     pNode->isDirty = 1;
94541     nodeReference(pParent);
94542   }
94543   return pNode;
94544 }
94545
94546 /*
94547 ** Obtain a reference to an r-tree node.
94548 */
94549 static int
94550 nodeAcquire(
94551   Rtree *pRtree,             /* R-tree structure */
94552   i64 iNode,                 /* Node number to load */
94553   RtreeNode *pParent,        /* Either the parent node or NULL */
94554   RtreeNode **ppNode         /* OUT: Acquired node */
94555 ){
94556   int rc;
94557   RtreeNode *pNode;
94558
94559   /* Check if the requested node is already in the hash table. If so,
94560   ** increase its reference count and return it.
94561   */
94562   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
94563     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
94564     if( pParent ){
94565       pNode->pParent = pParent;
94566     }
94567     pNode->nRef++;
94568     *ppNode = pNode;
94569     return SQLITE_OK;
94570   }
94571
94572   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
94573   if( !pNode ){
94574     *ppNode = 0;
94575     return SQLITE_NOMEM;
94576   }
94577   pNode->pParent = pParent;
94578   pNode->zData = (u8 *)&pNode[1];
94579   pNode->nRef = 1;
94580   pNode->iNode = iNode;
94581   pNode->isDirty = 0;
94582   pNode->pNext = 0;
94583
94584   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
94585   rc = sqlite3_step(pRtree->pReadNode);
94586   if( rc==SQLITE_ROW ){
94587     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
94588     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
94589     nodeReference(pParent);
94590   }else{
94591     sqlite3_free(pNode);
94592     pNode = 0;
94593   }
94594
94595   *ppNode = pNode;
94596   rc = sqlite3_reset(pRtree->pReadNode);
94597
94598   if( rc==SQLITE_OK && iNode==1 ){
94599     pRtree->iDepth = readInt16(pNode->zData);
94600   }
94601
94602   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
94603   nodeHashInsert(pRtree, pNode);
94604
94605   return rc;
94606 }
94607
94608 /*
94609 ** Overwrite cell iCell of node pNode with the contents of pCell.
94610 */
94611 static void nodeOverwriteCell(
94612   Rtree *pRtree, 
94613   RtreeNode *pNode,  
94614   RtreeCell *pCell, 
94615   int iCell
94616 ){
94617   int ii;
94618   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
94619   p += writeInt64(p, pCell->iRowid);
94620   for(ii=0; ii<(pRtree->nDim*2); ii++){
94621     p += writeCoord(p, &pCell->aCoord[ii]);
94622   }
94623   pNode->isDirty = 1;
94624 }
94625
94626 /*
94627 ** Remove cell the cell with index iCell from node pNode.
94628 */
94629 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
94630   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
94631   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
94632   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
94633   memmove(pDst, pSrc, nByte);
94634   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
94635   pNode->isDirty = 1;
94636 }
94637
94638 /*
94639 ** Insert the contents of cell pCell into node pNode. If the insert
94640 ** is successful, return SQLITE_OK.
94641 **
94642 ** If there is not enough free space in pNode, return SQLITE_FULL.
94643 */
94644 static int
94645 nodeInsertCell(
94646   Rtree *pRtree, 
94647   RtreeNode *pNode, 
94648   RtreeCell *pCell 
94649 ){
94650   int nCell;                    /* Current number of cells in pNode */
94651   int nMaxCell;                 /* Maximum number of cells for pNode */
94652
94653   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
94654   nCell = NCELL(pNode);
94655
94656   assert(nCell<=nMaxCell);
94657
94658   if( nCell<nMaxCell ){
94659     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
94660     writeInt16(&pNode->zData[2], nCell+1);
94661     pNode->isDirty = 1;
94662   }
94663
94664   return (nCell==nMaxCell);
94665 }
94666
94667 /*
94668 ** If the node is dirty, write it out to the database.
94669 */
94670 static int
94671 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
94672   int rc = SQLITE_OK;
94673   if( pNode->isDirty ){
94674     sqlite3_stmt *p = pRtree->pWriteNode;
94675     if( pNode->iNode ){
94676       sqlite3_bind_int64(p, 1, pNode->iNode);
94677     }else{
94678       sqlite3_bind_null(p, 1);
94679     }
94680     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
94681     sqlite3_step(p);
94682     pNode->isDirty = 0;
94683     rc = sqlite3_reset(p);
94684     if( pNode->iNode==0 && rc==SQLITE_OK ){
94685       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
94686       nodeHashInsert(pRtree, pNode);
94687     }
94688   }
94689   return rc;
94690 }
94691
94692 /*
94693 ** Release a reference to a node. If the node is dirty and the reference
94694 ** count drops to zero, the node data is written to the database.
94695 */
94696 static int
94697 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
94698   int rc = SQLITE_OK;
94699   if( pNode ){
94700     assert( pNode->nRef>0 );
94701     pNode->nRef--;
94702     if( pNode->nRef==0 ){
94703       if( pNode->iNode==1 ){
94704         pRtree->iDepth = -1;
94705       }
94706       if( pNode->pParent ){
94707         rc = nodeRelease(pRtree, pNode->pParent);
94708       }
94709       if( rc==SQLITE_OK ){
94710         rc = nodeWrite(pRtree, pNode);
94711       }
94712       nodeHashDelete(pRtree, pNode);
94713       sqlite3_free(pNode);
94714     }
94715   }
94716   return rc;
94717 }
94718
94719 /*
94720 ** Return the 64-bit integer value associated with cell iCell of
94721 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
94722 ** an internal node, then the 64-bit integer is a child page number.
94723 */
94724 static i64 nodeGetRowid(
94725   Rtree *pRtree, 
94726   RtreeNode *pNode, 
94727   int iCell
94728 ){
94729   assert( iCell<NCELL(pNode) );
94730   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
94731 }
94732
94733 /*
94734 ** Return coordinate iCoord from cell iCell in node pNode.
94735 */
94736 static void nodeGetCoord(
94737   Rtree *pRtree, 
94738   RtreeNode *pNode, 
94739   int iCell,
94740   int iCoord,
94741   RtreeCoord *pCoord           /* Space to write result to */
94742 ){
94743   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
94744 }
94745
94746 /*
94747 ** Deserialize cell iCell of node pNode. Populate the structure pointed
94748 ** to by pCell with the results.
94749 */
94750 static void nodeGetCell(
94751   Rtree *pRtree, 
94752   RtreeNode *pNode, 
94753   int iCell,
94754   RtreeCell *pCell
94755 ){
94756   int ii;
94757   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
94758   for(ii=0; ii<pRtree->nDim*2; ii++){
94759     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
94760   }
94761 }
94762
94763
94764 /* Forward declaration for the function that does the work of
94765 ** the virtual table module xCreate() and xConnect() methods.
94766 */
94767 static int rtreeInit(
94768   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int, int
94769 );
94770
94771 /* 
94772 ** Rtree virtual table module xCreate method.
94773 */
94774 static int rtreeCreate(
94775   sqlite3 *db,
94776   void *pAux,
94777   int argc, const char *const*argv,
94778   sqlite3_vtab **ppVtab,
94779   char **pzErr
94780 ){
94781   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1, (int)pAux);
94782 }
94783
94784 /* 
94785 ** Rtree virtual table module xConnect method.
94786 */
94787 static int rtreeConnect(
94788   sqlite3 *db,
94789   void *pAux,
94790   int argc, const char *const*argv,
94791   sqlite3_vtab **ppVtab,
94792   char **pzErr
94793 ){
94794   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0, (int)pAux);
94795 }
94796
94797 /*
94798 ** Increment the r-tree reference count.
94799 */
94800 static void rtreeReference(Rtree *pRtree){
94801   pRtree->nBusy++;
94802 }
94803
94804 /*
94805 ** Decrement the r-tree reference count. When the reference count reaches
94806 ** zero the structure is deleted.
94807 */
94808 static void rtreeRelease(Rtree *pRtree){
94809   pRtree->nBusy--;
94810   if( pRtree->nBusy==0 ){
94811     sqlite3_finalize(pRtree->pReadNode);
94812     sqlite3_finalize(pRtree->pWriteNode);
94813     sqlite3_finalize(pRtree->pDeleteNode);
94814     sqlite3_finalize(pRtree->pReadRowid);
94815     sqlite3_finalize(pRtree->pWriteRowid);
94816     sqlite3_finalize(pRtree->pDeleteRowid);
94817     sqlite3_finalize(pRtree->pReadParent);
94818     sqlite3_finalize(pRtree->pWriteParent);
94819     sqlite3_finalize(pRtree->pDeleteParent);
94820     sqlite3_free(pRtree);
94821   }
94822 }
94823
94824 /* 
94825 ** Rtree virtual table module xDisconnect method.
94826 */
94827 static int rtreeDisconnect(sqlite3_vtab *pVtab){
94828   rtreeRelease((Rtree *)pVtab);
94829   return SQLITE_OK;
94830 }
94831
94832 /* 
94833 ** Rtree virtual table module xDestroy method.
94834 */
94835 static int rtreeDestroy(sqlite3_vtab *pVtab){
94836   Rtree *pRtree = (Rtree *)pVtab;
94837   int rc;
94838   char *zCreate = sqlite3_mprintf(
94839     "DROP TABLE '%q'.'%q_node';"
94840     "DROP TABLE '%q'.'%q_rowid';"
94841     "DROP TABLE '%q'.'%q_parent';",
94842     pRtree->zDb, pRtree->zName, 
94843     pRtree->zDb, pRtree->zName,
94844     pRtree->zDb, pRtree->zName
94845   );
94846   if( !zCreate ){
94847     rc = SQLITE_NOMEM;
94848   }else{
94849     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
94850     sqlite3_free(zCreate);
94851   }
94852   if( rc==SQLITE_OK ){
94853     rtreeRelease(pRtree);
94854   }
94855
94856   return rc;
94857 }
94858
94859 /* 
94860 ** Rtree virtual table module xOpen method.
94861 */
94862 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
94863   int rc = SQLITE_NOMEM;
94864   RtreeCursor *pCsr;
94865
94866   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
94867   if( pCsr ){
94868     memset(pCsr, 0, sizeof(RtreeCursor));
94869     pCsr->base.pVtab = pVTab;
94870     rc = SQLITE_OK;
94871   }
94872   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
94873
94874   return rc;
94875 }
94876
94877 /* 
94878 ** Rtree virtual table module xClose method.
94879 */
94880 static int rtreeClose(sqlite3_vtab_cursor *cur){
94881   Rtree *pRtree = (Rtree *)(cur->pVtab);
94882   int rc;
94883   RtreeCursor *pCsr = (RtreeCursor *)cur;
94884   sqlite3_free(pCsr->aConstraint);
94885   rc = nodeRelease(pRtree, pCsr->pNode);
94886   sqlite3_free(pCsr);
94887   return rc;
94888 }
94889
94890 /*
94891 ** Rtree virtual table module xEof method.
94892 **
94893 ** Return non-zero if the cursor does not currently point to a valid 
94894 ** record (i.e if the scan has finished), or zero otherwise.
94895 */
94896 static int rtreeEof(sqlite3_vtab_cursor *cur){
94897   RtreeCursor *pCsr = (RtreeCursor *)cur;
94898   return (pCsr->pNode==0);
94899 }
94900
94901 /* 
94902 ** Cursor pCursor currently points to a cell in a non-leaf page.
94903 ** Return true if the sub-tree headed by the cell is filtered
94904 ** (excluded) by the constraints in the pCursor->aConstraint[] 
94905 ** array, or false otherwise.
94906 */
94907 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
94908   RtreeCell cell;
94909   int ii;
94910   int bRes = 0;
94911
94912   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
94913   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
94914     RtreeConstraint *p = &pCursor->aConstraint[ii];
94915     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
94916     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
94917
94918     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
94919         || p->op==RTREE_GT || p->op==RTREE_EQ
94920     );
94921
94922     switch( p->op ){
94923       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
94924       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
94925       case RTREE_EQ: 
94926         bRes = (p->rValue>cell_max || p->rValue<cell_min);
94927         break;
94928     }
94929   }
94930
94931   return bRes;
94932 }
94933
94934 /* 
94935 ** Return true if the cell that cursor pCursor currently points to
94936 ** would be filtered (excluded) by the constraints in the 
94937 ** pCursor->aConstraint[] array, or false otherwise.
94938 **
94939 ** This function assumes that the cell is part of a leaf node.
94940 */
94941 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
94942   RtreeCell cell;
94943   int ii;
94944
94945   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
94946   for(ii=0; ii<pCursor->nConstraint; ii++){
94947     RtreeConstraint *p = &pCursor->aConstraint[ii];
94948     double coord = DCOORD(cell.aCoord[p->iCoord]);
94949     int res;
94950     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
94951         || p->op==RTREE_GT || p->op==RTREE_EQ
94952     );
94953     switch( p->op ){
94954       case RTREE_LE: res = (coord<=p->rValue); break;
94955       case RTREE_LT: res = (coord<p->rValue);  break;
94956       case RTREE_GE: res = (coord>=p->rValue); break;
94957       case RTREE_GT: res = (coord>p->rValue);  break;
94958       case RTREE_EQ: res = (coord==p->rValue); break;
94959     }
94960
94961     if( !res ) return 1;
94962   }
94963
94964   return 0;
94965 }
94966
94967 /*
94968 ** Cursor pCursor currently points at a node that heads a sub-tree of
94969 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
94970 ** to point to the left-most cell of the sub-tree that matches the 
94971 ** configured constraints.
94972 */
94973 static int descendToCell(
94974   Rtree *pRtree, 
94975   RtreeCursor *pCursor, 
94976   int iHeight,
94977   int *pEof                 /* OUT: Set to true if cannot descend */
94978 ){
94979   int isEof;
94980   int rc;
94981   int ii;
94982   RtreeNode *pChild;
94983   sqlite3_int64 iRowid;
94984
94985   RtreeNode *pSavedNode = pCursor->pNode;
94986   int iSavedCell = pCursor->iCell;
94987
94988   assert( iHeight>=0 );
94989
94990   if( iHeight==0 ){
94991     isEof = testRtreeEntry(pRtree, pCursor);
94992   }else{
94993     isEof = testRtreeCell(pRtree, pCursor);
94994   }
94995   if( isEof || iHeight==0 ){
94996     *pEof = isEof;
94997     return SQLITE_OK;
94998   }
94999
95000   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
95001   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
95002   if( rc!=SQLITE_OK ){
95003     return rc;
95004   }
95005
95006   nodeRelease(pRtree, pCursor->pNode);
95007   pCursor->pNode = pChild;
95008   isEof = 1;
95009   for(ii=0; isEof && ii<NCELL(pChild); ii++){
95010     pCursor->iCell = ii;
95011     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
95012     if( rc!=SQLITE_OK ){
95013       return rc;
95014     }
95015   }
95016
95017   if( isEof ){
95018     assert( pCursor->pNode==pChild );
95019     nodeReference(pSavedNode);
95020     nodeRelease(pRtree, pChild);
95021     pCursor->pNode = pSavedNode;
95022     pCursor->iCell = iSavedCell;
95023   }
95024
95025   *pEof = isEof;
95026   return SQLITE_OK;
95027 }
95028
95029 /*
95030 ** One of the cells in node pNode is guaranteed to have a 64-bit 
95031 ** integer value equal to iRowid. Return the index of this cell.
95032 */
95033 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
95034   int ii;
95035   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
95036     assert( ii<(NCELL(pNode)-1) );
95037   }
95038   return ii;
95039 }
95040
95041 /*
95042 ** Return the index of the cell containing a pointer to node pNode
95043 ** in its parent. If pNode is the root node, return -1.
95044 */
95045 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
95046   RtreeNode *pParent = pNode->pParent;
95047   if( pParent ){
95048     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
95049   }
95050   return -1;
95051 }
95052
95053 /* 
95054 ** Rtree virtual table module xNext method.
95055 */
95056 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
95057   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
95058   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
95059   int rc = SQLITE_OK;
95060
95061   if( pCsr->iStrategy==1 ){
95062     /* This "scan" is a direct lookup by rowid. There is no next entry. */
95063     nodeRelease(pRtree, pCsr->pNode);
95064     pCsr->pNode = 0;
95065   }
95066
95067   else if( pCsr->pNode ){
95068     /* Move to the next entry that matches the configured constraints. */
95069     int iHeight = 0;
95070     while( pCsr->pNode ){
95071       RtreeNode *pNode = pCsr->pNode;
95072       int nCell = NCELL(pNode);
95073       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
95074         int isEof;
95075         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
95076         if( rc!=SQLITE_OK || !isEof ){
95077           return rc;
95078         }
95079       }
95080       pCsr->pNode = pNode->pParent;
95081       pCsr->iCell = nodeParentIndex(pRtree, pNode);
95082       nodeReference(pCsr->pNode);
95083       nodeRelease(pRtree, pNode);
95084       iHeight++;
95085     }
95086   }
95087
95088   return rc;
95089 }
95090
95091 /* 
95092 ** Rtree virtual table module xRowid method.
95093 */
95094 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
95095   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
95096   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
95097
95098   assert(pCsr->pNode);
95099   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
95100
95101   return SQLITE_OK;
95102 }
95103
95104 /* 
95105 ** Rtree virtual table module xColumn method.
95106 */
95107 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
95108   Rtree *pRtree = (Rtree *)cur->pVtab;
95109   RtreeCursor *pCsr = (RtreeCursor *)cur;
95110
95111   if( i==0 ){
95112     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
95113     sqlite3_result_int64(ctx, iRowid);
95114   }else{
95115     RtreeCoord c;
95116     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
95117     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
95118       sqlite3_result_double(ctx, c.f);
95119     }else{
95120       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
95121       sqlite3_result_int(ctx, c.i);
95122     }
95123   }
95124
95125   return SQLITE_OK;
95126 }
95127
95128 /* 
95129 ** Use nodeAcquire() to obtain the leaf node containing the record with 
95130 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
95131 ** return SQLITE_OK. If there is no such record in the table, set
95132 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
95133 ** to zero and return an SQLite error code.
95134 */
95135 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
95136   int rc;
95137   *ppLeaf = 0;
95138   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
95139   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
95140     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
95141     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
95142     sqlite3_reset(pRtree->pReadRowid);
95143   }else{
95144     rc = sqlite3_reset(pRtree->pReadRowid);
95145   }
95146   return rc;
95147 }
95148
95149
95150 /* 
95151 ** Rtree virtual table module xFilter method.
95152 */
95153 static int rtreeFilter(
95154   sqlite3_vtab_cursor *pVtabCursor, 
95155   int idxNum, const char *idxStr,
95156   int argc, sqlite3_value **argv
95157 ){
95158   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
95159   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
95160
95161   RtreeNode *pRoot = 0;
95162   int ii;
95163   int rc = SQLITE_OK;
95164
95165   rtreeReference(pRtree);
95166
95167   sqlite3_free(pCsr->aConstraint);
95168   pCsr->aConstraint = 0;
95169   pCsr->iStrategy = idxNum;
95170
95171   if( idxNum==1 ){
95172     /* Special case - lookup by rowid. */
95173     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
95174     i64 iRowid = sqlite3_value_int64(argv[0]);
95175     rc = findLeafNode(pRtree, iRowid, &pLeaf);
95176     pCsr->pNode = pLeaf; 
95177     if( pLeaf && rc==SQLITE_OK ){
95178       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
95179     }
95180   }else{
95181     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
95182     ** with the configured constraints. 
95183     */
95184     if( argc>0 ){
95185       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
95186       pCsr->nConstraint = argc;
95187       if( !pCsr->aConstraint ){
95188         rc = SQLITE_NOMEM;
95189       }else{
95190         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
95191         for(ii=0; ii<argc; ii++){
95192           RtreeConstraint *p = &pCsr->aConstraint[ii];
95193           p->op = idxStr[ii*2];
95194           p->iCoord = idxStr[ii*2+1]-'a';
95195           p->rValue = sqlite3_value_double(argv[ii]);
95196         }
95197       }
95198     }
95199   
95200     if( rc==SQLITE_OK ){
95201       pCsr->pNode = 0;
95202       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
95203     }
95204     if( rc==SQLITE_OK ){
95205       int isEof = 1;
95206       int nCell = NCELL(pRoot);
95207       pCsr->pNode = pRoot;
95208       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
95209         assert( pCsr->pNode==pRoot );
95210         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
95211         if( !isEof ){
95212           break;
95213         }
95214       }
95215       if( rc==SQLITE_OK && isEof ){
95216         assert( pCsr->pNode==pRoot );
95217         nodeRelease(pRtree, pRoot);
95218         pCsr->pNode = 0;
95219       }
95220       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
95221     }
95222   }
95223
95224   rtreeRelease(pRtree);
95225   return rc;
95226 }
95227
95228 /*
95229 ** Rtree virtual table module xBestIndex method. There are three
95230 ** table scan strategies to choose from (in order from most to 
95231 ** least desirable):
95232 **
95233 **   idxNum     idxStr        Strategy
95234 **   ------------------------------------------------
95235 **     1        Unused        Direct lookup by rowid.
95236 **     2        See below     R-tree query.
95237 **     3        Unused        Full table scan.
95238 **   ------------------------------------------------
95239 **
95240 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
95241 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
95242 ** constraint used. The first two bytes of idxStr correspond to 
95243 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
95244 ** (argvIndex==1) etc.
95245 **
95246 ** The first of each pair of bytes in idxStr identifies the constraint
95247 ** operator as follows:
95248 **
95249 **   Operator    Byte Value
95250 **   ----------------------
95251 **      =        0x41 ('A')
95252 **     <=        0x42 ('B')
95253 **      <        0x43 ('C')
95254 **     >=        0x44 ('D')
95255 **      >        0x45 ('E')
95256 **   ----------------------
95257 **
95258 ** The second of each pair of bytes identifies the coordinate column
95259 ** to which the constraint applies. The leftmost coordinate column
95260 ** is 'a', the second from the left 'b' etc.
95261 */
95262 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
95263   int rc = SQLITE_OK;
95264   int ii, cCol;
95265
95266   int iIdx = 0;
95267   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
95268   memset(zIdxStr, 0, sizeof(zIdxStr));
95269
95270   assert( pIdxInfo->idxStr==0 );
95271   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
95272     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
95273
95274     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
95275       /* We have an equality constraint on the rowid. Use strategy 1. */
95276       int jj;
95277       for(jj=0; jj<ii; jj++){
95278         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
95279         pIdxInfo->aConstraintUsage[jj].omit = 0;
95280       }
95281       pIdxInfo->idxNum = 1;
95282       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
95283       pIdxInfo->aConstraintUsage[jj].omit = 1;
95284
95285       /* This strategy involves a two rowid lookups on an B-Tree structures
95286       ** and then a linear search of an R-Tree node. This should be 
95287       ** considered almost as quick as a direct rowid lookup (for which 
95288       ** sqlite uses an internal cost of 0.0).
95289       */ 
95290       pIdxInfo->estimatedCost = 10.0;
95291       return SQLITE_OK;
95292     }
95293
95294     if( p->usable && p->iColumn>0 ){
95295       u8 op = 0;
95296       switch( p->op ){
95297         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
95298         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
95299         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
95300         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
95301         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
95302       }
95303       if( op ){
95304         /* Make sure this particular constraint has not been used before.
95305         ** If it has been used before, ignore it.
95306         **
95307         ** A <= or < can be used if there is a prior >= or >.
95308         ** A >= or > can be used if there is a prior < or <=.
95309         ** A <= or < is disqualified if there is a prior <=, <, or ==.
95310         ** A >= or > is disqualified if there is a prior >=, >, or ==.
95311         ** A == is disqualifed if there is any prior constraint.
95312         */
95313         int j, opmsk;
95314         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
95315         assert( compatible[RTREE_EQ & 7]==0 );
95316         assert( compatible[RTREE_LT & 7]==1 );
95317         assert( compatible[RTREE_LE & 7]==1 );
95318         assert( compatible[RTREE_GT & 7]==2 );
95319         assert( compatible[RTREE_GE & 7]==2 );
95320         cCol = p->iColumn - 1 + 'a';
95321         opmsk = compatible[op & 7];
95322         for(j=0; j<iIdx; j+=2){
95323           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
95324             op = 0;
95325             break;
95326           }
95327         }
95328       }
95329       if( op ){
95330         assert( iIdx<sizeof(zIdxStr)-1 );
95331         zIdxStr[iIdx++] = op;
95332         zIdxStr[iIdx++] = cCol;
95333         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
95334         pIdxInfo->aConstraintUsage[ii].omit = 1;
95335       }
95336     }
95337   }
95338
95339   pIdxInfo->idxNum = 2;
95340   pIdxInfo->needToFreeIdxStr = 1;
95341   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
95342     return SQLITE_NOMEM;
95343   }
95344   assert( iIdx>=0 );
95345   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
95346   return rc;
95347 }
95348
95349 /*
95350 ** Return the N-dimensional volumn of the cell stored in *p.
95351 */
95352 static float cellArea(Rtree *pRtree, RtreeCell *p){
95353   float area = 1.0;
95354   int ii;
95355   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
95356     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
95357   }
95358   return area;
95359 }
95360
95361 /*
95362 ** Return the margin length of cell p. The margin length is the sum
95363 ** of the objects size in each dimension.
95364 */
95365 static float cellMargin(Rtree *pRtree, RtreeCell *p){
95366   float margin = 0.0;
95367   int ii;
95368   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
95369     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
95370   }
95371   return margin;
95372 }
95373
95374 /*
95375 ** Store the union of cells p1 and p2 in p1.
95376 */
95377 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
95378   int ii;
95379   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
95380     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
95381       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
95382       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
95383     }
95384   }else{
95385     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
95386       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
95387       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
95388     }
95389   }
95390 }
95391
95392 /*
95393 ** Return true if the area covered by p2 is a subset of the area covered
95394 ** by p1. False otherwise.
95395 */
95396 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
95397   int ii;
95398   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
95399   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
95400     RtreeCoord *a1 = &p1->aCoord[ii];
95401     RtreeCoord *a2 = &p2->aCoord[ii];
95402     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
95403      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
95404     ){
95405       return 0;
95406     }
95407   }
95408   return 1;
95409 }
95410
95411 /*
95412 ** Return the amount cell p would grow by if it were unioned with pCell.
95413 */
95414 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
95415   float area;
95416   RtreeCell cell;
95417   memcpy(&cell, p, sizeof(RtreeCell));
95418   area = cellArea(pRtree, &cell);
95419   cellUnion(pRtree, &cell, pCell);
95420   return (cellArea(pRtree, &cell)-area);
95421 }
95422
95423 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
95424 static float cellOverlap(
95425   Rtree *pRtree, 
95426   RtreeCell *p, 
95427   RtreeCell *aCell, 
95428   int nCell, 
95429   int iExclude
95430 ){
95431   int ii;
95432   float overlap = 0.0;
95433   for(ii=0; ii<nCell; ii++){
95434     if( ii!=iExclude ){
95435       int jj;
95436       float o = 1.0;
95437       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
95438         double x1;
95439         double x2;
95440
95441         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
95442         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
95443
95444         if( x2<x1 ){
95445           o = 0.0;
95446           break;
95447         }else{
95448           o = o * (x2-x1);
95449         }
95450       }
95451       overlap += o;
95452     }
95453   }
95454   return overlap;
95455 }
95456 #endif
95457
95458 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95459 static float cellOverlapEnlargement(
95460   Rtree *pRtree, 
95461   RtreeCell *p, 
95462   RtreeCell *pInsert, 
95463   RtreeCell *aCell, 
95464   int nCell, 
95465   int iExclude
95466 ){
95467   float before;
95468   float after;
95469   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
95470   cellUnion(pRtree, p, pInsert);
95471   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
95472   return after-before;
95473 }
95474 #endif
95475
95476
95477 /*
95478 ** This function implements the ChooseLeaf algorithm from Gutman[84].
95479 ** ChooseSubTree in r*tree terminology.
95480 */
95481 static int ChooseLeaf(
95482   Rtree *pRtree,               /* Rtree table */
95483   RtreeCell *pCell,            /* Cell to insert into rtree */
95484   int iHeight,                 /* Height of sub-tree rooted at pCell */
95485   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
95486 ){
95487   int rc;
95488   int ii;
95489   RtreeNode *pNode;
95490   rc = nodeAcquire(pRtree, 1, 0, &pNode);
95491
95492   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
95493     int iCell;
95494     sqlite3_int64 iBest;
95495
95496     float fMinGrowth;
95497     float fMinArea;
95498     float fMinOverlap;
95499
95500     int nCell = NCELL(pNode);
95501     RtreeCell cell;
95502     RtreeNode *pChild;
95503
95504     RtreeCell *aCell = 0;
95505
95506 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95507     if( ii==(pRtree->iDepth-1) ){
95508       int jj;
95509       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
95510       if( !aCell ){
95511         rc = SQLITE_NOMEM;
95512         nodeRelease(pRtree, pNode);
95513         pNode = 0;
95514         continue;
95515       }
95516       for(jj=0; jj<nCell; jj++){
95517         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
95518       }
95519     }
95520 #endif
95521
95522     /* Select the child node which will be enlarged the least if pCell
95523     ** is inserted into it. Resolve ties by choosing the entry with
95524     ** the smallest area.
95525     */
95526     for(iCell=0; iCell<nCell; iCell++){
95527       float growth;
95528       float area;
95529       float overlap = 0.0;
95530       nodeGetCell(pRtree, pNode, iCell, &cell);
95531       growth = cellGrowth(pRtree, &cell, pCell);
95532       area = cellArea(pRtree, &cell);
95533 #if VARIANT_RSTARTREE_CHOOSESUBTREE
95534       if( ii==(pRtree->iDepth-1) ){
95535         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
95536       }
95537 #endif
95538       if( (iCell==0) 
95539        || (overlap<fMinOverlap) 
95540        || (overlap==fMinOverlap && growth<fMinGrowth)
95541        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
95542       ){
95543         fMinOverlap = overlap;
95544         fMinGrowth = growth;
95545         fMinArea = area;
95546         iBest = cell.iRowid;
95547       }
95548     }
95549
95550     sqlite3_free(aCell);
95551     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
95552     nodeRelease(pRtree, pNode);
95553     pNode = pChild;
95554   }
95555
95556   *ppLeaf = pNode;
95557   return rc;
95558 }
95559
95560 /*
95561 ** A cell with the same content as pCell has just been inserted into
95562 ** the node pNode. This function updates the bounding box cells in
95563 ** all ancestor elements.
95564 */
95565 static void AdjustTree(
95566   Rtree *pRtree,                    /* Rtree table */
95567   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
95568   RtreeCell *pCell                  /* This cell was just inserted */
95569 ){
95570   RtreeNode *p = pNode;
95571   while( p->pParent ){
95572     RtreeCell cell;
95573     RtreeNode *pParent = p->pParent;
95574     int iCell = nodeParentIndex(pRtree, p);
95575
95576     nodeGetCell(pRtree, pParent, iCell, &cell);
95577     if( !cellContains(pRtree, &cell, pCell) ){
95578       cellUnion(pRtree, &cell, pCell);
95579       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
95580     }
95581  
95582     p = pParent;
95583   }
95584 }
95585
95586 /*
95587 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
95588 */
95589 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
95590   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
95591   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
95592   sqlite3_step(pRtree->pWriteRowid);
95593   return sqlite3_reset(pRtree->pWriteRowid);
95594 }
95595
95596 /*
95597 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
95598 */
95599 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
95600   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
95601   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
95602   sqlite3_step(pRtree->pWriteParent);
95603   return sqlite3_reset(pRtree->pWriteParent);
95604 }
95605
95606 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
95607
95608 #if VARIANT_GUTTMAN_LINEAR_SPLIT
95609 /*
95610 ** Implementation of the linear variant of the PickNext() function from
95611 ** Guttman[84].
95612 */
95613 static RtreeCell *LinearPickNext(
95614   Rtree *pRtree,
95615   RtreeCell *aCell, 
95616   int nCell, 
95617   RtreeCell *pLeftBox, 
95618   RtreeCell *pRightBox,
95619   int *aiUsed
95620 ){
95621   int ii;
95622   for(ii=0; aiUsed[ii]; ii++);
95623   aiUsed[ii] = 1;
95624   return &aCell[ii];
95625 }
95626
95627 /*
95628 ** Implementation of the linear variant of the PickSeeds() function from
95629 ** Guttman[84].
95630 */
95631 static void LinearPickSeeds(
95632   Rtree *pRtree,
95633   RtreeCell *aCell, 
95634   int nCell, 
95635   int *piLeftSeed, 
95636   int *piRightSeed
95637 ){
95638   int i;
95639   int iLeftSeed = 0;
95640   int iRightSeed = 1;
95641   float maxNormalInnerWidth = 0.0;
95642
95643   /* Pick two "seed" cells from the array of cells. The algorithm used
95644   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
95645   ** indices of the two seed cells in the array are stored in local
95646   ** variables iLeftSeek and iRightSeed.
95647   */
95648   for(i=0; i<pRtree->nDim; i++){
95649     float x1 = aCell[0].aCoord[i*2];
95650     float x2 = aCell[0].aCoord[i*2+1];
95651     float x3 = x1;
95652     float x4 = x2;
95653     int jj;
95654
95655     int iCellLeft = 0;
95656     int iCellRight = 0;
95657
95658     for(jj=1; jj<nCell; jj++){
95659       float left = aCell[jj].aCoord[i*2];
95660       float right = aCell[jj].aCoord[i*2+1];
95661
95662       if( left<x1 ) x1 = left;
95663       if( right>x4 ) x4 = right;
95664       if( left>x3 ){
95665         x3 = left;
95666         iCellRight = jj;
95667       }
95668       if( right<x2 ){
95669         x2 = right;
95670         iCellLeft = jj;
95671       }
95672     }
95673
95674     if( x4!=x1 ){
95675       float normalwidth = (x3 - x2) / (x4 - x1);
95676       if( normalwidth>maxNormalInnerWidth ){
95677         iLeftSeed = iCellLeft;
95678         iRightSeed = iCellRight;
95679       }
95680     }
95681   }
95682
95683   *piLeftSeed = iLeftSeed;
95684   *piRightSeed = iRightSeed;
95685 }
95686 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
95687
95688 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
95689 /*
95690 ** Implementation of the quadratic variant of the PickNext() function from
95691 ** Guttman[84].
95692 */
95693 static RtreeCell *QuadraticPickNext(
95694   Rtree *pRtree,
95695   RtreeCell *aCell, 
95696   int nCell, 
95697   RtreeCell *pLeftBox, 
95698   RtreeCell *pRightBox,
95699   int *aiUsed
95700 ){
95701   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
95702
95703   int iSelect = -1;
95704   float fDiff;
95705   int ii;
95706   for(ii=0; ii<nCell; ii++){
95707     if( aiUsed[ii]==0 ){
95708       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
95709       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
95710       float diff = FABS(right-left);
95711       if( iSelect<0 || diff>fDiff ){
95712         fDiff = diff;
95713         iSelect = ii;
95714       }
95715     }
95716   }
95717   aiUsed[iSelect] = 1;
95718   return &aCell[iSelect];
95719 }
95720
95721 /*
95722 ** Implementation of the quadratic variant of the PickSeeds() function from
95723 ** Guttman[84].
95724 */
95725 static void QuadraticPickSeeds(
95726   Rtree *pRtree,
95727   RtreeCell *aCell, 
95728   int nCell, 
95729   int *piLeftSeed, 
95730   int *piRightSeed
95731 ){
95732   int ii;
95733   int jj;
95734
95735   int iLeftSeed = 0;
95736   int iRightSeed = 1;
95737   float fWaste = 0.0;
95738
95739   for(ii=0; ii<nCell; ii++){
95740     for(jj=ii+1; jj<nCell; jj++){
95741       float right = cellArea(pRtree, &aCell[jj]);
95742       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
95743       float waste = growth - right;
95744
95745       if( waste>fWaste ){
95746         iLeftSeed = ii;
95747         iRightSeed = jj;
95748         fWaste = waste;
95749       }
95750     }
95751   }
95752
95753   *piLeftSeed = iLeftSeed;
95754   *piRightSeed = iRightSeed;
95755 }
95756 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
95757
95758 /*
95759 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
95760 ** nIdx. The aIdx array contains the set of integers from 0 to 
95761 ** (nIdx-1) in no particular order. This function sorts the values
95762 ** in aIdx according to the indexed values in aDistance. For
95763 ** example, assuming the inputs:
95764 **
95765 **   aIdx      = { 0,   1,   2,   3 }
95766 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
95767 **
95768 ** this function sets the aIdx array to contain:
95769 **
95770 **   aIdx      = { 0,   1,   2,   3 }
95771 **
95772 ** The aSpare array is used as temporary working space by the
95773 ** sorting algorithm.
95774 */
95775 static void SortByDistance(
95776   int *aIdx, 
95777   int nIdx, 
95778   float *aDistance, 
95779   int *aSpare
95780 ){
95781   if( nIdx>1 ){
95782     int iLeft = 0;
95783     int iRight = 0;
95784
95785     int nLeft = nIdx/2;
95786     int nRight = nIdx-nLeft;
95787     int *aLeft = aIdx;
95788     int *aRight = &aIdx[nLeft];
95789
95790     SortByDistance(aLeft, nLeft, aDistance, aSpare);
95791     SortByDistance(aRight, nRight, aDistance, aSpare);
95792
95793     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
95794     aLeft = aSpare;
95795
95796     while( iLeft<nLeft || iRight<nRight ){
95797       if( iLeft==nLeft ){
95798         aIdx[iLeft+iRight] = aRight[iRight];
95799         iRight++;
95800       }else if( iRight==nRight ){
95801         aIdx[iLeft+iRight] = aLeft[iLeft];
95802         iLeft++;
95803       }else{
95804         float fLeft = aDistance[aLeft[iLeft]];
95805         float fRight = aDistance[aRight[iRight]];
95806         if( fLeft<fRight ){
95807           aIdx[iLeft+iRight] = aLeft[iLeft];
95808           iLeft++;
95809         }else{
95810           aIdx[iLeft+iRight] = aRight[iRight];
95811           iRight++;
95812         }
95813       }
95814     }
95815
95816 #if 0
95817     /* Check that the sort worked */
95818     {
95819       int jj;
95820       for(jj=1; jj<nIdx; jj++){
95821         float left = aDistance[aIdx[jj-1]];
95822         float right = aDistance[aIdx[jj]];
95823         assert( left<=right );
95824       }
95825     }
95826 #endif
95827   }
95828 }
95829
95830 /*
95831 ** Arguments aIdx, aCell and aSpare all point to arrays of size
95832 ** nIdx. The aIdx array contains the set of integers from 0 to 
95833 ** (nIdx-1) in no particular order. This function sorts the values
95834 ** in aIdx according to dimension iDim of the cells in aCell. The
95835 ** minimum value of dimension iDim is considered first, the
95836 ** maximum used to break ties.
95837 **
95838 ** The aSpare array is used as temporary working space by the
95839 ** sorting algorithm.
95840 */
95841 static void SortByDimension(
95842   Rtree *pRtree,
95843   int *aIdx, 
95844   int nIdx, 
95845   int iDim, 
95846   RtreeCell *aCell, 
95847   int *aSpare
95848 ){
95849   if( nIdx>1 ){
95850
95851     int iLeft = 0;
95852     int iRight = 0;
95853
95854     int nLeft = nIdx/2;
95855     int nRight = nIdx-nLeft;
95856     int *aLeft = aIdx;
95857     int *aRight = &aIdx[nLeft];
95858
95859     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
95860     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
95861
95862     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
95863     aLeft = aSpare;
95864     while( iLeft<nLeft || iRight<nRight ){
95865       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
95866       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
95867       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
95868       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
95869       if( (iLeft!=nLeft) && ((iRight==nRight)
95870        || (xleft1<xright1)
95871        || (xleft1==xright1 && xleft2<xright2)
95872       )){
95873         aIdx[iLeft+iRight] = aLeft[iLeft];
95874         iLeft++;
95875       }else{
95876         aIdx[iLeft+iRight] = aRight[iRight];
95877         iRight++;
95878       }
95879     }
95880
95881 #if 0
95882     /* Check that the sort worked */
95883     {
95884       int jj;
95885       for(jj=1; jj<nIdx; jj++){
95886         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
95887         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
95888         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
95889         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
95890         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
95891       }
95892     }
95893 #endif
95894   }
95895 }
95896
95897 #if VARIANT_RSTARTREE_SPLIT
95898 /*
95899 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
95900 */
95901 static int splitNodeStartree(
95902   Rtree *pRtree,
95903   RtreeCell *aCell,
95904   int nCell,
95905   RtreeNode *pLeft,
95906   RtreeNode *pRight,
95907   RtreeCell *pBboxLeft,
95908   RtreeCell *pBboxRight
95909 ){
95910   int **aaSorted;
95911   int *aSpare;
95912   int ii;
95913
95914   int iBestDim;
95915   int iBestSplit;
95916   float fBestMargin;
95917
95918   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
95919
95920   aaSorted = (int **)sqlite3_malloc(nByte);
95921   if( !aaSorted ){
95922     return SQLITE_NOMEM;
95923   }
95924
95925   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
95926   memset(aaSorted, 0, nByte);
95927   for(ii=0; ii<pRtree->nDim; ii++){
95928     int jj;
95929     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
95930     for(jj=0; jj<nCell; jj++){
95931       aaSorted[ii][jj] = jj;
95932     }
95933     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
95934   }
95935
95936   for(ii=0; ii<pRtree->nDim; ii++){
95937     float margin = 0.0;
95938     float fBestOverlap;
95939     float fBestArea;
95940     int iBestLeft;
95941     int nLeft;
95942
95943     for(
95944       nLeft=RTREE_MINCELLS(pRtree); 
95945       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
95946       nLeft++
95947     ){
95948       RtreeCell left;
95949       RtreeCell right;
95950       int kk;
95951       float overlap;
95952       float area;
95953
95954       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
95955       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
95956       for(kk=1; kk<(nCell-1); kk++){
95957         if( kk<nLeft ){
95958           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
95959         }else{
95960           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
95961         }
95962       }
95963       margin += cellMargin(pRtree, &left);
95964       margin += cellMargin(pRtree, &right);
95965       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
95966       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
95967       if( (nLeft==RTREE_MINCELLS(pRtree))
95968        || (overlap<fBestOverlap)
95969        || (overlap==fBestOverlap && area<fBestArea)
95970       ){
95971         iBestLeft = nLeft;
95972         fBestOverlap = overlap;
95973         fBestArea = area;
95974       }
95975     }
95976
95977     if( ii==0 || margin<fBestMargin ){
95978       iBestDim = ii;
95979       fBestMargin = margin;
95980       iBestSplit = iBestLeft;
95981     }
95982   }
95983
95984   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
95985   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
95986   for(ii=0; ii<nCell; ii++){
95987     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
95988     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
95989     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
95990     nodeInsertCell(pRtree, pTarget, pCell);
95991     cellUnion(pRtree, pBbox, pCell);
95992   }
95993
95994   sqlite3_free(aaSorted);
95995   return SQLITE_OK;
95996 }
95997 #endif
95998
95999 #if VARIANT_GUTTMAN_SPLIT
96000 /*
96001 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
96002 */
96003 static int splitNodeGuttman(
96004   Rtree *pRtree,
96005   RtreeCell *aCell,
96006   int nCell,
96007   RtreeNode *pLeft,
96008   RtreeNode *pRight,
96009   RtreeCell *pBboxLeft,
96010   RtreeCell *pBboxRight
96011 ){
96012   int iLeftSeed = 0;
96013   int iRightSeed = 1;
96014   int *aiUsed;
96015   int i;
96016
96017   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
96018   memset(aiUsed, 0, sizeof(int)*nCell);
96019
96020   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
96021
96022   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
96023   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
96024   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
96025   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
96026   aiUsed[iLeftSeed] = 1;
96027   aiUsed[iRightSeed] = 1;
96028
96029   for(i=nCell-2; i>0; i--){
96030     RtreeCell *pNext;
96031     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
96032     float diff =  
96033       cellGrowth(pRtree, pBboxLeft, pNext) - 
96034       cellGrowth(pRtree, pBboxRight, pNext)
96035     ;
96036     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
96037      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
96038     ){
96039       nodeInsertCell(pRtree, pRight, pNext);
96040       cellUnion(pRtree, pBboxRight, pNext);
96041     }else{
96042       nodeInsertCell(pRtree, pLeft, pNext);
96043       cellUnion(pRtree, pBboxLeft, pNext);
96044     }
96045   }
96046
96047   sqlite3_free(aiUsed);
96048   return SQLITE_OK;
96049 }
96050 #endif
96051
96052 static int updateMapping(
96053   Rtree *pRtree, 
96054   i64 iRowid, 
96055   RtreeNode *pNode, 
96056   int iHeight
96057 ){
96058   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
96059   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
96060   if( iHeight>0 ){
96061     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
96062     if( pChild ){
96063       nodeRelease(pRtree, pChild->pParent);
96064       nodeReference(pNode);
96065       pChild->pParent = pNode;
96066     }
96067   }
96068   return xSetMapping(pRtree, iRowid, pNode->iNode);
96069 }
96070
96071 static int SplitNode(
96072   Rtree *pRtree,
96073   RtreeNode *pNode,
96074   RtreeCell *pCell,
96075   int iHeight
96076 ){
96077   int i;
96078   int newCellIsRight = 0;
96079
96080   int rc = SQLITE_OK;
96081   int nCell = NCELL(pNode);
96082   RtreeCell *aCell;
96083   int *aiUsed;
96084
96085   RtreeNode *pLeft = 0;
96086   RtreeNode *pRight = 0;
96087
96088   RtreeCell leftbbox;
96089   RtreeCell rightbbox;
96090
96091   /* Allocate an array and populate it with a copy of pCell and 
96092   ** all cells from node pLeft. Then zero the original node.
96093   */
96094   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
96095   if( !aCell ){
96096     rc = SQLITE_NOMEM;
96097     goto splitnode_out;
96098   }
96099   aiUsed = (int *)&aCell[nCell+1];
96100   memset(aiUsed, 0, sizeof(int)*(nCell+1));
96101   for(i=0; i<nCell; i++){
96102     nodeGetCell(pRtree, pNode, i, &aCell[i]);
96103   }
96104   nodeZero(pRtree, pNode);
96105   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
96106   nCell++;
96107
96108   if( pNode->iNode==1 ){
96109     pRight = nodeNew(pRtree, pNode, 1);
96110     pLeft = nodeNew(pRtree, pNode, 1);
96111     pRtree->iDepth++;
96112     pNode->isDirty = 1;
96113     writeInt16(pNode->zData, pRtree->iDepth);
96114   }else{
96115     pLeft = pNode;
96116     pRight = nodeNew(pRtree, pLeft->pParent, 1);
96117     nodeReference(pLeft);
96118   }
96119
96120   if( !pLeft || !pRight ){
96121     rc = SQLITE_NOMEM;
96122     goto splitnode_out;
96123   }
96124
96125   memset(pLeft->zData, 0, pRtree->iNodeSize);
96126   memset(pRight->zData, 0, pRtree->iNodeSize);
96127
96128   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
96129   if( rc!=SQLITE_OK ){
96130     goto splitnode_out;
96131   }
96132
96133   /* Ensure both child nodes have node numbers assigned to them. */
96134   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
96135    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
96136   ){
96137     goto splitnode_out;
96138   }
96139
96140   rightbbox.iRowid = pRight->iNode;
96141   leftbbox.iRowid = pLeft->iNode;
96142
96143   if( pNode->iNode==1 ){
96144     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
96145     if( rc!=SQLITE_OK ){
96146       goto splitnode_out;
96147     }
96148   }else{
96149     RtreeNode *pParent = pLeft->pParent;
96150     int iCell = nodeParentIndex(pRtree, pLeft);
96151     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
96152     AdjustTree(pRtree, pParent, &leftbbox);
96153   }
96154   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
96155     goto splitnode_out;
96156   }
96157
96158   for(i=0; i<NCELL(pRight); i++){
96159     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
96160     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
96161     if( iRowid==pCell->iRowid ){
96162       newCellIsRight = 1;
96163     }
96164     if( rc!=SQLITE_OK ){
96165       goto splitnode_out;
96166     }
96167   }
96168   if( pNode->iNode==1 ){
96169     for(i=0; i<NCELL(pLeft); i++){
96170       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
96171       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
96172       if( rc!=SQLITE_OK ){
96173         goto splitnode_out;
96174       }
96175     }
96176   }else if( newCellIsRight==0 ){
96177     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
96178   }
96179
96180   if( rc==SQLITE_OK ){
96181     rc = nodeRelease(pRtree, pRight);
96182     pRight = 0;
96183   }
96184   if( rc==SQLITE_OK ){
96185     rc = nodeRelease(pRtree, pLeft);
96186     pLeft = 0;
96187   }
96188
96189 splitnode_out:
96190   nodeRelease(pRtree, pRight);
96191   nodeRelease(pRtree, pLeft);
96192   sqlite3_free(aCell);
96193   return rc;
96194 }
96195
96196 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
96197   int rc = SQLITE_OK;
96198   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
96199     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
96200     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
96201       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
96202       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
96203     }else{
96204       rc = SQLITE_ERROR;
96205     }
96206     sqlite3_reset(pRtree->pReadParent);
96207     if( rc==SQLITE_OK ){
96208       rc = fixLeafParent(pRtree, pLeaf->pParent);
96209     }
96210   }
96211   return rc;
96212 }
96213
96214 static int deleteCell(Rtree *, RtreeNode *, int, int);
96215
96216 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
96217   int rc;
96218   RtreeNode *pParent;
96219   int iCell;
96220
96221   assert( pNode->nRef==1 );
96222
96223   /* Remove the entry in the parent cell. */
96224   iCell = nodeParentIndex(pRtree, pNode);
96225   pParent = pNode->pParent;
96226   pNode->pParent = 0;
96227   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
96228    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
96229   ){
96230     return rc;
96231   }
96232
96233   /* Remove the xxx_node entry. */
96234   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
96235   sqlite3_step(pRtree->pDeleteNode);
96236   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
96237     return rc;
96238   }
96239
96240   /* Remove the xxx_parent entry. */
96241   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
96242   sqlite3_step(pRtree->pDeleteParent);
96243   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
96244     return rc;
96245   }
96246   
96247   /* Remove the node from the in-memory hash table and link it into
96248   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
96249   */
96250   nodeHashDelete(pRtree, pNode);
96251   pNode->iNode = iHeight;
96252   pNode->pNext = pRtree->pDeleted;
96253   pNode->nRef++;
96254   pRtree->pDeleted = pNode;
96255
96256   return SQLITE_OK;
96257 }
96258
96259 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
96260   RtreeNode *pParent = pNode->pParent;
96261   if( pParent ){
96262     int ii; 
96263     int nCell = NCELL(pNode);
96264     RtreeCell box;                            /* Bounding box for pNode */
96265     nodeGetCell(pRtree, pNode, 0, &box);
96266     for(ii=1; ii<nCell; ii++){
96267       RtreeCell cell;
96268       nodeGetCell(pRtree, pNode, ii, &cell);
96269       cellUnion(pRtree, &box, &cell);
96270     }
96271     box.iRowid = pNode->iNode;
96272     ii = nodeParentIndex(pRtree, pNode);
96273     nodeOverwriteCell(pRtree, pParent, &box, ii);
96274     fixBoundingBox(pRtree, pParent);
96275   }
96276 }
96277
96278 /*
96279 ** Delete the cell at index iCell of node pNode. After removing the
96280 ** cell, adjust the r-tree data structure if required.
96281 */
96282 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
96283   int rc;
96284
96285   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
96286     return rc;
96287   }
96288
96289   /* Remove the cell from the node. This call just moves bytes around
96290   ** the in-memory node image, so it cannot fail.
96291   */
96292   nodeDeleteCell(pRtree, pNode, iCell);
96293
96294   /* If the node is not the tree root and now has less than the minimum
96295   ** number of cells, remove it from the tree. Otherwise, update the
96296   ** cell in the parent node so that it tightly contains the updated
96297   ** node.
96298   */
96299   if( pNode->iNode!=1 ){
96300     RtreeNode *pParent = pNode->pParent;
96301     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
96302      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
96303     ){
96304       rc = removeNode(pRtree, pNode, iHeight);
96305     }else{
96306       fixBoundingBox(pRtree, pNode);
96307     }
96308   }
96309
96310   return rc;
96311 }
96312
96313 static int Reinsert(
96314   Rtree *pRtree, 
96315   RtreeNode *pNode, 
96316   RtreeCell *pCell, 
96317   int iHeight
96318 ){
96319   int *aOrder;
96320   int *aSpare;
96321   RtreeCell *aCell;
96322   float *aDistance;
96323   int nCell;
96324   float aCenterCoord[RTREE_MAX_DIMENSIONS];
96325   int iDim;
96326   int ii;
96327   int rc = SQLITE_OK;
96328
96329   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
96330
96331   nCell = NCELL(pNode)+1;
96332
96333   /* Allocate the buffers used by this operation. The allocation is
96334   ** relinquished before this function returns.
96335   */
96336   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
96337     sizeof(RtreeCell) +         /* aCell array */
96338     sizeof(int)       +         /* aOrder array */
96339     sizeof(int)       +         /* aSpare array */
96340     sizeof(float)               /* aDistance array */
96341   ));
96342   if( !aCell ){
96343     return SQLITE_NOMEM;
96344   }
96345   aOrder    = (int *)&aCell[nCell];
96346   aSpare    = (int *)&aOrder[nCell];
96347   aDistance = (float *)&aSpare[nCell];
96348
96349   for(ii=0; ii<nCell; ii++){
96350     if( ii==(nCell-1) ){
96351       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
96352     }else{
96353       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
96354     }
96355     aOrder[ii] = ii;
96356     for(iDim=0; iDim<pRtree->nDim; iDim++){
96357       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
96358       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
96359     }
96360   }
96361   for(iDim=0; iDim<pRtree->nDim; iDim++){
96362     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
96363   }
96364
96365   for(ii=0; ii<nCell; ii++){
96366     aDistance[ii] = 0.0;
96367     for(iDim=0; iDim<pRtree->nDim; iDim++){
96368       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
96369           DCOORD(aCell[ii].aCoord[iDim*2]);
96370       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
96371     }
96372   }
96373
96374   SortByDistance(aOrder, nCell, aDistance, aSpare);
96375   nodeZero(pRtree, pNode);
96376
96377   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
96378     RtreeCell *p = &aCell[aOrder[ii]];
96379     nodeInsertCell(pRtree, pNode, p);
96380     if( p->iRowid==pCell->iRowid ){
96381       if( iHeight==0 ){
96382         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
96383       }else{
96384         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
96385       }
96386     }
96387   }
96388   if( rc==SQLITE_OK ){
96389     fixBoundingBox(pRtree, pNode);
96390   }
96391   for(; rc==SQLITE_OK && ii<nCell; ii++){
96392     /* Find a node to store this cell in. pNode->iNode currently contains
96393     ** the height of the sub-tree headed by the cell.
96394     */
96395     RtreeNode *pInsert;
96396     RtreeCell *p = &aCell[aOrder[ii]];
96397     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
96398     if( rc==SQLITE_OK ){
96399       int rc2;
96400       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
96401       rc2 = nodeRelease(pRtree, pInsert);
96402       if( rc==SQLITE_OK ){
96403         rc = rc2;
96404       }
96405     }
96406   }
96407
96408   sqlite3_free(aCell);
96409   return rc;
96410 }
96411
96412 /*
96413 ** Insert cell pCell into node pNode. Node pNode is the head of a 
96414 ** subtree iHeight high (leaf nodes have iHeight==0).
96415 */
96416 static int rtreeInsertCell(
96417   Rtree *pRtree,
96418   RtreeNode *pNode,
96419   RtreeCell *pCell,
96420   int iHeight
96421 ){
96422   int rc = SQLITE_OK;
96423   if( iHeight>0 ){
96424     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
96425     if( pChild ){
96426       nodeRelease(pRtree, pChild->pParent);
96427       nodeReference(pNode);
96428       pChild->pParent = pNode;
96429     }
96430   }
96431   if( nodeInsertCell(pRtree, pNode, pCell) ){
96432 #if VARIANT_RSTARTREE_REINSERT
96433     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
96434       rc = SplitNode(pRtree, pNode, pCell, iHeight);
96435     }else{
96436       pRtree->iReinsertHeight = iHeight;
96437       rc = Reinsert(pRtree, pNode, pCell, iHeight);
96438     }
96439 #else
96440     rc = SplitNode(pRtree, pNode, pCell, iHeight);
96441 #endif
96442   }else{
96443     AdjustTree(pRtree, pNode, pCell);
96444     if( iHeight==0 ){
96445       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
96446     }else{
96447       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
96448     }
96449   }
96450   return rc;
96451 }
96452
96453 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
96454   int ii;
96455   int rc = SQLITE_OK;
96456   int nCell = NCELL(pNode);
96457
96458   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
96459     RtreeNode *pInsert;
96460     RtreeCell cell;
96461     nodeGetCell(pRtree, pNode, ii, &cell);
96462
96463     /* Find a node to store this cell in. pNode->iNode currently contains
96464     ** the height of the sub-tree headed by the cell.
96465     */
96466     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
96467     if( rc==SQLITE_OK ){
96468       int rc2;
96469       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
96470       rc2 = nodeRelease(pRtree, pInsert);
96471       if( rc==SQLITE_OK ){
96472         rc = rc2;
96473       }
96474     }
96475   }
96476   return rc;
96477 }
96478
96479 /*
96480 ** Select a currently unused rowid for a new r-tree record.
96481 */
96482 static int newRowid(Rtree *pRtree, i64 *piRowid){
96483   int rc;
96484   sqlite3_bind_null(pRtree->pWriteRowid, 1);
96485   sqlite3_bind_null(pRtree->pWriteRowid, 2);
96486   sqlite3_step(pRtree->pWriteRowid);
96487   rc = sqlite3_reset(pRtree->pWriteRowid);
96488   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
96489   return rc;
96490 }
96491
96492 #ifndef NDEBUG
96493 static int hashIsEmpty(Rtree *pRtree){
96494   int ii;
96495   for(ii=0; ii<HASHSIZE; ii++){
96496     assert( !pRtree->aHash[ii] );
96497   }
96498   return 1;
96499 }
96500 #endif
96501
96502 /*
96503 ** The xUpdate method for rtree module virtual tables.
96504 */
96505 int rtreeUpdate(
96506   sqlite3_vtab *pVtab, 
96507   int nData, 
96508   sqlite3_value **azData, 
96509   sqlite_int64 *pRowid
96510 ){
96511   Rtree *pRtree = (Rtree *)pVtab;
96512   int rc = SQLITE_OK;
96513
96514   rtreeReference(pRtree);
96515
96516   assert(nData>=1);
96517   assert(hashIsEmpty(pRtree));
96518
96519   /* If azData[0] is not an SQL NULL value, it is the rowid of a
96520   ** record to delete from the r-tree table. The following block does
96521   ** just that.
96522   */
96523   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
96524     i64 iDelete;                /* The rowid to delete */
96525     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
96526     int iCell;                  /* Index of iDelete cell in pLeaf */
96527     RtreeNode *pRoot;
96528
96529     /* Obtain a reference to the root node to initialise Rtree.iDepth */
96530     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
96531
96532     /* Obtain a reference to the leaf node that contains the entry 
96533     ** about to be deleted. 
96534     */
96535     if( rc==SQLITE_OK ){
96536       iDelete = sqlite3_value_int64(azData[0]);
96537       rc = findLeafNode(pRtree, iDelete, &pLeaf);
96538     }
96539
96540     /* Delete the cell in question from the leaf node. */
96541     if( rc==SQLITE_OK ){
96542       int rc2;
96543       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
96544       rc = deleteCell(pRtree, pLeaf, iCell, 0);
96545       rc2 = nodeRelease(pRtree, pLeaf);
96546       if( rc==SQLITE_OK ){
96547         rc = rc2;
96548       }
96549     }
96550
96551     /* Delete the corresponding entry in the <rtree>_rowid table. */
96552     if( rc==SQLITE_OK ){
96553       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
96554       sqlite3_step(pRtree->pDeleteRowid);
96555       rc = sqlite3_reset(pRtree->pDeleteRowid);
96556     }
96557
96558     /* Check if the root node now has exactly one child. If so, remove
96559     ** it, schedule the contents of the child for reinsertion and 
96560     ** reduce the tree height by one.
96561     **
96562     ** This is equivalent to copying the contents of the child into
96563     ** the root node (the operation that Gutman's paper says to perform 
96564     ** in this scenario).
96565     */
96566     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
96567       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
96568         RtreeNode *pChild;
96569         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
96570         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
96571         if( rc==SQLITE_OK ){
96572           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
96573         }
96574         if( rc==SQLITE_OK ){
96575           pRtree->iDepth--;
96576           writeInt16(pRoot->zData, pRtree->iDepth);
96577           pRoot->isDirty = 1;
96578         }
96579       }
96580     }
96581
96582     /* Re-insert the contents of any underfull nodes removed from the tree. */
96583     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
96584       if( rc==SQLITE_OK ){
96585         rc = reinsertNodeContent(pRtree, pLeaf);
96586       }
96587       pRtree->pDeleted = pLeaf->pNext;
96588       sqlite3_free(pLeaf);
96589     }
96590
96591     /* Release the reference to the root node. */
96592     if( rc==SQLITE_OK ){
96593       rc = nodeRelease(pRtree, pRoot);
96594     }else{
96595       nodeRelease(pRtree, pRoot);
96596     }
96597   }
96598
96599   /* If the azData[] array contains more than one element, elements
96600   ** (azData[2]..azData[argc-1]) contain a new record to insert into
96601   ** the r-tree structure.
96602   */
96603   if( rc==SQLITE_OK && nData>1 ){
96604     /* Insert a new record into the r-tree */
96605     RtreeCell cell;
96606     int ii;
96607     RtreeNode *pLeaf;
96608
96609     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
96610     assert( nData==(pRtree->nDim*2 + 3) );
96611     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
96612       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96613         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
96614         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
96615         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
96616           rc = SQLITE_CONSTRAINT;
96617           goto constraint;
96618         }
96619       }
96620     }else{
96621       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
96622         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
96623         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
96624         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
96625           rc = SQLITE_CONSTRAINT;
96626           goto constraint;
96627         }
96628       }
96629     }
96630
96631     /* Figure out the rowid of the new row. */
96632     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
96633       rc = newRowid(pRtree, &cell.iRowid);
96634     }else{
96635       cell.iRowid = sqlite3_value_int64(azData[2]);
96636       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
96637       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
96638         sqlite3_reset(pRtree->pReadRowid);
96639         rc = SQLITE_CONSTRAINT;
96640         goto constraint;
96641       }
96642       rc = sqlite3_reset(pRtree->pReadRowid);
96643     }
96644
96645     if( rc==SQLITE_OK ){
96646       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
96647     }
96648     if( rc==SQLITE_OK ){
96649       int rc2;
96650       pRtree->iReinsertHeight = -1;
96651       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
96652       rc2 = nodeRelease(pRtree, pLeaf);
96653       if( rc==SQLITE_OK ){
96654         rc = rc2;
96655       }
96656     }
96657   }
96658
96659 constraint:
96660   rtreeRelease(pRtree);
96661   return rc;
96662 }
96663
96664 /*
96665 ** The xRename method for rtree module virtual tables.
96666 */
96667 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
96668   Rtree *pRtree = (Rtree *)pVtab;
96669   int rc = SQLITE_NOMEM;
96670   char *zSql = sqlite3_mprintf(
96671     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
96672     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
96673     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
96674     , pRtree->zDb, pRtree->zName, zNewName 
96675     , pRtree->zDb, pRtree->zName, zNewName 
96676     , pRtree->zDb, pRtree->zName, zNewName
96677   );
96678   if( zSql ){
96679     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
96680     sqlite3_free(zSql);
96681   }
96682   return rc;
96683 }
96684
96685 static sqlite3_module rtreeModule = {
96686   0,                         /* iVersion */
96687   rtreeCreate,                /* xCreate - create a table */
96688   rtreeConnect,               /* xConnect - connect to an existing table */
96689   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
96690   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
96691   rtreeDestroy,               /* xDestroy - Drop a table */
96692   rtreeOpen,                  /* xOpen - open a cursor */
96693   rtreeClose,                 /* xClose - close a cursor */
96694   rtreeFilter,                /* xFilter - configure scan constraints */
96695   rtreeNext,                  /* xNext - advance a cursor */
96696   rtreeEof,                   /* xEof */
96697   rtreeColumn,                /* xColumn - read data */
96698   rtreeRowid,                 /* xRowid - read data */
96699   rtreeUpdate,                /* xUpdate - write data */
96700   0,                          /* xBegin - begin transaction */
96701   0,                          /* xSync - sync transaction */
96702   0,                          /* xCommit - commit transaction */
96703   0,                          /* xRollback - rollback transaction */
96704   0,                          /* xFindFunction - function overloading */
96705   rtreeRename                 /* xRename - rename the table */
96706 };
96707
96708 static int rtreeSqlInit(
96709   Rtree *pRtree, 
96710   sqlite3 *db, 
96711   const char *zDb, 
96712   const char *zPrefix, 
96713   int isCreate
96714 ){
96715   int rc = SQLITE_OK;
96716
96717   #define N_STATEMENT 9
96718   static const char *azSql[N_STATEMENT] = {
96719     /* Read and write the xxx_node table */
96720     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
96721     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
96722     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
96723
96724     /* Read and write the xxx_rowid table */
96725     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
96726     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
96727     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
96728
96729     /* Read and write the xxx_parent table */
96730     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
96731     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
96732     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
96733   };
96734   sqlite3_stmt **appStmt[N_STATEMENT];
96735   int i;
96736
96737   pRtree->db = db;
96738
96739   if( isCreate ){
96740     char *zCreate = sqlite3_mprintf(
96741 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
96742 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
96743 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
96744 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
96745       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
96746     );
96747     if( !zCreate ){
96748       return SQLITE_NOMEM;
96749     }
96750     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
96751     sqlite3_free(zCreate);
96752     if( rc!=SQLITE_OK ){
96753       return rc;
96754     }
96755   }
96756
96757   appStmt[0] = &pRtree->pReadNode;
96758   appStmt[1] = &pRtree->pWriteNode;
96759   appStmt[2] = &pRtree->pDeleteNode;
96760   appStmt[3] = &pRtree->pReadRowid;
96761   appStmt[4] = &pRtree->pWriteRowid;
96762   appStmt[5] = &pRtree->pDeleteRowid;
96763   appStmt[6] = &pRtree->pReadParent;
96764   appStmt[7] = &pRtree->pWriteParent;
96765   appStmt[8] = &pRtree->pDeleteParent;
96766
96767   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
96768     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
96769     if( zSql ){
96770       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
96771     }else{
96772       rc = SQLITE_NOMEM;
96773     }
96774     sqlite3_free(zSql);
96775   }
96776
96777   return rc;
96778 }
96779
96780 /*
96781 ** This routine queries database handle db for the page-size used by
96782 ** database zDb. If successful, the page-size in bytes is written to
96783 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
96784 ** code is returned.
96785 */
96786 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
96787   int rc = SQLITE_NOMEM;
96788   char *zSql;
96789   sqlite3_stmt *pStmt = 0;
96790
96791   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
96792   if( !zSql ){
96793     return SQLITE_NOMEM;
96794   }
96795
96796   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
96797   sqlite3_free(zSql);
96798   if( rc!=SQLITE_OK ){
96799     return rc;
96800   }
96801
96802   if( SQLITE_ROW==sqlite3_step(pStmt) ){
96803     *piPageSize = sqlite3_column_int(pStmt, 0);
96804   }
96805   return sqlite3_finalize(pStmt);
96806 }
96807
96808 /* 
96809 ** This function is the implementation of both the xConnect and xCreate
96810 ** methods of the r-tree virtual table.
96811 **
96812 **   argv[0]   -> module name
96813 **   argv[1]   -> database name
96814 **   argv[2]   -> table name
96815 **   argv[...] -> column names...
96816 */
96817 static int rtreeInit(
96818   sqlite3 *db,                        /* Database connection */
96819   void *pAux,                         /* Pointer to head of rtree list */
96820   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
96821   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
96822   char **pzErr,                       /* OUT: Error message, if any */
96823   int isCreate,                       /* True for xCreate, false for xConnect */
96824   int eCoordType                      /* One of the RTREE_COORD_* constants */
96825 ){
96826   int rc = SQLITE_OK;
96827   int iPageSize = 0;
96828   Rtree *pRtree;
96829   int nDb;              /* Length of string argv[1] */
96830   int nName;            /* Length of string argv[2] */
96831
96832   const char *aErrMsg[] = {
96833     0,                                                    /* 0 */
96834     "Wrong number of columns for an rtree table",         /* 1 */
96835     "Too few columns for an rtree table",                 /* 2 */
96836     "Too many columns for an rtree table"                 /* 3 */
96837   };
96838
96839   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
96840   if( aErrMsg[iErr] ){
96841     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
96842     return SQLITE_ERROR;
96843   }
96844
96845   rc = getPageSize(db, argv[1], &iPageSize);
96846   if( rc!=SQLITE_OK ){
96847     return rc;
96848   }
96849
96850   /* Allocate the sqlite3_vtab structure */
96851   nDb = strlen(argv[1]);
96852   nName = strlen(argv[2]);
96853   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
96854   if( !pRtree ){
96855     return SQLITE_NOMEM;
96856   }
96857   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
96858   pRtree->nBusy = 1;
96859   pRtree->base.pModule = &rtreeModule;
96860   pRtree->zDb = (char *)&pRtree[1];
96861   pRtree->zName = &pRtree->zDb[nDb+1];
96862   pRtree->nDim = (argc-4)/2;
96863   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
96864   pRtree->eCoordType = eCoordType;
96865   memcpy(pRtree->zDb, argv[1], nDb);
96866   memcpy(pRtree->zName, argv[2], nName);
96867
96868   /* Figure out the node size to use. By default, use 64 bytes less than
96869   ** the database page-size. This ensures that each node is stored on
96870   ** a single database page.
96871   **
96872   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
96873   ** entries would fit in a single node, use a smaller node-size.
96874   */
96875   pRtree->iNodeSize = iPageSize-64;
96876   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
96877     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
96878   }
96879
96880   /* Create/Connect to the underlying relational database schema. If
96881   ** that is successful, call sqlite3_declare_vtab() to configure
96882   ** the r-tree table schema.
96883   */
96884   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
96885     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
96886   }else{
96887     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
96888     char *zTmp;
96889     int ii;
96890     for(ii=4; zSql && ii<argc; ii++){
96891       zTmp = zSql;
96892       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
96893       sqlite3_free(zTmp);
96894     }
96895     if( zSql ){
96896       zTmp = zSql;
96897       zSql = sqlite3_mprintf("%s);", zTmp);
96898       sqlite3_free(zTmp);
96899     }
96900     if( !zSql || sqlite3_declare_vtab(db, zSql) ){
96901       rc = SQLITE_NOMEM;
96902     }
96903     sqlite3_free(zSql);
96904   }
96905
96906   if( rc==SQLITE_OK ){
96907     *ppVtab = (sqlite3_vtab *)pRtree;
96908   }else{
96909     rtreeRelease(pRtree);
96910   }
96911   return rc;
96912 }
96913
96914
96915 /*
96916 ** Implementation of a scalar function that decodes r-tree nodes to
96917 ** human readable strings. This can be used for debugging and analysis.
96918 **
96919 ** The scalar function takes two arguments, a blob of data containing
96920 ** an r-tree node, and the number of dimensions the r-tree indexes.
96921 ** For a two-dimensional r-tree structure called "rt", to deserialize
96922 ** all nodes, a statement like:
96923 **
96924 **   SELECT rtreenode(2, data) FROM rt_node;
96925 **
96926 ** The human readable string takes the form of a Tcl list with one
96927 ** entry for each cell in the r-tree node. Each entry is itself a
96928 ** list, containing the 8-byte rowid/pageno followed by the 
96929 ** <num-dimension>*2 coordinates.
96930 */
96931 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
96932   char *zText = 0;
96933   RtreeNode node;
96934   Rtree tree;
96935   int ii;
96936
96937   memset(&node, 0, sizeof(RtreeNode));
96938   memset(&tree, 0, sizeof(Rtree));
96939   tree.nDim = sqlite3_value_int(apArg[0]);
96940   tree.nBytesPerCell = 8 + 8 * tree.nDim;
96941   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
96942
96943   for(ii=0; ii<NCELL(&node); ii++){
96944     char zCell[512];
96945     int nCell = 0;
96946     RtreeCell cell;
96947     int jj;
96948
96949     nodeGetCell(&tree, &node, ii, &cell);
96950     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
96951     nCell = strlen(zCell);
96952     for(jj=0; jj<tree.nDim*2; jj++){
96953       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
96954       nCell = strlen(zCell);
96955     }
96956
96957     if( zText ){
96958       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
96959       sqlite3_free(zText);
96960       zText = zTextNew;
96961     }else{
96962       zText = sqlite3_mprintf("{%s}", zCell);
96963     }
96964   }
96965   
96966   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
96967 }
96968
96969 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
96970   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
96971    || sqlite3_value_bytes(apArg[0])<2
96972   ){
96973     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
96974   }else{
96975     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
96976     sqlite3_result_int(ctx, readInt16(zBlob));
96977   }
96978 }
96979
96980 /*
96981 ** Register the r-tree module with database handle db. This creates the
96982 ** virtual table module "rtree" and the debugging/analysis scalar 
96983 ** function "rtreenode".
96984 */
96985 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
96986   int rc = SQLITE_OK;
96987
96988   if( rc==SQLITE_OK ){
96989     int utf8 = SQLITE_UTF8;
96990     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
96991   }
96992   if( rc==SQLITE_OK ){
96993     int utf8 = SQLITE_UTF8;
96994     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
96995   }
96996   if( rc==SQLITE_OK ){
96997     void *c = (void *)RTREE_COORD_REAL32;
96998     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
96999   }
97000   if( rc==SQLITE_OK ){
97001     void *c = (void *)RTREE_COORD_INT32;
97002     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
97003   }
97004
97005   return rc;
97006 }
97007
97008 #if !SQLITE_CORE
97009 SQLITE_API int sqlite3_extension_init(
97010   sqlite3 *db,
97011   char **pzErrMsg,
97012   const sqlite3_api_routines *pApi
97013 ){
97014   SQLITE_EXTENSION_INIT2(pApi)
97015   return sqlite3RtreeInit(db);
97016 }
97017 #endif
97018
97019 #endif
97020
97021 /************** End of rtree.c ***********************************************/
97022 /************** Begin file icu.c *********************************************/
97023 /*
97024 ** 2007 May 6
97025 **
97026 ** The author disclaims copyright to this source code.  In place of
97027 ** a legal notice, here is a blessing:
97028 **
97029 **    May you do good and not evil.
97030 **    May you find forgiveness for yourself and forgive others.
97031 **    May you share freely, never taking more than you give.
97032 **
97033 *************************************************************************
97034 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
97035 **
97036 ** This file implements an integration between the ICU library 
97037 ** ("International Components for Unicode", an open-source library 
97038 ** for handling unicode data) and SQLite. The integration uses 
97039 ** ICU to provide the following to SQLite:
97040 **
97041 **   * An implementation of the SQL regexp() function (and hence REGEXP
97042 **     operator) using the ICU uregex_XX() APIs.
97043 **
97044 **   * Implementations of the SQL scalar upper() and lower() functions
97045 **     for case mapping.
97046 **
97047 **   * Integration of ICU and SQLite collation seqences.
97048 **
97049 **   * An implementation of the LIKE operator that uses ICU to 
97050 **     provide case-independent matching.
97051 */
97052
97053 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
97054
97055 /* Include ICU headers */
97056 #include <unicode/utypes.h>
97057 #include <unicode/uregex.h>
97058 #include <unicode/ustring.h>
97059 #include <unicode/ucol.h>
97060
97061
97062 #ifndef SQLITE_CORE
97063   SQLITE_EXTENSION_INIT1
97064 #else
97065 #endif
97066
97067 /*
97068 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
97069 ** operator.
97070 */
97071 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
97072 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
97073 #endif
97074
97075 /*
97076 ** Version of sqlite3_free() that is always a function, never a macro.
97077 */
97078 static void xFree(void *p){
97079   sqlite3_free(p);
97080 }
97081
97082 /*
97083 ** Compare two UTF-8 strings for equality where the first string is
97084 ** a "LIKE" expression. Return true (1) if they are the same and 
97085 ** false (0) if they are different.
97086 */
97087 static int icuLikeCompare(
97088   const uint8_t *zPattern,   /* LIKE pattern */
97089   const uint8_t *zString,    /* The UTF-8 string to compare against */
97090   const UChar32 uEsc         /* The escape character */
97091 ){
97092   static const int MATCH_ONE = (UChar32)'_';
97093   static const int MATCH_ALL = (UChar32)'%';
97094
97095   int iPattern = 0;       /* Current byte index in zPattern */
97096   int iString = 0;        /* Current byte index in zString */
97097
97098   int prevEscape = 0;     /* True if the previous character was uEsc */
97099
97100   while( zPattern[iPattern]!=0 ){
97101
97102     /* Read (and consume) the next character from the input pattern. */
97103     UChar32 uPattern;
97104     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
97105     assert(uPattern!=0);
97106
97107     /* There are now 4 possibilities:
97108     **
97109     **     1. uPattern is an unescaped match-all character "%",
97110     **     2. uPattern is an unescaped match-one character "_",
97111     **     3. uPattern is an unescaped escape character, or
97112     **     4. uPattern is to be handled as an ordinary character
97113     */
97114     if( !prevEscape && uPattern==MATCH_ALL ){
97115       /* Case 1. */
97116       uint8_t c;
97117
97118       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
97119       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
97120       ** test string.
97121       */
97122       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
97123         if( c==MATCH_ONE ){
97124           if( zString[iString]==0 ) return 0;
97125           U8_FWD_1_UNSAFE(zString, iString);
97126         }
97127         iPattern++;
97128       }
97129
97130       if( zPattern[iPattern]==0 ) return 1;
97131
97132       while( zString[iString] ){
97133         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
97134           return 1;
97135         }
97136         U8_FWD_1_UNSAFE(zString, iString);
97137       }
97138       return 0;
97139
97140     }else if( !prevEscape && uPattern==MATCH_ONE ){
97141       /* Case 2. */
97142       if( zString[iString]==0 ) return 0;
97143       U8_FWD_1_UNSAFE(zString, iString);
97144
97145     }else if( !prevEscape && uPattern==uEsc){
97146       /* Case 3. */
97147       prevEscape = 1;
97148
97149     }else{
97150       /* Case 4. */
97151       UChar32 uString;
97152       U8_NEXT_UNSAFE(zString, iString, uString);
97153       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
97154       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
97155       if( uString!=uPattern ){
97156         return 0;
97157       }
97158       prevEscape = 0;
97159     }
97160   }
97161
97162   return zString[iString]==0;
97163 }
97164
97165 /*
97166 ** Implementation of the like() SQL function.  This function implements
97167 ** the build-in LIKE operator.  The first argument to the function is the
97168 ** pattern and the second argument is the string.  So, the SQL statements:
97169 **
97170 **       A LIKE B
97171 **
97172 ** is implemented as like(B, A). If there is an escape character E, 
97173 **
97174 **       A LIKE B ESCAPE E
97175 **
97176 ** is mapped to like(B, A, E).
97177 */
97178 static void icuLikeFunc(
97179   sqlite3_context *context, 
97180   int argc, 
97181   sqlite3_value **argv
97182 ){
97183   const unsigned char *zA = sqlite3_value_text(argv[0]);
97184   const unsigned char *zB = sqlite3_value_text(argv[1]);
97185   UChar32 uEsc = 0;
97186
97187   /* Limit the length of the LIKE or GLOB pattern to avoid problems
97188   ** of deep recursion and N*N behavior in patternCompare().
97189   */
97190   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
97191     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
97192     return;
97193   }
97194
97195
97196   if( argc==3 ){
97197     /* The escape character string must consist of a single UTF-8 character.
97198     ** Otherwise, return an error.
97199     */
97200     int nE= sqlite3_value_bytes(argv[2]);
97201     const unsigned char *zE = sqlite3_value_text(argv[2]);
97202     int i = 0;
97203     if( zE==0 ) return;
97204     U8_NEXT(zE, i, nE, uEsc);
97205     if( i!=nE){
97206       sqlite3_result_error(context, 
97207           "ESCAPE expression must be a single character", -1);
97208       return;
97209     }
97210   }
97211
97212   if( zA && zB ){
97213     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
97214   }
97215 }
97216
97217 /*
97218 ** This function is called when an ICU function called from within
97219 ** the implementation of an SQL scalar function returns an error.
97220 **
97221 ** The scalar function context passed as the first argument is 
97222 ** loaded with an error message based on the following two args.
97223 */
97224 static void icuFunctionError(
97225   sqlite3_context *pCtx,       /* SQLite scalar function context */
97226   const char *zName,           /* Name of ICU function that failed */
97227   UErrorCode e                 /* Error code returned by ICU function */
97228 ){
97229   char zBuf[128];
97230   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
97231   zBuf[127] = '\0';
97232   sqlite3_result_error(pCtx, zBuf, -1);
97233 }
97234
97235 /*
97236 ** Function to delete compiled regexp objects. Registered as
97237 ** a destructor function with sqlite3_set_auxdata().
97238 */
97239 static void icuRegexpDelete(void *p){
97240   URegularExpression *pExpr = (URegularExpression *)p;
97241   uregex_close(pExpr);
97242 }
97243
97244 /*
97245 ** Implementation of SQLite REGEXP operator. This scalar function takes
97246 ** two arguments. The first is a regular expression pattern to compile
97247 ** the second is a string to match against that pattern. If either 
97248 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
97249 ** is 1 if the string matches the pattern, or 0 otherwise.
97250 **
97251 ** SQLite maps the regexp() function to the regexp() operator such
97252 ** that the following two are equivalent:
97253 **
97254 **     zString REGEXP zPattern
97255 **     regexp(zPattern, zString)
97256 **
97257 ** Uses the following ICU regexp APIs:
97258 **
97259 **     uregex_open()
97260 **     uregex_matches()
97261 **     uregex_close()
97262 */
97263 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
97264   UErrorCode status = U_ZERO_ERROR;
97265   URegularExpression *pExpr;
97266   UBool res;
97267   const UChar *zString = sqlite3_value_text16(apArg[1]);
97268
97269   /* If the left hand side of the regexp operator is NULL, 
97270   ** then the result is also NULL. 
97271   */
97272   if( !zString ){
97273     return;
97274   }
97275
97276   pExpr = sqlite3_get_auxdata(p, 0);
97277   if( !pExpr ){
97278     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
97279     if( !zPattern ){
97280       return;
97281     }
97282     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
97283
97284     if( U_SUCCESS(status) ){
97285       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
97286     }else{
97287       assert(!pExpr);
97288       icuFunctionError(p, "uregex_open", status);
97289       return;
97290     }
97291   }
97292
97293   /* Configure the text that the regular expression operates on. */
97294   uregex_setText(pExpr, zString, -1, &status);
97295   if( !U_SUCCESS(status) ){
97296     icuFunctionError(p, "uregex_setText", status);
97297     return;
97298   }
97299
97300   /* Attempt the match */
97301   res = uregex_matches(pExpr, 0, &status);
97302   if( !U_SUCCESS(status) ){
97303     icuFunctionError(p, "uregex_matches", status);
97304     return;
97305   }
97306
97307   /* Set the text that the regular expression operates on to a NULL
97308   ** pointer. This is not really necessary, but it is tidier than 
97309   ** leaving the regular expression object configured with an invalid
97310   ** pointer after this function returns.
97311   */
97312   uregex_setText(pExpr, 0, 0, &status);
97313
97314   /* Return 1 or 0. */
97315   sqlite3_result_int(p, res ? 1 : 0);
97316 }
97317
97318 /*
97319 ** Implementations of scalar functions for case mapping - upper() and 
97320 ** lower(). Function upper() converts its input to upper-case (ABC).
97321 ** Function lower() converts to lower-case (abc).
97322 **
97323 ** ICU provides two types of case mapping, "general" case mapping and
97324 ** "language specific". Refer to ICU documentation for the differences
97325 ** between the two.
97326 **
97327 ** To utilise "general" case mapping, the upper() or lower() scalar 
97328 ** functions are invoked with one argument:
97329 **
97330 **     upper('ABC') -> 'abc'
97331 **     lower('abc') -> 'ABC'
97332 **
97333 ** To access ICU "language specific" case mapping, upper() or lower()
97334 ** should be invoked with two arguments. The second argument is the name
97335 ** of the locale to use. Passing an empty string ("") or SQL NULL value
97336 ** as the second argument is the same as invoking the 1 argument version
97337 ** of upper() or lower().
97338 **
97339 **     lower('I', 'en_us') -> 'i'
97340 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
97341 **
97342 ** http://www.icu-project.org/userguide/posix.html#case_mappings
97343 */
97344 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
97345   const UChar *zInput;
97346   UChar *zOutput;
97347   int nInput;
97348   int nOutput;
97349
97350   UErrorCode status = U_ZERO_ERROR;
97351   const char *zLocale = 0;
97352
97353   assert(nArg==1 || nArg==2);
97354   if( nArg==2 ){
97355     zLocale = (const char *)sqlite3_value_text(apArg[1]);
97356   }
97357
97358   zInput = sqlite3_value_text16(apArg[0]);
97359   if( !zInput ){
97360     return;
97361   }
97362   nInput = sqlite3_value_bytes16(apArg[0]);
97363
97364   nOutput = nInput * 2 + 2;
97365   zOutput = sqlite3_malloc(nOutput);
97366   if( !zOutput ){
97367     return;
97368   }
97369
97370   if( sqlite3_user_data(p) ){
97371     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
97372   }else{
97373     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
97374   }
97375
97376   if( !U_SUCCESS(status) ){
97377     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
97378     return;
97379   }
97380
97381   sqlite3_result_text16(p, zOutput, -1, xFree);
97382 }
97383
97384 /*
97385 ** Collation sequence destructor function. The pCtx argument points to
97386 ** a UCollator structure previously allocated using ucol_open().
97387 */
97388 static void icuCollationDel(void *pCtx){
97389   UCollator *p = (UCollator *)pCtx;
97390   ucol_close(p);
97391 }
97392
97393 /*
97394 ** Collation sequence comparison function. The pCtx argument points to
97395 ** a UCollator structure previously allocated using ucol_open().
97396 */
97397 static int icuCollationColl(
97398   void *pCtx,
97399   int nLeft,
97400   const void *zLeft,
97401   int nRight,
97402   const void *zRight
97403 ){
97404   UCollationResult res;
97405   UCollator *p = (UCollator *)pCtx;
97406   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
97407   switch( res ){
97408     case UCOL_LESS:    return -1;
97409     case UCOL_GREATER: return +1;
97410     case UCOL_EQUAL:   return 0;
97411   }
97412   assert(!"Unexpected return value from ucol_strcoll()");
97413   return 0;
97414 }
97415
97416 /*
97417 ** Implementation of the scalar function icu_load_collation().
97418 **
97419 ** This scalar function is used to add ICU collation based collation 
97420 ** types to an SQLite database connection. It is intended to be called
97421 ** as follows:
97422 **
97423 **     SELECT icu_load_collation(<locale>, <collation-name>);
97424 **
97425 ** Where <locale> is a string containing an ICU locale identifier (i.e.
97426 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
97427 ** collation sequence to create.
97428 */
97429 static void icuLoadCollation(
97430   sqlite3_context *p, 
97431   int nArg, 
97432   sqlite3_value **apArg
97433 ){
97434   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
97435   UErrorCode status = U_ZERO_ERROR;
97436   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
97437   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
97438   UCollator *pUCollator;    /* ICU library collation object */
97439   int rc;                   /* Return code from sqlite3_create_collation_x() */
97440
97441   assert(nArg==2);
97442   zLocale = (const char *)sqlite3_value_text(apArg[0]);
97443   zName = (const char *)sqlite3_value_text(apArg[1]);
97444
97445   if( !zLocale || !zName ){
97446     return;
97447   }
97448
97449   pUCollator = ucol_open(zLocale, &status);
97450   if( !U_SUCCESS(status) ){
97451     icuFunctionError(p, "ucol_open", status);
97452     return;
97453   }
97454   assert(p);
97455
97456   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
97457       icuCollationColl, icuCollationDel
97458   );
97459   if( rc!=SQLITE_OK ){
97460     ucol_close(pUCollator);
97461     sqlite3_result_error(p, "Error registering collation function", -1);
97462   }
97463 }
97464
97465 /*
97466 ** Register the ICU extension functions with database db.
97467 */
97468 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
97469   struct IcuScalar {
97470     const char *zName;                        /* Function name */
97471     int nArg;                                 /* Number of arguments */
97472     int enc;                                  /* Optimal text encoding */
97473     void *pContext;                           /* sqlite3_user_data() context */
97474     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
97475   } scalars[] = {
97476     {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},
97477
97478     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
97479     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
97480     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
97481     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
97482
97483     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
97484     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
97485     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
97486     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
97487
97488     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
97489     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
97490
97491     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
97492   };
97493
97494   int rc = SQLITE_OK;
97495   int i;
97496
97497   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
97498     struct IcuScalar *p = &scalars[i];
97499     rc = sqlite3_create_function(
97500         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
97501     );
97502   }
97503
97504   return rc;
97505 }
97506
97507 #if !SQLITE_CORE
97508 SQLITE_API int sqlite3_extension_init(
97509   sqlite3 *db, 
97510   char **pzErrMsg,
97511   const sqlite3_api_routines *pApi
97512 ){
97513   SQLITE_EXTENSION_INIT2(pApi)
97514   return sqlite3IcuInit(db);
97515 }
97516 #endif
97517
97518 #endif
97519
97520 /************** End of icu.c *************************************************/
97521 /************** Begin file fts3_icu.c ****************************************/
97522 /*
97523 ** 2007 June 22
97524 **
97525 ** The author disclaims copyright to this source code.  In place of
97526 ** a legal notice, here is a blessing:
97527 **
97528 **    May you do good and not evil.
97529 **    May you find forgiveness for yourself and forgive others.
97530 **    May you share freely, never taking more than you give.
97531 **
97532 *************************************************************************
97533 ** This file implements a tokenizer for fts3 based on the ICU library.
97534 ** 
97535 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
97536 */
97537
97538 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
97539 #ifdef SQLITE_ENABLE_ICU
97540
97541
97542 #include <unicode/ubrk.h>
97543 #include <unicode/utf16.h>
97544
97545 typedef struct IcuTokenizer IcuTokenizer;
97546 typedef struct IcuCursor IcuCursor;
97547
97548 struct IcuTokenizer {
97549   sqlite3_tokenizer base;
97550   char *zLocale;
97551 };
97552
97553 struct IcuCursor {
97554   sqlite3_tokenizer_cursor base;
97555
97556   UBreakIterator *pIter;      /* ICU break-iterator object */
97557   int nChar;                  /* Number of UChar elements in pInput */
97558   UChar *aChar;               /* Copy of input using utf-16 encoding */
97559   int *aOffset;               /* Offsets of each character in utf-8 input */
97560
97561   int nBuffer;
97562   char *zBuffer;
97563
97564   int iToken;
97565 };
97566
97567 /*
97568 ** Create a new tokenizer instance.
97569 */
97570 static int icuCreate(
97571   int argc,                            /* Number of entries in argv[] */
97572   const char * const *argv,            /* Tokenizer creation arguments */
97573   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
97574 ){
97575   IcuTokenizer *p;
97576   int n = 0;
97577
97578   if( argc>0 ){
97579     n = strlen(argv[0])+1;
97580   }
97581   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
97582   if( !p ){
97583     return SQLITE_NOMEM;
97584   }
97585   memset(p, 0, sizeof(IcuTokenizer));
97586
97587   if( n ){
97588     p->zLocale = (char *)&p[1];
97589     memcpy(p->zLocale, argv[0], n);
97590   }
97591
97592   *ppTokenizer = (sqlite3_tokenizer *)p;
97593
97594   return SQLITE_OK;
97595 }
97596
97597 /*
97598 ** Destroy a tokenizer
97599 */
97600 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
97601   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
97602   sqlite3_free(p);
97603   return SQLITE_OK;
97604 }
97605
97606 /*
97607 ** Prepare to begin tokenizing a particular string.  The input
97608 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
97609 ** used to incrementally tokenize this string is returned in 
97610 ** *ppCursor.
97611 */
97612 static int icuOpen(
97613   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
97614   const char *zInput,                    /* Input string */
97615   int nInput,                            /* Length of zInput in bytes */
97616   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
97617 ){
97618   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
97619   IcuCursor *pCsr;
97620
97621   const int32_t opt = U_FOLD_CASE_DEFAULT;
97622   UErrorCode status = U_ZERO_ERROR;
97623   int nChar;
97624
97625   UChar32 c;
97626   int iInput = 0;
97627   int iOut = 0;
97628
97629   *ppCursor = 0;
97630
97631   if( nInput<0 ){
97632     nInput = strlen(zInput);
97633   }
97634   nChar = nInput+1;
97635   pCsr = (IcuCursor *)sqlite3_malloc(
97636       sizeof(IcuCursor) +                /* IcuCursor */
97637       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
97638       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
97639   );
97640   if( !pCsr ){
97641     return SQLITE_NOMEM;
97642   }
97643   memset(pCsr, 0, sizeof(IcuCursor));
97644   pCsr->aChar = (UChar *)&pCsr[1];
97645   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
97646
97647   pCsr->aOffset[iOut] = iInput;
97648   U8_NEXT(zInput, iInput, nInput, c); 
97649   while( c>0 ){
97650     int isError = 0;
97651     c = u_foldCase(c, opt);
97652     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
97653     if( isError ){
97654       sqlite3_free(pCsr);
97655       return SQLITE_ERROR;
97656     }
97657     pCsr->aOffset[iOut] = iInput;
97658
97659     if( iInput<nInput ){
97660       U8_NEXT(zInput, iInput, nInput, c);
97661     }else{
97662       c = 0;
97663     }
97664   }
97665
97666   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
97667   if( !U_SUCCESS(status) ){
97668     sqlite3_free(pCsr);
97669     return SQLITE_ERROR;
97670   }
97671   pCsr->nChar = iOut;
97672
97673   ubrk_first(pCsr->pIter);
97674   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
97675   return SQLITE_OK;
97676 }
97677
97678 /*
97679 ** Close a tokenization cursor previously opened by a call to icuOpen().
97680 */
97681 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
97682   IcuCursor *pCsr = (IcuCursor *)pCursor;
97683   ubrk_close(pCsr->pIter);
97684   sqlite3_free(pCsr->zBuffer);
97685   sqlite3_free(pCsr);
97686   return SQLITE_OK;
97687 }
97688
97689 /*
97690 ** Extract the next token from a tokenization cursor.
97691 */
97692 static int icuNext(
97693   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
97694   const char **ppToken,               /* OUT: *ppToken is the token text */
97695   int *pnBytes,                       /* OUT: Number of bytes in token */
97696   int *piStartOffset,                 /* OUT: Starting offset of token */
97697   int *piEndOffset,                   /* OUT: Ending offset of token */
97698   int *piPosition                     /* OUT: Position integer of token */
97699 ){
97700   IcuCursor *pCsr = (IcuCursor *)pCursor;
97701
97702   int iStart = 0;
97703   int iEnd = 0;
97704   int nByte = 0;
97705
97706   while( iStart==iEnd ){
97707     UChar32 c;
97708
97709     iStart = ubrk_current(pCsr->pIter);
97710     iEnd = ubrk_next(pCsr->pIter);
97711     if( iEnd==UBRK_DONE ){
97712       return SQLITE_DONE;
97713     }
97714
97715     while( iStart<iEnd ){
97716       int iWhite = iStart;
97717       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
97718       if( u_isspace(c) ){
97719         iStart = iWhite;
97720       }else{
97721         break;
97722       }
97723     }
97724     assert(iStart<=iEnd);
97725   }
97726
97727   do {
97728     UErrorCode status = U_ZERO_ERROR;
97729     if( nByte ){
97730       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
97731       if( !zNew ){
97732         return SQLITE_NOMEM;
97733       }
97734       pCsr->zBuffer = zNew;
97735       pCsr->nBuffer = nByte;
97736     }
97737
97738     u_strToUTF8(
97739         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
97740         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
97741         &status                                  /* Output success/failure */
97742     );
97743   } while( nByte>pCsr->nBuffer );
97744
97745   *ppToken = pCsr->zBuffer;
97746   *pnBytes = nByte;
97747   *piStartOffset = pCsr->aOffset[iStart];
97748   *piEndOffset = pCsr->aOffset[iEnd];
97749   *piPosition = pCsr->iToken++;
97750
97751   return SQLITE_OK;
97752 }
97753
97754 /*
97755 ** The set of routines that implement the simple tokenizer
97756 */
97757 static const sqlite3_tokenizer_module icuTokenizerModule = {
97758   0,                           /* iVersion */
97759   icuCreate,                   /* xCreate  */
97760   icuDestroy,                  /* xCreate  */
97761   icuOpen,                     /* xOpen    */
97762   icuClose,                    /* xClose   */
97763   icuNext,                     /* xNext    */
97764 };
97765
97766 /*
97767 ** Set *ppModule to point at the implementation of the ICU tokenizer.
97768 */
97769 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
97770   sqlite3_tokenizer_module const**ppModule
97771 ){
97772   *ppModule = &icuTokenizerModule;
97773 }
97774
97775 #endif /* defined(SQLITE_ENABLE_ICU) */
97776 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
97777
97778 /************** End of fts3_icu.c ********************************************/