version 0.3.32
[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.11.  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 ** 6938 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 2009-02-17 21:53:46 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.833 2009/02/05 16:53:43 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.10 2009/01/10 16:15:09 danielk1977 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 127
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 ** If this limit is changed, then the compiled library is technically
193 ** incompatible with an SQLite library compiled with a different limit. If
194 ** a process operating on a database with a page-size of 65536 bytes 
195 ** crashes, then an instance of SQLite compiled with the default page-size 
196 ** limit will not be able to rollback the aborted transaction. This could
197 ** lead to database corruption.
198 */
199 #ifndef SQLITE_MAX_PAGE_SIZE
200 # define SQLITE_MAX_PAGE_SIZE 32768
201 #endif
202
203
204 /*
205 ** The default size of a database page.
206 */
207 #ifndef SQLITE_DEFAULT_PAGE_SIZE
208 # define SQLITE_DEFAULT_PAGE_SIZE 1024
209 #endif
210 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
211 # undef SQLITE_DEFAULT_PAGE_SIZE
212 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
213 #endif
214
215 /*
216 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
217 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
218 ** device characteristics (sector-size and atomic write() support),
219 ** SQLite may choose a larger value. This constant is the maximum value
220 ** SQLite will choose on its own.
221 */
222 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
223 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
224 #endif
225 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
226 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
227 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
228 #endif
229
230
231 /*
232 ** Maximum number of pages in one database file.
233 **
234 ** This is really just the default value for the max_page_count pragma.
235 ** This value can be lowered (or raised) at run-time using that the
236 ** max_page_count macro.
237 */
238 #ifndef SQLITE_MAX_PAGE_COUNT
239 # define SQLITE_MAX_PAGE_COUNT 1073741823
240 #endif
241
242 /*
243 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
244 ** operator.
245 */
246 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
247 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
248 #endif
249
250 /************** End of sqliteLimit.h *****************************************/
251 /************** Continuing where we left off in sqliteInt.h ******************/
252
253 /* Disable nuisance warnings on Borland compilers */
254 #if defined(__BORLANDC__)
255 #pragma warn -rch /* unreachable code */
256 #pragma warn -ccc /* Condition is always true or false */
257 #pragma warn -aus /* Assigned value is never used */
258 #pragma warn -csu /* Comparing signed and unsigned */
259 #pragma warn -spa /* Suspicious pointer arithmetic */
260 #endif
261
262 /* Needed for various definitions... */
263 #ifndef _GNU_SOURCE
264 # define _GNU_SOURCE
265 #endif
266
267 /*
268 ** Include standard header files as necessary
269 */
270 #ifdef HAVE_STDINT_H
271 #include <stdint.h>
272 #endif
273 #ifdef HAVE_INTTYPES_H
274 #include <inttypes.h>
275 #endif
276
277 /*
278  * This macro is used to "hide" some ugliness in casting an int
279  * value to a ptr value under the MSVC 64-bit compiler.   Casting
280  * non 64-bit values to ptr types results in a "hard" error with 
281  * the MSVC 64-bit compiler which this attempts to avoid.  
282  *
283  * A simple compiler pragma or casting sequence could not be found
284  * to correct this in all situations, so this macro was introduced.
285  *
286  * It could be argued that the intptr_t type could be used in this
287  * case, but that type is not available on all compilers, or 
288  * requires the #include of specific headers which differs between
289  * platforms.
290  */
291 #define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
292 #define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
293
294 /*
295 ** These #defines should enable >2GB file support on POSIX if the
296 ** underlying operating system supports it.  If the OS lacks
297 ** large file support, or if the OS is windows, these should be no-ops.
298 **
299 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
300 ** system #includes.  Hence, this block of code must be the very first
301 ** code in all source files.
302 **
303 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
304 ** on the compiler command line.  This is necessary if you are compiling
305 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
306 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
307 ** without this option, LFS is enable.  But LFS does not exist in the kernel
308 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
309 ** portability you should omit LFS.
310 **
311 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
312 */
313 #ifndef SQLITE_DISABLE_LFS
314 # define _LARGE_FILE       1
315 # ifndef _FILE_OFFSET_BITS
316 #   define _FILE_OFFSET_BITS 64
317 # endif
318 # define _LARGEFILE_SOURCE 1
319 #endif
320
321
322 /*
323 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
324 ** Older versions of SQLite used an optional THREADSAFE macro.
325 ** We support that for legacy
326 */
327 #if !defined(SQLITE_THREADSAFE)
328 #if defined(THREADSAFE)
329 # define SQLITE_THREADSAFE THREADSAFE
330 #else
331 # define SQLITE_THREADSAFE 1
332 #endif
333 #endif
334
335 /*
336 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
337 ** It determines whether or not the features related to 
338 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
339 ** be overridden at runtime using the sqlite3_config() API.
340 */
341 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
342 # define SQLITE_DEFAULT_MEMSTATUS 1
343 #endif
344
345 /*
346 ** Exactly one of the following macros must be defined in order to
347 ** specify which memory allocation subsystem to use.
348 **
349 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
350 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
351 **     SQLITE_MEMORY_SIZE            // internal allocator #1
352 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
353 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
354 **
355 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
356 ** the default.
357 */
358 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
359     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
360     defined(SQLITE_POW2_MEMORY_SIZE)>1
361 # error "At most one of the following compile-time configuration options\
362  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
363  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
364 #endif
365 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
366     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
367     defined(SQLITE_POW2_MEMORY_SIZE)==0
368 # define SQLITE_SYSTEM_MALLOC 1
369 #endif
370
371 /*
372 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
373 ** sizes of memory allocations below this value where possible.
374 */
375 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
376 # define SQLITE_MALLOC_SOFT_LIMIT 1024
377 #endif
378
379 /*
380 ** We need to define _XOPEN_SOURCE as follows in order to enable
381 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
382 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
383 ** so it is omitted there.  See ticket #2673.
384 **
385 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
386 ** implemented on some systems.  So we avoid defining it at all
387 ** if it is already defined or if it is unneeded because we are
388 ** not doing a threadsafe build.  Ticket #2681.
389 **
390 ** See also ticket #2741.
391 */
392 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
393 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
394 #endif
395
396 /*
397 ** The TCL headers are only needed when compiling the TCL bindings.
398 */
399 #if defined(SQLITE_TCL) || defined(TCLSH)
400 # include <tcl.h>
401 #endif
402
403 /*
404 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
405 ** Setting NDEBUG makes the code smaller and run faster.  So the following
406 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
407 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
408 ** feature.
409 */
410 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
411 # define NDEBUG 1
412 #endif
413
414 /*
415 ** The testcase() macro is used to aid in coverage testing.  When 
416 ** doing coverage testing, the condition inside the argument to
417 ** testcase() must be evaluated both true and false in order to
418 ** get full branch coverage.  The testcase() macro is inserted
419 ** to help ensure adequate test coverage in places where simple
420 ** condition/decision coverage is inadequate.  For example, testcase()
421 ** can be used to make sure boundary values are tested.  For
422 ** bitmask tests, testcase() can be used to make sure each bit
423 ** is significant and used at least once.  On switch statements
424 ** where multiple cases go to the same block of code, testcase()
425 ** can insure that all cases are evaluated.
426 **
427 */
428 #ifdef SQLITE_COVERAGE_TEST
429 SQLITE_PRIVATE   void sqlite3Coverage(int);
430 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
431 #else
432 # define testcase(X)
433 #endif
434
435 /*
436 ** The TESTONLY macro is used to enclose variable declarations or
437 ** other bits of code that are needed to support the arguments
438 ** within testcase() and assert() macros.
439 */
440 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
441 # define TESTONLY(X)  X
442 #else
443 # define TESTONLY(X)
444 #endif
445
446 /*
447 ** The ALWAYS and NEVER macros surround boolean expressions which 
448 ** are intended to always be true or false, respectively.  Such
449 ** expressions could be omitted from the code completely.  But they
450 ** are included in a few cases in order to enhance the resilience
451 ** of SQLite to unexpected behavior - to make the code "self-healing"
452 ** or "ductile" rather than being "brittle" and crashing at the first
453 ** hint of unplanned behavior.
454 **
455 ** In other words, ALWAYS and NEVER are added for defensive code.
456 **
457 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
458 ** be true and false so that the unreachable code then specify will
459 ** not be counted as untested code.
460 */
461 #if defined(SQLITE_COVERAGE_TEST)
462 # define ALWAYS(X)      (1)
463 # define NEVER(X)       (0)
464 #elif !defined(NDEBUG)
465 SQLITE_PRIVATE   int sqlite3Assert(void);
466 # define ALWAYS(X)      ((X)?1:sqlite3Assert())
467 # define NEVER(X)       ((X)?sqlite3Assert():0)
468 #else
469 # define ALWAYS(X)      (X)
470 # define NEVER(X)       (X)
471 #endif
472
473 /*
474 ** The macro unlikely() is a hint that surrounds a boolean
475 ** expression that is usually false.  Macro likely() surrounds
476 ** a boolean expression that is usually true.  GCC is able to
477 ** use these hints to generate better code, sometimes.
478 */
479 #if defined(__GNUC__) && 0
480 # define likely(X)    __builtin_expect((X),1)
481 # define unlikely(X)  __builtin_expect((X),0)
482 #else
483 # define likely(X)    !!(X)
484 # define unlikely(X)  !!(X)
485 #endif
486
487 /*
488 ** Sometimes we need a small amount of code such as a variable initialization
489 ** to setup for a later assert() statement.  We do not want this code to
490 ** appear when assert() is disabled.  The following macro is therefore
491 ** used to contain that setup code.  The "VVA" acronym stands for
492 ** "Verification, Validation, and Accreditation".  In other words, the
493 ** code within VVA_ONLY() will only run during verification processes.
494 */
495 #ifndef NDEBUG
496 # define VVA_ONLY(X)  X
497 #else
498 # define VVA_ONLY(X)
499 #endif
500
501 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
502 /************** Begin file sqlite3.h *****************************************/
503 /*
504 ** 2001 September 15
505 **
506 ** The author disclaims copyright to this source code.  In place of
507 ** a legal notice, here is a blessing:
508 **
509 **    May you do good and not evil.
510 **    May you find forgiveness for yourself and forgive others.
511 **    May you share freely, never taking more than you give.
512 **
513 *************************************************************************
514 ** This header file defines the interface that the SQLite library
515 ** presents to client programs.  If a C-function, structure, datatype,
516 ** or constant definition does not appear in this file, then it is
517 ** not a published API of SQLite, is subject to change without
518 ** notice, and should not be referenced by programs that use SQLite.
519 **
520 ** Some of the definitions that are in this file are marked as
521 ** "experimental".  Experimental interfaces are normally new
522 ** features recently added to SQLite.  We do not anticipate changes
523 ** to experimental interfaces but reserve to make minor changes if
524 ** experience from use "in the wild" suggest such changes are prudent.
525 **
526 ** The official C-language API documentation for SQLite is derived
527 ** from comments in this file.  This file is the authoritative source
528 ** on how SQLite interfaces are suppose to operate.
529 **
530 ** The name of this file under configuration management is "sqlite.h.in".
531 ** The makefile makes some minor changes to this file (such as inserting
532 ** the version number) and changes its name to "sqlite3.h" as
533 ** part of the build process.
534 **
535 ** @(#) $Id: sqlite.h.in,v 1.432 2009/02/12 17:07:35 drh Exp $
536 */
537 #ifndef _SQLITE3_H_
538 #define _SQLITE3_H_
539 #include <stdarg.h>     /* Needed for the definition of va_list */
540
541 /*
542 ** Make sure we can call this stuff from C++.
543 */
544 #if 0
545 extern "C" {
546 #endif
547
548
549 /*
550 ** Add the ability to override 'extern'
551 */
552 #ifndef SQLITE_EXTERN
553 # define SQLITE_EXTERN extern
554 #endif
555
556 /*
557 ** These no-op macros are used in front of interfaces to mark those
558 ** interfaces as either deprecated or experimental.  New applications
559 ** should not use deprecated intrfaces - they are support for backwards
560 ** compatibility only.  Application writers should be aware that
561 ** experimental interfaces are subject to change in point releases.
562 **
563 ** These macros used to resolve to various kinds of compiler magic that
564 ** would generate warning messages when they were used.  But that
565 ** compiler magic ended up generating such a flurry of bug reports
566 ** that we have taken it all out and gone back to using simple
567 ** noop macros.
568 */
569 #define SQLITE_DEPRECATED
570 #define SQLITE_EXPERIMENTAL
571
572 /*
573 ** Ensure these symbols were not defined by some previous header file.
574 */
575 #ifdef SQLITE_VERSION
576 # undef SQLITE_VERSION
577 #endif
578 #ifdef SQLITE_VERSION_NUMBER
579 # undef SQLITE_VERSION_NUMBER
580 #endif
581
582 /*
583 ** CAPI3REF: Compile-Time Library Version Numbers {H10010} <S60100>
584 **
585 ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in
586 ** the sqlite3.h file specify the version of SQLite with which
587 ** that header file is associated.
588 **
589 ** The "version" of SQLite is a string of the form "X.Y.Z".
590 ** The phrase "alpha" or "beta" might be appended after the Z.
591 ** The X value is major version number always 3 in SQLite3.
592 ** The X value only changes when backwards compatibility is
593 ** broken and we intend to never break backwards compatibility.
594 ** The Y value is the minor version number and only changes when
595 ** there are major feature enhancements that are forwards compatible
596 ** but not backwards compatible.
597 ** The Z value is the release number and is incremented with
598 ** each release but resets back to 0 whenever Y is incremented.
599 **
600 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
601 **
602 ** INVARIANTS:
603 **
604 ** {H10011} The SQLITE_VERSION #define in the sqlite3.h header file shall
605 **          evaluate to a string literal that is the SQLite version
606 **          with which the header file is associated.
607 **
608 ** {H10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer
609 **          with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z
610 **          are the major version, minor version, and release number.
611 */
612 #define SQLITE_VERSION         "3.6.11"
613 #define SQLITE_VERSION_NUMBER  3006011
614
615 /*
616 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
617 ** KEYWORDS: sqlite3_version
618 **
619 ** These features provide the same information as the [SQLITE_VERSION]
620 ** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated
621 ** with the library instead of the header file.  Cautious programmers might
622 ** include a check in their application to verify that
623 ** sqlite3_libversion_number() always returns the value
624 ** [SQLITE_VERSION_NUMBER].
625 **
626 ** The sqlite3_libversion() function returns the same information as is
627 ** in the sqlite3_version[] string constant.  The function is provided
628 ** for use in DLLs since DLL users usually do not have direct access to string
629 ** constants within the DLL.
630 **
631 ** INVARIANTS:
632 **
633 ** {H10021} The [sqlite3_libversion_number()] interface shall return
634 **          an integer equal to [SQLITE_VERSION_NUMBER].
635 **
636 ** {H10022} The [sqlite3_version] string constant shall contain
637 **          the text of the [SQLITE_VERSION] string.
638 **
639 ** {H10023} The [sqlite3_libversion()] function shall return
640 **          a pointer to the [sqlite3_version] string constant.
641 */
642 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
643 SQLITE_API const char *sqlite3_libversion(void);
644 SQLITE_API int sqlite3_libversion_number(void);
645
646 /*
647 ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} <S60100>
648 **
649 ** SQLite can be compiled with or without mutexes.  When
650 ** the [SQLITE_THREADSAFE] C preprocessor macro 1 or 2, mutexes
651 ** are enabled and SQLite is threadsafe.  When the
652 ** [SQLITE_THREADSAFE] macro is 0, 
653 ** the mutexes are omitted.  Without the mutexes, it is not safe
654 ** to use SQLite concurrently from more than one thread.
655 **
656 ** Enabling mutexes incurs a measurable performance penalty.
657 ** So if speed is of utmost importance, it makes sense to disable
658 ** the mutexes.  But for maximum safety, mutexes should be enabled.
659 ** The default behavior is for mutexes to be enabled.
660 **
661 ** This interface can be used by a program to make sure that the
662 ** version of SQLite that it is linking against was compiled with
663 ** the desired setting of the [SQLITE_THREADSAFE] macro.
664 **
665 ** This interface only reports on the compile-time mutex setting
666 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
667 ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but
668 ** can be fully or partially disabled using a call to [sqlite3_config()]
669 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
670 ** or [SQLITE_CONFIG_MUTEX].  The return value of this function shows
671 ** only the default compile-time setting, not any run-time changes
672 ** to that setting.
673 **
674 ** See the [threading mode] documentation for additional information.
675 **
676 ** INVARIANTS:
677 **
678 ** {H10101} The [sqlite3_threadsafe()] function shall return zero if
679 **          and only if SQLite was compiled with mutexing code omitted.
680 **
681 ** {H10102} The value returned by the [sqlite3_threadsafe()] function
682 **          shall remain the same across calls to [sqlite3_config()].
683 */
684 SQLITE_API int sqlite3_threadsafe(void);
685
686 /*
687 ** CAPI3REF: Database Connection Handle {H12000} <S40200>
688 ** KEYWORDS: {database connection} {database connections}
689 **
690 ** Each open SQLite database is represented by a pointer to an instance of
691 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
692 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
693 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
694 ** is its destructor.  There are many other interfaces (such as
695 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
696 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
697 ** sqlite3 object.
698 */
699 typedef struct sqlite3 sqlite3;
700
701 /*
702 ** CAPI3REF: 64-Bit Integer Types {H10200} <S10110>
703 ** KEYWORDS: sqlite_int64 sqlite_uint64
704 **
705 ** Because there is no cross-platform way to specify 64-bit integer types
706 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
707 **
708 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
709 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
710 ** compatibility only.
711 **
712 ** INVARIANTS:
713 **
714 ** {H10201} The [sqlite_int64] and [sqlite3_int64] type shall specify
715 **          a 64-bit signed integer.
716 **
717 ** {H10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify
718 **          a 64-bit unsigned integer.
719 */
720 #ifdef SQLITE_INT64_TYPE
721   typedef SQLITE_INT64_TYPE sqlite_int64;
722   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
723 #elif defined(_MSC_VER) || defined(__BORLANDC__)
724   typedef __int64 sqlite_int64;
725   typedef unsigned __int64 sqlite_uint64;
726 #else
727   typedef long long int sqlite_int64;
728   typedef unsigned long long int sqlite_uint64;
729 #endif
730 typedef sqlite_int64 sqlite3_int64;
731 typedef sqlite_uint64 sqlite3_uint64;
732
733 /*
734 ** If compiling for a processor that lacks floating point support,
735 ** substitute integer for floating-point.
736 */
737 #ifdef SQLITE_OMIT_FLOATING_POINT
738 # define double sqlite3_int64
739 #endif
740
741 /*
742 ** CAPI3REF: Closing A Database Connection {H12010} <S30100><S40200>
743 **
744 ** This routine is the destructor for the [sqlite3] object.
745 **
746 ** Applications should [sqlite3_finalize | finalize] all [prepared statements]
747 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
748 ** the [sqlite3] object prior to attempting to close the object.
749 ** The [sqlite3_next_stmt()] interface can be used to locate all
750 ** [prepared statements] associated with a [database connection] if desired.
751 ** Typical code might look like this:
752 **
753 ** <blockquote><pre>
754 ** sqlite3_stmt *pStmt;
755 ** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
756 ** &nbsp;   sqlite3_finalize(pStmt);
757 ** }
758 ** </pre></blockquote>
759 **
760 ** If [sqlite3_close()] is invoked while a transaction is open,
761 ** the transaction is automatically rolled back.
762 **
763 ** INVARIANTS:
764 **
765 ** {H12011} A successful call to [sqlite3_close(C)] shall destroy the
766 **          [database connection] object C.
767 **
768 ** {H12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK.
769 **
770 ** {H12013} A successful call to [sqlite3_close(C)] shall release all
771 **          memory and system resources associated with [database connection]
772 **          C.
773 **
774 ** {H12014} A call to [sqlite3_close(C)] on a [database connection] C that
775 **          has one or more open [prepared statements] shall fail with
776 **          an [SQLITE_BUSY] error code.
777 **
778 ** {H12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall
779 **          be a harmless no-op returning SQLITE_OK.
780 **
781 ** {H12019} When [sqlite3_close(C)] is invoked on a [database connection] C
782 **          that has a pending transaction, the transaction shall be
783 **          rolled back.
784 **
785 ** ASSUMPTIONS:
786 **
787 ** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL
788 **          pointer or an [sqlite3] object pointer obtained
789 **          from [sqlite3_open()], [sqlite3_open16()], or
790 **          [sqlite3_open_v2()], and not previously closed.
791 */
792 SQLITE_API int sqlite3_close(sqlite3 *);
793
794 /*
795 ** The type for a callback function.
796 ** This is legacy and deprecated.  It is included for historical
797 ** compatibility and is not documented.
798 */
799 typedef int (*sqlite3_callback)(void*,int,char**, char**);
800
801 /*
802 ** CAPI3REF: One-Step Query Execution Interface {H12100} <S10000>
803 **
804 ** The sqlite3_exec() interface is a convenient way of running one or more
805 ** SQL statements without having to write a lot of C code.  The UTF-8 encoded
806 ** SQL statements are passed in as the second parameter to sqlite3_exec().
807 ** The statements are evaluated one by one until either an error or
808 ** an interrupt is encountered, or until they are all done.  The 3rd parameter
809 ** is an optional callback that is invoked once for each row of any query
810 ** results produced by the SQL statements.  The 5th parameter tells where
811 ** to write any error messages.
812 **
813 ** The error message passed back through the 5th parameter is held
814 ** in memory obtained from [sqlite3_malloc()].  To avoid a memory leak,
815 ** the calling application should call [sqlite3_free()] on any error
816 ** message returned through the 5th parameter when it has finished using
817 ** the error message.
818 **
819 ** If the SQL statement in the 2nd parameter is NULL or an empty string
820 ** or a string containing only whitespace and comments, then no SQL
821 ** statements are evaluated and the database is not changed.
822 **
823 ** The sqlite3_exec() interface is implemented in terms of
824 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
825 ** The sqlite3_exec() routine does nothing to the database that cannot be done
826 ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()].
827 **
828 ** INVARIANTS:
829 **
830 ** {H12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)]
831 **          shall sequentially evaluate all of the UTF-8 encoded,
832 **          semicolon-separated SQL statements in the zero-terminated
833 **          string S within the context of the [database connection] D.
834 **
835 ** {H12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then
836 **          the actions of the interface shall be the same as if the
837 **          S parameter were an empty string.
838 **
839 ** {H12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all
840 **          SQL statements run successfully and to completion.
841 **
842 ** {H12105} The return value of [sqlite3_exec()] shall be an appropriate
843 **          non-zero [error code] if any SQL statement fails.
844 **
845 ** {H12107} If one or more of the SQL statements handed to [sqlite3_exec()]
846 **          return results and the 3rd parameter is not NULL, then
847 **          the callback function specified by the 3rd parameter shall be
848 **          invoked once for each row of result.
849 **
850 ** {H12110} If the callback returns a non-zero value then [sqlite3_exec()]
851 **          shall abort the SQL statement it is currently evaluating,
852 **          skip all subsequent SQL statements, and return [SQLITE_ABORT].
853 **
854 ** {H12113} The [sqlite3_exec()] routine shall pass its 4th parameter through
855 **          as the 1st parameter of the callback.
856 **
857 ** {H12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its
858 **          callback to be the number of columns in the current row of
859 **          result.
860 **
861 ** {H12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its
862 **          callback to be an array of pointers to strings holding the
863 **          values for each column in the current result set row as
864 **          obtained from [sqlite3_column_text()].
865 **
866 ** {H12122} The [sqlite3_exec()] routine shall set the 4th parameter of its
867 **          callback to be an array of pointers to strings holding the
868 **          names of result columns as obtained from [sqlite3_column_name()].
869 **
870 ** {H12125} If the 3rd parameter to [sqlite3_exec()] is NULL then
871 **          [sqlite3_exec()] shall silently discard query results.
872 **
873 ** {H12131} If an error occurs while parsing or evaluating any of the SQL
874 **          statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if
875 **          the E parameter is not NULL, then [sqlite3_exec()] shall store
876 **          in *E an appropriate error message written into memory obtained
877 **          from [sqlite3_malloc()].
878 **
879 ** {H12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of
880 **          *E to NULL if E is not NULL and there are no errors.
881 **
882 ** {H12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code]
883 **          and message accessible via [sqlite3_errcode()], 
884 **          [sqlite3_extended_errcode()],
885 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()].
886 **
887 ** {H12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an
888 **          empty string or contains nothing other than whitespace, comments,
889 **          and/or semicolons, then results of [sqlite3_errcode()],
890 **          [sqlite3_extended_errcode()],
891 **          [sqlite3_errmsg()], and [sqlite3_errmsg16()]
892 **          shall reset to indicate no errors.
893 **
894 ** ASSUMPTIONS:
895 **
896 ** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open
897 **          [database connection].
898 **
899 ** {A12142} The database connection must not be closed while
900 **          [sqlite3_exec()] is running.
901 **
902 ** {A12143} The calling function should use [sqlite3_free()] to free
903 **          the memory that *errmsg is left pointing at once the error
904 **          message is no longer needed.
905 **
906 ** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()]
907 **          must remain unchanged while [sqlite3_exec()] is running.
908 */
909 SQLITE_API int sqlite3_exec(
910   sqlite3*,                                  /* An open database */
911   const char *sql,                           /* SQL to be evaluated */
912   int (*callback)(void*,int,char**,char**),  /* Callback function */
913   void *,                                    /* 1st argument to callback */
914   char **errmsg                              /* Error msg written here */
915 );
916
917 /*
918 ** CAPI3REF: Result Codes {H10210} <S10700>
919 ** KEYWORDS: SQLITE_OK {error code} {error codes}
920 ** KEYWORDS: {result code} {result codes}
921 **
922 ** Many SQLite functions return an integer result code from the set shown
923 ** here in order to indicates success or failure.
924 **
925 ** New error codes may be added in future versions of SQLite.
926 **
927 ** See also: [SQLITE_IOERR_READ | extended result codes]
928 */
929 #define SQLITE_OK           0   /* Successful result */
930 /* beginning-of-error-codes */
931 #define SQLITE_ERROR        1   /* SQL error or missing database */
932 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
933 #define SQLITE_PERM         3   /* Access permission denied */
934 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
935 #define SQLITE_BUSY         5   /* The database file is locked */
936 #define SQLITE_LOCKED       6   /* A table in the database is locked */
937 #define SQLITE_NOMEM        7   /* A malloc() failed */
938 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
939 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
940 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
941 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
942 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
943 #define SQLITE_FULL        13   /* Insertion failed because database is full */
944 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
945 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
946 #define SQLITE_EMPTY       16   /* Database is empty */
947 #define SQLITE_SCHEMA      17   /* The database schema changed */
948 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
949 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
950 #define SQLITE_MISMATCH    20   /* Data type mismatch */
951 #define SQLITE_MISUSE      21   /* Library used incorrectly */
952 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
953 #define SQLITE_AUTH        23   /* Authorization denied */
954 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
955 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
956 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
957 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
958 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
959 /* end-of-error-codes */
960
961 /*
962 ** CAPI3REF: Extended Result Codes {H10220} <S10700>
963 ** KEYWORDS: {extended error code} {extended error codes}
964 ** KEYWORDS: {extended result code} {extended result codes}
965 **
966 ** In its default configuration, SQLite API routines return one of 26 integer
967 ** [SQLITE_OK | result codes].  However, experience has shown that many of
968 ** these result codes are too coarse-grained.  They do not provide as
969 ** much information about problems as programmers might like.  In an effort to
970 ** address this, newer versions of SQLite (version 3.3.8 and later) include
971 ** support for additional result codes that provide more detailed information
972 ** about errors. The extended result codes are enabled or disabled
973 ** on a per database connection basis using the
974 ** [sqlite3_extended_result_codes()] API.
975 **
976 ** Some of the available extended result codes are listed here.
977 ** One may expect the number of extended result codes will be expand
978 ** over time.  Software that uses extended result codes should expect
979 ** to see new result codes in future releases of SQLite.
980 **
981 ** The SQLITE_OK result code will never be extended.  It will always
982 ** be exactly zero.
983 **
984 ** INVARIANTS:
985 **
986 ** {H10223} The symbolic name for an extended result code shall contains
987 **          a related primary result code as a prefix.
988 **
989 ** {H10224} Primary result code names shall contain a single "_" character.
990 **
991 ** {H10225} Extended result code names shall contain two or more "_" characters.
992 **
993 ** {H10226} The numeric value of an extended result code shall contain the
994 **          numeric value of its corresponding primary result code in
995 **          its least significant 8 bits.
996 */
997 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
998 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
999 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1000 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1001 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1002 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1003 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1004 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1005 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1006 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1007 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1008 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1009 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1010 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1011 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1012 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1013 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1014
1015 /*
1016 ** CAPI3REF: Flags For File Open Operations {H10230} <H11120> <H12700>
1017 **
1018 ** These bit values are intended for use in the
1019 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1020 ** in the 4th parameter to the xOpen method of the
1021 ** [sqlite3_vfs] object.
1022 */
1023 #define SQLITE_OPEN_READONLY         0x00000001
1024 #define SQLITE_OPEN_READWRITE        0x00000002
1025 #define SQLITE_OPEN_CREATE           0x00000004
1026 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008
1027 #define SQLITE_OPEN_EXCLUSIVE        0x00000010
1028 #define SQLITE_OPEN_MAIN_DB          0x00000100
1029 #define SQLITE_OPEN_TEMP_DB          0x00000200
1030 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400
1031 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800
1032 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000
1033 #define SQLITE_OPEN_SUBJOURNAL       0x00002000
1034 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000
1035 #define SQLITE_OPEN_NOMUTEX          0x00008000
1036 #define SQLITE_OPEN_FULLMUTEX        0x00010000
1037
1038 /*
1039 ** CAPI3REF: Device Characteristics {H10240} <H11120>
1040 **
1041 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
1042 ** object returns an integer which is a vector of the these
1043 ** bit values expressing I/O characteristics of the mass storage
1044 ** device that holds the file that the [sqlite3_io_methods]
1045 ** refers to.
1046 **
1047 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1048 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1049 ** mean that writes of blocks that are nnn bytes in size and
1050 ** are aligned to an address which is an integer multiple of
1051 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1052 ** that when data is appended to a file, the data is appended
1053 ** first then the size of the file is extended, never the other
1054 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1055 ** information is written to disk in the same order as calls
1056 ** to xWrite().
1057 */
1058 #define SQLITE_IOCAP_ATOMIC          0x00000001
1059 #define SQLITE_IOCAP_ATOMIC512       0x00000002
1060 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
1061 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1062 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1063 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1064 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1065 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1066 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1067 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1068 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1069
1070 /*
1071 ** CAPI3REF: File Locking Levels {H10250} <H11120> <H11310>
1072 **
1073 ** SQLite uses one of these integer values as the second
1074 ** argument to calls it makes to the xLock() and xUnlock() methods
1075 ** of an [sqlite3_io_methods] object.
1076 */
1077 #define SQLITE_LOCK_NONE          0
1078 #define SQLITE_LOCK_SHARED        1
1079 #define SQLITE_LOCK_RESERVED      2
1080 #define SQLITE_LOCK_PENDING       3
1081 #define SQLITE_LOCK_EXCLUSIVE     4
1082
1083 /*
1084 ** CAPI3REF: Synchronization Type Flags {H10260} <H11120>
1085 **
1086 ** When SQLite invokes the xSync() method of an
1087 ** [sqlite3_io_methods] object it uses a combination of
1088 ** these integer values as the second argument.
1089 **
1090 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1091 ** sync operation only needs to flush data to mass storage.  Inode
1092 ** information need not be flushed. The SQLITE_SYNC_NORMAL flag means
1093 ** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means
1094 ** to use Mac OS X style fullsync instead of fsync().
1095 */
1096 #define SQLITE_SYNC_NORMAL        0x00002
1097 #define SQLITE_SYNC_FULL          0x00003
1098 #define SQLITE_SYNC_DATAONLY      0x00010
1099
1100 /*
1101 ** CAPI3REF: OS Interface Open File Handle {H11110} <S20110>
1102 **
1103 ** An [sqlite3_file] object represents an open file in the OS
1104 ** interface layer.  Individual OS interface implementations will
1105 ** want to subclass this object by appending additional fields
1106 ** for their own use.  The pMethods entry is a pointer to an
1107 ** [sqlite3_io_methods] object that defines methods for performing
1108 ** I/O operations on the open file.
1109 */
1110 typedef struct sqlite3_file sqlite3_file;
1111 struct sqlite3_file {
1112   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1113 };
1114
1115 /*
1116 ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} <S20110>
1117 **
1118 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1119 ** [sqlite3_file] object (or, more commonly, a subclass of the
1120 ** [sqlite3_file] object) with a pointer to an instance of this object.
1121 ** This object defines the methods used to perform various operations
1122 ** against the open file represented by the [sqlite3_file] object.
1123 **
1124 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1125 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1126 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1127 ** flag may be ORed in to indicate that only the data of the file
1128 ** and not its inode needs to be synced.
1129 **
1130 ** The integer values to xLock() and xUnlock() are one of
1131 ** <ul>
1132 ** <li> [SQLITE_LOCK_NONE],
1133 ** <li> [SQLITE_LOCK_SHARED],
1134 ** <li> [SQLITE_LOCK_RESERVED],
1135 ** <li> [SQLITE_LOCK_PENDING], or
1136 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1137 ** </ul>
1138 ** xLock() increases the lock. xUnlock() decreases the lock.
1139 ** The xCheckReservedLock() method checks whether any database connection,
1140 ** either in this process or in some other process, is holding a RESERVED,
1141 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1142 ** if such a lock exists and false otherwise.
1143 **
1144 ** The xFileControl() method is a generic interface that allows custom
1145 ** VFS implementations to directly control an open file using the
1146 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1147 ** integer opcode.  The third argument is a generic pointer intended to
1148 ** point to a structure that may contain arguments or space in which to
1149 ** write return values.  Potential uses for xFileControl() might be
1150 ** functions to enable blocking locks with timeouts, to change the
1151 ** locking strategy (for example to use dot-file locks), to inquire
1152 ** about the status of a lock, or to break stale locks.  The SQLite
1153 ** core reserves all opcodes less than 100 for its own use.
1154 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1155 ** Applications that define a custom xFileControl method should use opcodes
1156 ** greater than 100 to avoid conflicts.
1157 **
1158 ** The xSectorSize() method returns the sector size of the
1159 ** device that underlies the file.  The sector size is the
1160 ** minimum write that can be performed without disturbing
1161 ** other bytes in the file.  The xDeviceCharacteristics()
1162 ** method returns a bit vector describing behaviors of the
1163 ** underlying device:
1164 **
1165 ** <ul>
1166 ** <li> [SQLITE_IOCAP_ATOMIC]
1167 ** <li> [SQLITE_IOCAP_ATOMIC512]
1168 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1169 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1170 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1171 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1172 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1173 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1174 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1175 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1176 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1177 ** </ul>
1178 **
1179 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1180 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1181 ** mean that writes of blocks that are nnn bytes in size and
1182 ** are aligned to an address which is an integer multiple of
1183 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1184 ** that when data is appended to a file, the data is appended
1185 ** first then the size of the file is extended, never the other
1186 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1187 ** information is written to disk in the same order as calls
1188 ** to xWrite().
1189 **
1190 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1191 ** in the unread portions of the buffer with zeros.  A VFS that
1192 ** fails to zero-fill short reads might seem to work.  However,
1193 ** failure to zero-fill short reads will eventually lead to
1194 ** database corruption.
1195 */
1196 typedef struct sqlite3_io_methods sqlite3_io_methods;
1197 struct sqlite3_io_methods {
1198   int iVersion;
1199   int (*xClose)(sqlite3_file*);
1200   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1201   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1202   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1203   int (*xSync)(sqlite3_file*, int flags);
1204   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1205   int (*xLock)(sqlite3_file*, int);
1206   int (*xUnlock)(sqlite3_file*, int);
1207   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1208   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1209   int (*xSectorSize)(sqlite3_file*);
1210   int (*xDeviceCharacteristics)(sqlite3_file*);
1211   /* Additional methods may be added in future releases */
1212 };
1213
1214 /*
1215 ** CAPI3REF: Standard File Control Opcodes {H11310} <S30800>
1216 **
1217 ** These integer constants are opcodes for the xFileControl method
1218 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1219 ** interface.
1220 **
1221 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1222 ** opcode causes the xFileControl method to write the current state of
1223 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1224 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1225 ** into an integer that the pArg argument points to. This capability
1226 ** is used during testing and only needs to be supported when SQLITE_TEST
1227 ** is defined.
1228 */
1229 #define SQLITE_FCNTL_LOCKSTATE        1
1230 #define SQLITE_GET_LOCKPROXYFILE      2
1231 #define SQLITE_SET_LOCKPROXYFILE      3
1232 #define SQLITE_LAST_ERRNO             4
1233
1234 /*
1235 ** CAPI3REF: Mutex Handle {H17110} <S20130>
1236 **
1237 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1238 ** abstract type for a mutex object.  The SQLite core never looks
1239 ** at the internal representation of an [sqlite3_mutex].  It only
1240 ** deals with pointers to the [sqlite3_mutex] object.
1241 **
1242 ** Mutexes are created using [sqlite3_mutex_alloc()].
1243 */
1244 typedef struct sqlite3_mutex sqlite3_mutex;
1245
1246 /*
1247 ** CAPI3REF: OS Interface Object {H11140} <S20100>
1248 **
1249 ** An instance of the sqlite3_vfs object defines the interface between
1250 ** the SQLite core and the underlying operating system.  The "vfs"
1251 ** in the name of the object stands for "virtual file system".
1252 **
1253 ** The value of the iVersion field is initially 1 but may be larger in
1254 ** future versions of SQLite.  Additional fields may be appended to this
1255 ** object when the iVersion value is increased.  Note that the structure
1256 ** of the sqlite3_vfs object changes in the transaction between
1257 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1258 ** modified.
1259 **
1260 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1261 ** structure used by this VFS.  mxPathname is the maximum length of
1262 ** a pathname in this VFS.
1263 **
1264 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1265 ** the pNext pointer.  The [sqlite3_vfs_register()]
1266 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1267 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1268 ** searches the list.  Neither the application code nor the VFS
1269 ** implementation should use the pNext pointer.
1270 **
1271 ** The pNext field is the only field in the sqlite3_vfs
1272 ** structure that SQLite will ever modify.  SQLite will only access
1273 ** or modify this field while holding a particular static mutex.
1274 ** The application should never modify anything within the sqlite3_vfs
1275 ** object once the object has been registered.
1276 **
1277 ** The zName field holds the name of the VFS module.  The name must
1278 ** be unique across all VFS modules.
1279 **
1280 ** SQLite will guarantee that the zFilename parameter to xOpen
1281 ** is either a NULL pointer or string obtained
1282 ** from xFullPathname().  SQLite further guarantees that
1283 ** the string will be valid and unchanged until xClose() is
1284 ** called. Because of the previous sentense,
1285 ** the [sqlite3_file] can safely store a pointer to the
1286 ** filename if it needs to remember the filename for some reason.
1287 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1288 ** must invite its own temporary name for the file.  Whenever the 
1289 ** xFilename parameter is NULL it will also be the case that the
1290 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1291 **
1292 ** The flags argument to xOpen() includes all bits set in
1293 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1294 ** or [sqlite3_open16()] is used, then flags includes at least
1295 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1296 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1297 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1298 **
1299 ** SQLite will also add one of the following flags to the xOpen()
1300 ** call, depending on the object being opened:
1301 **
1302 ** <ul>
1303 ** <li>  [SQLITE_OPEN_MAIN_DB]
1304 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1305 ** <li>  [SQLITE_OPEN_TEMP_DB]
1306 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1307 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1308 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1309 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1310 ** </ul>
1311 **
1312 ** The file I/O implementation can use the object type flags to
1313 ** change the way it deals with files.  For example, an application
1314 ** that does not care about crash recovery or rollback might make
1315 ** the open of a journal file a no-op.  Writes to this journal would
1316 ** also be no-ops, and any attempt to read the journal would return
1317 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1318 ** file will be doing page-aligned sector reads and writes in a random
1319 ** order and set up its I/O subsystem accordingly.
1320 **
1321 ** SQLite might also add one of the following flags to the xOpen method:
1322 **
1323 ** <ul>
1324 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1325 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1326 ** </ul>
1327 **
1328 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1329 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1330 ** will be set for TEMP  databases, journals and for subjournals.
1331 **
1332 ** The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened
1333 ** for exclusive access.  This flag is set for all files except
1334 ** for the main database file.
1335 **
1336 ** At least szOsFile bytes of memory are allocated by SQLite
1337 ** to hold the  [sqlite3_file] structure passed as the third
1338 ** argument to xOpen.  The xOpen method does not have to
1339 ** allocate the structure; it should just fill it in.
1340 **
1341 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1342 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1343 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1344 ** to test whether a file is at least readable.   The file can be a
1345 ** directory.
1346 **
1347 ** SQLite will always allocate at least mxPathname+1 bytes for the
1348 ** output buffer xFullPathname.  The exact size of the output buffer
1349 ** is also passed as a parameter to both  methods. If the output buffer
1350 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1351 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1352 ** to prevent this by setting mxPathname to a sufficiently large value.
1353 **
1354 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1355 ** are not strictly a part of the filesystem, but they are
1356 ** included in the VFS structure for completeness.
1357 ** The xRandomness() function attempts to return nBytes bytes
1358 ** of good-quality randomness into zOut.  The return value is
1359 ** the actual number of bytes of randomness obtained.
1360 ** The xSleep() method causes the calling thread to sleep for at
1361 ** least the number of microseconds given.  The xCurrentTime()
1362 ** method returns a Julian Day Number for the current date and time.
1363 **
1364 */
1365 typedef struct sqlite3_vfs sqlite3_vfs;
1366 struct sqlite3_vfs {
1367   int iVersion;            /* Structure version number */
1368   int szOsFile;            /* Size of subclassed sqlite3_file */
1369   int mxPathname;          /* Maximum file pathname length */
1370   sqlite3_vfs *pNext;      /* Next registered VFS */
1371   const char *zName;       /* Name of this virtual file system */
1372   void *pAppData;          /* Pointer to application-specific data */
1373   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1374                int flags, int *pOutFlags);
1375   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1376   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1377   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1378   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1379   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1380   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1381   void (*xDlClose)(sqlite3_vfs*, void*);
1382   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1383   int (*xSleep)(sqlite3_vfs*, int microseconds);
1384   int (*xCurrentTime)(sqlite3_vfs*, double*);
1385   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1386   /* New fields may be appended in figure versions.  The iVersion
1387   ** value will increment whenever this happens. */
1388 };
1389
1390 /*
1391 ** CAPI3REF: Flags for the xAccess VFS method {H11190} <H11140>
1392 **
1393 ** These integer constants can be used as the third parameter to
1394 ** the xAccess method of an [sqlite3_vfs] object. {END}  They determine
1395 ** what kind of permissions the xAccess method is looking for.
1396 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1397 ** simply checks whether the file exists.
1398 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1399 ** checks whether the file is both readable and writable.
1400 ** With SQLITE_ACCESS_READ, the xAccess method
1401 ** checks whether the file is readable.
1402 */
1403 #define SQLITE_ACCESS_EXISTS    0
1404 #define SQLITE_ACCESS_READWRITE 1
1405 #define SQLITE_ACCESS_READ      2
1406
1407 /*
1408 ** CAPI3REF: Initialize The SQLite Library {H10130} <S20000><S30100>
1409 **
1410 ** The sqlite3_initialize() routine initializes the
1411 ** SQLite library.  The sqlite3_shutdown() routine
1412 ** deallocates any resources that were allocated by sqlite3_initialize().
1413 **
1414 ** A call to sqlite3_initialize() is an "effective" call if it is
1415 ** the first time sqlite3_initialize() is invoked during the lifetime of
1416 ** the process, or if it is the first time sqlite3_initialize() is invoked
1417 ** following a call to sqlite3_shutdown().  Only an effective call
1418 ** of sqlite3_initialize() does any initialization.  All other calls
1419 ** are harmless no-ops.
1420 **
1421 ** Among other things, sqlite3_initialize() shall invoke
1422 ** sqlite3_os_init().  Similarly, sqlite3_shutdown()
1423 ** shall invoke sqlite3_os_end().
1424 **
1425 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1426 ** If for some reason, sqlite3_initialize() is unable to initialize
1427 ** the library (perhaps it is unable to allocate a needed resource such
1428 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1429 **
1430 ** The sqlite3_initialize() routine is called internally by many other
1431 ** SQLite interfaces so that an application usually does not need to
1432 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1433 ** calls sqlite3_initialize() so the SQLite library will be automatically
1434 ** initialized when [sqlite3_open()] is called if it has not be initialized
1435 ** already.  However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1436 ** compile-time option, then the automatic calls to sqlite3_initialize()
1437 ** are omitted and the application must call sqlite3_initialize() directly
1438 ** prior to using any other SQLite interface.  For maximum portability,
1439 ** it is recommended that applications always invoke sqlite3_initialize()
1440 ** directly prior to using any other SQLite interface.  Future releases
1441 ** of SQLite may require this.  In other words, the behavior exhibited
1442 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1443 ** default behavior in some future release of SQLite.
1444 **
1445 ** The sqlite3_os_init() routine does operating-system specific
1446 ** initialization of the SQLite library.  The sqlite3_os_end()
1447 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1448 ** performed by these routines include allocation or deallocation
1449 ** of static resources, initialization of global variables,
1450 ** setting up a default [sqlite3_vfs] module, or setting up
1451 ** a default configuration using [sqlite3_config()].
1452 **
1453 ** The application should never invoke either sqlite3_os_init()
1454 ** or sqlite3_os_end() directly.  The application should only invoke
1455 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1456 ** interface is called automatically by sqlite3_initialize() and
1457 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1458 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1459 ** are built into SQLite when it is compiled for unix, windows, or os/2.
1460 ** When built for other platforms (using the [SQLITE_OS_OTHER=1] compile-time
1461 ** option) the application must supply a suitable implementation for
1462 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1463 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1464 ** must return [SQLITE_OK] on success and some other [error code] upon
1465 ** failure.
1466 */
1467 SQLITE_API int sqlite3_initialize(void);
1468 SQLITE_API int sqlite3_shutdown(void);
1469 SQLITE_API int sqlite3_os_init(void);
1470 SQLITE_API int sqlite3_os_end(void);
1471
1472 /*
1473 ** CAPI3REF: Configuring The SQLite Library {H14100} <S20000><S30200>
1474 ** EXPERIMENTAL
1475 **
1476 ** The sqlite3_config() interface is used to make global configuration
1477 ** changes to SQLite in order to tune SQLite to the specific needs of
1478 ** the application.  The default configuration is recommended for most
1479 ** applications and so this routine is usually not necessary.  It is
1480 ** provided to support rare applications with unusual needs.
1481 **
1482 ** The sqlite3_config() interface is not threadsafe.  The application
1483 ** must insure that no other SQLite interfaces are invoked by other
1484 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1485 ** may only be invoked prior to library initialization using
1486 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1487 ** Note, however, that sqlite3_config() can be called as part of the
1488 ** implementation of an application-defined [sqlite3_os_init()].
1489 **
1490 ** The first argument to sqlite3_config() is an integer
1491 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1492 ** what property of SQLite is to be configured.  Subsequent arguments
1493 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1494 ** in the first argument.
1495 **
1496 ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1497 ** If the option is unknown or SQLite is unable to set the option
1498 ** then this routine returns a non-zero [error code].
1499 **
1500 ** INVARIANTS:
1501 **
1502 ** {H14103} A successful invocation of [sqlite3_config()] shall return
1503 **          [SQLITE_OK].
1504 **
1505 ** {H14106} The [sqlite3_config()] interface shall return [SQLITE_MISUSE]
1506 **          if it is invoked in between calls to [sqlite3_initialize()] and
1507 **          [sqlite3_shutdown()].
1508 **
1509 ** {H14120} A successful call to [sqlite3_config]([SQLITE_CONFIG_SINGLETHREAD])
1510 **          shall set the default [threading mode] to Single-thread.
1511 **
1512 ** {H14123} A successful call to [sqlite3_config]([SQLITE_CONFIG_MULTITHREAD])
1513 **          shall set the default [threading mode] to Multi-thread.
1514 **
1515 ** {H14126} A successful call to [sqlite3_config]([SQLITE_CONFIG_SERIALIZED])
1516 **          shall set the default [threading mode] to Serialized.
1517 **
1518 ** {H14129} A successful call to [sqlite3_config]([SQLITE_CONFIG_MUTEX],X)
1519 **          where X is a pointer to an initialized [sqlite3_mutex_methods]
1520 **          object shall cause all subsequent mutex operations performed
1521 **          by SQLite to use the mutex methods that were present in X
1522 **          during the call to [sqlite3_config()].
1523 **
1524 ** {H14132} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMUTEX],X)
1525 **          where X is a pointer to an [sqlite3_mutex_methods] object 
1526 **          shall overwrite the content of [sqlite3_mutex_methods] object
1527 **          with the mutex methods currently in use by SQLite.
1528 **
1529 ** {H14135} A successful call to [sqlite3_config]([SQLITE_CONFIG_MALLOC],M)
1530 **          where M is a pointer to an initialized [sqlite3_mem_methods]
1531 **          object shall cause all subsequent memory allocation operations
1532 **          performed by SQLite to use the methods that were present in 
1533 **          M during the call to [sqlite3_config()].
1534 **
1535 ** {H14138} A successful call to [sqlite3_config]([SQLITE_CONFIG_GETMALLOC],M)
1536 **          where M is a pointer to an [sqlite3_mem_methods] object shall
1537 **          overwrite the content of [sqlite3_mem_methods] object with 
1538 **          the memory allocation methods currently in use by
1539 **          SQLite.
1540 **
1541 ** {H14141} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],1)
1542 **          shall enable the memory allocation status collection logic.
1543 **
1544 ** {H14144} A successful call to [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],0)
1545 **          shall disable the memory allocation status collection logic.
1546 **
1547 ** {H14147} The memory allocation status collection logic shall be
1548 **          enabled by default.
1549 **
1550 ** {H14150} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1551 **          where Z and N are non-negative integers and 
1552 **          S is a pointer to an aligned memory buffer not less than
1553 **          Z*N bytes in size shall cause S to be used by the
1554 **          [scratch memory allocator] for as many as N simulataneous
1555 **          allocations each of size (Z & ~7).
1556 **
1557 ** {H14153} A successful call to [sqlite3_config]([SQLITE_CONFIG_SCRATCH],S,Z,N)
1558 **          where S is a NULL pointer shall disable the
1559 **          [scratch memory allocator].
1560 **
1561 ** {H14156} A successful call to
1562 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1563 **          where Z and N are non-negative integers and 
1564 **          S is a pointer to an aligned memory buffer not less than
1565 **          Z*N bytes in size shall cause S to be used by the
1566 **          [pagecache memory allocator] for as many as N simulataneous
1567 **          allocations each of size (Z & ~7).
1568 **
1569 ** {H14159} A successful call to
1570 **          [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],S,Z,N)
1571 **          where S is a NULL pointer shall disable the
1572 **          [pagecache memory allocator].
1573 **
1574 ** {H14162} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1575 **          where Z and N are non-negative integers and 
1576 **          H is a pointer to an aligned memory buffer not less than
1577 **          Z bytes in size shall enable the [memsys5] memory allocator
1578 **          and cause it to use buffer S as its memory source and to use
1579 **          a minimum allocation size of N.
1580 **
1581 ** {H14165} A successful call to [sqlite3_config]([SQLITE_CONFIG_HEAP],H,Z,N)
1582 **          where H is a NULL pointer shall disable the
1583 **          [memsys5] memory allocator.
1584 **
1585 ** {H14168} A successful call to [sqlite3_config]([SQLITE_CONFIG_LOOKASIDE],Z,N)
1586 **          shall cause the default [lookaside memory allocator] configuration
1587 **          for new [database connections] to be N slots of Z bytes each.
1588 */
1589 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1590
1591 /*
1592 ** CAPI3REF: Configure database connections  {H14200} <S20000>
1593 ** EXPERIMENTAL
1594 **
1595 ** The sqlite3_db_config() interface is used to make configuration
1596 ** changes to a [database connection].  The interface is similar to
1597 ** [sqlite3_config()] except that the changes apply to a single
1598 ** [database connection] (specified in the first argument).  The
1599 ** sqlite3_db_config() interface can only be used immediately after
1600 ** the database connection is created using [sqlite3_open()],
1601 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1602 **
1603 ** The second argument to sqlite3_db_config(D,V,...)  is the
1604 ** configuration verb - an integer code that indicates what
1605 ** aspect of the [database connection] is being configured.
1606 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1607 ** New verbs are likely to be added in future releases of SQLite.
1608 ** Additional arguments depend on the verb.
1609 **
1610 ** INVARIANTS:
1611 **
1612 ** {H14203} A call to [sqlite3_db_config(D,V,...)] shall return [SQLITE_OK]
1613 **          if and only if the call is successful.
1614 **
1615 ** {H14206} If one or more slots of the [lookaside memory allocator] for
1616 **          [database connection] D are in use, then a call to
1617 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],...) shall
1618 **          fail with an [SQLITE_BUSY] return code.
1619 **
1620 ** {H14209} A successful call to 
1621 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1622 **          D is an open [database connection] and Z and N are positive
1623 **          integers and B is an aligned buffer at least Z*N bytes in size
1624 **          shall cause the [lookaside memory allocator] for D to use buffer B 
1625 **          with N slots of Z bytes each.
1626 **
1627 ** {H14212} A successful call to 
1628 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1629 **          D is an open [database connection] and Z and N are positive
1630 **          integers and B is NULL pointer shall cause the
1631 **          [lookaside memory allocator] for D to a obtain Z*N byte buffer
1632 **          from the primary memory allocator and use that buffer
1633 **          with N lookaside slots of Z bytes each.
1634 **
1635 ** {H14215} A successful call to 
1636 **          [sqlite3_db_config](D,[SQLITE_DBCONFIG_LOOKASIDE],B,Z,N) where
1637 **          D is an open [database connection] and Z and N are zero shall
1638 **          disable the [lookaside memory allocator] for D.
1639 **
1640 **
1641 */
1642 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1643
1644 /*
1645 ** CAPI3REF: Memory Allocation Routines {H10155} <S20120>
1646 ** EXPERIMENTAL
1647 **
1648 ** An instance of this object defines the interface between SQLite
1649 ** and low-level memory allocation routines.
1650 **
1651 ** This object is used in only one place in the SQLite interface.
1652 ** A pointer to an instance of this object is the argument to
1653 ** [sqlite3_config()] when the configuration option is
1654 ** [SQLITE_CONFIG_MALLOC].  By creating an instance of this object
1655 ** and passing it to [sqlite3_config()] during configuration, an
1656 ** application can specify an alternative memory allocation subsystem
1657 ** for SQLite to use for all of its dynamic memory needs.
1658 **
1659 ** Note that SQLite comes with a built-in memory allocator that is
1660 ** perfectly adequate for the overwhelming majority of applications
1661 ** and that this object is only useful to a tiny minority of applications
1662 ** with specialized memory allocation requirements.  This object is
1663 ** also used during testing of SQLite in order to specify an alternative
1664 ** memory allocator that simulates memory out-of-memory conditions in
1665 ** order to verify that SQLite recovers gracefully from such
1666 ** conditions.
1667 **
1668 ** The xMalloc, xFree, and xRealloc methods must work like the
1669 ** malloc(), free(), and realloc() functions from the standard library.
1670 **
1671 ** xSize should return the allocated size of a memory allocation
1672 ** previously obtained from xMalloc or xRealloc.  The allocated size
1673 ** is always at least as big as the requested size but may be larger.
1674 **
1675 ** The xRoundup method returns what would be the allocated size of
1676 ** a memory allocation given a particular requested size.  Most memory
1677 ** allocators round up memory allocations at least to the next multiple
1678 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1679 **
1680 ** The xInit method initializes the memory allocator.  (For example,
1681 ** it might allocate any require mutexes or initialize internal data
1682 ** structures.  The xShutdown method is invoked (indirectly) by
1683 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1684 ** by xInit.  The pAppData pointer is used as the only parameter to
1685 ** xInit and xShutdown.
1686 */
1687 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1688 struct sqlite3_mem_methods {
1689   void *(*xMalloc)(int);         /* Memory allocation function */
1690   void (*xFree)(void*);          /* Free a prior allocation */
1691   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1692   int (*xSize)(void*);           /* Return the size of an allocation */
1693   int (*xRoundup)(int);          /* Round up request size to allocation size */
1694   int (*xInit)(void*);           /* Initialize the memory allocator */
1695   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1696   void *pAppData;                /* Argument to xInit() and xShutdown() */
1697 };
1698
1699 /*
1700 ** CAPI3REF: Configuration Options {H10160} <S20000>
1701 ** EXPERIMENTAL
1702 **
1703 ** These constants are the available integer configuration options that
1704 ** can be passed as the first argument to the [sqlite3_config()] interface.
1705 **
1706 ** New configuration options may be added in future releases of SQLite.
1707 ** Existing configuration options might be discontinued.  Applications
1708 ** should check the return code from [sqlite3_config()] to make sure that
1709 ** the call worked.  The [sqlite3_config()] interface will return a
1710 ** non-zero [error code] if a discontinued or unsupported configuration option
1711 ** is invoked.
1712 **
1713 ** <dl>
1714 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1715 ** <dd>There are no arguments to this option.  This option disables
1716 ** all mutexing and puts SQLite into a mode where it can only be used
1717 ** by a single thread.</dd>
1718 **
1719 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1720 ** <dd>There are no arguments to this option.  This option disables
1721 ** mutexing on [database connection] and [prepared statement] objects.
1722 ** The application is responsible for serializing access to
1723 ** [database connections] and [prepared statements].  But other mutexes
1724 ** are enabled so that SQLite will be safe to use in a multi-threaded
1725 ** environment as long as no two threads attempt to use the same
1726 ** [database connection] at the same time.  See the [threading mode]
1727 ** documentation for additional information.</dd>
1728 **
1729 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1730 ** <dd>There are no arguments to this option.  This option enables
1731 ** all mutexes including the recursive
1732 ** mutexes on [database connection] and [prepared statement] objects.
1733 ** In this mode (which is the default when SQLite is compiled with
1734 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1735 ** to [database connections] and [prepared statements] so that the
1736 ** application is free to use the same [database connection] or the
1737 ** same [prepared statement] in different threads at the same time.
1738 ** See the [threading mode] documentation for additional information.</dd>
1739 **
1740 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1741 ** <dd>This option takes a single argument which is a pointer to an
1742 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1743 ** alternative low-level memory allocation routines to be used in place of
1744 ** the memory allocation routines built into SQLite.</dd>
1745 **
1746 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1747 ** <dd>This option takes a single argument which is a pointer to an
1748 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1749 ** structure is filled with the currently defined memory allocation routines.
1750 ** This option can be used to overload the default memory allocation
1751 ** routines with a wrapper that simulations memory allocation failure or
1752 ** tracks memory usage, for example.</dd>
1753 **
1754 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1755 ** <dd>This option takes single argument of type int, interpreted as a 
1756 ** boolean, which enables or disables the collection of memory allocation 
1757 ** statistics. When disabled, the following SQLite interfaces become 
1758 ** non-operational:
1759 **   <ul>
1760 **   <li> [sqlite3_memory_used()]
1761 **   <li> [sqlite3_memory_highwater()]
1762 **   <li> [sqlite3_soft_heap_limit()]
1763 **   <li> [sqlite3_status()]
1764 **   </ul>
1765 ** </dd>
1766 **
1767 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1768 ** <dd>This option specifies a static memory buffer that SQLite can use for
1769 ** scratch memory.  There are three arguments:  A pointer to the memory, the
1770 ** size of each scratch buffer (sz), and the number of buffers (N).  The sz
1771 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1772 ** larger than the actual scratch space required due internal overhead.
1773 ** The first
1774 ** argument should point to an allocation of at least sz*N bytes of memory.
1775 ** SQLite will use no more than one scratch buffer at once per thread, so
1776 ** N should be set to the expected maximum number of threads.  The sz
1777 ** parameter should be 6 times the size of the largest database page size.
1778 ** Scratch buffers are used as part of the btree balance operation.  If
1779 ** The btree balancer needs additional memory beyond what is provided by
1780 ** scratch buffers or if no scratch buffer space is specified, then SQLite
1781 ** goes to [sqlite3_malloc()] to obtain the memory it needs.</dd>
1782 **
1783 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1784 ** <dd>This option specifies a static memory buffer that SQLite can use for
1785 ** the database page cache with the default page cache implemenation.  
1786 ** This configuration should not be used if an application-define page
1787 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1788 ** There are three arguments to this option: A pointer to the
1789 ** memory, the size of each page buffer (sz), and the number of pages (N).
1790 ** The sz argument must be a power of two between 512 and 32768.  The first
1791 ** argument should point to an allocation of at least sz*N bytes of memory.
1792 ** SQLite will use the memory provided by the first argument to satisfy its
1793 ** memory needs for the first N pages that it adds to cache.  If additional
1794 ** page cache memory is needed beyond what is provided by this option, then
1795 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1796 ** The implementation might use one or more of the N buffers to hold 
1797 ** memory accounting information. </dd>
1798 **
1799 ** <dt>SQLITE_CONFIG_HEAP</dt>
1800 ** <dd>This option specifies a static memory buffer that SQLite will use
1801 ** for all of its dynamic memory allocation needs beyond those provided
1802 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1803 ** There are three arguments: A pointer to the memory, the number of
1804 ** bytes in the memory buffer, and the minimum allocation size.  If
1805 ** the first pointer (the memory pointer) is NULL, then SQLite reverts
1806 ** to using its default memory allocator (the system malloc() implementation),
1807 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  If the
1808 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1809 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1810 ** allocator is engaged to handle all of SQLites memory allocation needs.</dd>
1811 **
1812 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1813 ** <dd>This option takes a single argument which is a pointer to an
1814 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1815 ** alternative low-level mutex routines to be used in place
1816 ** the mutex routines built into SQLite.</dd>
1817 **
1818 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1819 ** <dd>This option takes a single argument which is a pointer to an
1820 ** instance of the [sqlite3_mutex_methods] structure.  The
1821 ** [sqlite3_mutex_methods]
1822 ** structure is filled with the currently defined mutex routines.
1823 ** This option can be used to overload the default mutex allocation
1824 ** routines with a wrapper used to track mutex usage for performance
1825 ** profiling or testing, for example.</dd>
1826 **
1827 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1828 ** <dd>This option takes two arguments that determine the default
1829 ** memory allcation lookaside optimization.  The first argument is the
1830 ** size of each lookaside buffer slot and the second is the number of
1831 ** slots allocated to each database connection.</dd>
1832 **
1833 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1834 ** <dd>This option takes a single argument which is a pointer to
1835 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1836 ** to a custom page cache implementation.  SQLite makes a copy of the
1837 ** object and uses it for page cache memory allocations.</dd>
1838 **
1839 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1840 ** <dd>This option takes a single argument which is a pointer to an
1841 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1842 ** page cache implementation into that object.</dd>
1843 **
1844 ** </dl>
1845 */
1846 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1847 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1848 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1849 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1850 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1851 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1852 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1853 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1854 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1855 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1856 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1857 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1858 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1859 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1860 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1861
1862 /*
1863 ** CAPI3REF: Configuration Options {H10170} <S20000>
1864 ** EXPERIMENTAL
1865 **
1866 ** These constants are the available integer configuration options that
1867 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1868 **
1869 ** New configuration options may be added in future releases of SQLite.
1870 ** Existing configuration options might be discontinued.  Applications
1871 ** should check the return code from [sqlite3_db_config()] to make sure that
1872 ** the call worked.  The [sqlite3_db_config()] interface will return a
1873 ** non-zero [error code] if a discontinued or unsupported configuration option
1874 ** is invoked.
1875 **
1876 ** <dl>
1877 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1878 ** <dd>This option takes three additional arguments that determine the 
1879 ** [lookaside memory allocator] configuration for the [database connection].
1880 ** The first argument (the third parameter to [sqlite3_db_config()] is a
1881 ** pointer to a memory buffer to use for lookaside memory.  The first
1882 ** argument may be NULL in which case SQLite will allocate the lookaside
1883 ** buffer itself using [sqlite3_malloc()].  The second argument is the
1884 ** size of each lookaside buffer slot and the third argument is the number of
1885 ** slots.  The size of the buffer in the first argument must be greater than
1886 ** or equal to the product of the second and third arguments.</dd>
1887 **
1888 ** </dl>
1889 */
1890 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1891
1892
1893 /*
1894 ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} <S10700>
1895 **
1896 ** The sqlite3_extended_result_codes() routine enables or disables the
1897 ** [extended result codes] feature of SQLite. The extended result
1898 ** codes are disabled by default for historical compatibility considerations.
1899 **
1900 ** INVARIANTS:
1901 **
1902 ** {H12201} Each new [database connection] shall have the
1903 **          [extended result codes] feature disabled by default.
1904 **
1905 ** {H12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable
1906 **          [extended result codes] for the  [database connection] D
1907 **          if the F parameter is true, or disable them if F is false.
1908 */
1909 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1910
1911 /*
1912 ** CAPI3REF: Last Insert Rowid {H12220} <S10700>
1913 **
1914 ** Each entry in an SQLite table has a unique 64-bit signed
1915 ** integer key called the [ROWID | "rowid"]. The rowid is always available
1916 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1917 ** names are not also used by explicitly declared columns. If
1918 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1919 ** is another alias for the rowid.
1920 **
1921 ** This routine returns the [rowid] of the most recent
1922 ** successful [INSERT] into the database from the [database connection]
1923 ** in the first argument.  If no successful [INSERT]s
1924 ** have ever occurred on that database connection, zero is returned.
1925 **
1926 ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1927 ** row is returned by this routine as long as the trigger is running.
1928 ** But once the trigger terminates, the value returned by this routine
1929 ** reverts to the last value inserted before the trigger fired.
1930 **
1931 ** An [INSERT] that fails due to a constraint violation is not a
1932 ** successful [INSERT] and does not change the value returned by this
1933 ** routine.  Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1934 ** and INSERT OR ABORT make no changes to the return value of this
1935 ** routine when their insertion fails.  When INSERT OR REPLACE
1936 ** encounters a constraint violation, it does not fail.  The
1937 ** INSERT continues to completion after deleting rows that caused
1938 ** the constraint problem so INSERT OR REPLACE will always change
1939 ** the return value of this interface.
1940 **
1941 ** For the purposes of this routine, an [INSERT] is considered to
1942 ** be successful even if it is subsequently rolled back.
1943 **
1944 ** INVARIANTS:
1945 **
1946 ** {H12221} The [sqlite3_last_insert_rowid()] function shall return
1947 **          the [rowid]
1948 **          of the most recent successful [INSERT] performed on the same
1949 **          [database connection] and within the same or higher level
1950 **          trigger context, or zero if there have been no qualifying
1951 **          [INSERT] statements.
1952 **
1953 ** {H12223} The [sqlite3_last_insert_rowid()] function shall return the
1954 **          same value when called from the same trigger context
1955 **          immediately before and after a [ROLLBACK].
1956 **
1957 ** ASSUMPTIONS:
1958 **
1959 ** {A12232} If a separate thread performs a new [INSERT] on the same
1960 **          database connection while the [sqlite3_last_insert_rowid()]
1961 **          function is running and thus changes the last insert [rowid],
1962 **          then the value returned by [sqlite3_last_insert_rowid()] is
1963 **          unpredictable and might not equal either the old or the new
1964 **          last insert [rowid].
1965 */
1966 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1967
1968 /*
1969 ** CAPI3REF: Count The Number Of Rows Modified {H12240} <S10600>
1970 **
1971 ** This function returns the number of database rows that were changed
1972 ** or inserted or deleted by the most recently completed SQL statement
1973 ** on the [database connection] specified by the first parameter.
1974 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1975 ** or [DELETE] statement are counted.  Auxiliary changes caused by
1976 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1977 ** to find the total number of changes including changes caused by triggers.
1978 **
1979 ** A "row change" is a change to a single row of a single table
1980 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1981 ** are changed as side effects of REPLACE constraint resolution,
1982 ** rollback, ABORT processing, DROP TABLE, or by any other
1983 ** mechanisms do not count as direct row changes.
1984 **
1985 ** A "trigger context" is a scope of execution that begins and
1986 ** ends with the script of a trigger.  Most SQL statements are
1987 ** evaluated outside of any trigger.  This is the "top level"
1988 ** trigger context.  If a trigger fires from the top level, a
1989 ** new trigger context is entered for the duration of that one
1990 ** trigger.  Subtriggers create subcontexts for their duration.
1991 **
1992 ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1993 ** not create a new trigger context.
1994 **
1995 ** This function returns the number of direct row changes in the
1996 ** most recent INSERT, UPDATE, or DELETE statement within the same
1997 ** trigger context.
1998 **
1999 ** Thus, when called from the top level, this function returns the
2000 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2001 ** that also occurred at the top level.  Within the body of a trigger,
2002 ** the sqlite3_changes() interface can be called to find the number of
2003 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2004 ** statement within the body of the same trigger.
2005 ** However, the number returned does not include changes
2006 ** caused by subtriggers since those have their own context.
2007 **
2008 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
2009 ** by dropping and recreating the table.  Doing so is much faster than going
2010 ** through and deleting individual elements from the table.  Because of this
2011 ** optimization, the deletions in "DELETE FROM table" are not row changes and
2012 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
2013 ** functions, regardless of the number of elements that were originally
2014 ** in the table.  To get an accurate count of the number of rows deleted, use
2015 ** "DELETE FROM table WHERE 1" instead.  Or recompile using the
2016 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
2017 ** optimization on all queries.
2018 **
2019 ** INVARIANTS:
2020 **
2021 ** {H12241} The [sqlite3_changes()] function shall return the number of
2022 **          row changes caused by the most recent INSERT, UPDATE,
2023 **          or DELETE statement on the same database connection and
2024 **          within the same or higher trigger context, or zero if there have
2025 **          not been any qualifying row changes.
2026 **
2027 ** {H12243} Statements of the form "DELETE FROM tablename" with no
2028 **          WHERE clause shall cause subsequent calls to
2029 **          [sqlite3_changes()] to return zero, regardless of the
2030 **          number of rows originally in the table.
2031 **
2032 ** ASSUMPTIONS:
2033 **
2034 ** {A12252} If a separate thread makes changes on the same database connection
2035 **          while [sqlite3_changes()] is running then the value returned
2036 **          is unpredictable and not meaningful.
2037 */
2038 SQLITE_API int sqlite3_changes(sqlite3*);
2039
2040 /*
2041 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
2042 **
2043 ** This function returns the number of row changes caused by INSERT,
2044 ** UPDATE or DELETE statements since the [database connection] was opened.
2045 ** The count includes all changes from all trigger contexts.  However,
2046 ** the count does not include changes used to implement REPLACE constraints,
2047 ** do rollbacks or ABORT processing, or DROP table processing.
2048 ** The changes are counted as soon as the statement that makes them is
2049 ** completed (when the statement handle is passed to [sqlite3_reset()] or
2050 ** [sqlite3_finalize()]).
2051 **
2052 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
2053 ** by dropping and recreating the table.  (This is much faster than going
2054 ** through and deleting individual elements from the table.)  Because of this
2055 ** optimization, the deletions in "DELETE FROM table" are not row changes and
2056 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
2057 ** functions, regardless of the number of elements that were originally
2058 ** in the table.  To get an accurate count of the number of rows deleted, use
2059 ** "DELETE FROM table WHERE 1" instead.   Or recompile using the
2060 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
2061 ** optimization on all queries.
2062 **
2063 ** See also the [sqlite3_changes()] interface.
2064 **
2065 ** INVARIANTS:
2066 **
2067 ** {H12261} The [sqlite3_total_changes()] returns the total number
2068 **          of row changes caused by INSERT, UPDATE, and/or DELETE
2069 **          statements on the same [database connection], in any
2070 **          trigger context, since the database connection was created.
2071 **
2072 ** {H12263} Statements of the form "DELETE FROM tablename" with no
2073 **          WHERE clause shall not change the value returned
2074 **          by [sqlite3_total_changes()].
2075 **
2076 ** ASSUMPTIONS:
2077 **
2078 ** {A12264} If a separate thread makes changes on the same database connection
2079 **          while [sqlite3_total_changes()] is running then the value
2080 **          returned is unpredictable and not meaningful.
2081 */
2082 SQLITE_API int sqlite3_total_changes(sqlite3*);
2083
2084 /*
2085 ** CAPI3REF: Interrupt A Long-Running Query {H12270} <S30500>
2086 **
2087 ** This function causes any pending database operation to abort and
2088 ** return at its earliest opportunity. This routine is typically
2089 ** called in response to a user action such as pressing "Cancel"
2090 ** or Ctrl-C where the user wants a long query operation to halt
2091 ** immediately.
2092 **
2093 ** It is safe to call this routine from a thread different from the
2094 ** thread that is currently running the database operation.  But it
2095 ** is not safe to call this routine with a [database connection] that
2096 ** is closed or might close before sqlite3_interrupt() returns.
2097 **
2098 ** If an SQL operation is very nearly finished at the time when
2099 ** sqlite3_interrupt() is called, then it might not have an opportunity
2100 ** to be interrupted and might continue to completion.
2101 **
2102 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2103 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2104 ** that is inside an explicit transaction, then the entire transaction
2105 ** will be rolled back automatically.
2106 **
2107 ** A call to sqlite3_interrupt() has no effect on SQL statements
2108 ** that are started after sqlite3_interrupt() returns.
2109 **
2110 ** INVARIANTS:
2111 **
2112 ** {H12271} The [sqlite3_interrupt()] interface will force all running
2113 **          SQL statements associated with the same database connection
2114 **          to halt after processing at most one additional row of data.
2115 **
2116 ** {H12272} Any SQL statement that is interrupted by [sqlite3_interrupt()]
2117 **          will return [SQLITE_INTERRUPT].
2118 **
2119 ** ASSUMPTIONS:
2120 **
2121 ** {A12279} If the database connection closes while [sqlite3_interrupt()]
2122 **          is running then bad things will likely happen.
2123 */
2124 SQLITE_API void sqlite3_interrupt(sqlite3*);
2125
2126 /*
2127 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
2128 **
2129 ** These routines are useful for command-line input to determine if the
2130 ** currently entered text seems to form complete a SQL statement or
2131 ** if additional input is needed before sending the text into
2132 ** SQLite for parsing.  These routines return true if the input string
2133 ** appears to be a complete SQL statement.  A statement is judged to be
2134 ** complete if it ends with a semicolon token and is not a fragment of a
2135 ** CREATE TRIGGER statement.  Semicolons that are embedded within
2136 ** string literals or quoted identifier names or comments are not
2137 ** independent tokens (they are part of the token in which they are
2138 ** embedded) and thus do not count as a statement terminator.
2139 **
2140 ** These routines do not parse the SQL statements thus
2141 ** will not detect syntactically incorrect SQL.
2142 **
2143 ** INVARIANTS:
2144 **
2145 ** {H10511} A successful evaluation of [sqlite3_complete()] or
2146 **          [sqlite3_complete16()] functions shall
2147 **          return a numeric 1 if and only if the last non-whitespace
2148 **          token in their input is a semicolon that is not in between
2149 **          the BEGIN and END of a CREATE TRIGGER statement.
2150 **
2151 ** {H10512} If a memory allocation error occurs during an invocation
2152 **          of [sqlite3_complete()] or [sqlite3_complete16()] then the
2153 **          routine shall return [SQLITE_NOMEM].
2154 **
2155 ** ASSUMPTIONS:
2156 **
2157 ** {A10512} The input to [sqlite3_complete()] must be a zero-terminated
2158 **          UTF-8 string.
2159 **
2160 ** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated
2161 **          UTF-16 string in native byte order.
2162 */
2163 SQLITE_API int sqlite3_complete(const char *sql);
2164 SQLITE_API int sqlite3_complete16(const void *sql);
2165
2166 /*
2167 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} <S40400>
2168 **
2169 ** This routine sets a callback function that might be invoked whenever
2170 ** an attempt is made to open a database table that another thread
2171 ** or process has locked.
2172 **
2173 ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2174 ** is returned immediately upon encountering the lock. If the busy callback
2175 ** is not NULL, then the callback will be invoked with two arguments.
2176 **
2177 ** The first argument to the handler is a copy of the void* pointer which
2178 ** is the third argument to sqlite3_busy_handler().  The second argument to
2179 ** the handler callback is the number of times that the busy handler has
2180 ** been invoked for this locking event.  If the
2181 ** busy callback returns 0, then no additional attempts are made to
2182 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2183 ** If the callback returns non-zero, then another attempt
2184 ** is made to open the database for reading and the cycle repeats.
2185 **
2186 ** The presence of a busy handler does not guarantee that it will be invoked
2187 ** when there is lock contention. If SQLite determines that invoking the busy
2188 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2189 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2190 ** Consider a scenario where one process is holding a read lock that
2191 ** it is trying to promote to a reserved lock and
2192 ** a second process is holding a reserved lock that it is trying
2193 ** to promote to an exclusive lock.  The first process cannot proceed
2194 ** because it is blocked by the second and the second process cannot
2195 ** proceed because it is blocked by the first.  If both processes
2196 ** invoke the busy handlers, neither will make any progress.  Therefore,
2197 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2198 ** will induce the first process to release its read lock and allow
2199 ** the second process to proceed.
2200 **
2201 ** The default busy callback is NULL.
2202 **
2203 ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2204 ** when SQLite is in the middle of a large transaction where all the
2205 ** changes will not fit into the in-memory cache.  SQLite will
2206 ** already hold a RESERVED lock on the database file, but it needs
2207 ** to promote this lock to EXCLUSIVE so that it can spill cache
2208 ** pages into the database file without harm to concurrent
2209 ** readers.  If it is unable to promote the lock, then the in-memory
2210 ** cache will be left in an inconsistent state and so the error
2211 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2212 ** the more severe [SQLITE_IOERR_BLOCKED].  This error code promotion
2213 ** forces an automatic rollback of the changes.  See the
2214 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2215 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2216 ** this is important.
2217 **
2218 ** There can only be a single busy handler defined for each
2219 ** [database connection].  Setting a new busy handler clears any
2220 ** previously set handler.  Note that calling [sqlite3_busy_timeout()]
2221 ** will also set or clear the busy handler.
2222 **
2223 ** The busy callback should not take any actions which modify the
2224 ** database connection that invoked the busy handler.  Any such actions
2225 ** result in undefined behavior.
2226 ** 
2227 ** INVARIANTS:
2228 **
2229 ** {H12311} The [sqlite3_busy_handler(D,C,A)] function shall replace
2230 **          busy callback in the [database connection] D with a new
2231 **          a new busy handler C and application data pointer A.
2232 **
2233 ** {H12312} Newly created [database connections] shall have a busy
2234 **          handler of NULL.
2235 **
2236 ** {H12314} When two or more [database connections] share a
2237 **          [sqlite3_enable_shared_cache | common cache],
2238 **          the busy handler for the database connection currently using
2239 **          the cache shall be invoked when the cache encounters a lock.
2240 **
2241 ** {H12316} If a busy handler callback returns zero, then the SQLite interface
2242 **          that provoked the locking event shall return [SQLITE_BUSY].
2243 **
2244 ** {H12318} SQLite shall invokes the busy handler with two arguments which
2245 **          are a copy of the pointer supplied by the 3rd parameter to
2246 **          [sqlite3_busy_handler()] and a count of the number of prior
2247 **          invocations of the busy handler for the same locking event.
2248 **
2249 ** ASSUMPTIONS:
2250 **
2251 ** {A12319} A busy handler must not close the database connection
2252 **          or [prepared statement] that invoked the busy handler.
2253 */
2254 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2255
2256 /*
2257 ** CAPI3REF: Set A Busy Timeout {H12340} <S40410>
2258 **
2259 ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2260 ** for a specified amount of time when a table is locked.  The handler
2261 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2262 ** have accumulated. {H12343} After "ms" milliseconds of sleeping,
2263 ** the handler returns 0 which causes [sqlite3_step()] to return
2264 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2265 **
2266 ** Calling this routine with an argument less than or equal to zero
2267 ** turns off all busy handlers.
2268 **
2269 ** There can only be a single busy handler for a particular
2270 ** [database connection] any any given moment.  If another busy handler
2271 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2272 ** this routine, that other busy handler is cleared.
2273 **
2274 ** INVARIANTS:
2275 **
2276 ** {H12341} The [sqlite3_busy_timeout()] function shall override any prior
2277 **          [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting
2278 **          on the same [database connection].
2279 **
2280 ** {H12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than
2281 **          or equal to zero, then the busy handler shall be cleared so that
2282 **          all subsequent locking events immediately return [SQLITE_BUSY].
2283 **
2284 ** {H12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive
2285 **          number N, then a busy handler shall be set that repeatedly calls
2286 **          the xSleep() method in the [sqlite3_vfs | VFS interface] until
2287 **          either the lock clears or until the cumulative sleep time
2288 **          reported back by xSleep() exceeds N milliseconds.
2289 */
2290 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2291
2292 /*
2293 ** CAPI3REF: Convenience Routines For Running Queries {H12370} <S10000>
2294 **
2295 ** Definition: A <b>result table</b> is memory data structure created by the
2296 ** [sqlite3_get_table()] interface.  A result table records the
2297 ** complete query results from one or more queries.
2298 **
2299 ** The table conceptually has a number of rows and columns.  But
2300 ** these numbers are not part of the result table itself.  These
2301 ** numbers are obtained separately.  Let N be the number of rows
2302 ** and M be the number of columns.
2303 **
2304 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2305 ** There are (N+1)*M elements in the array.  The first M pointers point
2306 ** to zero-terminated strings that  contain the names of the columns.
2307 ** The remaining entries all point to query results.  NULL values result
2308 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2309 ** string representation as returned by [sqlite3_column_text()].
2310 **
2311 ** A result table might consist of one or more memory allocations.
2312 ** It is not safe to pass a result table directly to [sqlite3_free()].
2313 ** A result table should be deallocated using [sqlite3_free_table()].
2314 **
2315 ** As an example of the result table format, suppose a query result
2316 ** is as follows:
2317 **
2318 ** <blockquote><pre>
2319 **        Name        | Age
2320 **        -----------------------
2321 **        Alice       | 43
2322 **        Bob         | 28
2323 **        Cindy       | 21
2324 ** </pre></blockquote>
2325 **
2326 ** There are two column (M==2) and three rows (N==3).  Thus the
2327 ** result table has 8 entries.  Suppose the result table is stored
2328 ** in an array names azResult.  Then azResult holds this content:
2329 **
2330 ** <blockquote><pre>
2331 **        azResult&#91;0] = "Name";
2332 **        azResult&#91;1] = "Age";
2333 **        azResult&#91;2] = "Alice";
2334 **        azResult&#91;3] = "43";
2335 **        azResult&#91;4] = "Bob";
2336 **        azResult&#91;5] = "28";
2337 **        azResult&#91;6] = "Cindy";
2338 **        azResult&#91;7] = "21";
2339 ** </pre></blockquote>
2340 **
2341 ** The sqlite3_get_table() function evaluates one or more
2342 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2343 ** string of its 2nd parameter.  It returns a result table to the
2344 ** pointer given in its 3rd parameter.
2345 **
2346 ** After the calling function has finished using the result, it should
2347 ** pass the pointer to the result table to sqlite3_free_table() in order to
2348 ** release the memory that was malloced.  Because of the way the
2349 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2350 ** function must not try to call [sqlite3_free()] directly.  Only
2351 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2352 **
2353 ** The sqlite3_get_table() interface is implemented as a wrapper around
2354 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2355 ** to any internal data structures of SQLite.  It uses only the public
2356 ** interface defined here.  As a consequence, errors that occur in the
2357 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2358 ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()].
2359 **
2360 ** INVARIANTS:
2361 **
2362 ** {H12371} If a [sqlite3_get_table()] fails a memory allocation, then
2363 **          it shall free the result table under construction, abort the
2364 **          query in process, skip any subsequent queries, set the
2365 **          *pazResult output pointer to NULL and return [SQLITE_NOMEM].
2366 **
2367 ** {H12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL
2368 **          then a successful invocation of [sqlite3_get_table()] shall
2369 **          write the number of columns in the
2370 **          result set of the query into *pnColumn.
2371 **
2372 ** {H12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL
2373 **          then a successful invocation of [sqlite3_get_table()] shall
2374 **          writes the number of rows in the
2375 **          result set of the query into *pnRow.
2376 **
2377 ** {H12376} A successful invocation of [sqlite3_get_table()] that computes
2378 **          N rows of result with C columns per row shall make *pazResult
2379 **          point to an array of pointers to (N+1)*C strings where the first
2380 **          C strings are column names as obtained from
2381 **          [sqlite3_column_name()] and the rest are column result values
2382 **          obtained from [sqlite3_column_text()].
2383 **
2384 ** {H12379} The values in the pazResult array returned by [sqlite3_get_table()]
2385 **          shall remain valid until cleared by [sqlite3_free_table()].
2386 **
2387 ** {H12382} When an error occurs during evaluation of [sqlite3_get_table()]
2388 **          the function shall set *pazResult to NULL, write an error message
2389 **          into memory obtained from [sqlite3_malloc()], make
2390 **          **pzErrmsg point to that error message, and return a
2391 **          appropriate [error code].
2392 */
2393 SQLITE_API int sqlite3_get_table(
2394   sqlite3 *db,          /* An open database */
2395   const char *zSql,     /* SQL to be evaluated */
2396   char ***pazResult,    /* Results of the query */
2397   int *pnRow,           /* Number of result rows written here */
2398   int *pnColumn,        /* Number of result columns written here */
2399   char **pzErrmsg       /* Error msg written here */
2400 );
2401 SQLITE_API void sqlite3_free_table(char **result);
2402
2403 /*
2404 ** CAPI3REF: Formatted String Printing Functions {H17400} <S70000><S20000>
2405 **
2406 ** These routines are workalikes of the "printf()" family of functions
2407 ** from the standard C library.
2408 **
2409 ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2410 ** results into memory obtained from [sqlite3_malloc()].
2411 ** The strings returned by these two routines should be
2412 ** released by [sqlite3_free()].  Both routines return a
2413 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2414 ** memory to hold the resulting string.
2415 **
2416 ** In sqlite3_snprintf() routine is similar to "snprintf()" from
2417 ** the standard C library.  The result is written into the
2418 ** buffer supplied as the second parameter whose size is given by
2419 ** the first parameter. Note that the order of the
2420 ** first two parameters is reversed from snprintf().  This is an
2421 ** historical accident that cannot be fixed without breaking
2422 ** backwards compatibility.  Note also that sqlite3_snprintf()
2423 ** returns a pointer to its buffer instead of the number of
2424 ** characters actually written into the buffer.  We admit that
2425 ** the number of characters written would be a more useful return
2426 ** value but we cannot change the implementation of sqlite3_snprintf()
2427 ** now without breaking compatibility.
2428 **
2429 ** As long as the buffer size is greater than zero, sqlite3_snprintf()
2430 ** guarantees that the buffer is always zero-terminated.  The first
2431 ** parameter "n" is the total size of the buffer, including space for
2432 ** the zero terminator.  So the longest string that can be completely
2433 ** written will be n-1 characters.
2434 **
2435 ** These routines all implement some additional formatting
2436 ** options that are useful for constructing SQL statements.
2437 ** All of the usual printf() formatting options apply.  In addition, there
2438 ** is are "%q", "%Q", and "%z" options.
2439 **
2440 ** The %q option works like %s in that it substitutes a null-terminated
2441 ** string from the argument list.  But %q also doubles every '\'' character.
2442 ** %q is designed for use inside a string literal.  By doubling each '\''
2443 ** character it escapes that character and allows it to be inserted into
2444 ** the string.
2445 **
2446 ** For example, assume the string variable zText contains text as follows:
2447 **
2448 ** <blockquote><pre>
2449 **  char *zText = "It's a happy day!";
2450 ** </pre></blockquote>
2451 **
2452 ** One can use this text in an SQL statement as follows:
2453 **
2454 ** <blockquote><pre>
2455 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2456 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2457 **  sqlite3_free(zSQL);
2458 ** </pre></blockquote>
2459 **
2460 ** Because the %q format string is used, the '\'' character in zText
2461 ** is escaped and the SQL generated is as follows:
2462 **
2463 ** <blockquote><pre>
2464 **  INSERT INTO table1 VALUES('It''s a happy day!')
2465 ** </pre></blockquote>
2466 **
2467 ** This is correct.  Had we used %s instead of %q, the generated SQL
2468 ** would have looked like this:
2469 **
2470 ** <blockquote><pre>
2471 **  INSERT INTO table1 VALUES('It's a happy day!');
2472 ** </pre></blockquote>
2473 **
2474 ** This second example is an SQL syntax error.  As a general rule you should
2475 ** always use %q instead of %s when inserting text into a string literal.
2476 **
2477 ** The %Q option works like %q except it also adds single quotes around
2478 ** the outside of the total string.  Additionally, if the parameter in the
2479 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2480 ** single quotes) in place of the %Q option.  So, for example, one could say:
2481 **
2482 ** <blockquote><pre>
2483 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2484 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2485 **  sqlite3_free(zSQL);
2486 ** </pre></blockquote>
2487 **
2488 ** The code above will render a correct SQL statement in the zSQL
2489 ** variable even if the zText variable is a NULL pointer.
2490 **
2491 ** The "%z" formatting option works exactly like "%s" with the
2492 ** addition that after the string has been read and copied into
2493 ** the result, [sqlite3_free()] is called on the input string. {END}
2494 **
2495 ** INVARIANTS:
2496 **
2497 ** {H17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
2498 **           return either pointers to zero-terminated UTF-8 strings held in
2499 **           memory obtained from [sqlite3_malloc()] or NULL pointers if
2500 **           a call to [sqlite3_malloc()] fails.
2501 **
2502 ** {H17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
2503 **           UTF-8 string into the buffer pointed to by the second parameter
2504 **           provided that the first parameter is greater than zero.
2505 **
2506 ** {H17407}  The [sqlite3_snprintf()] interface does not write slots of
2507 **           its output buffer (the second parameter) outside the range
2508 **           of 0 through N-1 (where N is the first parameter)
2509 **           regardless of the length of the string
2510 **           requested by the format specification.
2511 */
2512 SQLITE_API char *sqlite3_mprintf(const char*,...);
2513 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2514 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2515
2516 /*
2517 ** CAPI3REF: Memory Allocation Subsystem {H17300} <S20000>
2518 **
2519 ** The SQLite core  uses these three routines for all of its own
2520 ** internal memory allocation needs. "Core" in the previous sentence
2521 ** does not include operating-system specific VFS implementation.  The
2522 ** Windows VFS uses native malloc() and free() for some operations.
2523 **
2524 ** The sqlite3_malloc() routine returns a pointer to a block
2525 ** of memory at least N bytes in length, where N is the parameter.
2526 ** If sqlite3_malloc() is unable to obtain sufficient free
2527 ** memory, it returns a NULL pointer.  If the parameter N to
2528 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2529 ** a NULL pointer.
2530 **
2531 ** Calling sqlite3_free() with a pointer previously returned
2532 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2533 ** that it might be reused.  The sqlite3_free() routine is
2534 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2535 ** to sqlite3_free() is harmless.  After being freed, memory
2536 ** should neither be read nor written.  Even reading previously freed
2537 ** memory might result in a segmentation fault or other severe error.
2538 ** Memory corruption, a segmentation fault, or other severe error
2539 ** might result if sqlite3_free() is called with a non-NULL pointer that
2540 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2541 **
2542 ** The sqlite3_realloc() interface attempts to resize a
2543 ** prior memory allocation to be at least N bytes, where N is the
2544 ** second parameter.  The memory allocation to be resized is the first
2545 ** parameter.  If the first parameter to sqlite3_realloc()
2546 ** is a NULL pointer then its behavior is identical to calling
2547 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2548 ** If the second parameter to sqlite3_realloc() is zero or
2549 ** negative then the behavior is exactly the same as calling
2550 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2551 ** sqlite3_realloc() returns a pointer to a memory allocation
2552 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2553 ** If M is the size of the prior allocation, then min(N,M) bytes
2554 ** of the prior allocation are copied into the beginning of buffer returned
2555 ** by sqlite3_realloc() and the prior allocation is freed.
2556 ** If sqlite3_realloc() returns NULL, then the prior allocation
2557 ** is not freed.
2558 **
2559 ** The memory returned by sqlite3_malloc() and sqlite3_realloc()
2560 ** is always aligned to at least an 8 byte boundary. {END}
2561 **
2562 ** The default implementation of the memory allocation subsystem uses
2563 ** the malloc(), realloc() and free() provided by the standard C library.
2564 ** {H17382} However, if SQLite is compiled with the
2565 ** SQLITE_MEMORY_SIZE=<i>NNN</i> C preprocessor macro (where <i>NNN</i>
2566 ** is an integer), then SQLite create a static array of at least
2567 ** <i>NNN</i> bytes in size and uses that array for all of its dynamic
2568 ** memory allocation needs. {END}  Additional memory allocator options
2569 ** may be added in future releases.
2570 **
2571 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2572 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2573 ** implementation of these routines to be omitted.  That capability
2574 ** is no longer provided.  Only built-in memory allocators can be used.
2575 **
2576 ** The Windows OS interface layer calls
2577 ** the system malloc() and free() directly when converting
2578 ** filenames between the UTF-8 encoding used by SQLite
2579 ** and whatever filename encoding is used by the particular Windows
2580 ** installation.  Memory allocation errors are detected, but
2581 ** they are reported back as [SQLITE_CANTOPEN] or
2582 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2583 **
2584 ** INVARIANTS:
2585 **
2586 ** {H17303}  The [sqlite3_malloc(N)] interface returns either a pointer to
2587 **           a newly checked-out block of at least N bytes of memory
2588 **           that is 8-byte aligned, or it returns NULL if it is unable
2589 **           to fulfill the request.
2590 **
2591 ** {H17304}  The [sqlite3_malloc(N)] interface returns a NULL pointer if
2592 **           N is less than or equal to zero.
2593 **
2594 ** {H17305}  The [sqlite3_free(P)] interface releases memory previously
2595 **           returned from [sqlite3_malloc()] or [sqlite3_realloc()],
2596 **           making it available for reuse.
2597 **
2598 ** {H17306}  A call to [sqlite3_free(NULL)] is a harmless no-op.
2599 **
2600 ** {H17310}  A call to [sqlite3_realloc(0,N)] is equivalent to a call
2601 **           to [sqlite3_malloc(N)].
2602 **
2603 ** {H17312}  A call to [sqlite3_realloc(P,0)] is equivalent to a call
2604 **           to [sqlite3_free(P)].
2605 **
2606 ** {H17315}  The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()],
2607 **           and [sqlite3_free()] for all of its memory allocation and
2608 **           deallocation needs.
2609 **
2610 ** {H17318}  The [sqlite3_realloc(P,N)] interface returns either a pointer
2611 **           to a block of checked-out memory of at least N bytes in size
2612 **           that is 8-byte aligned, or a NULL pointer.
2613 **
2614 ** {H17321}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2615 **           copies the first K bytes of content from P into the newly
2616 **           allocated block, where K is the lesser of N and the size of
2617 **           the buffer P.
2618 **
2619 ** {H17322}  When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first
2620 **           releases the buffer P.
2621 **
2622 ** {H17323}  When [sqlite3_realloc(P,N)] returns NULL, the buffer P is
2623 **           not modified or released.
2624 **
2625 ** ASSUMPTIONS:
2626 **
2627 ** {A17350}  The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2628 **           must be either NULL or else pointers obtained from a prior
2629 **           invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2630 **           not yet been released.
2631 **
2632 ** {A17351}  The application must not read or write any part of
2633 **           a block of memory after it has been released using
2634 **           [sqlite3_free()] or [sqlite3_realloc()].
2635 */
2636 SQLITE_API void *sqlite3_malloc(int);
2637 SQLITE_API void *sqlite3_realloc(void*, int);
2638 SQLITE_API void sqlite3_free(void*);
2639
2640 /*
2641 ** CAPI3REF: Memory Allocator Statistics {H17370} <S30210>
2642 **
2643 ** SQLite provides these two interfaces for reporting on the status
2644 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2645 ** routines, which form the built-in memory allocation subsystem.
2646 **
2647 ** INVARIANTS:
2648 **
2649 ** {H17371} The [sqlite3_memory_used()] routine returns the number of bytes
2650 **          of memory currently outstanding (malloced but not freed).
2651 **
2652 ** {H17373} The [sqlite3_memory_highwater()] routine returns the maximum
2653 **          value of [sqlite3_memory_used()] since the high-water mark
2654 **          was last reset.
2655 **
2656 ** {H17374} The values returned by [sqlite3_memory_used()] and
2657 **          [sqlite3_memory_highwater()] include any overhead
2658 **          added by SQLite in its implementation of [sqlite3_malloc()],
2659 **          but not overhead added by the any underlying system library
2660 **          routines that [sqlite3_malloc()] may call.
2661 **
2662 ** {H17375} The memory high-water mark is reset to the current value of
2663 **          [sqlite3_memory_used()] if and only if the parameter to
2664 **          [sqlite3_memory_highwater()] is true.  The value returned
2665 **          by [sqlite3_memory_highwater(1)] is the high-water mark
2666 **          prior to the reset.
2667 */
2668 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2669 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2670
2671 /*
2672 ** CAPI3REF: Pseudo-Random Number Generator {H17390} <S20000>
2673 **
2674 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2675 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2676 ** already uses the largest possible [ROWID].  The PRNG is also used for
2677 ** the build-in random() and randomblob() SQL functions.  This interface allows
2678 ** applications to access the same PRNG for other purposes.
2679 **
2680 ** A call to this routine stores N bytes of randomness into buffer P.
2681 **
2682 ** The first time this routine is invoked (either internally or by
2683 ** the application) the PRNG is seeded using randomness obtained
2684 ** from the xRandomness method of the default [sqlite3_vfs] object.
2685 ** On all subsequent invocations, the pseudo-randomness is generated
2686 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2687 ** method.
2688 **
2689 ** INVARIANTS:
2690 **
2691 ** {H17392} The [sqlite3_randomness(N,P)] interface writes N bytes of
2692 **          high-quality pseudo-randomness into buffer P.
2693 */
2694 SQLITE_API void sqlite3_randomness(int N, void *P);
2695
2696 /*
2697 ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} <S70100>
2698 **
2699 ** This routine registers a authorizer callback with a particular
2700 ** [database connection], supplied in the first argument.
2701 ** The authorizer callback is invoked as SQL statements are being compiled
2702 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2703 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  At various
2704 ** points during the compilation process, as logic is being created
2705 ** to perform various actions, the authorizer callback is invoked to
2706 ** see if those actions are allowed.  The authorizer callback should
2707 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2708 ** specific action but allow the SQL statement to continue to be
2709 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2710 ** rejected with an error.  If the authorizer callback returns
2711 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2712 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2713 ** the authorizer will fail with an error message.
2714 **
2715 ** When the callback returns [SQLITE_OK], that means the operation
2716 ** requested is ok.  When the callback returns [SQLITE_DENY], the
2717 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2718 ** authorizer will fail with an error message explaining that
2719 ** access is denied.  If the authorizer code is [SQLITE_READ]
2720 ** and the callback returns [SQLITE_IGNORE] then the
2721 ** [prepared statement] statement is constructed to substitute
2722 ** a NULL value in place of the table column that would have
2723 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2724 ** return can be used to deny an untrusted user access to individual
2725 ** columns of a table.
2726 **
2727 ** The first parameter to the authorizer callback is a copy of the third
2728 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2729 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2730 ** the particular action to be authorized. The third through sixth parameters
2731 ** to the callback are zero-terminated strings that contain additional
2732 ** details about the action to be authorized.
2733 **
2734 ** An authorizer is used when [sqlite3_prepare | preparing]
2735 ** SQL statements from an untrusted source, to ensure that the SQL statements
2736 ** do not try to access data they are not allowed to see, or that they do not
2737 ** try to execute malicious statements that damage the database.  For
2738 ** example, an application may allow a user to enter arbitrary
2739 ** SQL queries for evaluation by a database.  But the application does
2740 ** not want the user to be able to make arbitrary changes to the
2741 ** database.  An authorizer could then be put in place while the
2742 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2743 ** disallows everything except [SELECT] statements.
2744 **
2745 ** Applications that need to process SQL from untrusted sources
2746 ** might also consider lowering resource limits using [sqlite3_limit()]
2747 ** and limiting database size using the [max_page_count] [PRAGMA]
2748 ** in addition to using an authorizer.
2749 **
2750 ** Only a single authorizer can be in place on a database connection
2751 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2752 ** previous call.  Disable the authorizer by installing a NULL callback.
2753 ** The authorizer is disabled by default.
2754 **
2755 ** The authorizer callback must not do anything that will modify
2756 ** the database connection that invoked the authorizer callback.
2757 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2758 ** database connections for the meaning of "modify" in this paragraph.
2759 **
2760 ** When [sqlite3_prepare_v2()] is used to prepare a statement, the
2761 ** statement might be reprepared during [sqlite3_step()] due to a 
2762 ** schema change.  Hence, the application should ensure that the
2763 ** correct authorizer callback remains in place during the [sqlite3_step()].
2764 **
2765 ** Note that the authorizer callback is invoked only during
2766 ** [sqlite3_prepare()] or its variants.  Authorization is not
2767 ** performed during statement evaluation in [sqlite3_step()].
2768 **
2769 ** INVARIANTS:
2770 **
2771 ** {H12501} The [sqlite3_set_authorizer(D,...)] interface registers a
2772 **          authorizer callback with database connection D.
2773 **
2774 ** {H12502} The authorizer callback is invoked as SQL statements are
2775 **          being parseed and compiled.
2776 **
2777 ** {H12503} If the authorizer callback returns any value other than
2778 **          [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then
2779 **          the application interface call that caused
2780 **          the authorizer callback to run shall fail with an
2781 **          [SQLITE_ERROR] error code and an appropriate error message.
2782 **
2783 ** {H12504} When the authorizer callback returns [SQLITE_OK], the operation
2784 **          described is processed normally.
2785 **
2786 ** {H12505} When the authorizer callback returns [SQLITE_DENY], the
2787 **          application interface call that caused the
2788 **          authorizer callback to run shall fail
2789 **          with an [SQLITE_ERROR] error code and an error message
2790 **          explaining that access is denied.
2791 **
2792 ** {H12506} If the authorizer code (the 2nd parameter to the authorizer
2793 **          callback) is [SQLITE_READ] and the authorizer callback returns
2794 **          [SQLITE_IGNORE], then the prepared statement is constructed to
2795 **          insert a NULL value in place of the table column that would have
2796 **          been read if [SQLITE_OK] had been returned.
2797 **
2798 ** {H12507} If the authorizer code (the 2nd parameter to the authorizer
2799 **          callback) is anything other than [SQLITE_READ], then
2800 **          a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY].
2801 **
2802 ** {H12510} The first parameter to the authorizer callback is a copy of
2803 **          the third parameter to the [sqlite3_set_authorizer()] interface.
2804 **
2805 ** {H12511} The second parameter to the callback is an integer
2806 **          [SQLITE_COPY | action code] that specifies the particular action
2807 **          to be authorized.
2808 **
2809 ** {H12512} The third through sixth parameters to the callback are
2810 **          zero-terminated strings that contain
2811 **          additional details about the action to be authorized.
2812 **
2813 ** {H12520} Each call to [sqlite3_set_authorizer()] overrides
2814 **          any previously installed authorizer.
2815 **
2816 ** {H12521} A NULL authorizer means that no authorization
2817 **          callback is invoked.
2818 **
2819 ** {H12522} The default authorizer is NULL.
2820 */
2821 SQLITE_API int sqlite3_set_authorizer(
2822   sqlite3*,
2823   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2824   void *pUserData
2825 );
2826
2827 /*
2828 ** CAPI3REF: Authorizer Return Codes {H12590} <H12500>
2829 **
2830 ** The [sqlite3_set_authorizer | authorizer callback function] must
2831 ** return either [SQLITE_OK] or one of these two constants in order
2832 ** to signal SQLite whether or not the action is permitted.  See the
2833 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2834 ** information.
2835 */
2836 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2837 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2838
2839 /*
2840 ** CAPI3REF: Authorizer Action Codes {H12550} <H12500>
2841 **
2842 ** The [sqlite3_set_authorizer()] interface registers a callback function
2843 ** that is invoked to authorize certain SQL statement actions.  The
2844 ** second parameter to the callback is an integer code that specifies
2845 ** what action is being authorized.  These are the integer action codes that
2846 ** the authorizer callback may be passed.
2847 **
2848 ** These action code values signify what kind of operation is to be
2849 ** authorized.  The 3rd and 4th parameters to the authorization
2850 ** callback function will be parameters or NULL depending on which of these
2851 ** codes is used as the second parameter.  The 5th parameter to the
2852 ** authorizer callback is the name of the database ("main", "temp",
2853 ** etc.) if applicable.  The 6th parameter to the authorizer callback
2854 ** is the name of the inner-most trigger or view that is responsible for
2855 ** the access attempt or NULL if this access attempt is directly from
2856 ** top-level SQL code.
2857 **
2858 ** INVARIANTS:
2859 **
2860 ** {H12551} The second parameter to an
2861 **          [sqlite3_set_authorizer | authorizer callback] shall be an integer
2862 **          [SQLITE_COPY | authorizer code] that specifies what action
2863 **          is being authorized.
2864 **
2865 ** {H12552} The 3rd and 4th parameters to the
2866 **          [sqlite3_set_authorizer | authorization callback]
2867 **          shall be parameters or NULL depending on which
2868 **          [SQLITE_COPY | authorizer code] is used as the second parameter.
2869 **
2870 ** {H12553} The 5th parameter to the
2871 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2872 **          of the database (example: "main", "temp", etc.) if applicable.
2873 **
2874 ** {H12554} The 6th parameter to the
2875 **          [sqlite3_set_authorizer | authorizer callback] shall be the name
2876 **          of the inner-most trigger or view that is responsible for
2877 **          the access attempt or NULL if this access attempt is directly from
2878 **          top-level SQL code.
2879 */
2880 /******************************************* 3rd ************ 4th ***********/
2881 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2882 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2883 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2884 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2885 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2886 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2887 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2888 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2889 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2890 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2891 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2892 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2893 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2894 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2895 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2896 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2897 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2898 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2899 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2900 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2901 #define SQLITE_SELECT               21   /* NULL            NULL            */
2902 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2903 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2904 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2905 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2906 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2907 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2908 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2909 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2910 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2911 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2912 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2913 #define SQLITE_COPY                  0   /* No longer used */
2914
2915 /*
2916 ** CAPI3REF: Tracing And Profiling Functions {H12280} <S60400>
2917 ** EXPERIMENTAL
2918 **
2919 ** These routines register callback functions that can be used for
2920 ** tracing and profiling the execution of SQL statements.
2921 **
2922 ** The callback function registered by sqlite3_trace() is invoked at
2923 ** various times when an SQL statement is being run by [sqlite3_step()].
2924 ** The callback returns a UTF-8 rendering of the SQL statement text
2925 ** as the statement first begins executing.  Additional callbacks occur
2926 ** as each triggered subprogram is entered.  The callbacks for triggers
2927 ** contain a UTF-8 SQL comment that identifies the trigger.
2928 **
2929 ** The callback function registered by sqlite3_profile() is invoked
2930 ** as each SQL statement finishes.  The profile callback contains
2931 ** the original statement text and an estimate of wall-clock time
2932 ** of how long that statement took to run.
2933 **
2934 ** INVARIANTS:
2935 **
2936 ** {H12281} The callback function registered by [sqlite3_trace()] 
2937 **          shall be invoked
2938 **          whenever an SQL statement first begins to execute and
2939 **          whenever a trigger subprogram first begins to run.
2940 **
2941 ** {H12282} Each call to [sqlite3_trace()] shall override the previously
2942 **          registered trace callback.
2943 **
2944 ** {H12283} A NULL trace callback shall disable tracing.
2945 **
2946 ** {H12284} The first argument to the trace callback shall be a copy of
2947 **          the pointer which was the 3rd argument to [sqlite3_trace()].
2948 **
2949 ** {H12285} The second argument to the trace callback is a
2950 **          zero-terminated UTF-8 string containing the original text
2951 **          of the SQL statement as it was passed into [sqlite3_prepare_v2()]
2952 **          or the equivalent, or an SQL comment indicating the beginning
2953 **          of a trigger subprogram.
2954 **
2955 ** {H12287} The callback function registered by [sqlite3_profile()] is invoked
2956 **          as each SQL statement finishes.
2957 **
2958 ** {H12288} The first parameter to the profile callback is a copy of
2959 **          the 3rd parameter to [sqlite3_profile()].
2960 **
2961 ** {H12289} The second parameter to the profile callback is a
2962 **          zero-terminated UTF-8 string that contains the complete text of
2963 **          the SQL statement as it was processed by [sqlite3_prepare_v2()]
2964 **          or the equivalent.
2965 **
2966 ** {H12290} The third parameter to the profile callback is an estimate
2967 **          of the number of nanoseconds of wall-clock time required to
2968 **          run the SQL statement from start to finish.
2969 */
2970 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2971 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2972    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2973
2974 /*
2975 ** CAPI3REF: Query Progress Callbacks {H12910} <S60400>
2976 **
2977 ** This routine configures a callback function - the
2978 ** progress callback - that is invoked periodically during long
2979 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2980 ** [sqlite3_get_table()].  An example use for this
2981 ** interface is to keep a GUI updated during a large query.
2982 **
2983 ** If the progress callback returns non-zero, the operation is
2984 ** interrupted.  This feature can be used to implement a
2985 ** "Cancel" button on a GUI progress dialog box.
2986 **
2987 ** The progress handler must not do anything that will modify
2988 ** the database connection that invoked the progress handler.
2989 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2990 ** database connections for the meaning of "modify" in this paragraph.
2991 **
2992 ** INVARIANTS:
2993 **
2994 ** {H12911} The callback function registered by sqlite3_progress_handler()
2995 **          is invoked periodically during long running calls to
2996 **          [sqlite3_step()].
2997 **
2998 ** {H12912} The progress callback is invoked once for every N virtual
2999 **          machine opcodes, where N is the second argument to
3000 **          the [sqlite3_progress_handler()] call that registered
3001 **          the callback.  If N is less than 1, sqlite3_progress_handler()
3002 **          acts as if a NULL progress handler had been specified.
3003 **
3004 ** {H12913} The progress callback itself is identified by the third
3005 **          argument to sqlite3_progress_handler().
3006 **
3007 ** {H12914} The fourth argument to sqlite3_progress_handler() is a
3008 **          void pointer passed to the progress callback
3009 **          function each time it is invoked.
3010 **
3011 ** {H12915} If a call to [sqlite3_step()] results in fewer than N opcodes
3012 **          being executed, then the progress callback is never invoked.
3013 **
3014 ** {H12916} Every call to [sqlite3_progress_handler()]
3015 **          overwrites any previously registered progress handler.
3016 **
3017 ** {H12917} If the progress handler callback is NULL then no progress
3018 **          handler is invoked.
3019 **
3020 ** {H12918} If the progress callback returns a result other than 0, then
3021 **          the behavior is a if [sqlite3_interrupt()] had been called.
3022 **          <S30500>
3023 */
3024 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3025
3026 /*
3027 ** CAPI3REF: Opening A New Database Connection {H12700} <S40200>
3028 **
3029 ** These routines open an SQLite database file whose name is given by the
3030 ** filename argument. The filename argument is interpreted as UTF-8 for
3031 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3032 ** order for sqlite3_open16(). A [database connection] handle is usually
3033 ** returned in *ppDb, even if an error occurs.  The only exception is that
3034 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3035 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3036 ** object. If the database is opened (and/or created) successfully, then
3037 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.  The
3038 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3039 ** an English language description of the error.
3040 **
3041 ** The default encoding for the database will be UTF-8 if
3042 ** sqlite3_open() or sqlite3_open_v2() is called and
3043 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3044 **
3045 ** Whether or not an error occurs when it is opened, resources
3046 ** associated with the [database connection] handle should be released by
3047 ** passing it to [sqlite3_close()] when it is no longer required.
3048 **
3049 ** The sqlite3_open_v2() interface works like sqlite3_open()
3050 ** except that it accepts two additional parameters for additional control
3051 ** over the new database connection.  The flags parameter can take one of
3052 ** the following three values, optionally combined with the 
3053 ** [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags:
3054 **
3055 ** <dl>
3056 ** <dt>[SQLITE_OPEN_READONLY]</dt>
3057 ** <dd>The database is opened in read-only mode.  If the database does not
3058 ** already exist, an error is returned.</dd>
3059 **
3060 ** <dt>[SQLITE_OPEN_READWRITE]</dt>
3061 ** <dd>The database is opened for reading and writing if possible, or reading
3062 ** only if the file is write protected by the operating system.  In either
3063 ** case the database must already exist, otherwise an error is returned.</dd>
3064 **
3065 ** <dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3066 ** <dd>The database is opened for reading and writing, and is creates it if
3067 ** it does not already exist. This is the behavior that is always used for
3068 ** sqlite3_open() and sqlite3_open16().</dd>
3069 ** </dl>
3070 **
3071 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3072 ** combinations shown above or one of the combinations shown above combined
3073 ** with the [SQLITE_OPEN_NOMUTEX] or [SQLITE_OPEN_FULLMUTEX] flags,
3074 ** then the behavior is undefined.
3075 **
3076 ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3077 ** opens in the multi-thread [threading mode] as long as the single-thread
3078 ** mode has not been set at compile-time or start-time.  If the
3079 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3080 ** in the serialized [threading mode] unless single-thread was
3081 ** previously selected at compile-time or start-time.
3082 **
3083 ** If the filename is ":memory:", then a private, temporary in-memory database
3084 ** is created for the connection.  This in-memory database will vanish when
3085 ** the database connection is closed.  Future versions of SQLite might
3086 ** make use of additional special filenames that begin with the ":" character.
3087 ** It is recommended that when a database filename actually does begin with
3088 ** a ":" character you should prefix the filename with a pathname such as
3089 ** "./" to avoid ambiguity.
3090 **
3091 ** If the filename is an empty string, then a private, temporary
3092 ** on-disk database will be created.  This private database will be
3093 ** automatically deleted as soon as the database connection is closed.
3094 **
3095 ** The fourth parameter to sqlite3_open_v2() is the name of the
3096 ** [sqlite3_vfs] object that defines the operating system interface that
3097 ** the new database connection should use.  If the fourth parameter is
3098 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3099 **
3100 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3101 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3102 ** codepage is currently defined.  Filenames containing international
3103 ** characters must be converted to UTF-8 prior to passing them into
3104 ** sqlite3_open() or sqlite3_open_v2().
3105 **
3106 ** INVARIANTS:
3107 **
3108 ** {H12701} The [sqlite3_open()], [sqlite3_open16()], and
3109 **          [sqlite3_open_v2()] interfaces create a new
3110 **          [database connection] associated with
3111 **          the database file given in their first parameter.
3112 **
3113 ** {H12702} The filename argument is interpreted as UTF-8
3114 **          for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16
3115 **          in the native byte order for [sqlite3_open16()].
3116 **
3117 ** {H12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()],
3118 **          or [sqlite3_open_v2()] writes a pointer to a new
3119 **          [database connection] into *ppDb.
3120 **
3121 ** {H12704} The [sqlite3_open()], [sqlite3_open16()], and
3122 **          [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success,
3123 **          or an appropriate [error code] on failure.
3124 **
3125 ** {H12706} The default text encoding for a new database created using
3126 **          [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8.
3127 **
3128 ** {H12707} The default text encoding for a new database created using
3129 **          [sqlite3_open16()] will be UTF-16.
3130 **
3131 ** {H12709} The [sqlite3_open(F,D)] interface is equivalent to
3132 **          [sqlite3_open_v2(F,D,G,0)] where the G parameter is
3133 **          [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE].
3134 **
3135 ** {H12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3136 **          bit value [SQLITE_OPEN_READONLY] then the database is opened
3137 **          for reading only.
3138 **
3139 ** {H12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3140 **          bit value [SQLITE_OPEN_READWRITE] then the database is opened
3141 **          reading and writing if possible, or for reading only if the
3142 **          file is write protected by the operating system.
3143 **
3144 ** {H12713} If the G parameter to [sqlite3_open_v2(F,D,G,V)] omits the
3145 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3146 **          previously exist, an error is returned.
3147 **
3148 ** {H12714} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the
3149 **          bit value [SQLITE_OPEN_CREATE] and the database does not
3150 **          previously exist, then an attempt is made to create and
3151 **          initialize the database.
3152 **
3153 ** {H12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()],
3154 **          or [sqlite3_open_v2()] is ":memory:", then an private,
3155 **          ephemeral, in-memory database is created for the connection.
3156 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3157 **          in sqlite3_open_v2()?</todo>
3158 **
3159 ** {H12719} If the filename is NULL or an empty string, then a private,
3160 **          ephemeral on-disk database will be created.
3161 **          <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required
3162 **          in sqlite3_open_v2()?</todo>
3163 **
3164 ** {H12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)]
3165 **          will use the [sqlite3_vfs] object identified by the V parameter,
3166 **          or the default [sqlite3_vfs] object if V is a NULL pointer.
3167 **
3168 ** {H12723} Two [database connections] will share a common cache if both were
3169 **          opened with the same VFS while [shared cache mode] was enabled and
3170 **          if both filenames compare equal using memcmp() after having been
3171 **          processed by the [sqlite3_vfs | xFullPathname] method of the VFS.
3172 */
3173 SQLITE_API int sqlite3_open(
3174   const char *filename,   /* Database filename (UTF-8) */
3175   sqlite3 **ppDb          /* OUT: SQLite db handle */
3176 );
3177 SQLITE_API int sqlite3_open16(
3178   const void *filename,   /* Database filename (UTF-16) */
3179   sqlite3 **ppDb          /* OUT: SQLite db handle */
3180 );
3181 SQLITE_API int sqlite3_open_v2(
3182   const char *filename,   /* Database filename (UTF-8) */
3183   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3184   int flags,              /* Flags */
3185   const char *zVfs        /* Name of VFS module to use */
3186 );
3187
3188 /*
3189 ** CAPI3REF: Error Codes And Messages {H12800} <S60200>
3190 **
3191 ** The sqlite3_errcode() interface returns the numeric [result code] or
3192 ** [extended result code] for the most recent failed sqlite3_* API call
3193 ** associated with a [database connection]. If a prior API call failed
3194 ** but the most recent API call succeeded, the return value from
3195 ** sqlite3_errcode() is undefined.  The sqlite3_extended_errcode()
3196 ** interface is the same except that it always returns the 
3197 ** [extended result code] even when extended result codes are
3198 ** disabled.
3199 **
3200 ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3201 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3202 ** Memory to hold the error message string is managed internally.
3203 ** The application does not need to worry about freeing the result.
3204 ** However, the error string might be overwritten or deallocated by
3205 ** subsequent calls to other SQLite interface functions.
3206 **
3207 ** When the serialized [threading mode] is in use, it might be the
3208 ** case that a second error occurs on a separate thread in between
3209 ** the time of the first error and the call to these interfaces.
3210 ** When that happens, the second error will be reported since these
3211 ** interfaces always report the most recent result.  To avoid
3212 ** this, each thread can obtain exclusive use of the [database connection] D
3213 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3214 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3215 ** all calls to the interfaces listed here are completed.
3216 **
3217 ** If an interface fails with SQLITE_MISUSE, that means the interface
3218 ** was invoked incorrectly by the application.  In that case, the
3219 ** error code and message may or may not be set.
3220 **
3221 ** INVARIANTS:
3222 **
3223 ** {H12801} The [sqlite3_errcode(D)] interface returns the numeric
3224 **          [result code] or [extended result code] for the most recently
3225 **          failed interface call associated with the [database connection] D.
3226 **
3227 ** {H12802} The [sqlite3_extended_errcode(D)] interface returns the numeric
3228 **          [extended result code] for the most recently
3229 **          failed interface call associated with the [database connection] D.
3230 **
3231 ** {H12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)]
3232 **          interfaces return English-language text that describes
3233 **          the error in the mostly recently failed interface call,
3234 **          encoded as either UTF-8 or UTF-16 respectively.
3235 **
3236 ** {H12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]
3237 **          are valid until the next SQLite interface call.
3238 **
3239 ** {H12808} Calls to API routines that do not return an error code
3240 **          (example: [sqlite3_data_count()]) do not
3241 **          change the error code or message returned by
3242 **          [sqlite3_errcode()], [sqlite3_extended_errcode()],
3243 **          [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3244 **
3245 ** {H12809} Interfaces that are not associated with a specific
3246 **          [database connection] (examples:
3247 **          [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()]
3248 **          do not change the values returned by
3249 **          [sqlite3_errcode()], [sqlite3_extended_errcode()],
3250 **          [sqlite3_errmsg()], or [sqlite3_errmsg16()].
3251 */
3252 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3253 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3254 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3255 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3256
3257 /*
3258 ** CAPI3REF: SQL Statement Object {H13000} <H13010>
3259 ** KEYWORDS: {prepared statement} {prepared statements}
3260 **
3261 ** An instance of this object represents a single SQL statement.
3262 ** This object is variously known as a "prepared statement" or a
3263 ** "compiled SQL statement" or simply as a "statement".
3264 **
3265 ** The life of a statement object goes something like this:
3266 **
3267 ** <ol>
3268 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3269 **      function.
3270 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3271 **      interfaces.
3272 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3273 ** <li> Reset the statement using [sqlite3_reset()] then go back
3274 **      to step 2.  Do this zero or more times.
3275 ** <li> Destroy the object using [sqlite3_finalize()].
3276 ** </ol>
3277 **
3278 ** Refer to documentation on individual methods above for additional
3279 ** information.
3280 */
3281 typedef struct sqlite3_stmt sqlite3_stmt;
3282
3283 /*
3284 ** CAPI3REF: Run-time Limits {H12760} <S20600>
3285 **
3286 ** This interface allows the size of various constructs to be limited
3287 ** on a connection by connection basis.  The first parameter is the
3288 ** [database connection] whose limit is to be set or queried.  The
3289 ** second parameter is one of the [limit categories] that define a
3290 ** class of constructs to be size limited.  The third parameter is the
3291 ** new limit for that construct.  The function returns the old limit.
3292 **
3293 ** If the new limit is a negative number, the limit is unchanged.
3294 ** For the limit category of SQLITE_LIMIT_XYZ there is a 
3295 ** [limits | hard upper bound]
3296 ** set by a compile-time C preprocessor macro named 
3297 ** [limits | SQLITE_MAX_XYZ].
3298 ** (The "_LIMIT_" in the name is changed to "_MAX_".)
3299 ** Attempts to increase a limit above its hard upper bound are
3300 ** silently truncated to the hard upper limit.
3301 **
3302 ** Run time limits are intended for use in applications that manage
3303 ** both their own internal database and also databases that are controlled
3304 ** by untrusted external sources.  An example application might be a
3305 ** web browser that has its own databases for storing history and
3306 ** separate databases controlled by JavaScript applications downloaded
3307 ** off the Internet.  The internal databases can be given the
3308 ** large, default limits.  Databases managed by external sources can
3309 ** be given much smaller limits designed to prevent a denial of service
3310 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3311 ** interface to further control untrusted SQL.  The size of the database
3312 ** created by an untrusted script can be contained using the
3313 ** [max_page_count] [PRAGMA].
3314 **
3315 ** New run-time limit categories may be added in future releases.
3316 **
3317 ** INVARIANTS:
3318 **
3319 ** {H12762} A successful call to [sqlite3_limit(D,C,V)] where V is
3320 **          positive changes the limit on the size of construct C in the
3321 **          [database connection] D to the lesser of V and the hard upper
3322 **          bound on the size of C that is set at compile-time.
3323 **
3324 ** {H12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative
3325 **          leaves the state of the [database connection] D unchanged.
3326 **
3327 ** {H12769} A successful call to [sqlite3_limit(D,C,V)] returns the
3328 **          value of the limit on the size of construct C in the
3329 **          [database connection] D as it was prior to the call.
3330 */
3331 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3332
3333 /*
3334 ** CAPI3REF: Run-Time Limit Categories {H12790} <H12760>
3335 ** KEYWORDS: {limit category} {limit categories}
3336 **
3337 ** These constants define various performance limits
3338 ** that can be lowered at run-time using [sqlite3_limit()].
3339 ** The synopsis of the meanings of the various limits is shown below.
3340 ** Additional information is available at [limits | Limits in SQLite].
3341 **
3342 ** <dl>
3343 ** <dt>SQLITE_LIMIT_LENGTH</dt>
3344 ** <dd>The maximum size of any string or BLOB or table row.<dd>
3345 **
3346 ** <dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3347 ** <dd>The maximum length of an SQL statement.</dd>
3348 **
3349 ** <dt>SQLITE_LIMIT_COLUMN</dt>
3350 ** <dd>The maximum number of columns in a table definition or in the
3351 ** result set of a [SELECT] or the maximum number of columns in an index
3352 ** or in an ORDER BY or GROUP BY clause.</dd>
3353 **
3354 ** <dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3355 ** <dd>The maximum depth of the parse tree on any expression.</dd>
3356 **
3357 ** <dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3358 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>
3359 **
3360 ** <dt>SQLITE_LIMIT_VDBE_OP</dt>
3361 ** <dd>The maximum number of instructions in a virtual machine program
3362 ** used to implement an SQL statement.</dd>
3363 **
3364 ** <dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3365 ** <dd>The maximum number of arguments on a function.</dd>
3366 **
3367 ** <dt>SQLITE_LIMIT_ATTACHED</dt>
3368 ** <dd>The maximum number of [ATTACH | attached databases].</dd>
3369 **
3370 ** <dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3371 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3372 ** [GLOB] operators.</dd>
3373 **
3374 ** <dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3375 ** <dd>The maximum number of variables in an SQL statement that can
3376 ** be bound.</dd>
3377 ** </dl>
3378 */
3379 #define SQLITE_LIMIT_LENGTH                    0
3380 #define SQLITE_LIMIT_SQL_LENGTH                1
3381 #define SQLITE_LIMIT_COLUMN                    2
3382 #define SQLITE_LIMIT_EXPR_DEPTH                3
3383 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3384 #define SQLITE_LIMIT_VDBE_OP                   5
3385 #define SQLITE_LIMIT_FUNCTION_ARG              6
3386 #define SQLITE_LIMIT_ATTACHED                  7
3387 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3388 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3389
3390 /*
3391 ** CAPI3REF: Compiling An SQL Statement {H13010} <S10000>
3392 ** KEYWORDS: {SQL statement compiler}
3393 **
3394 ** To execute an SQL query, it must first be compiled into a byte-code
3395 ** program using one of these routines.
3396 **
3397 ** The first argument, "db", is a [database connection] obtained from a
3398 ** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()].
3399 **
3400 ** The second argument, "zSql", is the statement to be compiled, encoded
3401 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3402 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3403 ** use UTF-16.
3404 **
3405 ** If the nByte argument is less than zero, then zSql is read up to the
3406 ** first zero terminator. If nByte is non-negative, then it is the maximum
3407 ** number of  bytes read from zSql.  When nByte is non-negative, the
3408 ** zSql string ends at either the first '\000' or '\u0000' character or
3409 ** the nByte-th byte, whichever comes first. If the caller knows
3410 ** that the supplied string is nul-terminated, then there is a small
3411 ** performance advantage to be gained by passing an nByte parameter that
3412 ** is equal to the number of bytes in the input string <i>including</i>
3413 ** the nul-terminator bytes.
3414 **
3415 ** *pzTail is made to point to the first byte past the end of the
3416 ** first SQL statement in zSql.  These routines only compile the first
3417 ** statement in zSql, so *pzTail is left pointing to what remains
3418 ** uncompiled.
3419 **
3420 ** *ppStmt is left pointing to a compiled [prepared statement] that can be
3421 ** executed using [sqlite3_step()].  If there is an error, *ppStmt is set
3422 ** to NULL.  If the input text contains no SQL (if the input is an empty
3423 ** string or a comment) then *ppStmt is set to NULL.
3424 ** {A13018} The calling procedure is responsible for deleting the compiled
3425 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3426 **
3427 ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned.
3428 **
3429 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3430 ** recommended for all new programs. The two older interfaces are retained
3431 ** for backwards compatibility, but their use is discouraged.
3432 ** In the "v2" interfaces, the prepared statement
3433 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3434 ** original SQL text. This causes the [sqlite3_step()] interface to
3435 ** behave a differently in two ways:
3436 **
3437 ** <ol>
3438 ** <li>
3439 ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3440 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3441 ** statement and try to run it again.  If the schema has changed in
3442 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3443 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3444 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3445 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
3446 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3447 ** </li>
3448 **
3449 ** <li>
3450 ** When an error occurs, [sqlite3_step()] will return one of the detailed
3451 ** [error codes] or [extended error codes].  The legacy behavior was that
3452 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3453 ** and you would have to make a second call to [sqlite3_reset()] in order
3454 ** to find the underlying cause of the problem. With the "v2" prepare
3455 ** interfaces, the underlying reason for the error is returned immediately.
3456 ** </li>
3457 ** </ol>
3458 **
3459 ** INVARIANTS:
3460 **
3461 ** {H13011} The [sqlite3_prepare(db,zSql,...)] and
3462 **          [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the
3463 **          text in their zSql parameter as UTF-8.
3464 **
3465 ** {H13012} The [sqlite3_prepare16(db,zSql,...)] and
3466 **          [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the
3467 **          text in their zSql parameter as UTF-16 in the native byte order.
3468 **
3469 ** {H13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3470 **          and its variants is less than zero, the SQL text is
3471 **          read from zSql is read up to the first zero terminator.
3472 **
3473 ** {H13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)]
3474 **          and its variants is non-negative, then at most nBytes bytes of
3475 **          SQL text is read from zSql.
3476 **
3477 ** {H13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants
3478 **          if the zSql input text contains more than one SQL statement
3479 **          and pzTail is not NULL, then *pzTail is made to point to the
3480 **          first byte past the end of the first SQL statement in zSql.
3481 **          <todo>What does *pzTail point to if there is one statement?</todo>
3482 **
3483 ** {H13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)]
3484 **          or one of its variants writes into *ppStmt a pointer to a new
3485 **          [prepared statement] or a pointer to NULL if zSql contains
3486 **          nothing other than whitespace or comments.
3487 **
3488 ** {H13019} The [sqlite3_prepare_v2()] interface and its variants return
3489 **          [SQLITE_OK] or an appropriate [error code] upon failure.
3490 **
3491 ** {H13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its
3492 **          variants returns an error (any value other than [SQLITE_OK]),
3493 **          they first set *ppStmt to NULL.
3494 */
3495 SQLITE_API int sqlite3_prepare(
3496   sqlite3 *db,            /* Database handle */
3497   const char *zSql,       /* SQL statement, UTF-8 encoded */
3498   int nByte,              /* Maximum length of zSql in bytes. */
3499   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3500   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3501 );
3502 SQLITE_API int sqlite3_prepare_v2(
3503   sqlite3 *db,            /* Database handle */
3504   const char *zSql,       /* SQL statement, UTF-8 encoded */
3505   int nByte,              /* Maximum length of zSql in bytes. */
3506   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3507   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3508 );
3509 SQLITE_API int sqlite3_prepare16(
3510   sqlite3 *db,            /* Database handle */
3511   const void *zSql,       /* SQL statement, UTF-16 encoded */
3512   int nByte,              /* Maximum length of zSql in bytes. */
3513   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3514   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3515 );
3516 SQLITE_API int sqlite3_prepare16_v2(
3517   sqlite3 *db,            /* Database handle */
3518   const void *zSql,       /* SQL statement, UTF-16 encoded */
3519   int nByte,              /* Maximum length of zSql in bytes. */
3520   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3521   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3522 );
3523
3524 /*
3525 ** CAPI3REF: Retrieving Statement SQL {H13100} <H13000>
3526 **
3527 ** This interface can be used to retrieve a saved copy of the original
3528 ** SQL text used to create a [prepared statement] if that statement was
3529 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3530 **
3531 ** INVARIANTS:
3532 **
3533 ** {H13101} If the [prepared statement] passed as the argument to
3534 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or
3535 **          [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns
3536 **          a pointer to a zero-terminated string containing a UTF-8 rendering
3537 **          of the original SQL statement.
3538 **
3539 ** {H13102} If the [prepared statement] passed as the argument to
3540 **          [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or
3541 **          [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer.
3542 **
3543 ** {H13103} The string returned by [sqlite3_sql(S)] is valid until the
3544 **          [prepared statement] S is deleted using [sqlite3_finalize(S)].
3545 */
3546 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3547
3548 /*
3549 ** CAPI3REF: Dynamically Typed Value Object {H15000} <S20200>
3550 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3551 **
3552 ** SQLite uses the sqlite3_value object to represent all values
3553 ** that can be stored in a database table. SQLite uses dynamic typing
3554 ** for the values it stores. Values stored in sqlite3_value objects
3555 ** can be integers, floating point values, strings, BLOBs, or NULL.
3556 **
3557 ** An sqlite3_value object may be either "protected" or "unprotected".
3558 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3559 ** will accept either a protected or an unprotected sqlite3_value.
3560 ** Every interface that accepts sqlite3_value arguments specifies
3561 ** whether or not it requires a protected sqlite3_value.
3562 **
3563 ** The terms "protected" and "unprotected" refer to whether or not
3564 ** a mutex is held.  A internal mutex is held for a protected
3565 ** sqlite3_value object but no mutex is held for an unprotected
3566 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3567 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3568 ** or if SQLite is run in one of reduced mutex modes 
3569 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3570 ** then there is no distinction between protected and unprotected
3571 ** sqlite3_value objects and they can be used interchangeably.  However,
3572 ** for maximum code portability it is recommended that applications
3573 ** still make the distinction between between protected and unprotected
3574 ** sqlite3_value objects even when not strictly required.
3575 **
3576 ** The sqlite3_value objects that are passed as parameters into the
3577 ** implementation of [application-defined SQL functions] are protected.
3578 ** The sqlite3_value object returned by
3579 ** [sqlite3_column_value()] is unprotected.
3580 ** Unprotected sqlite3_value objects may only be used with
3581 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3582 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3583 ** interfaces require protected sqlite3_value objects.
3584 */
3585 typedef struct Mem sqlite3_value;
3586
3587 /*
3588 ** CAPI3REF: SQL Function Context Object {H16001} <S20200>
3589 **
3590 ** The context in which an SQL function executes is stored in an
3591 ** sqlite3_context object.  A pointer to an sqlite3_context object
3592 ** is always first parameter to [application-defined SQL functions].
3593 ** The application-defined SQL function implementation will pass this
3594 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3595 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3596 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3597 ** and/or [sqlite3_set_auxdata()].
3598 */
3599 typedef struct sqlite3_context sqlite3_context;
3600
3601 /*
3602 ** CAPI3REF: Binding Values To Prepared Statements {H13500} <S70300>
3603 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3604 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3605 **
3606 ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants,
3607 ** literals may be replaced by a [parameter] in one of these forms:
3608 **
3609 ** <ul>
3610 ** <li>  ?
3611 ** <li>  ?NNN
3612 ** <li>  :VVV
3613 ** <li>  @VVV
3614 ** <li>  $VVV
3615 ** </ul>
3616 **
3617 ** In the parameter forms shown above NNN is an integer literal,
3618 ** and VVV is an alpha-numeric parameter name. The values of these
3619 ** parameters (also called "host parameter names" or "SQL parameters")
3620 ** can be set using the sqlite3_bind_*() routines defined here.
3621 **
3622 ** The first argument to the sqlite3_bind_*() routines is always
3623 ** a pointer to the [sqlite3_stmt] object returned from
3624 ** [sqlite3_prepare_v2()] or its variants.
3625 **
3626 ** The second argument is the index of the SQL parameter to be set.
3627 ** The leftmost SQL parameter has an index of 1.  When the same named
3628 ** SQL parameter is used more than once, second and subsequent
3629 ** occurrences have the same index as the first occurrence.
3630 ** The index for named parameters can be looked up using the
3631 ** [sqlite3_bind_parameter_index()] API if desired.  The index
3632 ** for "?NNN" parameters is the value of NNN.
3633 ** The NNN value must be between 1 and the [sqlite3_limit()]
3634 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3635 **
3636 ** The third argument is the value to bind to the parameter.
3637 **
3638 ** In those routines that have a fourth argument, its value is the
3639 ** number of bytes in the parameter.  To be clear: the value is the
3640 ** number of <u>bytes</u> in the value, not the number of characters.
3641 ** If the fourth parameter is negative, the length of the string is
3642 ** the number of bytes up to the first zero terminator.
3643 **
3644 ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3645 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3646 ** string after SQLite has finished with it. If the fifth argument is
3647 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3648 ** information is in static, unmanaged space and does not need to be freed.
3649 ** If the fifth argument has the value [SQLITE_TRANSIENT], then
3650 ** SQLite makes its own private copy of the data immediately, before
3651 ** the sqlite3_bind_*() routine returns.
3652 **
3653 ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3654 ** is filled with zeroes.  A zeroblob uses a fixed amount of memory
3655 ** (just an integer to hold its size) while it is being processed.
3656 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3657 ** content is later written using
3658 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3659 ** A negative value for the zeroblob results in a zero-length BLOB.
3660 **
3661 ** The sqlite3_bind_*() routines must be called after
3662 ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and
3663 ** before [sqlite3_step()].
3664 ** Bindings are not cleared by the [sqlite3_reset()] routine.
3665 ** Unbound parameters are interpreted as NULL.
3666 **
3667 ** These routines return [SQLITE_OK] on success or an error code if
3668 ** anything goes wrong.  [SQLITE_RANGE] is returned if the parameter
3669 ** index is out of range.  [SQLITE_NOMEM] is returned if malloc() fails.
3670 ** [SQLITE_MISUSE] might be returned if these routines are called on a
3671 ** virtual machine that is the wrong state or which has already been finalized.
3672 ** Detection of misuse is unreliable.  Applications should not depend
3673 ** on SQLITE_MISUSE returns.  SQLITE_MISUSE is intended to indicate a
3674 ** a logic error in the application.  Future versions of SQLite might
3675 ** panic rather than return SQLITE_MISUSE.
3676 **
3677 ** See also: [sqlite3_bind_parameter_count()],
3678 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3679 **
3680 ** INVARIANTS:
3681 **
3682 ** {H13506} The [SQL statement compiler] recognizes tokens of the forms
3683 **          "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters,
3684 **          where NNN is any sequence of one or more digits
3685 **          and where VVV is any sequence of one or more alphanumeric
3686 **          characters or "::" optionally followed by a string containing
3687 **          no spaces and contained within parentheses.
3688 **
3689 ** {H13509} The initial value of an SQL parameter is NULL.
3690 **
3691 ** {H13512} The index of an "?" SQL parameter is one larger than the
3692 **          largest index of SQL parameter to the left, or 1 if
3693 **          the "?" is the leftmost SQL parameter.
3694 **
3695 ** {H13515} The index of an "?NNN" SQL parameter is the integer NNN.
3696 **
3697 ** {H13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is
3698 **          the same as the index of leftmost occurrences of the same
3699 **          parameter, or one more than the largest index over all
3700 **          parameters to the left if this is the first occurrence
3701 **          of this parameter, or 1 if this is the leftmost parameter.
3702 **
3703 ** {H13521} The [SQL statement compiler] fails with an [SQLITE_RANGE]
3704 **          error if the index of an SQL parameter is less than 1
3705 **          or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER
3706 **          parameter.
3707 **
3708 ** {H13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)]
3709 **          associate the value V with all SQL parameters having an
3710 **          index of N in the [prepared statement] S.
3711 **
3712 ** {H13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)]
3713 **          override prior calls with the same values of S and N.
3714 **
3715 ** {H13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)]
3716 **          persist across calls to [sqlite3_reset(S)].
3717 **
3718 ** {H13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3719 **          [sqlite3_bind_text(S,N,V,L,D)], or
3720 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L
3721 **          bytes of the BLOB or string pointed to by V, when L
3722 **          is non-negative.
3723 **
3724 ** {H13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or
3725 **          [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters
3726 **          from V through the first zero character when L is negative.
3727 **
3728 ** {H13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3729 **          [sqlite3_bind_text(S,N,V,L,D)], or
3730 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3731 **          constant [SQLITE_STATIC], SQLite assumes that the value V
3732 **          is held in static unmanaged space that will not change
3733 **          during the lifetime of the binding.
3734 **
3735 ** {H13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3736 **          [sqlite3_bind_text(S,N,V,L,D)], or
3737 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is the special
3738 **          constant [SQLITE_TRANSIENT], the routine makes a
3739 **          private copy of the value V before it returns.
3740 **
3741 ** {H13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)],
3742 **          [sqlite3_bind_text(S,N,V,L,D)], or
3743 **          [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to
3744 **          a function, SQLite invokes that function to destroy the
3745 **          value V after it has finished using the value V.
3746 **
3747 ** {H13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound
3748 **          is a BLOB of L bytes, or a zero-length BLOB if L is negative.
3749 **
3750 ** {H13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may
3751 **          be either a [protected sqlite3_value] object or an
3752 **          [unprotected sqlite3_value] object.
3753 */
3754 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3755 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3756 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3757 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3758 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3759 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3760 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3761 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3762 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3763
3764 /*
3765 ** CAPI3REF: Number Of SQL Parameters {H13600} <S70300>
3766 **
3767 ** This routine can be used to find the number of [SQL parameters]
3768 ** in a [prepared statement].  SQL parameters are tokens of the
3769 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3770 ** placeholders for values that are [sqlite3_bind_blob | bound]
3771 ** to the parameters at a later time.
3772 **
3773 ** This routine actually returns the index of the largest (rightmost)
3774 ** parameter. For all forms except ?NNN, this will correspond to the
3775 ** number of unique parameters.  If parameters of the ?NNN are used,
3776 ** there may be gaps in the list.
3777 **
3778 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3779 ** [sqlite3_bind_parameter_name()], and
3780 ** [sqlite3_bind_parameter_index()].
3781 **
3782 ** INVARIANTS:
3783 **
3784 ** {H13601} The [sqlite3_bind_parameter_count(S)] interface returns
3785 **          the largest index of all SQL parameters in the
3786 **          [prepared statement] S, or 0 if S contains no SQL parameters.
3787 */
3788 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3789
3790 /*
3791 ** CAPI3REF: Name Of A Host Parameter {H13620} <S70300>
3792 **
3793 ** This routine returns a pointer to the name of the n-th
3794 ** [SQL parameter] in a [prepared statement].
3795 ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3796 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3797 ** respectively.
3798 ** In other words, the initial ":" or "$" or "@" or "?"
3799 ** is included as part of the name.
3800 ** Parameters of the form "?" without a following integer have no name
3801 ** and are also referred to as "anonymous parameters".
3802 **
3803 ** The first host parameter has an index of 1, not 0.
3804 **
3805 ** If the value n is out of range or if the n-th parameter is
3806 ** nameless, then NULL is returned.  The returned string is
3807 ** always in UTF-8 encoding even if the named parameter was
3808 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3809 ** [sqlite3_prepare16_v2()].
3810 **
3811 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3812 ** [sqlite3_bind_parameter_count()], and
3813 ** [sqlite3_bind_parameter_index()].
3814 **
3815 ** INVARIANTS:
3816 **
3817 ** {H13621} The [sqlite3_bind_parameter_name(S,N)] interface returns
3818 **          a UTF-8 rendering of the name of the SQL parameter in
3819 **          the [prepared statement] S having index N, or
3820 **          NULL if there is no SQL parameter with index N or if the
3821 **          parameter with index N is an anonymous parameter "?".
3822 */
3823 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3824
3825 /*
3826 ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} <S70300>
3827 **
3828 ** Return the index of an SQL parameter given its name.  The
3829 ** index value returned is suitable for use as the second
3830 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  A zero
3831 ** is returned if no matching parameter is found.  The parameter
3832 ** name must be given in UTF-8 even if the original statement
3833 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3834 **
3835 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3836 ** [sqlite3_bind_parameter_count()], and
3837 ** [sqlite3_bind_parameter_index()].
3838 **
3839 ** INVARIANTS:
3840 **
3841 ** {H13641} The [sqlite3_bind_parameter_index(S,N)] interface returns
3842 **          the index of SQL parameter in the [prepared statement]
3843 **          S whose name matches the UTF-8 string N, or 0 if there is
3844 **          no match.
3845 */
3846 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3847
3848 /*
3849 ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} <S70300>
3850 **
3851 ** Contrary to the intuition of many, [sqlite3_reset()] does not reset
3852 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3853 ** Use this routine to reset all host parameters to NULL.
3854 **
3855 ** INVARIANTS:
3856 **
3857 ** {H13661} The [sqlite3_clear_bindings(S)] interface resets all SQL
3858 **          parameter bindings in the [prepared statement] S back to NULL.
3859 */
3860 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3861
3862 /*
3863 ** CAPI3REF: Number Of Columns In A Result Set {H13710} <S10700>
3864 **
3865 ** Return the number of columns in the result set returned by the
3866 ** [prepared statement]. This routine returns 0 if pStmt is an SQL
3867 ** statement that does not return data (for example an [UPDATE]).
3868 **
3869 ** INVARIANTS:
3870 **
3871 ** {H13711} The [sqlite3_column_count(S)] interface returns the number of
3872 **          columns in the result set generated by the [prepared statement] S,
3873 **          or 0 if S does not generate a result set.
3874 */
3875 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3876
3877 /*
3878 ** CAPI3REF: Column Names In A Result Set {H13720} <S10700>
3879 **
3880 ** These routines return the name assigned to a particular column
3881 ** in the result set of a [SELECT] statement.  The sqlite3_column_name()
3882 ** interface returns a pointer to a zero-terminated UTF-8 string
3883 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3884 ** UTF-16 string.  The first parameter is the [prepared statement]
3885 ** that implements the [SELECT] statement. The second parameter is the
3886 ** column number.  The leftmost column is number 0.
3887 **
3888 ** The returned string pointer is valid until either the [prepared statement]
3889 ** is destroyed by [sqlite3_finalize()] or until the next call to
3890 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3891 **
3892 ** If sqlite3_malloc() fails during the processing of either routine
3893 ** (for example during a conversion from UTF-8 to UTF-16) then a
3894 ** NULL pointer is returned.
3895 **
3896 ** The name of a result column is the value of the "AS" clause for
3897 ** that column, if there is an AS clause.  If there is no AS clause
3898 ** then the name of the column is unspecified and may change from
3899 ** one release of SQLite to the next.
3900 **
3901 ** INVARIANTS:
3902 **
3903 ** {H13721} A successful invocation of the [sqlite3_column_name(S,N)]
3904 **          interface returns the name of the Nth column (where 0 is
3905 **          the leftmost column) for the result set of the
3906 **          [prepared statement] S as a zero-terminated UTF-8 string.
3907 **
3908 ** {H13723} A successful invocation of the [sqlite3_column_name16(S,N)]
3909 **          interface returns the name of the Nth column (where 0 is
3910 **          the leftmost column) for the result set of the
3911 **          [prepared statement] S as a zero-terminated UTF-16 string
3912 **          in the native byte order.
3913 **
3914 ** {H13724} The [sqlite3_column_name()] and [sqlite3_column_name16()]
3915 **          interfaces return a NULL pointer if they are unable to
3916 **          allocate memory to hold their normal return strings.
3917 **
3918 ** {H13725} If the N parameter to [sqlite3_column_name(S,N)] or
3919 **          [sqlite3_column_name16(S,N)] is out of range, then the
3920 **          interfaces return a NULL pointer.
3921 **
3922 ** {H13726} The strings returned by [sqlite3_column_name(S,N)] and
3923 **          [sqlite3_column_name16(S,N)] are valid until the next
3924 **          call to either routine with the same S and N parameters
3925 **          or until [sqlite3_finalize(S)] is called.
3926 **
3927 ** {H13727} When a result column of a [SELECT] statement contains
3928 **          an AS clause, the name of that column is the identifier
3929 **          to the right of the AS keyword.
3930 */
3931 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3932 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3933
3934 /*
3935 ** CAPI3REF: Source Of Data In A Query Result {H13740} <S10700>
3936 **
3937 ** These routines provide a means to determine what column of what
3938 ** table in which database a result of a [SELECT] statement comes from.
3939 ** The name of the database or table or column can be returned as
3940 ** either a UTF-8 or UTF-16 string.  The _database_ routines return
3941 ** the database name, the _table_ routines return the table name, and
3942 ** the origin_ routines return the column name.
3943 ** The returned string is valid until the [prepared statement] is destroyed
3944 ** using [sqlite3_finalize()] or until the same information is requested
3945 ** again in a different encoding.
3946 **
3947 ** The names returned are the original un-aliased names of the
3948 ** database, table, and column.
3949 **
3950 ** The first argument to the following calls is a [prepared statement].
3951 ** These functions return information about the Nth column returned by
3952 ** the statement, where N is the second function argument.
3953 **
3954 ** If the Nth column returned by the statement is an expression or
3955 ** subquery and is not a column value, then all of these functions return
3956 ** NULL.  These routine might also return NULL if a memory allocation error
3957 ** occurs.  Otherwise, they return the name of the attached database, table
3958 ** and column that query result column was extracted from.
3959 **
3960 ** As with all other SQLite APIs, those postfixed with "16" return
3961 ** UTF-16 encoded strings, the other functions return UTF-8. {END}
3962 **
3963 ** These APIs are only available if the library was compiled with the
3964 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
3965 **
3966 ** {A13751}
3967 ** If two or more threads call one or more of these routines against the same
3968 ** prepared statement and column at the same time then the results are
3969 ** undefined.
3970 **
3971 ** INVARIANTS:
3972 **
3973 ** {H13741} The [sqlite3_column_database_name(S,N)] interface returns either
3974 **          the UTF-8 zero-terminated name of the database from which the
3975 **          Nth result column of the [prepared statement] S is extracted,
3976 **          or NULL if the Nth column of S is a general expression
3977 **          or if unable to allocate memory to store the name.
3978 **
3979 ** {H13742} The [sqlite3_column_database_name16(S,N)] interface returns either
3980 **          the UTF-16 native byte order zero-terminated name of the database
3981 **          from which the Nth result column of the [prepared statement] S is
3982 **          extracted, or NULL if the Nth column of S is a general expression
3983 **          or if unable to allocate memory to store the name.
3984 **
3985 ** {H13743} The [sqlite3_column_table_name(S,N)] interface returns either
3986 **          the UTF-8 zero-terminated name of the table from which the
3987 **          Nth result column of the [prepared statement] S is extracted,
3988 **          or NULL if the Nth column of S is a general expression
3989 **          or if unable to allocate memory to store the name.
3990 **
3991 ** {H13744} The [sqlite3_column_table_name16(S,N)] interface returns either
3992 **          the UTF-16 native byte order zero-terminated name of the table
3993 **          from which the Nth result column of the [prepared statement] S is
3994 **          extracted, or NULL if the Nth column of S is a general expression
3995 **          or if unable to allocate memory to store the name.
3996 **
3997 ** {H13745} The [sqlite3_column_origin_name(S,N)] interface returns either
3998 **          the UTF-8 zero-terminated name of the table column from which the
3999 **          Nth result column of the [prepared statement] S is extracted,
4000 **          or NULL if the Nth column of S is a general expression
4001 **          or if unable to allocate memory to store the name.
4002 **
4003 ** {H13746} The [sqlite3_column_origin_name16(S,N)] interface returns either
4004 **          the UTF-16 native byte order zero-terminated name of the table
4005 **          column from which the Nth result column of the
4006 **          [prepared statement] S is extracted, or NULL if the Nth column
4007 **          of S is a general expression or if unable to allocate memory
4008 **          to store the name.
4009 **
4010 ** {H13748} The return values from
4011 **          [sqlite3_column_database_name | column metadata interfaces]
4012 **          are valid for the lifetime of the [prepared statement]
4013 **          or until the encoding is changed by another metadata
4014 **          interface call for the same prepared statement and column.
4015 **
4016 ** ASSUMPTIONS:
4017 **
4018 ** {A13751} If two or more threads call one or more
4019 **          [sqlite3_column_database_name | column metadata interfaces]
4020 **          for the same [prepared statement] and result column
4021 **          at the same time then the results are undefined.
4022 */
4023 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4024 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4025 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4026 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4027 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4028 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4029
4030 /*
4031 ** CAPI3REF: Declared Datatype Of A Query Result {H13760} <S10700>
4032 **
4033 ** The first parameter is a [prepared statement].
4034 ** If this statement is a [SELECT] statement and the Nth column of the
4035 ** returned result set of that [SELECT] is a table column (not an
4036 ** expression or subquery) then the declared type of the table
4037 ** column is returned.  If the Nth column of the result set is an
4038 ** expression or subquery, then a NULL pointer is returned.
4039 ** The returned string is always UTF-8 encoded. {END}
4040 **
4041 ** For example, given the database schema:
4042 **
4043 ** CREATE TABLE t1(c1 VARIANT);
4044 **
4045 ** and the following statement to be compiled:
4046 **
4047 ** SELECT c1 + 1, c1 FROM t1;
4048 **
4049 ** this routine would return the string "VARIANT" for the second result
4050 ** column (i==1), and a NULL pointer for the first result column (i==0).
4051 **
4052 ** SQLite uses dynamic run-time typing.  So just because a column
4053 ** is declared to contain a particular type does not mean that the
4054 ** data stored in that column is of the declared type.  SQLite is
4055 ** strongly typed, but the typing is dynamic not static.  Type
4056 ** is associated with individual values, not with the containers
4057 ** used to hold those values.
4058 **
4059 ** INVARIANTS:
4060 **
4061 ** {H13761}  A successful call to [sqlite3_column_decltype(S,N)] returns a
4062 **           zero-terminated UTF-8 string containing the declared datatype
4063 **           of the table column that appears as the Nth column (numbered
4064 **           from 0) of the result set to the [prepared statement] S.
4065 **
4066 ** {H13762}  A successful call to [sqlite3_column_decltype16(S,N)]
4067 **           returns a zero-terminated UTF-16 native byte order string
4068 **           containing the declared datatype of the table column that appears
4069 **           as the Nth column (numbered from 0) of the result set to the
4070 **           [prepared statement] S.
4071 **
4072 ** {H13763}  If N is less than 0 or N is greater than or equal to
4073 **           the number of columns in the [prepared statement] S,
4074 **           or if the Nth column of S is an expression or subquery rather
4075 **           than a table column, or if a memory allocation failure
4076 **           occurs during encoding conversions, then
4077 **           calls to [sqlite3_column_decltype(S,N)] or
4078 **           [sqlite3_column_decltype16(S,N)] return NULL.
4079 */
4080 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4081 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4082
4083 /*
4084 ** CAPI3REF: Evaluate An SQL Statement {H13200} <S10000>
4085 **
4086 ** After a [prepared statement] has been prepared using either
4087 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4088 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4089 ** must be called one or more times to evaluate the statement.
4090 **
4091 ** The details of the behavior of the sqlite3_step() interface depend
4092 ** on whether the statement was prepared using the newer "v2" interface
4093 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4094 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4095 ** new "v2" interface is recommended for new applications but the legacy
4096 ** interface will continue to be supported.
4097 **
4098 ** In the legacy interface, the return value will be either [SQLITE_BUSY],
4099 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4100 ** With the "v2" interface, any of the other [result codes] or
4101 ** [extended result codes] might be returned as well.
4102 **
4103 ** [SQLITE_BUSY] means that the database engine was unable to acquire the
4104 ** database locks it needs to do its job.  If the statement is a [COMMIT]
4105 ** or occurs outside of an explicit transaction, then you can retry the
4106 ** statement.  If the statement is not a [COMMIT] and occurs within a
4107 ** explicit transaction then you should rollback the transaction before
4108 ** continuing.
4109 **
4110 ** [SQLITE_DONE] means that the statement has finished executing
4111 ** successfully.  sqlite3_step() should not be called again on this virtual
4112 ** machine without first calling [sqlite3_reset()] to reset the virtual
4113 ** machine back to its initial state.
4114 **
4115 ** If the SQL statement being executed returns any data, then [SQLITE_ROW]
4116 ** is returned each time a new row of data is ready for processing by the
4117 ** caller. The values may be accessed using the [column access functions].
4118 ** sqlite3_step() is called again to retrieve the next row of data.
4119 **
4120 ** [SQLITE_ERROR] means that a run-time error (such as a constraint
4121 ** violation) has occurred.  sqlite3_step() should not be called again on
4122 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4123 ** With the legacy interface, a more specific error code (for example,
4124 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4125 ** can be obtained by calling [sqlite3_reset()] on the
4126 ** [prepared statement].  In the "v2" interface,
4127 ** the more specific error code is returned directly by sqlite3_step().
4128 **
4129 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4130 ** Perhaps it was called on a [prepared statement] that has
4131 ** already been [sqlite3_finalize | finalized] or on one that had
4132 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4133 ** be the case that the same database connection is being used by two or
4134 ** more threads at the same moment in time.
4135 **
4136 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4137 ** API always returns a generic error code, [SQLITE_ERROR], following any
4138 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4139 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4140 ** specific [error codes] that better describes the error.
4141 ** We admit that this is a goofy design.  The problem has been fixed
4142 ** with the "v2" interface.  If you prepare all of your SQL statements
4143 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4144 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4145 ** then the more specific [error codes] are returned directly
4146 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4147 **
4148 ** INVARIANTS:
4149 **
4150 ** {H13202}  If the [prepared statement] S is ready to be run, then
4151 **           [sqlite3_step(S)] advances that prepared statement until
4152 **           completion or until it is ready to return another row of the
4153 **           result set, or until an [sqlite3_interrupt | interrupt]
4154 **           or a run-time error occurs.
4155 **
4156 ** {H15304}  When a call to [sqlite3_step(S)] causes the [prepared statement]
4157 **           S to run to completion, the function returns [SQLITE_DONE].
4158 **
4159 ** {H15306}  When a call to [sqlite3_step(S)] stops because it is ready to
4160 **           return another row of the result set, it returns [SQLITE_ROW].
4161 **
4162 ** {H15308}  If a call to [sqlite3_step(S)] encounters an
4163 **           [sqlite3_interrupt | interrupt] or a run-time error,
4164 **           it returns an appropriate error code that is not one of
4165 **           [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE].
4166 **
4167 ** {H15310}  If an [sqlite3_interrupt | interrupt] or a run-time error
4168 **           occurs during a call to [sqlite3_step(S)]
4169 **           for a [prepared statement] S created using
4170 **           legacy interfaces [sqlite3_prepare()] or
4171 **           [sqlite3_prepare16()], then the function returns either
4172 **           [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE].
4173 */
4174 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4175
4176 /*
4177 ** CAPI3REF: Number of columns in a result set {H13770} <S10700>
4178 **
4179 ** Returns the number of values in the current row of the result set.
4180 **
4181 ** INVARIANTS:
4182 **
4183 ** {H13771}  After a call to [sqlite3_step(S)] that returns [SQLITE_ROW],
4184 **           the [sqlite3_data_count(S)] routine will return the same value
4185 **           as the [sqlite3_column_count(S)] function.
4186 **
4187 ** {H13772}  After [sqlite3_step(S)] has returned any value other than
4188 **           [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the
4189 **           [prepared statement] for the first time since it was
4190 **           [sqlite3_prepare | prepared] or [sqlite3_reset | reset],
4191 **           the [sqlite3_data_count(S)] routine returns zero.
4192 */
4193 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4194
4195 /*
4196 ** CAPI3REF: Fundamental Datatypes {H10265} <S10110><S10120>
4197 ** KEYWORDS: SQLITE_TEXT
4198 **
4199 ** {H10266} Every value in SQLite has one of five fundamental datatypes:
4200 **
4201 ** <ul>
4202 ** <li> 64-bit signed integer
4203 ** <li> 64-bit IEEE floating point number
4204 ** <li> string
4205 ** <li> BLOB
4206 ** <li> NULL
4207 ** </ul> {END}
4208 **
4209 ** These constants are codes for each of those types.
4210 **
4211 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4212 ** for a completely different meaning.  Software that links against both
4213 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4214 ** SQLITE_TEXT.
4215 */
4216 #define SQLITE_INTEGER  1
4217 #define SQLITE_FLOAT    2
4218 #define SQLITE_BLOB     4
4219 #define SQLITE_NULL     5
4220 #ifdef SQLITE_TEXT
4221 # undef SQLITE_TEXT
4222 #else
4223 # define SQLITE_TEXT     3
4224 #endif
4225 #define SQLITE3_TEXT     3
4226
4227 /*
4228 ** CAPI3REF: Result Values From A Query {H13800} <S10700>
4229 ** KEYWORDS: {column access functions}
4230 **
4231 ** These routines form the "result set query" interface.
4232 **
4233 ** These routines return information about a single column of the current
4234 ** result row of a query.  In every case the first argument is a pointer
4235 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4236 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4237 ** and the second argument is the index of the column for which information
4238 ** should be returned.  The leftmost column of the result set has the index 0.
4239 **
4240 ** If the SQL statement does not currently point to a valid row, or if the
4241 ** column index is out of range, the result is undefined.
4242 ** These routines may only be called when the most recent call to
4243 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4244 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4245 ** If any of these routines are called after [sqlite3_reset()] or
4246 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4247 ** something other than [SQLITE_ROW], the results are undefined.
4248 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4249 ** are called from a different thread while any of these routines
4250 ** are pending, then the results are undefined.
4251 **
4252 ** The sqlite3_column_type() routine returns the
4253 ** [SQLITE_INTEGER | datatype code] for the initial data type
4254 ** of the result column.  The returned value is one of [SQLITE_INTEGER],
4255 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4256 ** returned by sqlite3_column_type() is only meaningful if no type
4257 ** conversions have occurred as described below.  After a type conversion,
4258 ** the value returned by sqlite3_column_type() is undefined.  Future
4259 ** versions of SQLite may change the behavior of sqlite3_column_type()
4260 ** following a type conversion.
4261 **
4262 ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4263 ** routine returns the number of bytes in that BLOB or string.
4264 ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4265 ** the string to UTF-8 and then returns the number of bytes.
4266 ** If the result is a numeric value then sqlite3_column_bytes() uses
4267 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4268 ** the number of bytes in that string.
4269 ** The value returned does not include the zero terminator at the end
4270 ** of the string.  For clarity: the value returned is the number of
4271 ** bytes in the string, not the number of characters.
4272 **
4273 ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4274 ** even empty strings, are always zero terminated.  The return
4275 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
4276 ** pointer, possibly even a NULL pointer.
4277 **
4278 ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
4279 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
4280 ** The zero terminator is not included in this count.
4281 **
4282 ** The object returned by [sqlite3_column_value()] is an
4283 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4284 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4285 ** If the [unprotected sqlite3_value] object returned by
4286 ** [sqlite3_column_value()] is used in any other way, including calls
4287 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4288 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4289 **
4290 ** These routines attempt to convert the value where appropriate.  For
4291 ** example, if the internal representation is FLOAT and a text result
4292 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4293 ** conversion automatically.  The following table details the conversions
4294 ** that are applied:
4295 **
4296 ** <blockquote>
4297 ** <table border="1">
4298 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4299 **
4300 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4301 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4302 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4303 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4304 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4305 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4306 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4307 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4308 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4309 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4310 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4311 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4312 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4313 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4314 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4315 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4316 ** </table>
4317 ** </blockquote>
4318 **
4319 ** The table above makes reference to standard C library functions atoi()
4320 ** and atof().  SQLite does not really use these functions.  It has its
4321 ** own equivalent internal routines.  The atoi() and atof() names are
4322 ** used in the table for brevity and because they are familiar to most
4323 ** C programmers.
4324 **
4325 ** Note that when type conversions occur, pointers returned by prior
4326 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4327 ** sqlite3_column_text16() may be invalidated.
4328 ** Type conversions and pointer invalidations might occur
4329 ** in the following cases:
4330 **
4331 ** <ul>
4332 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4333 **      sqlite3_column_text16() is called.  A zero-terminator might
4334 **      need to be added to the string.</li>
4335 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4336 **      sqlite3_column_text16() is called.  The content must be converted
4337 **      to UTF-16.</li>
4338 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4339 **      sqlite3_column_text() is called.  The content must be converted
4340 **      to UTF-8.</li>
4341 ** </ul>
4342 **
4343 ** Conversions between UTF-16be and UTF-16le are always done in place and do
4344 ** not invalidate a prior pointer, though of course the content of the buffer
4345 ** that the prior pointer points to will have been modified.  Other kinds
4346 ** of conversion are done in place when it is possible, but sometimes they
4347 ** are not possible and in those cases prior pointers are invalidated.
4348 **
4349 ** The safest and easiest to remember policy is to invoke these routines
4350 ** in one of the following ways:
4351 **
4352 ** <ul>
4353 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4354 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4355 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4356 ** </ul>
4357 **
4358 ** In other words, you should call sqlite3_column_text(),
4359 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4360 ** into the desired format, then invoke sqlite3_column_bytes() or
4361 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4362 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4363 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4364 ** with calls to sqlite3_column_bytes().
4365 **
4366 ** The pointers returned are valid until a type conversion occurs as
4367 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4368 ** [sqlite3_finalize()] is called.  The memory space used to hold strings
4369 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4370 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4371 ** [sqlite3_free()].
4372 **
4373 ** If a memory allocation error occurs during the evaluation of any
4374 ** of these routines, a default value is returned.  The default value
4375 ** is either the integer 0, the floating point number 0.0, or a NULL
4376 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4377 ** [SQLITE_NOMEM].
4378 **
4379 ** INVARIANTS:
4380 **
4381 ** {H13803} The [sqlite3_column_blob(S,N)] interface converts the
4382 **          Nth column in the current row of the result set for
4383 **          the [prepared statement] S into a BLOB and then returns a
4384 **          pointer to the converted value.
4385 **
4386 ** {H13806} The [sqlite3_column_bytes(S,N)] interface returns the
4387 **          number of bytes in the BLOB or string (exclusive of the
4388 **          zero terminator on the string) that was returned by the
4389 **          most recent call to [sqlite3_column_blob(S,N)] or
4390 **          [sqlite3_column_text(S,N)].
4391 **
4392 ** {H13809} The [sqlite3_column_bytes16(S,N)] interface returns the
4393 **          number of bytes in the string (exclusive of the
4394 **          zero terminator on the string) that was returned by the
4395 **          most recent call to [sqlite3_column_text16(S,N)].
4396 **
4397 ** {H13812} The [sqlite3_column_double(S,N)] interface converts the
4398 **          Nth column in the current row of the result set for the
4399 **          [prepared statement] S into a floating point value and
4400 **          returns a copy of that value.
4401 **
4402 ** {H13815} The [sqlite3_column_int(S,N)] interface converts the
4403 **          Nth column in the current row of the result set for the
4404 **          [prepared statement] S into a 64-bit signed integer and
4405 **          returns the lower 32 bits of that integer.
4406 **
4407 ** {H13818} The [sqlite3_column_int64(S,N)] interface converts the
4408 **          Nth column in the current row of the result set for the
4409 **          [prepared statement] S into a 64-bit signed integer and
4410 **          returns a copy of that integer.
4411 **
4412 ** {H13821} The [sqlite3_column_text(S,N)] interface converts the
4413 **          Nth column in the current row of the result set for
4414 **          the [prepared statement] S into a zero-terminated UTF-8
4415 **          string and returns a pointer to that string.
4416 **
4417 ** {H13824} The [sqlite3_column_text16(S,N)] interface converts the
4418 **          Nth column in the current row of the result set for the
4419 **          [prepared statement] S into a zero-terminated 2-byte
4420 **          aligned UTF-16 native byte order string and returns
4421 **          a pointer to that string.
4422 **
4423 ** {H13827} The [sqlite3_column_type(S,N)] interface returns
4424 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4425 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4426 **          the Nth column in the current row of the result set for
4427 **          the [prepared statement] S.
4428 **
4429 ** {H13830} The [sqlite3_column_value(S,N)] interface returns a
4430 **          pointer to an [unprotected sqlite3_value] object for the
4431 **          Nth column in the current row of the result set for
4432 **          the [prepared statement] S.
4433 */
4434 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4435 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4436 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4437 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4438 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4439 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4440 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4441 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4442 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4443 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4444
4445 /*
4446 ** CAPI3REF: Destroy A Prepared Statement Object {H13300} <S70300><S30100>
4447 **
4448 ** The sqlite3_finalize() function is called to delete a [prepared statement].
4449 ** If the statement was executed successfully or not executed at all, then
4450 ** SQLITE_OK is returned. If execution of the statement failed then an
4451 ** [error code] or [extended error code] is returned.
4452 **
4453 ** This routine can be called at any point during the execution of the
4454 ** [prepared statement].  If the virtual machine has not
4455 ** completed execution when this routine is called, that is like
4456 ** encountering an error or an [sqlite3_interrupt | interrupt].
4457 ** Incomplete updates may be rolled back and transactions canceled,
4458 ** depending on the circumstances, and the
4459 ** [error code] returned will be [SQLITE_ABORT].
4460 **
4461 ** INVARIANTS:
4462 **
4463 ** {H11302} The [sqlite3_finalize(S)] interface destroys the
4464 **          [prepared statement] S and releases all
4465 **          memory and file resources held by that object.
4466 **
4467 ** {H11304} If the most recent call to [sqlite3_step(S)] for the
4468 **          [prepared statement] S returned an error,
4469 **          then [sqlite3_finalize(S)] returns that same error.
4470 */
4471 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4472
4473 /*
4474 ** CAPI3REF: Reset A Prepared Statement Object {H13330} <S70300>
4475 **
4476 ** The sqlite3_reset() function is called to reset a [prepared statement]
4477 ** object back to its initial state, ready to be re-executed.
4478 ** Any SQL statement variables that had values bound to them using
4479 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4480 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4481 **
4482 ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S
4483 **          back to the beginning of its program.
4484 **
4485 ** {H11334} If the most recent call to [sqlite3_step(S)] for the
4486 **          [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4487 **          or if [sqlite3_step(S)] has never before been called on S,
4488 **          then [sqlite3_reset(S)] returns [SQLITE_OK].
4489 **
4490 ** {H11336} If the most recent call to [sqlite3_step(S)] for the
4491 **          [prepared statement] S indicated an error, then
4492 **          [sqlite3_reset(S)] returns an appropriate [error code].
4493 **
4494 ** {H11338} The [sqlite3_reset(S)] interface does not change the values
4495 **          of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4496 */
4497 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4498
4499 /*
4500 ** CAPI3REF: Create Or Redefine SQL Functions {H16100} <S20200>
4501 ** KEYWORDS: {function creation routines}
4502 ** KEYWORDS: {application-defined SQL function}
4503 ** KEYWORDS: {application-defined SQL functions}
4504 **
4505 ** These two functions (collectively known as "function creation routines")
4506 ** are used to add SQL functions or aggregates or to redefine the behavior
4507 ** of existing SQL functions or aggregates.  The only difference between the
4508 ** two is that the second parameter, the name of the (scalar) function or
4509 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
4510 ** for sqlite3_create_function16().
4511 **
4512 ** The first parameter is the [database connection] to which the SQL
4513 ** function is to be added.  If a single program uses more than one database
4514 ** connection internally, then SQL functions must be added individually to
4515 ** each database connection.
4516 **
4517 ** The second parameter is the name of the SQL function to be created or
4518 ** redefined.  The length of the name is limited to 255 bytes, exclusive of
4519 ** the zero-terminator.  Note that the name length limit is in bytes, not
4520 ** characters.  Any attempt to create a function with a longer name
4521 ** will result in [SQLITE_ERROR] being returned.
4522 **
4523 ** The third parameter (nArg)
4524 ** is the number of arguments that the SQL function or
4525 ** aggregate takes. If this parameter is negative, then the SQL function or
4526 ** aggregate may take any number of arguments.
4527 **
4528 ** The fourth parameter, eTextRep, specifies what
4529 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4530 ** its parameters.  Any SQL function implementation should be able to work
4531 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4532 ** more efficient with one encoding than another.  It is allowed to
4533 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4534 ** times with the same function but with different values of eTextRep.
4535 ** When multiple implementations of the same function are available, SQLite
4536 ** will pick the one that involves the least amount of data conversion.
4537 ** If there is only a single implementation which does not care what text
4538 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4539 **
4540 ** The fifth parameter is an arbitrary pointer.  The implementation of the
4541 ** function can gain access to this pointer using [sqlite3_user_data()].
4542 **
4543 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
4544 ** pointers to C-language functions that implement the SQL function or
4545 ** aggregate. A scalar SQL function requires an implementation of the xFunc
4546 ** callback only, NULL pointers should be passed as the xStep and xFinal
4547 ** parameters. An aggregate SQL function requires an implementation of xStep
4548 ** and xFinal and NULL should be passed for xFunc. To delete an existing
4549 ** SQL function or aggregate, pass NULL for all three function callbacks.
4550 **
4551 ** It is permitted to register multiple implementations of the same
4552 ** functions with the same name but with either differing numbers of
4553 ** arguments or differing preferred text encodings.  SQLite will use
4554 ** the implementation most closely matches the way in which the
4555 ** SQL function is used.  A function implementation with a non-negative
4556 ** nArg parameter is a better match than a function implementation with
4557 ** a negative nArg.  A function where the preferred text encoding
4558 ** matches the database encoding is a better
4559 ** match than a function where the encoding is different.  
4560 ** A function where the encoding difference is between UTF16le and UTF16be
4561 ** is a closer match than a function where the encoding difference is
4562 ** between UTF8 and UTF16.
4563 **
4564 ** Built-in functions may be overloaded by new application-defined functions.
4565 ** The first application-defined function with a given name overrides all
4566 ** built-in functions in the same [database connection] with the same name.
4567 ** Subsequent application-defined functions of the same name only override 
4568 ** prior application-defined functions that are an exact match for the
4569 ** number of parameters and preferred encoding.
4570 **
4571 ** An application-defined function is permitted to call other
4572 ** SQLite interfaces.  However, such calls must not
4573 ** close the database connection nor finalize or reset the prepared
4574 ** statement in which the function is running.
4575 **
4576 ** INVARIANTS:
4577 **
4578 ** {H16103} The [sqlite3_create_function16(D,X,...)] interface shall behave
4579 **          as [sqlite3_create_function(D,X,...)] in every way except that it
4580 **          interprets the X argument as zero-terminated UTF-16
4581 **          native byte order instead of as zero-terminated UTF-8.
4582 **
4583 ** {H16106} A successful invocation of the
4584 **          [sqlite3_create_function(D,X,N,E,...)] interface shall register
4585 **          or replaces callback functions in the [database connection] D
4586 **          used to implement the SQL function named X with N parameters
4587 **          and having a preferred text encoding of E.
4588 **
4589 ** {H16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4590 **          shall replace the P, F, S, and L values from any prior calls with
4591 **          the same D, X, N, and E values.
4592 **
4593 ** {H16112} The [sqlite3_create_function(D,X,...)] interface shall fail
4594 **          if the SQL function name X is
4595 **          longer than 255 bytes exclusive of the zero terminator.
4596 **
4597 ** {H16118} The [sqlite3_create_function(D,X,N,E,P,F,S,L)] interface
4598 **          shall fail unless either F is NULL and S and L are non-NULL or
4599 ***         F is non-NULL and S and L are NULL.
4600 **
4601 ** {H16121} The [sqlite3_create_function(D,...)] interface shall fails with an
4602 **          error code of [SQLITE_BUSY] if there exist [prepared statements]
4603 **          associated with the [database connection] D.
4604 **
4605 ** {H16124} The [sqlite3_create_function(D,X,N,...)] interface shall fail with
4606 **          an error code of [SQLITE_ERROR] if parameter N is less
4607 **          than -1 or greater than 127.
4608 **
4609 ** {H16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)]
4610 **          interface shall register callbacks to be invoked for the
4611 **          SQL function
4612 **          named X when the number of arguments to the SQL function is
4613 **          exactly N.
4614 **
4615 ** {H16130} When N is -1, the [sqlite3_create_function(D,X,N,...)]
4616 **          interface shall register callbacks to be invoked for the SQL
4617 **          function named X with any number of arguments.
4618 **
4619 ** {H16133} When calls to [sqlite3_create_function(D,X,N,...)]
4620 **          specify multiple implementations of the same function X
4621 **          and when one implementation has N>=0 and the other has N=(-1)
4622 **          the implementation with a non-zero N shall be preferred.
4623 **
4624 ** {H16136} When calls to [sqlite3_create_function(D,X,N,E,...)]
4625 **          specify multiple implementations of the same function X with
4626 **          the same number of arguments N but with different
4627 **          encodings E, then the implementation where E matches the
4628 **          database encoding shall preferred.
4629 **
4630 ** {H16139} For an aggregate SQL function created using
4631 **          [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer
4632 **          function L shall always be invoked exactly once if the
4633 **          step function S is called one or more times.
4634 **
4635 ** {H16142} When SQLite invokes either the xFunc or xStep function of
4636 **          an application-defined SQL function or aggregate created
4637 **          by [sqlite3_create_function()] or [sqlite3_create_function16()],
4638 **          then the array of [sqlite3_value] objects passed as the
4639 **          third parameter shall be [protected sqlite3_value] objects.
4640 */
4641 SQLITE_API int sqlite3_create_function(
4642   sqlite3 *db,
4643   const char *zFunctionName,
4644   int nArg,
4645   int eTextRep,
4646   void *pApp,
4647   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4648   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4649   void (*xFinal)(sqlite3_context*)
4650 );
4651 SQLITE_API int sqlite3_create_function16(
4652   sqlite3 *db,
4653   const void *zFunctionName,
4654   int nArg,
4655   int eTextRep,
4656   void *pApp,
4657   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4658   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4659   void (*xFinal)(sqlite3_context*)
4660 );
4661
4662 /*
4663 ** CAPI3REF: Text Encodings {H10267} <S50200> <H16100>
4664 **
4665 ** These constant define integer codes that represent the various
4666 ** text encodings supported by SQLite.
4667 */
4668 #define SQLITE_UTF8           1
4669 #define SQLITE_UTF16LE        2
4670 #define SQLITE_UTF16BE        3
4671 #define SQLITE_UTF16          4    /* Use native byte order */
4672 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4673 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4674
4675 /*
4676 ** CAPI3REF: Deprecated Functions
4677 ** DEPRECATED
4678 **
4679 ** These functions are [deprecated].  In order to maintain
4680 ** backwards compatibility with older code, these functions continue 
4681 ** to be supported.  However, new applications should avoid
4682 ** the use of these functions.  To help encourage people to avoid
4683 ** using these functions, we are not going to tell you what they do.
4684 */
4685 #ifndef SQLITE_OMIT_DEPRECATED
4686 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4687 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4688 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4689 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4690 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4691 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4692 #endif
4693
4694 /*
4695 ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} <S20200>
4696 **
4697 ** The C-language implementation of SQL functions and aggregates uses
4698 ** this set of interface routines to access the parameter values on
4699 ** the function or aggregate.
4700 **
4701 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4702 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4703 ** define callbacks that implement the SQL functions and aggregates.
4704 ** The 4th parameter to these callbacks is an array of pointers to
4705 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4706 ** each parameter to the SQL function.  These routines are used to
4707 ** extract values from the [sqlite3_value] objects.
4708 **
4709 ** These routines work only with [protected sqlite3_value] objects.
4710 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4711 ** object results in undefined behavior.
4712 **
4713 ** These routines work just like the corresponding [column access functions]
4714 ** except that  these routines take a single [protected sqlite3_value] object
4715 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4716 **
4717 ** The sqlite3_value_text16() interface extracts a UTF-16 string
4718 ** in the native byte-order of the host machine.  The
4719 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4720 ** extract UTF-16 strings as big-endian and little-endian respectively.
4721 **
4722 ** The sqlite3_value_numeric_type() interface attempts to apply
4723 ** numeric affinity to the value.  This means that an attempt is
4724 ** made to convert the value to an integer or floating point.  If
4725 ** such a conversion is possible without loss of information (in other
4726 ** words, if the value is a string that looks like a number)
4727 ** then the conversion is performed.  Otherwise no conversion occurs.
4728 ** The [SQLITE_INTEGER | datatype] after conversion is returned.
4729 **
4730 ** Please pay particular attention to the fact that the pointer returned
4731 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4732 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4733 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4734 ** or [sqlite3_value_text16()].
4735 **
4736 ** These routines must be called from the same thread as
4737 ** the SQL function that supplied the [sqlite3_value*] parameters.
4738 **
4739 ** INVARIANTS:
4740 **
4741 ** {H15103} The [sqlite3_value_blob(V)] interface converts the
4742 **          [protected sqlite3_value] object V into a BLOB and then
4743 **          returns a pointer to the converted value.
4744 **
4745 ** {H15106} The [sqlite3_value_bytes(V)] interface returns the
4746 **          number of bytes in the BLOB or string (exclusive of the
4747 **          zero terminator on the string) that was returned by the
4748 **          most recent call to [sqlite3_value_blob(V)] or
4749 **          [sqlite3_value_text(V)].
4750 **
4751 ** {H15109} The [sqlite3_value_bytes16(V)] interface returns the
4752 **          number of bytes in the string (exclusive of the
4753 **          zero terminator on the string) that was returned by the
4754 **          most recent call to [sqlite3_value_text16(V)],
4755 **          [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)].
4756 **
4757 ** {H15112} The [sqlite3_value_double(V)] interface converts the
4758 **          [protected sqlite3_value] object V into a floating point value and
4759 **          returns a copy of that value.
4760 **
4761 ** {H15115} The [sqlite3_value_int(V)] interface converts the
4762 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4763 **          returns the lower 32 bits of that integer.
4764 **
4765 ** {H15118} The [sqlite3_value_int64(V)] interface converts the
4766 **          [protected sqlite3_value] object V into a 64-bit signed integer and
4767 **          returns a copy of that integer.
4768 **
4769 ** {H15121} The [sqlite3_value_text(V)] interface converts the
4770 **          [protected sqlite3_value] object V into a zero-terminated UTF-8
4771 **          string and returns a pointer to that string.
4772 **
4773 ** {H15124} The [sqlite3_value_text16(V)] interface converts the
4774 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4775 **          aligned UTF-16 native byte order
4776 **          string and returns a pointer to that string.
4777 **
4778 ** {H15127} The [sqlite3_value_text16be(V)] interface converts the
4779 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4780 **          aligned UTF-16 big-endian
4781 **          string and returns a pointer to that string.
4782 **
4783 ** {H15130} The [sqlite3_value_text16le(V)] interface converts the
4784 **          [protected sqlite3_value] object V into a zero-terminated 2-byte
4785 **          aligned UTF-16 little-endian
4786 **          string and returns a pointer to that string.
4787 **
4788 ** {H15133} The [sqlite3_value_type(V)] interface returns
4789 **          one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT],
4790 **          [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for
4791 **          the [sqlite3_value] object V.
4792 **
4793 ** {H15136} The [sqlite3_value_numeric_type(V)] interface converts
4794 **          the [protected sqlite3_value] object V into either an integer or
4795 **          a floating point value if it can do so without loss of
4796 **          information, and returns one of [SQLITE_NULL],
4797 **          [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or
4798 **          [SQLITE_BLOB] as appropriate for the
4799 **          [protected sqlite3_value] object V after the conversion attempt.
4800 */
4801 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4802 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4803 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4804 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4805 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4806 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4807 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4808 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4809 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4810 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4811 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4812 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4813
4814 /*
4815 ** CAPI3REF: Obtain Aggregate Function Context {H16210} <S20200>
4816 **
4817 ** The implementation of aggregate SQL functions use this routine to allocate
4818 ** a structure for storing their state.
4819 **
4820 ** The first time the sqlite3_aggregate_context() routine is called for a
4821 ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that
4822 ** memory, and returns a pointer to it. On second and subsequent calls to
4823 ** sqlite3_aggregate_context() for the same aggregate function index,
4824 ** the same buffer is returned. The implementation of the aggregate can use
4825 ** the returned buffer to accumulate data.
4826 **
4827 ** SQLite automatically frees the allocated buffer when the aggregate
4828 ** query concludes.
4829 **
4830 ** The first parameter should be a copy of the
4831 ** [sqlite3_context | SQL function context] that is the first parameter
4832 ** to the callback routine that implements the aggregate function.
4833 **
4834 ** This routine must be called from the same thread in which
4835 ** the aggregate SQL function is running.
4836 **
4837 ** INVARIANTS:
4838 **
4839 ** {H16211} The first invocation of [sqlite3_aggregate_context(C,N)] for
4840 **          a particular instance of an aggregate function (for a particular
4841 **          context C) causes SQLite to allocate N bytes of memory,
4842 **          zero that memory, and return a pointer to the allocated memory.
4843 **
4844 ** {H16213} If a memory allocation error occurs during
4845 **          [sqlite3_aggregate_context(C,N)] then the function returns 0.
4846 **
4847 ** {H16215} Second and subsequent invocations of
4848 **          [sqlite3_aggregate_context(C,N)] for the same context pointer C
4849 **          ignore the N parameter and return a pointer to the same
4850 **          block of memory returned by the first invocation.
4851 **
4852 ** {H16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is
4853 **          automatically freed on the next call to [sqlite3_reset()]
4854 **          or [sqlite3_finalize()] for the [prepared statement] containing
4855 **          the aggregate function associated with context C.
4856 */
4857 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4858
4859 /*
4860 ** CAPI3REF: User Data For Functions {H16240} <S20200>
4861 **
4862 ** The sqlite3_user_data() interface returns a copy of
4863 ** the pointer that was the pUserData parameter (the 5th parameter)
4864 ** of the [sqlite3_create_function()]
4865 ** and [sqlite3_create_function16()] routines that originally
4866 ** registered the application defined function. {END}
4867 **
4868 ** This routine must be called from the same thread in which
4869 ** the application-defined function is running.
4870 **
4871 ** INVARIANTS:
4872 **
4873 ** {H16243} The [sqlite3_user_data(C)] interface returns a copy of the
4874 **          P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4875 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4876 **          registered the SQL function associated with [sqlite3_context] C.
4877 */
4878 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4879
4880 /*
4881 ** CAPI3REF: Database Connection For Functions {H16250} <S60600><S20200>
4882 **
4883 ** The sqlite3_context_db_handle() interface returns a copy of
4884 ** the pointer to the [database connection] (the 1st parameter)
4885 ** of the [sqlite3_create_function()]
4886 ** and [sqlite3_create_function16()] routines that originally
4887 ** registered the application defined function.
4888 **
4889 ** INVARIANTS:
4890 **
4891 ** {H16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the
4892 **          D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)]
4893 **          or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that
4894 **          registered the SQL function associated with [sqlite3_context] C.
4895 */
4896 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4897
4898 /*
4899 ** CAPI3REF: Function Auxiliary Data {H16270} <S20200>
4900 **
4901 ** The following two functions may be used by scalar SQL functions to
4902 ** associate metadata with argument values. If the same value is passed to
4903 ** multiple invocations of the same SQL function during query execution, under
4904 ** some circumstances the associated metadata may be preserved. This may
4905 ** be used, for example, to add a regular-expression matching scalar
4906 ** function. The compiled version of the regular expression is stored as
4907 ** metadata associated with the SQL value passed as the regular expression
4908 ** pattern.  The compiled regular expression can be reused on multiple
4909 ** invocations of the same function so that the original pattern string
4910 ** does not need to be recompiled on each invocation.
4911 **
4912 ** The sqlite3_get_auxdata() interface returns a pointer to the metadata
4913 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4914 ** value to the application-defined function. If no metadata has been ever
4915 ** been set for the Nth argument of the function, or if the corresponding
4916 ** function parameter has changed since the meta-data was set,
4917 ** then sqlite3_get_auxdata() returns a NULL pointer.
4918 **
4919 ** The sqlite3_set_auxdata() interface saves the metadata
4920 ** pointed to by its 3rd parameter as the metadata for the N-th
4921 ** argument of the application-defined function.  Subsequent
4922 ** calls to sqlite3_get_auxdata() might return this data, if it has
4923 ** not been destroyed.
4924 ** If it is not NULL, SQLite will invoke the destructor
4925 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4926 ** the metadata when the corresponding function parameter changes
4927 ** or when the SQL statement completes, whichever comes first.
4928 **
4929 ** SQLite is free to call the destructor and drop metadata on any
4930 ** parameter of any function at any time.  The only guarantee is that
4931 ** the destructor will be called before the metadata is dropped.
4932 **
4933 ** In practice, metadata is preserved between function calls for
4934 ** expressions that are constant at compile time. This includes literal
4935 ** values and SQL variables.
4936 **
4937 ** These routines must be called from the same thread in which
4938 ** the SQL function is running.
4939 **
4940 ** INVARIANTS:
4941 **
4942 ** {H16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer
4943 **          to metadata associated with the Nth parameter of the SQL function
4944 **          whose context is C, or NULL if there is no metadata associated
4945 **          with that parameter.
4946 **
4947 ** {H16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata
4948 **          pointer P to the Nth parameter of the SQL function with context C.
4949 **
4950 ** {H16276} SQLite will invoke the destructor D with a single argument
4951 **          which is the metadata pointer P following a call to
4952 **          [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold
4953 **          the metadata.
4954 **
4955 ** {H16277} SQLite ceases to hold metadata for an SQL function parameter
4956 **          when the value of that parameter changes.
4957 **
4958 ** {H16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor
4959 **          is called for any prior metadata associated with the same function
4960 **          context C and parameter N.
4961 **
4962 ** {H16279} SQLite will call destructors for any metadata it is holding
4963 **          in a particular [prepared statement] S when either
4964 **          [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called.
4965 */
4966 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4967 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4968
4969
4970 /*
4971 ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} <S30100>
4972 **
4973 ** These are special values for the destructor that is passed in as the
4974 ** final argument to routines like [sqlite3_result_blob()].  If the destructor
4975 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4976 ** and will never change.  It does not need to be destroyed.  The
4977 ** SQLITE_TRANSIENT value means that the content will likely change in
4978 ** the near future and that SQLite should make its own private copy of
4979 ** the content before returning.
4980 **
4981 ** The typedef is necessary to work around problems in certain
4982 ** C++ compilers.  See ticket #2191.
4983 */
4984 typedef void (*sqlite3_destructor_type)(void*);
4985 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4986 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4987
4988 /*
4989 ** CAPI3REF: Setting The Result Of An SQL Function {H16400} <S20200>
4990 **
4991 ** These routines are used by the xFunc or xFinal callbacks that
4992 ** implement SQL functions and aggregates.  See
4993 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4994 ** for additional information.
4995 **
4996 ** These functions work very much like the [parameter binding] family of
4997 ** functions used to bind values to host parameters in prepared statements.
4998 ** Refer to the [SQL parameter] documentation for additional information.
4999 **
5000 ** The sqlite3_result_blob() interface sets the result from
5001 ** an application-defined function to be the BLOB whose content is pointed
5002 ** to by the second parameter and which is N bytes long where N is the
5003 ** third parameter.
5004 **
5005 ** The sqlite3_result_zeroblob() interfaces set the result of
5006 ** the application-defined function to be a BLOB containing all zero
5007 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
5008 **
5009 ** The sqlite3_result_double() interface sets the result from
5010 ** an application-defined function to be a floating point value specified
5011 ** by its 2nd argument.
5012 **
5013 ** The sqlite3_result_error() and sqlite3_result_error16() functions
5014 ** cause the implemented SQL function to throw an exception.
5015 ** SQLite uses the string pointed to by the
5016 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5017 ** as the text of an error message.  SQLite interprets the error
5018 ** message string from sqlite3_result_error() as UTF-8. SQLite
5019 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
5020 ** byte order.  If the third parameter to sqlite3_result_error()
5021 ** or sqlite3_result_error16() is negative then SQLite takes as the error
5022 ** message all text up through the first zero character.
5023 ** If the third parameter to sqlite3_result_error() or
5024 ** sqlite3_result_error16() is non-negative then SQLite takes that many
5025 ** bytes (not characters) from the 2nd parameter as the error message.
5026 ** The sqlite3_result_error() and sqlite3_result_error16()
5027 ** routines make a private copy of the error message text before
5028 ** they return.  Hence, the calling function can deallocate or
5029 ** modify the text after they return without harm.
5030 ** The sqlite3_result_error_code() function changes the error code
5031 ** returned by SQLite as a result of an error in a function.  By default,
5032 ** the error code is SQLITE_ERROR.  A subsequent call to sqlite3_result_error()
5033 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5034 **
5035 ** The sqlite3_result_toobig() interface causes SQLite to throw an error
5036 ** indicating that a string or BLOB is to long to represent.
5037 **
5038 ** The sqlite3_result_nomem() interface causes SQLite to throw an error
5039 ** indicating that a memory allocation failed.
5040 **
5041 ** The sqlite3_result_int() interface sets the return value
5042 ** of the application-defined function to be the 32-bit signed integer
5043 ** value given in the 2nd argument.
5044 ** The sqlite3_result_int64() interface sets the return value
5045 ** of the application-defined function to be the 64-bit signed integer
5046 ** value given in the 2nd argument.
5047 **
5048 ** The sqlite3_result_null() interface sets the return value
5049 ** of the application-defined function to be NULL.
5050 **
5051 ** The sqlite3_result_text(), sqlite3_result_text16(),
5052 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5053 ** set the return value of the application-defined function to be
5054 ** a text string which is represented as UTF-8, UTF-16 native byte order,
5055 ** UTF-16 little endian, or UTF-16 big endian, respectively.
5056 ** SQLite takes the text result from the application from
5057 ** the 2nd parameter of the sqlite3_result_text* interfaces.
5058 ** If the 3rd parameter to the sqlite3_result_text* interfaces
5059 ** is negative, then SQLite takes result text from the 2nd parameter
5060 ** through the first zero character.
5061 ** If the 3rd parameter to the sqlite3_result_text* interfaces
5062 ** is non-negative, then as many bytes (not characters) of the text
5063 ** pointed to by the 2nd parameter are taken as the application-defined
5064 ** function result.
5065 ** If the 4th parameter to the sqlite3_result_text* interfaces
5066 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5067 ** function as the destructor on the text or BLOB result when it has
5068 ** finished using that result.
5069 ** If the 4th parameter to the sqlite3_result_text* interfaces or
5070 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5071 ** assumes that the text or BLOB result is in constant space and does not
5072 ** copy the it or call a destructor when it has finished using that result.
5073 ** If the 4th parameter to the sqlite3_result_text* interfaces
5074 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5075 ** then SQLite makes a copy of the result into space obtained from
5076 ** from [sqlite3_malloc()] before it returns.
5077 **
5078 ** The sqlite3_result_value() interface sets the result of
5079 ** the application-defined function to be a copy the
5080 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  The
5081 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5082 ** so that the [sqlite3_value] specified in the parameter may change or
5083 ** be deallocated after sqlite3_result_value() returns without harm.
5084 ** A [protected sqlite3_value] object may always be used where an
5085 ** [unprotected sqlite3_value] object is required, so either
5086 ** kind of [sqlite3_value] object can be used with this interface.
5087 **
5088 ** If these routines are called from within the different thread
5089 ** than the one containing the application-defined function that received
5090 ** the [sqlite3_context] pointer, the results are undefined.
5091 **
5092 ** INVARIANTS:
5093 **
5094 ** {H16403} The default return value from any SQL function is NULL.
5095 **
5096 ** {H16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the
5097 **          return value of function C to be a BLOB that is N bytes
5098 **          in length and with content pointed to by V.
5099 **
5100 ** {H16409} The [sqlite3_result_double(C,V)] interface changes the
5101 **          return value of function C to be the floating point value V.
5102 **
5103 ** {H16412} The [sqlite3_result_error(C,V,N)] interface changes the return
5104 **          value of function C to be an exception with error code
5105 **          [SQLITE_ERROR] and a UTF-8 error message copied from V up to the
5106 **          first zero byte or until N bytes are read if N is positive.
5107 **
5108 ** {H16415} The [sqlite3_result_error16(C,V,N)] interface changes the return
5109 **          value of function C to be an exception with error code
5110 **          [SQLITE_ERROR] and a UTF-16 native byte order error message
5111 **          copied from V up to the first zero terminator or until N bytes
5112 **          are read if N is positive.
5113 **
5114 ** {H16418} The [sqlite3_result_error_toobig(C)] interface changes the return
5115 **          value of the function C to be an exception with error code
5116 **          [SQLITE_TOOBIG] and an appropriate error message.
5117 **
5118 ** {H16421} The [sqlite3_result_error_nomem(C)] interface changes the return
5119 **          value of the function C to be an exception with error code
5120 **          [SQLITE_NOMEM] and an appropriate error message.
5121 **
5122 ** {H16424} The [sqlite3_result_error_code(C,E)] interface changes the return
5123 **          value of the function C to be an exception with error code E.
5124 **          The error message text is unchanged.
5125 **
5126 ** {H16427} The [sqlite3_result_int(C,V)] interface changes the
5127 **          return value of function C to be the 32-bit integer value V.
5128 **
5129 ** {H16430} The [sqlite3_result_int64(C,V)] interface changes the
5130 **          return value of function C to be the 64-bit integer value V.
5131 **
5132 ** {H16433} The [sqlite3_result_null(C)] interface changes the
5133 **          return value of function C to be NULL.
5134 **
5135 ** {H16436} The [sqlite3_result_text(C,V,N,D)] interface changes the
5136 **          return value of function C to be the UTF-8 string
5137 **          V up to the first zero if N is negative
5138 **          or the first N bytes of V if N is non-negative.
5139 **
5140 ** {H16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the
5141 **          return value of function C to be the UTF-16 native byte order
5142 **          string V up to the first zero if N is negative
5143 **          or the first N bytes of V if N is non-negative.
5144 **
5145 ** {H16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the
5146 **          return value of function C to be the UTF-16 big-endian
5147 **          string V up to the first zero if N is negative
5148 **          or the first N bytes or V if N is non-negative.
5149 **
5150 ** {H16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the
5151 **          return value of function C to be the UTF-16 little-endian
5152 **          string V up to the first zero if N is negative
5153 **          or the first N bytes of V if N is non-negative.
5154 **
5155 ** {H16448} The [sqlite3_result_value(C,V)] interface changes the
5156 **          return value of function C to be the [unprotected sqlite3_value]
5157 **          object V.
5158 **
5159 ** {H16451} The [sqlite3_result_zeroblob(C,N)] interface changes the
5160 **          return value of function C to be an N-byte BLOB of all zeros.
5161 **
5162 ** {H16454} The [sqlite3_result_error()] and [sqlite3_result_error16()]
5163 **          interfaces make a copy of their error message strings before
5164 **          returning.
5165 **
5166 ** {H16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5167 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5168 **          [sqlite3_result_text16be(C,V,N,D)], or
5169 **          [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC]
5170 **          then no destructor is ever called on the pointer V and SQLite
5171 **          assumes that V is immutable.
5172 **
5173 ** {H16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5174 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5175 **          [sqlite3_result_text16be(C,V,N,D)], or
5176 **          [sqlite3_result_text16le(C,V,N,D)] is the constant
5177 **          [SQLITE_TRANSIENT] then the interfaces makes a copy of the
5178 **          content of V and retains the copy.
5179 **
5180 ** {H16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)],
5181 **          [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)],
5182 **          [sqlite3_result_text16be(C,V,N,D)], or
5183 **          [sqlite3_result_text16le(C,V,N,D)] is some value other than
5184 **          the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then
5185 **          SQLite will invoke the destructor D with V as its only argument
5186 **          when it has finished with the V value.
5187 */
5188 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5189 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
5190 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5191 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5192 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
5193 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
5194 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
5195 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
5196 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5197 SQLITE_API void sqlite3_result_null(sqlite3_context*);
5198 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5199 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5200 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5201 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5202 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
5203 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
5204
5205 /*
5206 ** CAPI3REF: Define New Collating Sequences {H16600} <S20300>
5207 **
5208 ** These functions are used to add new collation sequences to the
5209 ** [database connection] specified as the first argument.
5210 **
5211 ** The name of the new collation sequence is specified as a UTF-8 string
5212 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5213 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
5214 ** the name is passed as the second function argument.
5215 **
5216 ** The third argument may be one of the constants [SQLITE_UTF8],
5217 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
5218 ** routine expects to be passed pointers to strings encoded using UTF-8,
5219 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
5220 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
5221 ** the routine expects pointers to 16-bit word aligned strings
5222 ** of UTF-16 in the native byte order of the host computer.
5223 **
5224 ** A pointer to the user supplied routine must be passed as the fifth
5225 ** argument.  If it is NULL, this is the same as deleting the collation
5226 ** sequence (so that SQLite cannot call it anymore).
5227 ** Each time the application supplied function is invoked, it is passed
5228 ** as its first parameter a copy of the void* passed as the fourth argument
5229 ** to sqlite3_create_collation() or sqlite3_create_collation16().
5230 **
5231 ** The remaining arguments to the application-supplied routine are two strings,
5232 ** each represented by a (length, data) pair and encoded in the encoding
5233 ** that was passed as the third argument when the collation sequence was
5234 ** registered. {END}  The application defined collation routine should
5235 ** return negative, zero or positive if the first string is less than,
5236 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
5237 **
5238 ** The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5239 ** except that it takes an extra argument which is a destructor for
5240 ** the collation.  The destructor is called when the collation is
5241 ** destroyed and is passed a copy of the fourth parameter void* pointer
5242 ** of the sqlite3_create_collation_v2().
5243 ** Collations are destroyed when they are overridden by later calls to the
5244 ** collation creation functions or when the [database connection] is closed
5245 ** using [sqlite3_close()].
5246 **
5247 ** INVARIANTS:
5248 **
5249 ** {H16603} A successful call to the
5250 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface
5251 **          registers function F as the comparison function used to
5252 **          implement collation X on the [database connection] B for
5253 **          databases having encoding E.
5254 **
5255 ** {H16604} SQLite understands the X parameter to
5256 **          [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated
5257 **          UTF-8 string in which case is ignored for ASCII characters and
5258 **          is significant for non-ASCII characters.
5259 **
5260 ** {H16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5261 **          with the same values for B, X, and E, override prior values
5262 **          of P, F, and D.
5263 **
5264 ** {H16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5265 **          is not NULL then it is called with argument P when the
5266 **          collating function is dropped by SQLite.
5267 **
5268 ** {H16612} A collating function is dropped when it is overloaded.
5269 **
5270 ** {H16615} A collating function is dropped when the database connection
5271 **          is closed using [sqlite3_close()].
5272 **
5273 ** {H16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)]
5274 **          is passed through as the first parameter to the comparison
5275 **          function F for all subsequent invocations of F.
5276 **
5277 ** {H16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly
5278 **          the same as a call to [sqlite3_create_collation_v2()] with
5279 **          the same parameters and a NULL destructor.
5280 **
5281 ** {H16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)],
5282 **          SQLite uses the comparison function F for all text comparison
5283 **          operations on the [database connection] B on text values that
5284 **          use the collating sequence named X.
5285 **
5286 ** {H16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same
5287 **          as [sqlite3_create_collation(B,X,E,P,F)] except that the
5288 **          collation name X is understood as UTF-16 in native byte order
5289 **          instead of UTF-8.
5290 **
5291 ** {H16630} When multiple comparison functions are available for the same
5292 **          collating sequence, SQLite chooses the one whose text encoding
5293 **          requires the least amount of conversion from the default
5294 **          text encoding of the database.
5295 */
5296 SQLITE_API int sqlite3_create_collation(
5297   sqlite3*, 
5298   const char *zName, 
5299   int eTextRep, 
5300   void*,
5301   int(*xCompare)(void*,int,const void*,int,const void*)
5302 );
5303 SQLITE_API int sqlite3_create_collation_v2(
5304   sqlite3*, 
5305   const char *zName, 
5306   int eTextRep, 
5307   void*,
5308   int(*xCompare)(void*,int,const void*,int,const void*),
5309   void(*xDestroy)(void*)
5310 );
5311 SQLITE_API int sqlite3_create_collation16(
5312   sqlite3*, 
5313   const void *zName,
5314   int eTextRep, 
5315   void*,
5316   int(*xCompare)(void*,int,const void*,int,const void*)
5317 );
5318
5319 /*
5320 ** CAPI3REF: Collation Needed Callbacks {H16700} <S20300>
5321 **
5322 ** To avoid having to register all collation sequences before a database
5323 ** can be used, a single callback function may be registered with the
5324 ** [database connection] to be called whenever an undefined collation
5325 ** sequence is required.
5326 **
5327 ** If the function is registered using the sqlite3_collation_needed() API,
5328 ** then it is passed the names of undefined collation sequences as strings
5329 ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used,
5330 ** the names are passed as UTF-16 in machine native byte order.
5331 ** A call to either function replaces any existing callback.
5332 **
5333 ** When the callback is invoked, the first argument passed is a copy
5334 ** of the second argument to sqlite3_collation_needed() or
5335 ** sqlite3_collation_needed16().  The second argument is the database
5336 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5337 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5338 ** sequence function required.  The fourth parameter is the name of the
5339 ** required collation sequence.
5340 **
5341 ** The callback function should register the desired collation using
5342 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5343 ** [sqlite3_create_collation_v2()].
5344 **
5345 ** INVARIANTS:
5346 **
5347 ** {H16702} A successful call to [sqlite3_collation_needed(D,P,F)]
5348 **          or [sqlite3_collation_needed16(D,P,F)] causes
5349 **          the [database connection] D to invoke callback F with first
5350 **          parameter P whenever it needs a comparison function for a
5351 **          collating sequence that it does not know about.
5352 **
5353 ** {H16704} Each successful call to [sqlite3_collation_needed()] or
5354 **          [sqlite3_collation_needed16()] overrides the callback registered
5355 **          on the same [database connection] by prior calls to either
5356 **          interface.
5357 **
5358 ** {H16706} The name of the requested collating function passed in the
5359 **          4th parameter to the callback is in UTF-8 if the callback
5360 **          was registered using [sqlite3_collation_needed()] and
5361 **          is in UTF-16 native byte order if the callback was
5362 **          registered using [sqlite3_collation_needed16()].
5363 */
5364 SQLITE_API int sqlite3_collation_needed(
5365   sqlite3*, 
5366   void*, 
5367   void(*)(void*,sqlite3*,int eTextRep,const char*)
5368 );
5369 SQLITE_API int sqlite3_collation_needed16(
5370   sqlite3*, 
5371   void*,
5372   void(*)(void*,sqlite3*,int eTextRep,const void*)
5373 );
5374
5375 /*
5376 ** Specify the key for an encrypted database.  This routine should be
5377 ** called right after sqlite3_open().
5378 **
5379 ** The code to implement this API is not available in the public release
5380 ** of SQLite.
5381 */
5382 SQLITE_API int sqlite3_key(
5383   sqlite3 *db,                   /* Database to be rekeyed */
5384   const void *pKey, int nKey     /* The key */
5385 );
5386
5387 /*
5388 ** Change the key on an open database.  If the current database is not
5389 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5390 ** database is decrypted.
5391 **
5392 ** The code to implement this API is not available in the public release
5393 ** of SQLite.
5394 */
5395 SQLITE_API int sqlite3_rekey(
5396   sqlite3 *db,                   /* Database to be rekeyed */
5397   const void *pKey, int nKey     /* The new key */
5398 );
5399
5400 /*
5401 ** CAPI3REF: Suspend Execution For A Short Time {H10530} <S40410>
5402 **
5403 ** The sqlite3_sleep() function causes the current thread to suspend execution
5404 ** for at least a number of milliseconds specified in its parameter.
5405 **
5406 ** If the operating system does not support sleep requests with
5407 ** millisecond time resolution, then the time will be rounded up to
5408 ** the nearest second. The number of milliseconds of sleep actually
5409 ** requested from the operating system is returned.
5410 **
5411 ** SQLite implements this interface by calling the xSleep()
5412 ** method of the default [sqlite3_vfs] object.
5413 **
5414 ** INVARIANTS:
5415 **
5416 ** {H10533} The [sqlite3_sleep(M)] interface invokes the xSleep
5417 **          method of the default [sqlite3_vfs|VFS] in order to
5418 **          suspend execution of the current thread for at least
5419 **          M milliseconds.
5420 **
5421 ** {H10536} The [sqlite3_sleep(M)] interface returns the number of
5422 **          milliseconds of sleep actually requested of the operating
5423 **          system, which might be larger than the parameter M.
5424 */
5425 SQLITE_API int sqlite3_sleep(int);
5426
5427 /*
5428 ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} <S20000>
5429 **
5430 ** If this global variable is made to point to a string which is
5431 ** the name of a folder (a.k.a. directory), then all temporary files
5432 ** created by SQLite will be placed in that directory.  If this variable
5433 ** is a NULL pointer, then SQLite performs a search for an appropriate
5434 ** temporary file directory.
5435 **
5436 ** It is not safe to modify this variable once a [database connection]
5437 ** has been opened.  It is intended that this variable be set once
5438 ** as part of process initialization and before any SQLite interface
5439 ** routines have been call and remain unchanged thereafter.
5440 */
5441 SQLITE_API char *sqlite3_temp_directory;
5442
5443 /*
5444 ** CAPI3REF: Test For Auto-Commit Mode {H12930} <S60200>
5445 ** KEYWORDS: {autocommit mode}
5446 **
5447 ** The sqlite3_get_autocommit() interface returns non-zero or
5448 ** zero if the given database connection is or is not in autocommit mode,
5449 ** respectively.  Autocommit mode is on by default.
5450 ** Autocommit mode is disabled by a [BEGIN] statement.
5451 ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5452 **
5453 ** If certain kinds of errors occur on a statement within a multi-statement
5454 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5455 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5456 ** transaction might be rolled back automatically.  The only way to
5457 ** find out whether SQLite automatically rolled back the transaction after
5458 ** an error is to use this function.
5459 **
5460 ** INVARIANTS:
5461 **
5462 ** {H12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or
5463 **          zero if the [database connection] D is or is not in autocommit
5464 **          mode, respectively.
5465 **
5466 ** {H12932} Autocommit mode is on by default.
5467 **
5468 ** {H12933} Autocommit mode is disabled by a successful [BEGIN] statement.
5469 **
5470 ** {H12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK]
5471 **          statement.
5472 **
5473 ** ASSUMPTIONS:
5474 **
5475 ** {A12936} If another thread changes the autocommit status of the database
5476 **          connection while this routine is running, then the return value
5477 **          is undefined.
5478 */
5479 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5480
5481 /*
5482 ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} <S60600>
5483 **
5484 ** The sqlite3_db_handle interface returns the [database connection] handle
5485 ** to which a [prepared statement] belongs.  The [database connection]
5486 ** returned by sqlite3_db_handle is the same [database connection] that was the first argument
5487 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5488 ** create the statement in the first place.
5489 **
5490 ** INVARIANTS:
5491 **
5492 ** {H13123} The [sqlite3_db_handle(S)] interface returns a pointer
5493 **          to the [database connection] associated with the
5494 **          [prepared statement] S.
5495 */
5496 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5497
5498 /*
5499 ** CAPI3REF: Find the next prepared statement {H13140} <S60600>
5500 **
5501 ** This interface returns a pointer to the next [prepared statement] after
5502 ** pStmt associated with the [database connection] pDb.  If pStmt is NULL
5503 ** then this interface returns a pointer to the first prepared statement
5504 ** associated with the database connection pDb.  If no prepared statement
5505 ** satisfies the conditions of this routine, it returns NULL.
5506 **
5507 ** INVARIANTS:
5508 **
5509 ** {H13143} If D is a [database connection] that holds one or more
5510 **          unfinalized [prepared statements] and S is a NULL pointer,
5511 **          then [sqlite3_next_stmt(D, S)] routine shall return a pointer
5512 **          to one of the prepared statements associated with D.
5513 **
5514 ** {H13146} If D is a [database connection] that holds no unfinalized
5515 **          [prepared statements] and S is a NULL pointer, then
5516 **          [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer.
5517 **
5518 ** {H13149} If S is a [prepared statement] in the [database connection] D
5519 **          and S is not the last prepared statement in D, then
5520 **          [sqlite3_next_stmt(D, S)] routine shall return a pointer
5521 **          to the next prepared statement in D after S.
5522 **
5523 ** {H13152} If S is the last [prepared statement] in the
5524 **          [database connection] D then the [sqlite3_next_stmt(D, S)]
5525 **          routine shall return a NULL pointer.
5526 **
5527 ** ASSUMPTIONS:
5528 **
5529 ** {A13154} The [database connection] pointer D in a call to
5530 **          [sqlite3_next_stmt(D,S)] must refer to an open database
5531 **          connection and in particular must not be a NULL pointer.
5532 */
5533 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5534
5535 /*
5536 ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} <S60400>
5537 **
5538 ** The sqlite3_commit_hook() interface registers a callback
5539 ** function to be invoked whenever a transaction is committed.
5540 ** Any callback set by a previous call to sqlite3_commit_hook()
5541 ** for the same database connection is overridden.
5542 ** The sqlite3_rollback_hook() interface registers a callback
5543 ** function to be invoked whenever a transaction is committed.
5544 ** Any callback set by a previous call to sqlite3_commit_hook()
5545 ** for the same database connection is overridden.
5546 ** The pArg argument is passed through to the callback.
5547 ** If the callback on a commit hook function returns non-zero,
5548 ** then the commit is converted into a rollback.
5549 **
5550 ** If another function was previously registered, its
5551 ** pArg value is returned.  Otherwise NULL is returned.
5552 **
5553 ** The callback implementation must not do anything that will modify
5554 ** the database connection that invoked the callback.  Any actions
5555 ** to modify the database connection must be deferred until after the
5556 ** completion of the [sqlite3_step()] call that triggered the commit
5557 ** or rollback hook in the first place.
5558 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5559 ** database connections for the meaning of "modify" in this paragraph.
5560 **
5561 ** Registering a NULL function disables the callback.
5562 **
5563 ** For the purposes of this API, a transaction is said to have been
5564 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5565 ** an error or constraint causes an implicit rollback to occur.
5566 ** The rollback callback is not invoked if a transaction is
5567 ** automatically rolled back because the database connection is closed.
5568 ** The rollback callback is not invoked if a transaction is
5569 ** rolled back because a commit callback returned non-zero.
5570 ** <todo> Check on this </todo>
5571 **
5572 ** INVARIANTS:
5573 **
5574 ** {H12951} The [sqlite3_commit_hook(D,F,P)] interface registers the
5575 **          callback function F to be invoked with argument P whenever
5576 **          a transaction commits on the [database connection] D.
5577 **
5578 ** {H12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument
5579 **          from the previous call with the same [database connection] D,
5580 **          or NULL on the first call for a particular database connection D.
5581 **
5582 ** {H12953} Each call to [sqlite3_commit_hook()] overwrites the callback
5583 **          registered by prior calls.
5584 **
5585 ** {H12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL
5586 **          then the commit hook callback is canceled and no callback
5587 **          is invoked when a transaction commits.
5588 **
5589 ** {H12955} If the commit callback returns non-zero then the commit is
5590 **          converted into a rollback.
5591 **
5592 ** {H12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the
5593 **          callback function F to be invoked with argument P whenever
5594 **          a transaction rolls back on the [database connection] D.
5595 **
5596 ** {H12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P
5597 **          argument from the previous call with the same
5598 **          [database connection] D, or NULL on the first call
5599 **          for a particular database connection D.
5600 **
5601 ** {H12963} Each call to [sqlite3_rollback_hook()] overwrites the callback
5602 **          registered by prior calls.
5603 **
5604 ** {H12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL
5605 **          then the rollback hook callback is canceled and no callback
5606 **          is invoked when a transaction rolls back.
5607 */
5608 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5609 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5610
5611 /*
5612 ** CAPI3REF: Data Change Notification Callbacks {H12970} <S60400>
5613 **
5614 ** The sqlite3_update_hook() interface registers a callback function
5615 ** with the [database connection] identified by the first argument
5616 ** to be invoked whenever a row is updated, inserted or deleted.
5617 ** Any callback set by a previous call to this function
5618 ** for the same database connection is overridden.
5619 **
5620 ** The second argument is a pointer to the function to invoke when a
5621 ** row is updated, inserted or deleted.
5622 ** The first argument to the callback is a copy of the third argument
5623 ** to sqlite3_update_hook().
5624 ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5625 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5626 ** to be invoked.
5627 ** The third and fourth arguments to the callback contain pointers to the
5628 ** database and table name containing the affected row.
5629 ** The final callback parameter is the [rowid] of the row.
5630 ** In the case of an update, this is the [rowid] after the update takes place.
5631 **
5632 ** The update hook is not invoked when internal system tables are
5633 ** modified (i.e. sqlite_master and sqlite_sequence).
5634 **
5635 ** The update hook implementation must not do anything that will modify
5636 ** the database connection that invoked the update hook.  Any actions
5637 ** to modify the database connection must be deferred until after the
5638 ** completion of the [sqlite3_step()] call that triggered the update hook.
5639 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5640 ** database connections for the meaning of "modify" in this paragraph.
5641 **
5642 ** If another function was previously registered, its pArg value
5643 ** is returned.  Otherwise NULL is returned.
5644 **
5645 ** INVARIANTS:
5646 **
5647 ** {H12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback
5648 **          function F to be invoked with first parameter P whenever
5649 **          a table row is modified, inserted, or deleted on
5650 **          the [database connection] D.
5651 **
5652 ** {H12973} The [sqlite3_update_hook(D,F,P)] interface returns the value
5653 **          of P for the previous call on the same [database connection] D,
5654 **          or NULL for the first call.
5655 **
5656 ** {H12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)]
5657 **          is NULL then the no update callbacks are made.
5658 **
5659 ** {H12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls
5660 **          to the same interface on the same [database connection] D.
5661 **
5662 ** {H12979} The update hook callback is not invoked when internal system
5663 **          tables such as sqlite_master and sqlite_sequence are modified.
5664 **
5665 ** {H12981} The second parameter to the update callback
5666 **          is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE],
5667 **          depending on the operation that caused the callback to be invoked.
5668 **
5669 ** {H12983} The third and fourth arguments to the callback contain pointers
5670 **          to zero-terminated UTF-8 strings which are the names of the
5671 **          database and table that is being updated.
5672
5673 ** {H12985} The final callback parameter is the [rowid] of the row after
5674 **          the change occurs.
5675 */
5676 SQLITE_API void *sqlite3_update_hook(
5677   sqlite3*, 
5678   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5679   void*
5680 );
5681
5682 /*
5683 ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} <S30900>
5684 ** KEYWORDS: {shared cache} {shared cache mode}
5685 **
5686 ** This routine enables or disables the sharing of the database cache
5687 ** and schema data structures between [database connection | connections]
5688 ** to the same database. Sharing is enabled if the argument is true
5689 ** and disabled if the argument is false.
5690 **
5691 ** Cache sharing is enabled and disabled for an entire process.
5692 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5693 ** sharing was enabled or disabled for each thread separately.
5694 **
5695 ** The cache sharing mode set by this interface effects all subsequent
5696 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5697 ** Existing database connections continue use the sharing mode
5698 ** that was in effect at the time they were opened.
5699 **
5700 ** Virtual tables cannot be used with a shared cache.  When shared
5701 ** cache is enabled, the [sqlite3_create_module()] API used to register
5702 ** virtual tables will always return an error.
5703 **
5704 ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5705 ** successfully.  An [error code] is returned otherwise.
5706 **
5707 ** Shared cache is disabled by default. But this might change in
5708 ** future releases of SQLite.  Applications that care about shared
5709 ** cache setting should set it explicitly.
5710 **
5711 ** See Also:  [SQLite Shared-Cache Mode]
5712 **
5713 ** INVARIANTS:
5714 **
5715 ** {H10331} A successful invocation of [sqlite3_enable_shared_cache(B)]
5716 **          will enable or disable shared cache mode for any subsequently
5717 **          created [database connection] in the same process.
5718 **
5719 ** {H10336} When shared cache is enabled, the [sqlite3_create_module()]
5720 **          interface will always return an error.
5721 **
5722 ** {H10337} The [sqlite3_enable_shared_cache(B)] interface returns
5723 **          [SQLITE_OK] if shared cache was enabled or disabled successfully.
5724 **
5725 ** {H10339} Shared cache is disabled by default.
5726 */
5727 SQLITE_API int sqlite3_enable_shared_cache(int);
5728
5729 /*
5730 ** CAPI3REF: Attempt To Free Heap Memory {H17340} <S30220>
5731 **
5732 ** The sqlite3_release_memory() interface attempts to free N bytes
5733 ** of heap memory by deallocating non-essential memory allocations
5734 ** held by the database library. {END}  Memory used to cache database
5735 ** pages to improve performance is an example of non-essential memory.
5736 ** sqlite3_release_memory() returns the number of bytes actually freed,
5737 ** which might be more or less than the amount requested.
5738 **
5739 ** INVARIANTS:
5740 **
5741 ** {H17341} The [sqlite3_release_memory(N)] interface attempts to
5742 **          free N bytes of heap memory by deallocating non-essential
5743 **          memory allocations held by the database library.
5744 **
5745 ** {H16342} The [sqlite3_release_memory(N)] returns the number
5746 **          of bytes actually freed, which might be more or less
5747 **          than the amount requested.
5748 */
5749 SQLITE_API int sqlite3_release_memory(int);
5750
5751 /*
5752 ** CAPI3REF: Impose A Limit On Heap Size {H17350} <S30220>
5753 **
5754 ** The sqlite3_soft_heap_limit() interface places a "soft" limit
5755 ** on the amount of heap memory that may be allocated by SQLite.
5756 ** If an internal allocation is requested that would exceed the
5757 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
5758 ** more times to free up some space before the allocation is performed.
5759 **
5760 ** The limit is called "soft", because if [sqlite3_release_memory()]
5761 ** cannot free sufficient memory to prevent the limit from being exceeded,
5762 ** the memory is allocated anyway and the current operation proceeds.
5763 **
5764 ** A negative or zero value for N means that there is no soft heap limit and
5765 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
5766 ** The default value for the soft heap limit is zero.
5767 **
5768 ** SQLite makes a best effort to honor the soft heap limit.
5769 ** But if the soft heap limit cannot be honored, execution will
5770 ** continue without error or notification.  This is why the limit is
5771 ** called a "soft" limit.  It is advisory only.
5772 **
5773 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
5774 ** allocated by a single thread - the same thread in which this routine
5775 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
5776 ** applied to all threads. The value specified for the soft heap limit
5777 ** is an upper bound on the total memory allocation for all threads. In
5778 ** version 3.5.0 there is no mechanism for limiting the heap usage for
5779 ** individual threads.
5780 **
5781 ** INVARIANTS:
5782 **
5783 ** {H16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit
5784 **          of N bytes on the amount of heap memory that may be allocated
5785 **          using [sqlite3_malloc()] or [sqlite3_realloc()] at any point
5786 **          in time.
5787 **
5788 ** {H16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would
5789 **          cause the total amount of allocated memory to exceed the
5790 **          soft heap limit, then [sqlite3_release_memory()] is invoked
5791 **          in an attempt to reduce the memory usage prior to proceeding
5792 **          with the memory allocation attempt.
5793 **
5794 ** {H16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger
5795 **          attempts to reduce memory usage through the soft heap limit
5796 **          mechanism continue even if the attempt to reduce memory
5797 **          usage is unsuccessful.
5798 **
5799 ** {H16354} A negative or zero value for N in a call to
5800 **          [sqlite3_soft_heap_limit(N)] means that there is no soft
5801 **          heap limit and [sqlite3_release_memory()] will only be
5802 **          called when memory is completely exhausted.
5803 **
5804 ** {H16355} The default value for the soft heap limit is zero.
5805 **
5806 ** {H16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the
5807 **          values set by all prior calls.
5808 */
5809 SQLITE_API void sqlite3_soft_heap_limit(int);
5810
5811 /*
5812 ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} <S60300>
5813 **
5814 ** This routine returns metadata about a specific column of a specific
5815 ** database table accessible using the [database connection] handle
5816 ** passed as the first function argument.
5817 **
5818 ** The column is identified by the second, third and fourth parameters to
5819 ** this function. The second parameter is either the name of the database
5820 ** (i.e. "main", "temp" or an attached database) containing the specified
5821 ** table or NULL. If it is NULL, then all attached databases are searched
5822 ** for the table using the same algorithm used by the database engine to
5823 ** resolve unqualified table references.
5824 **
5825 ** The third and fourth parameters to this function are the table and column
5826 ** name of the desired column, respectively. Neither of these parameters
5827 ** may be NULL.
5828 **
5829 ** Metadata is returned by writing to the memory locations passed as the 5th
5830 ** and subsequent parameters to this function. Any of these arguments may be
5831 ** NULL, in which case the corresponding element of metadata is omitted.
5832 **
5833 ** <blockquote>
5834 ** <table border="1">
5835 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5836 **
5837 ** <tr><td> 5th <td> const char* <td> Data type
5838 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5839 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5840 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5841 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5842 ** </table>
5843 ** </blockquote>
5844 **
5845 ** The memory pointed to by the character pointers returned for the
5846 ** declaration type and collation sequence is valid only until the next
5847 ** call to any SQLite API function.
5848 **
5849 ** If the specified table is actually a view, an [error code] is returned.
5850 **
5851 ** If the specified column is "rowid", "oid" or "_rowid_" and an
5852 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5853 ** parameters are set for the explicitly declared column. If there is no
5854 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5855 ** parameters are set as follows:
5856 **
5857 ** <pre>
5858 **     data type: "INTEGER"
5859 **     collation sequence: "BINARY"
5860 **     not null: 0
5861 **     primary key: 1
5862 **     auto increment: 0
5863 ** </pre>
5864 **
5865 ** This function may load one or more schemas from database files. If an
5866 ** error occurs during this process, or if the requested table or column
5867 ** cannot be found, an [error code] is returned and an error message left
5868 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).
5869 **
5870 ** This API is only available if the library was compiled with the
5871 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5872 */
5873 SQLITE_API int sqlite3_table_column_metadata(
5874   sqlite3 *db,                /* Connection handle */
5875   const char *zDbName,        /* Database name or NULL */
5876   const char *zTableName,     /* Table name */
5877   const char *zColumnName,    /* Column name */
5878   char const **pzDataType,    /* OUTPUT: Declared data type */
5879   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5880   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5881   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5882   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5883 );
5884
5885 /*
5886 ** CAPI3REF: Load An Extension {H12600} <S20500>
5887 **
5888 ** This interface loads an SQLite extension library from the named file.
5889 **
5890 ** {H12601} The sqlite3_load_extension() interface attempts to load an
5891 **          SQLite extension library contained in the file zFile.
5892 **
5893 ** {H12602} The entry point is zProc.
5894 **
5895 ** {H12603} zProc may be 0, in which case the name of the entry point
5896 **          defaults to "sqlite3_extension_init".
5897 **
5898 ** {H12604} The sqlite3_load_extension() interface shall return
5899 **          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5900 **
5901 ** {H12605} If an error occurs and pzErrMsg is not 0, then the
5902 **          [sqlite3_load_extension()] interface shall attempt to
5903 **          fill *pzErrMsg with error message text stored in memory
5904 **          obtained from [sqlite3_malloc()]. {END}  The calling function
5905 **          should free this memory by calling [sqlite3_free()].
5906 **
5907 ** {H12606} Extension loading must be enabled using
5908 **          [sqlite3_enable_load_extension()] prior to calling this API,
5909 **          otherwise an error will be returned.
5910 */
5911 SQLITE_API int sqlite3_load_extension(
5912   sqlite3 *db,          /* Load the extension into this database connection */
5913   const char *zFile,    /* Name of the shared library containing extension */
5914   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5915   char **pzErrMsg       /* Put error message here if not 0 */
5916 );
5917
5918 /*
5919 ** CAPI3REF: Enable Or Disable Extension Loading {H12620} <S20500>
5920 **
5921 ** So as not to open security holes in older applications that are
5922 ** unprepared to deal with extension loading, and as a means of disabling
5923 ** extension loading while evaluating user-entered SQL, the following API
5924 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5925 **
5926 ** Extension loading is off by default. See ticket #1863.
5927 **
5928 ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1
5929 **          to turn extension loading on and call it with onoff==0 to turn
5930 **          it back off again.
5931 **
5932 ** {H12622} Extension loading is off by default.
5933 */
5934 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5935
5936 /*
5937 ** CAPI3REF: Automatically Load An Extensions {H12640} <S20500>
5938 **
5939 ** This API can be invoked at program startup in order to register
5940 ** one or more statically linked extensions that will be available
5941 ** to all new [database connections]. {END}
5942 **
5943 ** This routine stores a pointer to the extension in an array that is
5944 ** obtained from [sqlite3_malloc()].  If you run a memory leak checker
5945 ** on your program and it reports a leak because of this array, invoke
5946 ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
5947 **
5948 ** {H12641} This function registers an extension entry point that is
5949 **          automatically invoked whenever a new [database connection]
5950 **          is opened using [sqlite3_open()], [sqlite3_open16()],
5951 **          or [sqlite3_open_v2()].
5952 **
5953 ** {H12642} Duplicate extensions are detected so calling this routine
5954 **          multiple times with the same extension is harmless.
5955 **
5956 ** {H12643} This routine stores a pointer to the extension in an array
5957 **          that is obtained from [sqlite3_malloc()].
5958 **
5959 ** {H12644} Automatic extensions apply across all threads.
5960 */
5961 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5962
5963 /*
5964 ** CAPI3REF: Reset Automatic Extension Loading {H12660} <S20500>
5965 **
5966 ** This function disables all previously registered automatic
5967 ** extensions. {END}  It undoes the effect of all prior
5968 ** [sqlite3_auto_extension()] calls.
5969 **
5970 ** {H12661} This function disables all previously registered
5971 **          automatic extensions.
5972 **
5973 ** {H12662} This function disables automatic extensions in all threads.
5974 */
5975 SQLITE_API void sqlite3_reset_auto_extension(void);
5976
5977 /*
5978 ****** EXPERIMENTAL - subject to change without notice **************
5979 **
5980 ** The interface to the virtual-table mechanism is currently considered
5981 ** to be experimental.  The interface might change in incompatible ways.
5982 ** If this is a problem for you, do not use the interface at this time.
5983 **
5984 ** When the virtual-table mechanism stabilizes, we will declare the
5985 ** interface fixed, support it indefinitely, and remove this comment.
5986 */
5987
5988 /*
5989 ** Structures used by the virtual table interface
5990 */
5991 typedef struct sqlite3_vtab sqlite3_vtab;
5992 typedef struct sqlite3_index_info sqlite3_index_info;
5993 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5994 typedef struct sqlite3_module sqlite3_module;
5995
5996 /*
5997 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
5998 ** KEYWORDS: sqlite3_module
5999 ** EXPERIMENTAL
6000 **
6001 ** A module is a class of virtual tables.  Each module is defined
6002 ** by an instance of the following structure.  This structure consists
6003 ** mostly of methods for the module.
6004 **
6005 ** This interface is experimental and is subject to change or
6006 ** removal in future releases of SQLite.
6007 */
6008 struct sqlite3_module {
6009   int iVersion;
6010   int (*xCreate)(sqlite3*, void *pAux,
6011                int argc, const char *const*argv,
6012                sqlite3_vtab **ppVTab, char**);
6013   int (*xConnect)(sqlite3*, void *pAux,
6014                int argc, const char *const*argv,
6015                sqlite3_vtab **ppVTab, char**);
6016   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6017   int (*xDisconnect)(sqlite3_vtab *pVTab);
6018   int (*xDestroy)(sqlite3_vtab *pVTab);
6019   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6020   int (*xClose)(sqlite3_vtab_cursor*);
6021   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6022                 int argc, sqlite3_value **argv);
6023   int (*xNext)(sqlite3_vtab_cursor*);
6024   int (*xEof)(sqlite3_vtab_cursor*);
6025   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6026   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6027   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6028   int (*xBegin)(sqlite3_vtab *pVTab);
6029   int (*xSync)(sqlite3_vtab *pVTab);
6030   int (*xCommit)(sqlite3_vtab *pVTab);
6031   int (*xRollback)(sqlite3_vtab *pVTab);
6032   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6033                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6034                        void **ppArg);
6035   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6036 };
6037
6038 /*
6039 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
6040 ** KEYWORDS: sqlite3_index_info
6041 ** EXPERIMENTAL
6042 **
6043 ** The sqlite3_index_info structure and its substructures is used to
6044 ** pass information into and receive the reply from the xBestIndex
6045 ** method of an sqlite3_module.  The fields under **Inputs** are the
6046 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
6047 ** results into the **Outputs** fields.
6048 **
6049 ** The aConstraint[] array records WHERE clause constraints of the form:
6050 **
6051 ** <pre>column OP expr</pre>
6052 **
6053 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.  The particular operator is
6054 ** stored in aConstraint[].op.  The index of the column is stored in
6055 ** aConstraint[].iColumn.  aConstraint[].usable is TRUE if the
6056 ** expr on the right-hand side can be evaluated (and thus the constraint
6057 ** is usable) and false if it cannot.
6058 **
6059 ** The optimizer automatically inverts terms of the form "expr OP column"
6060 ** and makes other simplifications to the WHERE clause in an attempt to
6061 ** get as many WHERE clause terms into the form shown above as possible.
6062 ** The aConstraint[] array only reports WHERE clause terms in the correct
6063 ** form that refer to the particular virtual table being queried.
6064 **
6065 ** Information about the ORDER BY clause is stored in aOrderBy[].
6066 ** Each term of aOrderBy records a column of the ORDER BY clause.
6067 **
6068 ** The xBestIndex method must fill aConstraintUsage[] with information
6069 ** about what parameters to pass to xFilter.  If argvIndex>0 then
6070 ** the right-hand side of the corresponding aConstraint[] is evaluated
6071 ** and becomes the argvIndex-th entry in argv.  If aConstraintUsage[].omit
6072 ** is true, then the constraint is assumed to be fully handled by the
6073 ** virtual table and is not checked again by SQLite.
6074 **
6075 ** The idxNum and idxPtr values are recorded and passed into xFilter.
6076 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
6077 **
6078 ** The orderByConsumed means that output from xFilter will occur in
6079 ** the correct order to satisfy the ORDER BY clause so that no separate
6080 ** sorting step is required.
6081 **
6082 ** The estimatedCost value is an estimate of the cost of doing the
6083 ** particular lookup.  A full scan of a table with N entries should have
6084 ** a cost of N.  A binary search of a table of N entries should have a
6085 ** cost of approximately log(N).
6086 **
6087 ** This interface is experimental and is subject to change or
6088 ** removal in future releases of SQLite.
6089 */
6090 struct sqlite3_index_info {
6091   /* Inputs */
6092   int nConstraint;           /* Number of entries in aConstraint */
6093   struct sqlite3_index_constraint {
6094      int iColumn;              /* Column on left-hand side of constraint */
6095      unsigned char op;         /* Constraint operator */
6096      unsigned char usable;     /* True if this constraint is usable */
6097      int iTermOffset;          /* Used internally - xBestIndex should ignore */
6098   } *aConstraint;            /* Table of WHERE clause constraints */
6099   int nOrderBy;              /* Number of terms in the ORDER BY clause */
6100   struct sqlite3_index_orderby {
6101      int iColumn;              /* Column number */
6102      unsigned char desc;       /* True for DESC.  False for ASC. */
6103   } *aOrderBy;               /* The ORDER BY clause */
6104   /* Outputs */
6105   struct sqlite3_index_constraint_usage {
6106     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
6107     unsigned char omit;      /* Do not code a test for this constraint */
6108   } *aConstraintUsage;
6109   int idxNum;                /* Number used to identify the index */
6110   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
6111   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
6112   int orderByConsumed;       /* True if output is already ordered */
6113   double estimatedCost;      /* Estimated cost of using this index */
6114 };
6115 #define SQLITE_INDEX_CONSTRAINT_EQ    2
6116 #define SQLITE_INDEX_CONSTRAINT_GT    4
6117 #define SQLITE_INDEX_CONSTRAINT_LE    8
6118 #define SQLITE_INDEX_CONSTRAINT_LT    16
6119 #define SQLITE_INDEX_CONSTRAINT_GE    32
6120 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6121
6122 /*
6123 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
6124 ** EXPERIMENTAL
6125 **
6126 ** This routine is used to register a new module name with a
6127 ** [database connection].  Module names must be registered before
6128 ** creating new virtual tables on the module, or before using
6129 ** preexisting virtual tables of the module.
6130 **
6131 ** This interface is experimental and is subject to change or
6132 ** removal in future releases of SQLite.
6133 */
6134 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
6135   sqlite3 *db,               /* SQLite connection to register module with */
6136   const char *zName,         /* Name of the module */
6137   const sqlite3_module *,    /* Methods for the module */
6138   void *                     /* Client data for xCreate/xConnect */
6139 );
6140
6141 /*
6142 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
6143 ** EXPERIMENTAL
6144 **
6145 ** This routine is identical to the [sqlite3_create_module()] method above,
6146 ** except that it allows a destructor function to be specified. It is
6147 ** even more experimental than the rest of the virtual tables API.
6148 */
6149 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
6150   sqlite3 *db,               /* SQLite connection to register module with */
6151   const char *zName,         /* Name of the module */
6152   const sqlite3_module *,    /* Methods for the module */
6153   void *,                    /* Client data for xCreate/xConnect */
6154   void(*xDestroy)(void*)     /* Module destructor function */
6155 );
6156
6157 /*
6158 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
6159 ** KEYWORDS: sqlite3_vtab
6160 ** EXPERIMENTAL
6161 **
6162 ** Every module implementation uses a subclass of the following structure
6163 ** to describe a particular instance of the module.  Each subclass will
6164 ** be tailored to the specific needs of the module implementation.
6165 ** The purpose of this superclass is to define certain fields that are
6166 ** common to all module implementations.
6167 **
6168 ** Virtual tables methods can set an error message by assigning a
6169 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
6170 ** take care that any prior string is freed by a call to [sqlite3_free()]
6171 ** prior to assigning a new string to zErrMsg.  After the error message
6172 ** is delivered up to the client application, the string will be automatically
6173 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.  Note
6174 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
6175 ** since virtual tables are commonly implemented in loadable extensions which
6176 ** do not have access to sqlite3MPrintf() or sqlite3Free().
6177 **
6178 ** This interface is experimental and is subject to change or
6179 ** removal in future releases of SQLite.
6180 */
6181 struct sqlite3_vtab {
6182   const sqlite3_module *pModule;  /* The module for this virtual table */
6183   int nRef;                       /* Used internally */
6184   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
6185   /* Virtual table implementations will typically add additional fields */
6186 };
6187
6188 /*
6189 ** CAPI3REF: Virtual Table Cursor Object  {H18020} <S20400>
6190 ** KEYWORDS: sqlite3_vtab_cursor
6191 ** EXPERIMENTAL
6192 **
6193 ** Every module implementation uses a subclass of the following structure
6194 ** to describe cursors that point into the virtual table and are used
6195 ** to loop through the virtual table.  Cursors are created using the
6196 ** xOpen method of the module.  Each module implementation will define
6197 ** the content of a cursor structure to suit its own needs.
6198 **
6199 ** This superclass exists in order to define fields of the cursor that
6200 ** are common to all implementations.
6201 **
6202 ** This interface is experimental and is subject to change or
6203 ** removal in future releases of SQLite.
6204 */
6205 struct sqlite3_vtab_cursor {
6206   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
6207   /* Virtual table implementations will typically add additional fields */
6208 };
6209
6210 /*
6211 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
6212 ** EXPERIMENTAL
6213 **
6214 ** The xCreate and xConnect methods of a module use the following API
6215 ** to declare the format (the names and datatypes of the columns) of
6216 ** the virtual tables they implement.
6217 **
6218 ** This interface is experimental and is subject to change or
6219 ** removal in future releases of SQLite.
6220 */
6221 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
6222
6223 /*
6224 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
6225 ** EXPERIMENTAL
6226 **
6227 ** Virtual tables can provide alternative implementations of functions
6228 ** using the xFindFunction method.  But global versions of those functions
6229 ** must exist in order to be overloaded.
6230 **
6231 ** This API makes sure a global version of a function with a particular
6232 ** name and number of parameters exists.  If no such function exists
6233 ** before this API is called, a new function is created.  The implementation
6234 ** of the new function always causes an exception to be thrown.  So
6235 ** the new function is not good for anything by itself.  Its only
6236 ** purpose is to be a placeholder function that can be overloaded
6237 ** by virtual tables.
6238 **
6239 ** This API should be considered part of the virtual table interface,
6240 ** which is experimental and subject to change.
6241 */
6242 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6243
6244 /*
6245 ** The interface to the virtual-table mechanism defined above (back up
6246 ** to a comment remarkably similar to this one) is currently considered
6247 ** to be experimental.  The interface might change in incompatible ways.
6248 ** If this is a problem for you, do not use the interface at this time.
6249 **
6250 ** When the virtual-table mechanism stabilizes, we will declare the
6251 ** interface fixed, support it indefinitely, and remove this comment.
6252 **
6253 ****** EXPERIMENTAL - subject to change without notice **************
6254 */
6255
6256 /*
6257 ** CAPI3REF: A Handle To An Open BLOB {H17800} <S30230>
6258 ** KEYWORDS: {BLOB handle} {BLOB handles}
6259 **
6260 ** An instance of this object represents an open BLOB on which
6261 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6262 ** Objects of this type are created by [sqlite3_blob_open()]
6263 ** and destroyed by [sqlite3_blob_close()].
6264 ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6265 ** can be used to read or write small subsections of the BLOB.
6266 ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6267 */
6268 typedef struct sqlite3_blob sqlite3_blob;
6269
6270 /*
6271 ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} <S30230>
6272 **
6273 ** This interfaces opens a [BLOB handle | handle] to the BLOB located
6274 ** in row iRow, column zColumn, table zTable in database zDb;
6275 ** in other words, the same BLOB that would be selected by:
6276 **
6277 ** <pre>
6278 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6279 ** </pre> {END}
6280 **
6281 ** If the flags parameter is non-zero, the the BLOB is opened for read
6282 ** and write access. If it is zero, the BLOB is opened for read access.
6283 **
6284 ** Note that the database name is not the filename that contains
6285 ** the database but rather the symbolic name of the database that
6286 ** is assigned when the database is connected using [ATTACH].
6287 ** For the main database file, the database name is "main".
6288 ** For TEMP tables, the database name is "temp".
6289 **
6290 ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6291 ** to *ppBlob. Otherwise an [error code] is returned and any value written
6292 ** to *ppBlob should not be used by the caller.
6293 ** This function sets the [database connection] error code and message
6294 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()].
6295 **
6296 ** If the row that a BLOB handle points to is modified by an
6297 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6298 ** then the BLOB handle is marked as "expired".
6299 ** This is true if any column of the row is changed, even a column
6300 ** other than the one the BLOB handle is open on.
6301 ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6302 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
6303 ** Changes written into a BLOB prior to the BLOB expiring are not
6304 ** rollback by the expiration of the BLOB.  Such changes will eventually
6305 ** commit if the transaction continues to completion.
6306 **
6307 ** INVARIANTS:
6308 **
6309 ** {H17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)]
6310 **          interface shall open an [sqlite3_blob] object P on the BLOB
6311 **          in column C of the table T in the database B on
6312 **          the [database connection] D.
6313 **
6314 ** {H17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start
6315 **          a new transaction on the [database connection] D if that
6316 **          connection is not already in a transaction.
6317 **
6318 ** {H17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open
6319 **          the BLOB for read and write access if and only if the F
6320 **          parameter is non-zero.
6321 **
6322 ** {H17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on
6323 **          success and an appropriate [error code] on failure.
6324 **
6325 ** {H17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)]
6326 **          then subsequent calls to [sqlite3_errcode(D)],
6327 **          [sqlite3_extended_errcode()], 
6328 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6329 **          information appropriate for that error.
6330 **
6331 ** {H17824} If any column in the row that a [sqlite3_blob] has open is
6332 **          changed by a separate [UPDATE] or [DELETE] statement or by
6333 **          an [ON CONFLICT] side effect, then the [sqlite3_blob] shall
6334 **          be marked as invalid.
6335 */
6336 SQLITE_API int sqlite3_blob_open(
6337   sqlite3*,
6338   const char *zDb,
6339   const char *zTable,
6340   const char *zColumn,
6341   sqlite3_int64 iRow,
6342   int flags,
6343   sqlite3_blob **ppBlob
6344 );
6345
6346 /*
6347 ** CAPI3REF: Close A BLOB Handle {H17830} <S30230>
6348 **
6349 ** Closes an open [BLOB handle].
6350 **
6351 ** Closing a BLOB shall cause the current transaction to commit
6352 ** if there are no other BLOBs, no pending prepared statements, and the
6353 ** database connection is in [autocommit mode].
6354 ** If any writes were made to the BLOB, they might be held in cache
6355 ** until the close operation if they will fit. {END}
6356 **
6357 ** Closing the BLOB often forces the changes
6358 ** out to disk and so if any I/O errors occur, they will likely occur
6359 ** at the time when the BLOB is closed.  {H17833} Any errors that occur during
6360 ** closing are reported as a non-zero return value.
6361 **
6362 ** The BLOB is closed unconditionally.  Even if this routine returns
6363 ** an error code, the BLOB is still closed.
6364 **
6365 ** INVARIANTS:
6366 **
6367 ** {H17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob]
6368 **          object P previously opened using [sqlite3_blob_open()].
6369 **
6370 ** {H17836} Closing an [sqlite3_blob] object using
6371 **          [sqlite3_blob_close()] shall cause the current transaction to
6372 **          commit if there are no other open [sqlite3_blob] objects
6373 **          or [prepared statements] on the same [database connection] and
6374 **          the database connection is in [autocommit mode].
6375 **
6376 ** {H17839} The [sqlite3_blob_close(P)] interfaces shall close the
6377 **          [sqlite3_blob] object P unconditionally, even if
6378 **          [sqlite3_blob_close(P)] returns something other than [SQLITE_OK].
6379 */
6380 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6381
6382 /*
6383 ** CAPI3REF: Return The Size Of An Open BLOB {H17840} <S30230>
6384 **
6385 ** Returns the size in bytes of the BLOB accessible via the open
6386 ** []BLOB handle] in its only argument.
6387 **
6388 ** INVARIANTS:
6389 **
6390 ** {H17843} The [sqlite3_blob_bytes(P)] interface returns the size
6391 **          in bytes of the BLOB that the [sqlite3_blob] object P
6392 **          refers to.
6393 */
6394 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6395
6396 /*
6397 ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} <S30230>
6398 **
6399 ** This function is used to read data from an open [BLOB handle] into a
6400 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6401 ** from the open BLOB, starting at offset iOffset.
6402 **
6403 ** If offset iOffset is less than N bytes from the end of the BLOB,
6404 ** [SQLITE_ERROR] is returned and no data is read.  If N or iOffset is
6405 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6406 **
6407 ** An attempt to read from an expired [BLOB handle] fails with an
6408 ** error code of [SQLITE_ABORT].
6409 **
6410 ** On success, SQLITE_OK is returned.
6411 ** Otherwise, an [error code] or an [extended error code] is returned.
6412 **
6413 ** INVARIANTS:
6414 **
6415 ** {H17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] 
6416 **          shall reads N bytes of data out of the BLOB referenced by
6417 **          [BLOB handle] P beginning at offset X and store those bytes
6418 **          into buffer Z.
6419 **
6420 ** {H17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB
6421 **          is less than N+X bytes, then the function shall leave the
6422 **          Z buffer unchanged and return [SQLITE_ERROR].
6423 **
6424 ** {H17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero
6425 **          then the function shall leave the Z buffer unchanged
6426 **          and return [SQLITE_ERROR].
6427 **
6428 ** {H17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK]
6429 **          if N bytes are successfully read into buffer Z.
6430 **
6431 ** {H17863} If the [BLOB handle] P is expired and X and N are within bounds
6432 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer
6433 **          unchanged and return [SQLITE_ABORT].
6434 **
6435 ** {H17865} If the requested read could not be completed,
6436 **          the [sqlite3_blob_read(P,Z,N,X)] interface shall return an
6437 **          appropriate [error code] or [extended error code].
6438 **
6439 ** {H17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)]
6440 **          then subsequent calls to [sqlite3_errcode(D)],
6441 **          [sqlite3_extended_errcode()],
6442 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6443 **          information appropriate for that error, where D is the
6444 **          [database connection] that was used to open the [BLOB handle] P.
6445 */
6446 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6447
6448 /*
6449 ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} <S30230>
6450 **
6451 ** This function is used to write data into an open [BLOB handle] from a
6452 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6453 ** into the open BLOB, starting at offset iOffset.
6454 **
6455 ** If the [BLOB handle] passed as the first argument was not opened for
6456 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6457 ** this function returns [SQLITE_READONLY].
6458 **
6459 ** This function may only modify the contents of the BLOB; it is
6460 ** not possible to increase the size of a BLOB using this API.
6461 ** If offset iOffset is less than N bytes from the end of the BLOB,
6462 ** [SQLITE_ERROR] is returned and no data is written.  If N is
6463 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6464 **
6465 ** An attempt to write to an expired [BLOB handle] fails with an
6466 ** error code of [SQLITE_ABORT].  Writes to the BLOB that occurred
6467 ** before the [BLOB handle] expired are not rolled back by the
6468 ** expiration of the handle, though of course those changes might
6469 ** have been overwritten by the statement that expired the BLOB handle
6470 ** or by other independent statements.
6471 **
6472 ** On success, SQLITE_OK is returned.
6473 ** Otherwise, an  [error code] or an [extended error code] is returned.
6474 **
6475 ** INVARIANTS:
6476 **
6477 ** {H17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)]
6478 **          shall write N bytes of data from buffer Z into the BLOB 
6479 **          referenced by [BLOB handle] P beginning at offset X into
6480 **          the BLOB.
6481 **
6482 ** {H17874} In the absence of other overridding changes, the changes
6483 **          written to a BLOB by [sqlite3_blob_write()] shall
6484 **          remain in effect after the associated [BLOB handle] expires.
6485 **
6486 ** {H17875} If the [BLOB handle] P was opened for reading only then
6487 **          an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave
6488 **          the referenced BLOB unchanged and return [SQLITE_READONLY].
6489 **
6490 ** {H17876} If the size of the BLOB referenced by [BLOB handle] P is
6491 **          less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall
6492 **          leave the BLOB unchanged and return [SQLITE_ERROR].
6493 **
6494 ** {H17877} If the [BLOB handle] P is expired and X and N are within bounds
6495 **          then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB
6496 **          unchanged and return [SQLITE_ABORT].
6497 **
6498 ** {H17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)]
6499 **          shall leave the BLOB referenced by [BLOB handle] P unchanged
6500 **          and return [SQLITE_ERROR].
6501 **
6502 ** {H17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return
6503 **          [SQLITE_OK] if N bytes where successfully written into the BLOB.
6504 **
6505 ** {H17885} If the requested write could not be completed,
6506 **          the [sqlite3_blob_write(P,Z,N,X)] interface shall return an
6507 **          appropriate [error code] or [extended error code].
6508 **
6509 ** {H17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)]
6510 **          then subsequent calls to [sqlite3_errcode(D)],
6511 **          [sqlite3_extended_errcode()],
6512 **          [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return
6513 **          information appropriate for that error.
6514 */
6515 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6516
6517 /*
6518 ** CAPI3REF: Virtual File System Objects {H11200} <S20100>
6519 **
6520 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6521 ** that SQLite uses to interact
6522 ** with the underlying operating system.  Most SQLite builds come with a
6523 ** single default VFS that is appropriate for the host computer.
6524 ** New VFSes can be registered and existing VFSes can be unregistered.
6525 ** The following interfaces are provided.
6526 **
6527 ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6528 ** Names are case sensitive.
6529 ** Names are zero-terminated UTF-8 strings.
6530 ** If there is no match, a NULL pointer is returned.
6531 ** If zVfsName is NULL then the default VFS is returned.
6532 **
6533 ** New VFSes are registered with sqlite3_vfs_register().
6534 ** Each new VFS becomes the default VFS if the makeDflt flag is set.
6535 ** The same VFS can be registered multiple times without injury.
6536 ** To make an existing VFS into the default VFS, register it again
6537 ** with the makeDflt flag set.  If two different VFSes with the
6538 ** same name are registered, the behavior is undefined.  If a
6539 ** VFS is registered with a name that is NULL or an empty string,
6540 ** then the behavior is undefined.
6541 **
6542 ** Unregister a VFS with the sqlite3_vfs_unregister() interface.
6543 ** If the default VFS is unregistered, another VFS is chosen as
6544 ** the default.  The choice for the new VFS is arbitrary.
6545 **
6546 ** INVARIANTS:
6547 **
6548 ** {H11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the
6549 **          registered [sqlite3_vfs] object whose name exactly matches
6550 **          the zero-terminated UTF-8 string N, or it returns NULL if
6551 **          there is no match.
6552 **
6553 ** {H11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then
6554 **          the function returns a pointer to the default [sqlite3_vfs]
6555 **          object if there is one, or NULL if there is no default
6556 **          [sqlite3_vfs] object.
6557 **
6558 ** {H11209} The [sqlite3_vfs_register(P,F)] interface registers the
6559 **          well-formed [sqlite3_vfs] object P using the name given
6560 **          by the zName field of the object.
6561 **
6562 ** {H11212} Using the [sqlite3_vfs_register(P,F)] interface to register
6563 **          the same [sqlite3_vfs] object multiple times is a harmless no-op.
6564 **
6565 ** {H11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs]
6566 **          object P the default [sqlite3_vfs] object if F is non-zero.
6567 **
6568 ** {H11218} The [sqlite3_vfs_unregister(P)] interface unregisters the
6569 **          [sqlite3_vfs] object P so that it is no longer returned by
6570 **          subsequent calls to [sqlite3_vfs_find()].
6571 */
6572 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6573 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6574 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6575
6576 /*
6577 ** CAPI3REF: Mutexes {H17000} <S20000>
6578 **
6579 ** The SQLite core uses these routines for thread
6580 ** synchronization. Though they are intended for internal
6581 ** use by SQLite, code that links against SQLite is
6582 ** permitted to use any of these routines.
6583 **
6584 ** The SQLite source code contains multiple implementations
6585 ** of these mutex routines.  An appropriate implementation
6586 ** is selected automatically at compile-time.  The following
6587 ** implementations are available in the SQLite core:
6588 **
6589 ** <ul>
6590 ** <li>   SQLITE_MUTEX_OS2
6591 ** <li>   SQLITE_MUTEX_PTHREAD
6592 ** <li>   SQLITE_MUTEX_W32
6593 ** <li>   SQLITE_MUTEX_NOOP
6594 ** </ul>
6595 **
6596 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6597 ** that does no real locking and is appropriate for use in
6598 ** a single-threaded application.  The SQLITE_MUTEX_OS2,
6599 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
6600 ** are appropriate for use on OS/2, Unix, and Windows.
6601 **
6602 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6603 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6604 ** implementation is included with the library. In this case the
6605 ** application must supply a custom mutex implementation using the
6606 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6607 ** before calling sqlite3_initialize() or any other public sqlite3_
6608 ** function that calls sqlite3_initialize().
6609 **
6610 ** {H17011} The sqlite3_mutex_alloc() routine allocates a new
6611 ** mutex and returns a pointer to it. {H17012} If it returns NULL
6612 ** that means that a mutex could not be allocated. {H17013} SQLite
6613 ** will unwind its stack and return an error. {H17014} The argument
6614 ** to sqlite3_mutex_alloc() is one of these integer constants:
6615 **
6616 ** <ul>
6617 ** <li>  SQLITE_MUTEX_FAST
6618 ** <li>  SQLITE_MUTEX_RECURSIVE
6619 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6620 ** <li>  SQLITE_MUTEX_STATIC_MEM
6621 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6622 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6623 ** <li>  SQLITE_MUTEX_STATIC_LRU
6624 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6625 ** </ul>
6626 **
6627 ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create
6628 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6629 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END}
6630 ** The mutex implementation does not need to make a distinction
6631 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6632 ** not want to.  {H17016} But SQLite will only request a recursive mutex in
6633 ** cases where it really needs one.  {END} If a faster non-recursive mutex
6634 ** implementation is available on the host platform, the mutex subsystem
6635 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6636 **
6637 ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return
6638 ** a pointer to a static preexisting mutex. {END}  Four static mutexes are
6639 ** used by the current version of SQLite.  Future versions of SQLite
6640 ** may add additional static mutexes.  Static mutexes are for internal
6641 ** use by SQLite only.  Applications that use SQLite mutexes should
6642 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6643 ** SQLITE_MUTEX_RECURSIVE.
6644 **
6645 ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6646 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6647 ** returns a different mutex on every call.  {H17034} But for the static
6648 ** mutex types, the same mutex is returned on every call that has
6649 ** the same type number.
6650 **
6651 ** {H17019} The sqlite3_mutex_free() routine deallocates a previously
6652 ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every
6653 ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in
6654 ** use when they are deallocated. {A17022} Attempting to deallocate a static
6655 ** mutex results in undefined behavior. {H17023} SQLite never deallocates
6656 ** a static mutex. {END}
6657 **
6658 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6659 ** to enter a mutex. {H17024} If another thread is already within the mutex,
6660 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6661 ** SQLITE_BUSY. {H17025}  The sqlite3_mutex_try() interface returns [SQLITE_OK]
6662 ** upon successful entry.  {H17026} Mutexes created using
6663 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6664 ** {H17027} In such cases the,
6665 ** mutex must be exited an equal number of times before another thread
6666 ** can enter.  {A17028} If the same thread tries to enter any other
6667 ** kind of mutex more than once, the behavior is undefined.
6668 ** {H17029} SQLite will never exhibit
6669 ** such behavior in its own use of mutexes.
6670 **
6671 ** Some systems (for example, Windows 95) do not support the operation
6672 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6673 ** will always return SQLITE_BUSY.  {H17030} The SQLite core only ever uses
6674 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.
6675 **
6676 ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was
6677 ** previously entered by the same thread.  {A17032} The behavior
6678 ** is undefined if the mutex is not currently entered by the
6679 ** calling thread or is not currently allocated.  {H17033} SQLite will
6680 ** never do either. {END}
6681 **
6682 ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6683 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6684 ** behave as no-ops.
6685 **
6686 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6687 */
6688 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6689 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6690 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6691 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6692 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6693
6694 /*
6695 ** CAPI3REF: Mutex Methods Object {H17120} <S20130>
6696 ** EXPERIMENTAL
6697 **
6698 ** An instance of this structure defines the low-level routines
6699 ** used to allocate and use mutexes.
6700 **
6701 ** Usually, the default mutex implementations provided by SQLite are
6702 ** sufficient, however the user has the option of substituting a custom
6703 ** implementation for specialized deployments or systems for which SQLite
6704 ** does not provide a suitable implementation. In this case, the user
6705 ** creates and populates an instance of this structure to pass
6706 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6707 ** Additionally, an instance of this structure can be used as an
6708 ** output variable when querying the system for the current mutex
6709 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6710 **
6711 ** The xMutexInit method defined by this structure is invoked as
6712 ** part of system initialization by the sqlite3_initialize() function.
6713 ** {H17001} The xMutexInit routine shall be called by SQLite once for each
6714 ** effective call to [sqlite3_initialize()].
6715 **
6716 ** The xMutexEnd method defined by this structure is invoked as
6717 ** part of system shutdown by the sqlite3_shutdown() function. The
6718 ** implementation of this method is expected to release all outstanding
6719 ** resources obtained by the mutex methods implementation, especially
6720 ** those obtained by the xMutexInit method. {H17003} The xMutexEnd()
6721 ** interface shall be invoked once for each call to [sqlite3_shutdown()].
6722 **
6723 ** The remaining seven methods defined by this structure (xMutexAlloc,
6724 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6725 ** xMutexNotheld) implement the following interfaces (respectively):
6726 **
6727 ** <ul>
6728 **   <li>  [sqlite3_mutex_alloc()] </li>
6729 **   <li>  [sqlite3_mutex_free()] </li>
6730 **   <li>  [sqlite3_mutex_enter()] </li>
6731 **   <li>  [sqlite3_mutex_try()] </li>
6732 **   <li>  [sqlite3_mutex_leave()] </li>
6733 **   <li>  [sqlite3_mutex_held()] </li>
6734 **   <li>  [sqlite3_mutex_notheld()] </li>
6735 ** </ul>
6736 **
6737 ** The only difference is that the public sqlite3_XXX functions enumerated
6738 ** above silently ignore any invocations that pass a NULL pointer instead
6739 ** of a valid mutex handle. The implementations of the methods defined
6740 ** by this structure are not required to handle this case, the results
6741 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6742 ** (i.e. it is acceptable to provide an implementation that segfaults if
6743 ** it is passed a NULL pointer).
6744 */
6745 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6746 struct sqlite3_mutex_methods {
6747   int (*xMutexInit)(void);
6748   int (*xMutexEnd)(void);
6749   sqlite3_mutex *(*xMutexAlloc)(int);
6750   void (*xMutexFree)(sqlite3_mutex *);
6751   void (*xMutexEnter)(sqlite3_mutex *);
6752   int (*xMutexTry)(sqlite3_mutex *);
6753   void (*xMutexLeave)(sqlite3_mutex *);
6754   int (*xMutexHeld)(sqlite3_mutex *);
6755   int (*xMutexNotheld)(sqlite3_mutex *);
6756 };
6757
6758 /*
6759 ** CAPI3REF: Mutex Verification Routines {H17080} <S20130> <S30800>
6760 **
6761 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6762 ** are intended for use inside assert() statements. {H17081} The SQLite core
6763 ** never uses these routines except inside an assert() and applications
6764 ** are advised to follow the lead of the core.  {H17082} The core only
6765 ** provides implementations for these routines when it is compiled
6766 ** with the SQLITE_DEBUG flag.  {A17087} External mutex implementations
6767 ** are only required to provide these routines if SQLITE_DEBUG is
6768 ** defined and if NDEBUG is not defined.
6769 **
6770 ** {H17083} These routines should return true if the mutex in their argument
6771 ** is held or not held, respectively, by the calling thread.
6772 **
6773 ** {X17084} The implementation is not required to provided versions of these
6774 ** routines that actually work. If the implementation does not provide working
6775 ** versions of these routines, it should at least provide stubs that always
6776 ** return true so that one does not get spurious assertion failures.
6777 **
6778 ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then
6779 ** the routine should return 1.  {END} This seems counter-intuitive since
6780 ** clearly the mutex cannot be held if it does not exist.  But the
6781 ** the reason the mutex does not exist is because the build is not
6782 ** using mutexes.  And we do not want the assert() containing the
6783 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6784 ** the appropriate thing to do.  {H17086} The sqlite3_mutex_notheld()
6785 ** interface should also return 1 when given a NULL pointer.
6786 */
6787 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6788 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6789
6790 /*
6791 ** CAPI3REF: Mutex Types {H17001} <H17000>
6792 **
6793 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6794 ** which is one of these integer constants.
6795 **
6796 ** The set of static mutexes may change from one SQLite release to the
6797 ** next.  Applications that override the built-in mutex logic must be
6798 ** prepared to accommodate additional static mutexes.
6799 */
6800 #define SQLITE_MUTEX_FAST             0
6801 #define SQLITE_MUTEX_RECURSIVE        1
6802 #define SQLITE_MUTEX_STATIC_MASTER    2
6803 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6804 #define SQLITE_MUTEX_STATIC_MEM2      4  /* sqlite3_release_memory() */
6805 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6806 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6807 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
6808
6809 /*
6810 ** CAPI3REF: Retrieve the mutex for a database connection {H17002} <H17000>
6811 **
6812 ** This interface returns a pointer the [sqlite3_mutex] object that 
6813 ** serializes access to the [database connection] given in the argument
6814 ** when the [threading mode] is Serialized.
6815 ** If the [threading mode] is Single-thread or Multi-thread then this
6816 ** routine returns a NULL pointer.
6817 */
6818 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6819
6820 /*
6821 ** CAPI3REF: Low-Level Control Of Database Files {H11300} <S30800>
6822 **
6823 ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the
6824 ** xFileControl method for the [sqlite3_io_methods] object associated
6825 ** with a particular database identified by the second argument. {H11302} The
6826 ** name of the database is the name assigned to the database by the
6827 ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the
6828 ** database. {H11303} To control the main database file, use the name "main"
6829 ** or a NULL pointer. {H11304} The third and fourth parameters to this routine
6830 ** are passed directly through to the second and third parameters of
6831 ** the xFileControl method.  {H11305} The return value of the xFileControl
6832 ** method becomes the return value of this routine.
6833 **
6834 ** {H11306} If the second parameter (zDbName) does not match the name of any
6835 ** open database file, then SQLITE_ERROR is returned. {H11307} This error
6836 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6837 ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might
6838 ** also return SQLITE_ERROR.  {A11309} There is no way to distinguish between
6839 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6840 ** xFileControl method. {END}
6841 **
6842 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6843 */
6844 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6845
6846 /*
6847 ** CAPI3REF: Testing Interface {H11400} <S30800>
6848 **
6849 ** The sqlite3_test_control() interface is used to read out internal
6850 ** state of SQLite and to inject faults into SQLite for testing
6851 ** purposes.  The first parameter is an operation code that determines
6852 ** the number, meaning, and operation of all subsequent parameters.
6853 **
6854 ** This interface is not for use by applications.  It exists solely
6855 ** for verifying the correct operation of the SQLite library.  Depending
6856 ** on how the SQLite library is compiled, this interface might not exist.
6857 **
6858 ** The details of the operation codes, their meanings, the parameters
6859 ** they take, and what they do are all subject to change without notice.
6860 ** Unlike most of the SQLite API, this function is not guaranteed to
6861 ** operate consistently from one release to the next.
6862 */
6863 SQLITE_API int sqlite3_test_control(int op, ...);
6864
6865 /*
6866 ** CAPI3REF: Testing Interface Operation Codes {H11410} <H11400>
6867 **
6868 ** These constants are the valid operation code parameters used
6869 ** as the first argument to [sqlite3_test_control()].
6870 **
6871 ** These parameters and their meanings are subject to change
6872 ** without notice.  These values are for testing purposes only.
6873 ** Applications should not use any of these parameters or the
6874 ** [sqlite3_test_control()] interface.
6875 */
6876 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6877 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6878 #define SQLITE_TESTCTRL_PRNG_RESET               7
6879 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6880 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6881 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6882 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6883
6884 /*
6885 ** CAPI3REF: SQLite Runtime Status {H17200} <S60200>
6886 ** EXPERIMENTAL
6887 **
6888 ** This interface is used to retrieve runtime status information
6889 ** about the preformance of SQLite, and optionally to reset various
6890 ** highwater marks.  The first argument is an integer code for
6891 ** the specific parameter to measure.  Recognized integer codes
6892 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].
6893 ** The current value of the parameter is returned into *pCurrent.
6894 ** The highest recorded value is returned in *pHighwater.  If the
6895 ** resetFlag is true, then the highest record value is reset after
6896 ** *pHighwater is written. Some parameters do not record the highest
6897 ** value.  For those parameters
6898 ** nothing is written into *pHighwater and the resetFlag is ignored.
6899 ** Other parameters record only the highwater mark and not the current
6900 ** value.  For these latter parameters nothing is written into *pCurrent.
6901 **
6902 ** This routine returns SQLITE_OK on success and a non-zero
6903 ** [error code] on failure.
6904 **
6905 ** This routine is threadsafe but is not atomic.  This routine can
6906 ** called while other threads are running the same or different SQLite
6907 ** interfaces.  However the values returned in *pCurrent and
6908 ** *pHighwater reflect the status of SQLite at different points in time
6909 ** and it is possible that another thread might change the parameter
6910 ** in between the times when *pCurrent and *pHighwater are written.
6911 **
6912 ** See also: [sqlite3_db_status()]
6913 */
6914 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6915
6916
6917 /*
6918 ** CAPI3REF: Status Parameters {H17250} <H17200>
6919 ** EXPERIMENTAL
6920 **
6921 ** These integer constants designate various run-time status parameters
6922 ** that can be returned by [sqlite3_status()].
6923 **
6924 ** <dl>
6925 ** <dt>SQLITE_STATUS_MEMORY_USED</dt>
6926 ** <dd>This parameter is the current amount of memory checked out
6927 ** using [sqlite3_malloc()], either directly or indirectly.  The
6928 ** figure includes calls made to [sqlite3_malloc()] by the application
6929 ** and internal memory usage by the SQLite library.  Scratch memory
6930 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6931 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6932 ** this parameter.  The amount returned is the sum of the allocation
6933 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>
6934 **
6935 ** <dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6936 ** <dd>This parameter records the largest memory allocation request
6937 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6938 ** internal equivalents).  Only the value returned in the
6939 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6940 ** The value written into the *pCurrent parameter is undefined.</dd>
6941 **
6942 ** <dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6943 ** <dd>This parameter returns the number of pages used out of the
6944 ** [pagecache memory allocator] that was configured using 
6945 ** [SQLITE_CONFIG_PAGECACHE].  The
6946 ** value returned is in pages, not in bytes.</dd>
6947 **
6948 ** <dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6949 ** <dd>This parameter returns the number of bytes of page cache
6950 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
6951 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6952 ** returned value includes allocations that overflowed because they
6953 ** where too large (they were larger than the "sz" parameter to
6954 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6955 ** no space was left in the page cache.</dd>
6956 **
6957 ** <dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6958 ** <dd>This parameter records the largest memory allocation request
6959 ** handed to [pagecache memory allocator].  Only the value returned in the
6960 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6961 ** The value written into the *pCurrent parameter is undefined.</dd>
6962 **
6963 ** <dt>SQLITE_STATUS_SCRATCH_USED</dt>
6964 ** <dd>This parameter returns the number of allocations used out of the
6965 ** [scratch memory allocator] configured using
6966 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6967 ** in bytes.  Since a single thread may only have one scratch allocation
6968 ** outstanding at time, this parameter also reports the number of threads
6969 ** using scratch memory at the same time.</dd>
6970 **
6971 ** <dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6972 ** <dd>This parameter returns the number of bytes of scratch memory
6973 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
6974 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6975 ** returned include overflows because the requested allocation was too
6976 ** larger (that is, because the requested allocation was larger than the
6977 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6978 ** slots were available.
6979 ** </dd>
6980 **
6981 ** <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6982 ** <dd>This parameter records the largest memory allocation request
6983 ** handed to [scratch memory allocator].  Only the value returned in the
6984 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6985 ** The value written into the *pCurrent parameter is undefined.</dd>
6986 **
6987 ** <dt>SQLITE_STATUS_PARSER_STACK</dt>
6988 ** <dd>This parameter records the deepest parser stack.  It is only
6989 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>
6990 ** </dl>
6991 **
6992 ** New status parameters may be added from time to time.
6993 */
6994 #define SQLITE_STATUS_MEMORY_USED          0
6995 #define SQLITE_STATUS_PAGECACHE_USED       1
6996 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6997 #define SQLITE_STATUS_SCRATCH_USED         3
6998 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6999 #define SQLITE_STATUS_MALLOC_SIZE          5
7000 #define SQLITE_STATUS_PARSER_STACK         6
7001 #define SQLITE_STATUS_PAGECACHE_SIZE       7
7002 #define SQLITE_STATUS_SCRATCH_SIZE         8
7003
7004 /*
7005 ** CAPI3REF: Database Connection Status {H17500} <S60200>
7006 ** EXPERIMENTAL
7007 **
7008 ** This interface is used to retrieve runtime status information 
7009 ** about a single [database connection].  The first argument is the
7010 ** database connection object to be interrogated.  The second argument
7011 ** is the parameter to interrogate.  Currently, the only allowed value
7012 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
7013 ** Additional options will likely appear in future releases of SQLite.
7014 **
7015 ** The current value of the requested parameter is written into *pCur
7016 ** and the highest instantaneous value is written into *pHiwtr.  If
7017 ** the resetFlg is true, then the highest instantaneous value is
7018 ** reset back down to the current value.
7019 **
7020 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7021 */
7022 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7023
7024 /*
7025 ** CAPI3REF: Status Parameters for database connections {H17520} <H17500>
7026 ** EXPERIMENTAL
7027 **
7028 ** Status verbs for [sqlite3_db_status()].
7029 **
7030 ** <dl>
7031 ** <dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7032 ** <dd>This parameter returns the number of lookaside memory slots currently
7033 ** checked out.</dd>
7034 ** </dl>
7035 */
7036 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
7037
7038
7039 /*
7040 ** CAPI3REF: Prepared Statement Status {H17550} <S60200>
7041 ** EXPERIMENTAL
7042 **
7043 ** Each prepared statement maintains various
7044 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
7045 ** of times it has performed specific operations.  These counters can
7046 ** be used to monitor the performance characteristics of the prepared
7047 ** statements.  For example, if the number of table steps greatly exceeds
7048 ** the number of table searches or result rows, that would tend to indicate
7049 ** that the prepared statement is using a full table scan rather than
7050 ** an index.  
7051 **
7052 ** This interface is used to retrieve and reset counter values from
7053 ** a [prepared statement].  The first argument is the prepared statement
7054 ** object to be interrogated.  The second argument
7055 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
7056 ** to be interrogated. 
7057 ** The current value of the requested counter is returned.
7058 ** If the resetFlg is true, then the counter is reset to zero after this
7059 ** interface call returns.
7060 **
7061 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7062 */
7063 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7064
7065 /*
7066 ** CAPI3REF: Status Parameters for prepared statements {H17570} <H17550>
7067 ** EXPERIMENTAL
7068 **
7069 ** These preprocessor macros define integer codes that name counter
7070 ** values associated with the [sqlite3_stmt_status()] interface.
7071 ** The meanings of the various counters are as follows:
7072 **
7073 ** <dl>
7074 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7075 ** <dd>This is the number of times that SQLite has stepped forward in
7076 ** a table as part of a full table scan.  Large numbers for this counter
7077 ** may indicate opportunities for performance improvement through 
7078 ** careful use of indices.</dd>
7079 **
7080 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
7081 ** <dd>This is the number of sort operations that have occurred.
7082 ** A non-zero value in this counter may indicate an opportunity to
7083 ** improvement performance through careful use of indices.</dd>
7084 **
7085 ** </dl>
7086 */
7087 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
7088 #define SQLITE_STMTSTATUS_SORT              2
7089
7090 /*
7091 ** CAPI3REF: Custom Page Cache Object
7092 ** EXPERIMENTAL
7093 **
7094 ** The sqlite3_pcache type is opaque.  It is implemented by
7095 ** the pluggable module.  The SQLite core has no knowledge of
7096 ** its size or internal structure and never deals with the
7097 ** sqlite3_pcache object except by holding and passing pointers
7098 ** to the object.
7099 **
7100 ** See [sqlite3_pcache_methods] for additional information.
7101 */
7102 typedef struct sqlite3_pcache sqlite3_pcache;
7103
7104 /*
7105 ** CAPI3REF: Application Defined Page Cache.
7106 ** EXPERIMENTAL
7107 **
7108 ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
7109 ** register an alternative page cache implementation by passing in an 
7110 ** instance of the sqlite3_pcache_methods structure. The majority of the 
7111 ** heap memory used by sqlite is used by the page cache to cache data read 
7112 ** from, or ready to be written to, the database file. By implementing a 
7113 ** custom page cache using this API, an application can control more 
7114 ** precisely the amount of memory consumed by sqlite, the way in which 
7115 ** said memory is allocated and released, and the policies used to 
7116 ** determine exactly which parts of a database file are cached and for 
7117 ** how long.
7118 **
7119 ** The contents of the structure are copied to an internal buffer by sqlite
7120 ** within the call to [sqlite3_config].
7121 **
7122 ** The xInit() method is called once for each call to [sqlite3_initialize()]
7123 ** (usually only once during the lifetime of the process). It is passed
7124 ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set
7125 ** up global structures and mutexes required by the custom page cache 
7126 ** implementation. The xShutdown() method is called from within 
7127 ** [sqlite3_shutdown()], if the application invokes this API. It can be used
7128 ** to clean up any outstanding resources before process shutdown, if required.
7129 **
7130 ** The xCreate() method is used to construct a new cache instance. The
7131 ** first parameter, szPage, is the size in bytes of the pages that must
7132 ** be allocated by the cache. szPage will not be a power of two. The
7133 ** second argument, bPurgeable, is true if the cache being created will
7134 ** be used to cache database pages read from a file stored on disk, or
7135 ** false if it is used for an in-memory database. The cache implementation
7136 ** does not have to do anything special based on the value of bPurgeable,
7137 ** it is purely advisory. 
7138 **
7139 ** The xCachesize() method may be called at any time by SQLite to set the
7140 ** suggested maximum cache-size (number of pages stored by) the cache
7141 ** instance passed as the first argument. This is the value configured using
7142 ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter,
7143 ** the implementation is not required to do anything special with this
7144 ** value, it is advisory only.
7145 **
7146 ** The xPagecount() method should return the number of pages currently
7147 ** stored in the cache supplied as an argument.
7148 ** 
7149 ** The xFetch() method is used to fetch a page and return a pointer to it. 
7150 ** A 'page', in this context, is a buffer of szPage bytes aligned at an
7151 ** 8-byte boundary. The page to be fetched is determined by the key. The
7152 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
7153 ** is considered to be pinned.
7154 **
7155 ** If the requested page is already in the page cache, then a pointer to
7156 ** the cached buffer should be returned with its contents intact. If the
7157 ** page is not already in the cache, then the expected behaviour of the
7158 ** cache is determined by the value of the createFlag parameter passed
7159 ** to xFetch, according to the following table:
7160 **
7161 ** <table border=1 width=85% align=center>
7162 **   <tr><th>createFlag<th>Expected Behaviour
7163 **   <tr><td>0<td>NULL should be returned. No new cache entry is created.
7164 **   <tr><td>1<td>If createFlag is set to 1, this indicates that 
7165 **                SQLite is holding pinned pages that can be unpinned
7166 **                by writing their contents to the database file (a
7167 **                relatively expensive operation). In this situation the
7168 **                cache implementation has two choices: it can return NULL,
7169 **                in which case SQLite will attempt to unpin one or more 
7170 **                pages before re-requesting the same page, or it can
7171 **                allocate a new page and return a pointer to it. If a new
7172 **                page is allocated, then the first sizeof(void*) bytes of
7173 **                it (at least) must be zeroed before it is returned.
7174 **   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
7175 **                pinned pages associated with the specific cache passed
7176 **                as the first argument to xFetch() that can be unpinned. The
7177 **                cache implementation should attempt to allocate a new
7178 **                cache entry and return a pointer to it. Again, the first
7179 **                sizeof(void*) bytes of the page should be zeroed before 
7180 **                it is returned. If the xFetch() method returns NULL when 
7181 **                createFlag==2, SQLite assumes that a memory allocation 
7182 **                failed and returns SQLITE_NOMEM to the user.
7183 ** </table>
7184 **
7185 ** xUnpin() is called by SQLite with a pointer to a currently pinned page
7186 ** as its second argument. If the third parameter, discard, is non-zero,
7187 ** then the page should be evicted from the cache. In this case SQLite 
7188 ** assumes that the next time the page is retrieved from the cache using
7189 ** the xFetch() method, it will be zeroed. If the discard parameter is
7190 ** zero, then the page is considered to be unpinned. The cache implementation
7191 ** may choose to reclaim (free or recycle) unpinned pages at any time.
7192 ** SQLite assumes that next time the page is retrieved from the cache
7193 ** it will either be zeroed, or contain the same data that it did when it
7194 ** was unpinned.
7195 **
7196 ** The cache is not required to perform any reference counting. A single 
7197 ** call to xUnpin() unpins the page regardless of the number of prior calls 
7198 ** to xFetch().
7199 **
7200 ** The xRekey() method is used to change the key value associated with the
7201 ** page passed as the second argument from oldKey to newKey. If the cache
7202 ** previously contains an entry associated with newKey, it should be
7203 ** discarded. Any prior cache entry associated with newKey is guaranteed not
7204 ** to be pinned.
7205 **
7206 ** When SQLite calls the xTruncate() method, the cache must discard all
7207 ** existing cache entries with page numbers (keys) greater than or equal
7208 ** to the value of the iLimit parameter passed to xTruncate(). If any
7209 ** of these pages are pinned, they are implicitly unpinned, meaning that
7210 ** they can be safely discarded.
7211 **
7212 ** The xDestroy() method is used to delete a cache allocated by xCreate().
7213 ** All resources associated with the specified cache should be freed. After
7214 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7215 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
7216 ** functions.
7217 */
7218 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7219 struct sqlite3_pcache_methods {
7220   void *pArg;
7221   int (*xInit)(void*);
7222   void (*xShutdown)(void*);
7223   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7224   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7225   int (*xPagecount)(sqlite3_pcache*);
7226   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7227   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7228   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7229   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7230   void (*xDestroy)(sqlite3_pcache*);
7231 };
7232
7233 /*
7234 ** CAPI3REF: Online Backup Object
7235 ** EXPERIMENTAL
7236 **
7237 ** The sqlite3_backup object records state information about an ongoing
7238 ** online backup operation.  The sqlite3_backup object is created by
7239 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7240 ** [sqlite3_backup_finish()].
7241 **
7242 ** See Also: [Using the SQLite Online Backup API]
7243 */
7244 typedef struct sqlite3_backup sqlite3_backup;
7245
7246 /*
7247 ** CAPI3REF: Online Backup API.
7248 ** EXPERIMENTAL
7249 **
7250 ** This API is used to overwrite the contents of one database with that
7251 ** of another. It is useful either for creating backups of databases or
7252 ** for copying in-memory databases to or from persistent files. 
7253 **
7254 ** See Also: [Using the SQLite Online Backup API]
7255 **
7256 ** Exclusive access is required to the destination database for the 
7257 ** duration of the operation. However the source database is only
7258 ** read-locked while it is actually being read, it is not locked
7259 ** continuously for the entire operation. Thus, the backup may be
7260 ** performed on a live database without preventing other users from
7261 ** writing to the database for an extended period of time.
7262 ** 
7263 ** To perform a backup operation: 
7264 **   <ol>
7265 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7266 **         backup, 
7267 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
7268 **         the data between the two databases, and finally
7269 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
7270 **         associated with the backup operation. 
7271 **   </ol>
7272 ** There should be exactly one call to sqlite3_backup_finish() for each
7273 ** successful call to sqlite3_backup_init().
7274 **
7275 ** <b>sqlite3_backup_init()</b>
7276 **
7277 ** The first two arguments passed to [sqlite3_backup_init()] are the database
7278 ** handle associated with the destination database and the database name 
7279 ** used to attach the destination database to the handle. The database name
7280 ** is "main" for the main database, "temp" for the temporary database, or
7281 ** the name specified as part of the [ATTACH] statement if the destination is
7282 ** an attached database. The third and fourth arguments passed to 
7283 ** sqlite3_backup_init() identify the [database connection]
7284 ** and database name used
7285 ** to access the source database. The values passed for the source and 
7286 ** destination [database connection] parameters must not be the same.
7287 **
7288 ** If an error occurs within sqlite3_backup_init(), then NULL is returned
7289 ** and an error code and error message written into the [database connection] 
7290 ** passed as the first argument. They may be retrieved using the
7291 ** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions.
7292 ** Otherwise, if successful, a pointer to an [sqlite3_backup] object is
7293 ** returned. This pointer may be used with the sqlite3_backup_step() and
7294 ** sqlite3_backup_finish() functions to perform the specified backup 
7295 ** operation.
7296 **
7297 ** <b>sqlite3_backup_step()</b>
7298 **
7299 ** Function [sqlite3_backup_step()] is used to copy up to nPage pages between 
7300 ** the source and destination databases, where nPage is the value of the 
7301 ** second parameter passed to sqlite3_backup_step(). If nPage is a negative
7302 ** value, all remaining source pages are copied. If the required pages are 
7303 ** succesfully copied, but there are still more pages to copy before the 
7304 ** backup is complete, it returns [SQLITE_OK]. If no error occured and there 
7305 ** are no more pages to copy, then [SQLITE_DONE] is returned. If an error 
7306 ** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and
7307 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7308 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7309 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7310 **
7311 ** As well as the case where the destination database file was opened for
7312 ** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if
7313 ** the destination is an in-memory database with a different page size
7314 ** from the source database.
7315 **
7316 ** If sqlite3_backup_step() cannot obtain a required file-system lock, then
7317 ** the [sqlite3_busy_handler | busy-handler function]
7318 ** is invoked (if one is specified). If the 
7319 ** busy-handler returns non-zero before the lock is available, then 
7320 ** [SQLITE_BUSY] is returned to the caller. In this case the call to
7321 ** sqlite3_backup_step() can be retried later. If the source
7322 ** [database connection]
7323 ** is being used to write to the source database when sqlite3_backup_step()
7324 ** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this
7325 ** case the call to sqlite3_backup_step() can be retried later on. If
7326 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7327 ** [SQLITE_READONLY] is returned, then 
7328 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7329 ** errors are considered fatal. At this point the application must accept 
7330 ** that the backup operation has failed and pass the backup operation handle 
7331 ** to the sqlite3_backup_finish() to release associated resources.
7332 **
7333 ** Following the first call to sqlite3_backup_step(), an exclusive lock is
7334 ** obtained on the destination file. It is not released until either 
7335 ** sqlite3_backup_finish() is called or the backup operation is complete 
7336 ** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time 
7337 ** a call to sqlite3_backup_step() is made a [shared lock] is obtained on
7338 ** the source database file. This lock is released before the
7339 ** sqlite3_backup_step() call returns. Because the source database is not
7340 ** locked between calls to sqlite3_backup_step(), it may be modified mid-way
7341 ** through the backup procedure. If the source database is modified by an
7342 ** external process or via a database connection other than the one being
7343 ** used by the backup operation, then the backup will be transparently
7344 ** restarted by the next call to sqlite3_backup_step(). If the source 
7345 ** database is modified by the using the same database connection as is used
7346 ** by the backup operation, then the backup database is transparently 
7347 ** updated at the same time.
7348 **
7349 ** <b>sqlite3_backup_finish()</b>
7350 **
7351 ** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7352 ** application wishes to abandon the backup operation, the [sqlite3_backup]
7353 ** object should be passed to sqlite3_backup_finish(). This releases all
7354 ** resources associated with the backup operation. If sqlite3_backup_step()
7355 ** has not yet returned [SQLITE_DONE], then any active write-transaction on the
7356 ** destination database is rolled back. The [sqlite3_backup] object is invalid
7357 ** and may not be used following a call to sqlite3_backup_finish().
7358 **
7359 ** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error
7360 ** occurred, regardless or whether or not sqlite3_backup_step() was called
7361 ** a sufficient number of times to complete the backup operation. Or, if
7362 ** an out-of-memory condition or IO error occured during a call to
7363 ** sqlite3_backup_step() then [SQLITE_NOMEM] or an
7364 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code
7365 ** is returned. In this case the error code and an error message are
7366 ** written to the destination [database connection].
7367 **
7368 ** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is
7369 ** not a permanent error and does not affect the return value of
7370 ** sqlite3_backup_finish().
7371 **
7372 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
7373 **
7374 ** Each call to sqlite3_backup_step() sets two values stored internally
7375 ** by an [sqlite3_backup] object. The number of pages still to be backed
7376 ** up, which may be queried by sqlite3_backup_remaining(), and the total
7377 ** number of pages in the source database file, which may be queried by
7378 ** sqlite3_backup_pagecount().
7379 **
7380 ** The values returned by these functions are only updated by
7381 ** sqlite3_backup_step(). If the source database is modified during a backup
7382 ** operation, then the values are not updated to account for any extra
7383 ** pages that need to be updated or the size of the source database file
7384 ** changing.
7385 **
7386 ** <b>Concurrent Usage of Database Handles</b>
7387 **
7388 ** The source [database connection] may be used by the application for other
7389 ** purposes while a backup operation is underway or being initialized.
7390 ** If SQLite is compiled and configured to support threadsafe database
7391 ** connections, then the source database connection may be used concurrently
7392 ** from within other threads.
7393 **
7394 ** However, the application must guarantee that the destination database
7395 ** connection handle is not passed to any other API (by any thread) after 
7396 ** sqlite3_backup_init() is called and before the corresponding call to
7397 ** sqlite3_backup_finish(). Unfortunately SQLite does not currently check
7398 ** for this, if the application does use the destination [database connection]
7399 ** for some other purpose during a backup operation, things may appear to
7400 ** work correctly but in fact be subtly malfunctioning.  Use of the
7401 ** destination database connection while a backup is in progress might
7402 ** also cause a mutex deadlock.
7403 **
7404 ** Furthermore, if running in [shared cache mode], the application must
7405 ** guarantee that the shared cache used by the destination database
7406 ** is not accessed while the backup is running. In practice this means
7407 ** that the application must guarantee that the file-system file being 
7408 ** backed up to is not accessed by any connection within the process,
7409 ** not just the specific connection that was passed to sqlite3_backup_init().
7410 **
7411 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7412 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7413 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7414 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7415 ** same time as another thread is invoking sqlite3_backup_step() it is
7416 ** possible that they return invalid values.
7417 */
7418 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7419   sqlite3 *pDest,                        /* Destination database handle */
7420   const char *zDestName,                 /* Destination database name */
7421   sqlite3 *pSource,                      /* Source database handle */
7422   const char *zSourceName                /* Source database name */
7423 );
7424 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7425 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7426 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7427 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7428
7429 /*
7430 ** Undo the hack that converts floating point types to integer for
7431 ** builds on processors without floating point support.
7432 */
7433 #ifdef SQLITE_OMIT_FLOATING_POINT
7434 # undef double
7435 #endif
7436
7437 #if 0
7438 }  /* End of the 'extern "C"' block */
7439 #endif
7440 #endif
7441
7442 /************** End of sqlite3.h *********************************************/
7443 /************** Continuing where we left off in sqliteInt.h ******************/
7444 /************** Include hash.h in the middle of sqliteInt.h ******************/
7445 /************** Begin file hash.h ********************************************/
7446 /*
7447 ** 2001 September 22
7448 **
7449 ** The author disclaims copyright to this source code.  In place of
7450 ** a legal notice, here is a blessing:
7451 **
7452 **    May you do good and not evil.
7453 **    May you find forgiveness for yourself and forgive others.
7454 **    May you share freely, never taking more than you give.
7455 **
7456 *************************************************************************
7457 ** This is the header file for the generic hash-table implemenation
7458 ** used in SQLite.
7459 **
7460 ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
7461 */
7462 #ifndef _SQLITE_HASH_H_
7463 #define _SQLITE_HASH_H_
7464
7465 /* Forward declarations of structures. */
7466 typedef struct Hash Hash;
7467 typedef struct HashElem HashElem;
7468
7469 /* A complete hash table is an instance of the following structure.
7470 ** The internals of this structure are intended to be opaque -- client
7471 ** code should not attempt to access or modify the fields of this structure
7472 ** directly.  Change this structure only by using the routines below.
7473 ** However, many of the "procedures" and "functions" for modifying and
7474 ** accessing this structure are really macros, so we can't really make
7475 ** this structure opaque.
7476 */
7477 struct Hash {
7478   unsigned int copyKey: 1;  /* True if copy of key made on insert */
7479   unsigned int htsize : 31; /* Number of buckets in the hash table */
7480   unsigned int count;       /* Number of entries in this table */
7481   HashElem *first;          /* The first element of the array */
7482   struct _ht {              /* the hash table */
7483     int count;                 /* Number of entries with this hash */
7484     HashElem *chain;           /* Pointer to first entry with this hash */
7485   } *ht;
7486 };
7487
7488 /* Each element in the hash table is an instance of the following 
7489 ** structure.  All elements are stored on a single doubly-linked list.
7490 **
7491 ** Again, this structure is intended to be opaque, but it can't really
7492 ** be opaque because it is used by macros.
7493 */
7494 struct HashElem {
7495   HashElem *next, *prev;   /* Next and previous elements in the table */
7496   void *data;              /* Data associated with this element */
7497   void *pKey; int nKey;    /* Key associated with this element */
7498 };
7499
7500 /*
7501 ** Access routines.  To delete, insert a NULL pointer.
7502 */
7503 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
7504 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
7505 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
7506 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
7507 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7508
7509 /*
7510 ** Macros for looping over all elements of a hash table.  The idiom is
7511 ** like this:
7512 **
7513 **   Hash h;
7514 **   HashElem *p;
7515 **   ...
7516 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7517 **     SomeStructure *pData = sqliteHashData(p);
7518 **     // do something with pData
7519 **   }
7520 */
7521 #define sqliteHashFirst(H)  ((H)->first)
7522 #define sqliteHashNext(E)   ((E)->next)
7523 #define sqliteHashData(E)   ((E)->data)
7524 #define sqliteHashKey(E)    ((E)->pKey)
7525 #define sqliteHashKeysize(E) ((E)->nKey)
7526
7527 /*
7528 ** Number of entries in a hash table
7529 */
7530 #define sqliteHashCount(H)  ((H)->count)
7531
7532 #endif /* _SQLITE_HASH_H_ */
7533
7534 /************** End of hash.h ************************************************/
7535 /************** Continuing where we left off in sqliteInt.h ******************/
7536 /************** Include parse.h in the middle of sqliteInt.h *****************/
7537 /************** Begin file parse.h *******************************************/
7538 #define TK_SEMI                            1
7539 #define TK_EXPLAIN                         2
7540 #define TK_QUERY                           3
7541 #define TK_PLAN                            4
7542 #define TK_BEGIN                           5
7543 #define TK_TRANSACTION                     6
7544 #define TK_DEFERRED                        7
7545 #define TK_IMMEDIATE                       8
7546 #define TK_EXCLUSIVE                       9
7547 #define TK_COMMIT                         10
7548 #define TK_END                            11
7549 #define TK_ROLLBACK                       12
7550 #define TK_SAVEPOINT                      13
7551 #define TK_RELEASE                        14
7552 #define TK_TO                             15
7553 #define TK_CREATE                         16
7554 #define TK_TABLE                          17
7555 #define TK_IF                             18
7556 #define TK_NOT                            19
7557 #define TK_EXISTS                         20
7558 #define TK_TEMP                           21
7559 #define TK_LP                             22
7560 #define TK_RP                             23
7561 #define TK_AS                             24
7562 #define TK_COMMA                          25
7563 #define TK_ID                             26
7564 #define TK_ABORT                          27
7565 #define TK_AFTER                          28
7566 #define TK_ANALYZE                        29
7567 #define TK_ASC                            30
7568 #define TK_ATTACH                         31
7569 #define TK_BEFORE                         32
7570 #define TK_BY                             33
7571 #define TK_CASCADE                        34
7572 #define TK_CAST                           35
7573 #define TK_COLUMNKW                       36
7574 #define TK_CONFLICT                       37
7575 #define TK_DATABASE                       38
7576 #define TK_DESC                           39
7577 #define TK_DETACH                         40
7578 #define TK_EACH                           41
7579 #define TK_FAIL                           42
7580 #define TK_FOR                            43
7581 #define TK_IGNORE                         44
7582 #define TK_INITIALLY                      45
7583 #define TK_INSTEAD                        46
7584 #define TK_LIKE_KW                        47
7585 #define TK_MATCH                          48
7586 #define TK_KEY                            49
7587 #define TK_OF                             50
7588 #define TK_OFFSET                         51
7589 #define TK_PRAGMA                         52
7590 #define TK_RAISE                          53
7591 #define TK_REPLACE                        54
7592 #define TK_RESTRICT                       55
7593 #define TK_ROW                            56
7594 #define TK_TRIGGER                        57
7595 #define TK_VACUUM                         58
7596 #define TK_VIEW                           59
7597 #define TK_VIRTUAL                        60
7598 #define TK_REINDEX                        61
7599 #define TK_RENAME                         62
7600 #define TK_CTIME_KW                       63
7601 #define TK_ANY                            64
7602 #define TK_OR                             65
7603 #define TK_AND                            66
7604 #define TK_IS                             67
7605 #define TK_BETWEEN                        68
7606 #define TK_IN                             69
7607 #define TK_ISNULL                         70
7608 #define TK_NOTNULL                        71
7609 #define TK_NE                             72
7610 #define TK_EQ                             73
7611 #define TK_GT                             74
7612 #define TK_LE                             75
7613 #define TK_LT                             76
7614 #define TK_GE                             77
7615 #define TK_ESCAPE                         78
7616 #define TK_BITAND                         79
7617 #define TK_BITOR                          80
7618 #define TK_LSHIFT                         81
7619 #define TK_RSHIFT                         82
7620 #define TK_PLUS                           83
7621 #define TK_MINUS                          84
7622 #define TK_STAR                           85
7623 #define TK_SLASH                          86
7624 #define TK_REM                            87
7625 #define TK_CONCAT                         88
7626 #define TK_COLLATE                        89
7627 #define TK_UMINUS                         90
7628 #define TK_UPLUS                          91
7629 #define TK_BITNOT                         92
7630 #define TK_STRING                         93
7631 #define TK_JOIN_KW                        94
7632 #define TK_CONSTRAINT                     95
7633 #define TK_DEFAULT                        96
7634 #define TK_NULL                           97
7635 #define TK_PRIMARY                        98
7636 #define TK_UNIQUE                         99
7637 #define TK_CHECK                          100
7638 #define TK_REFERENCES                     101
7639 #define TK_AUTOINCR                       102
7640 #define TK_ON                             103
7641 #define TK_DELETE                         104
7642 #define TK_UPDATE                         105
7643 #define TK_INSERT                         106
7644 #define TK_SET                            107
7645 #define TK_DEFERRABLE                     108
7646 #define TK_FOREIGN                        109
7647 #define TK_DROP                           110
7648 #define TK_UNION                          111
7649 #define TK_ALL                            112
7650 #define TK_EXCEPT                         113
7651 #define TK_INTERSECT                      114
7652 #define TK_SELECT                         115
7653 #define TK_DISTINCT                       116
7654 #define TK_DOT                            117
7655 #define TK_FROM                           118
7656 #define TK_JOIN                           119
7657 #define TK_INDEXED                        120
7658 #define TK_USING                          121
7659 #define TK_ORDER                          122
7660 #define TK_GROUP                          123
7661 #define TK_HAVING                         124
7662 #define TK_LIMIT                          125
7663 #define TK_WHERE                          126
7664 #define TK_INTO                           127
7665 #define TK_VALUES                         128
7666 #define TK_INTEGER                        129
7667 #define TK_FLOAT                          130
7668 #define TK_BLOB                           131
7669 #define TK_REGISTER                       132
7670 #define TK_VARIABLE                       133
7671 #define TK_CASE                           134
7672 #define TK_WHEN                           135
7673 #define TK_THEN                           136
7674 #define TK_ELSE                           137
7675 #define TK_INDEX                          138
7676 #define TK_ALTER                          139
7677 #define TK_ADD                            140
7678 #define TK_TO_TEXT                        141
7679 #define TK_TO_BLOB                        142
7680 #define TK_TO_NUMERIC                     143
7681 #define TK_TO_INT                         144
7682 #define TK_TO_REAL                        145
7683 #define TK_END_OF_FILE                    146
7684 #define TK_ILLEGAL                        147
7685 #define TK_SPACE                          148
7686 #define TK_UNCLOSED_STRING                149
7687 #define TK_FUNCTION                       150
7688 #define TK_COLUMN                         151
7689 #define TK_AGG_FUNCTION                   152
7690 #define TK_AGG_COLUMN                     153
7691 #define TK_CONST_FUNC                     154
7692
7693 /************** End of parse.h ***********************************************/
7694 /************** Continuing where we left off in sqliteInt.h ******************/
7695 #include <stdio.h>
7696 #include <stdlib.h>
7697 #include <string.h>
7698 #include <assert.h>
7699 #include <stddef.h>
7700
7701 /*
7702 ** If compiling for a processor that lacks floating point support,
7703 ** substitute integer for floating-point
7704 */
7705 #ifdef SQLITE_OMIT_FLOATING_POINT
7706 # define double sqlite_int64
7707 # define LONGDOUBLE_TYPE sqlite_int64
7708 # ifndef SQLITE_BIG_DBL
7709 #   define SQLITE_BIG_DBL (0x7fffffffffffffff)
7710 # endif
7711 # define SQLITE_OMIT_DATETIME_FUNCS 1
7712 # define SQLITE_OMIT_TRACE 1
7713 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7714 #endif
7715 #ifndef SQLITE_BIG_DBL
7716 # define SQLITE_BIG_DBL (1e99)
7717 #endif
7718
7719 /*
7720 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7721 ** afterward. Having this macro allows us to cause the C compiler 
7722 ** to omit code used by TEMP tables without messy #ifndef statements.
7723 */
7724 #ifdef SQLITE_OMIT_TEMPDB
7725 #define OMIT_TEMPDB 1
7726 #else
7727 #define OMIT_TEMPDB 0
7728 #endif
7729
7730 /*
7731 ** If the following macro is set to 1, then NULL values are considered
7732 ** distinct when determining whether or not two entries are the same
7733 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
7734 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
7735 ** is the way things are suppose to work.
7736 **
7737 ** If the following macro is set to 0, the NULLs are indistinct for
7738 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
7739 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
7740 ** work.
7741 */
7742 #define NULL_DISTINCT_FOR_UNIQUE 1
7743
7744 /*
7745 ** The "file format" number is an integer that is incremented whenever
7746 ** the VDBE-level file format changes.  The following macros define the
7747 ** the default file format for new databases and the maximum file format
7748 ** that the library can read.
7749 */
7750 #define SQLITE_MAX_FILE_FORMAT 4
7751 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7752 # define SQLITE_DEFAULT_FILE_FORMAT 1
7753 #endif
7754
7755 /*
7756 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7757 ** on the command-line
7758 */
7759 #ifndef SQLITE_TEMP_STORE
7760 # define SQLITE_TEMP_STORE 1
7761 #endif
7762
7763 /*
7764 ** GCC does not define the offsetof() macro so we'll have to do it
7765 ** ourselves.
7766 */
7767 #ifndef offsetof
7768 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7769 #endif
7770
7771 /*
7772 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7773 ** not, there are still machines out there that use EBCDIC.)
7774 */
7775 #if 'A' == '\301'
7776 # define SQLITE_EBCDIC 1
7777 #else
7778 # define SQLITE_ASCII 1
7779 #endif
7780
7781 /*
7782 ** Integers of known sizes.  These typedefs might change for architectures
7783 ** where the sizes very.  Preprocessor macros are available so that the
7784 ** types can be conveniently redefined at compile-type.  Like this:
7785 **
7786 **         cc '-DUINTPTR_TYPE=long long int' ...
7787 */
7788 #ifndef UINT32_TYPE
7789 # ifdef HAVE_UINT32_T
7790 #  define UINT32_TYPE uint32_t
7791 # else
7792 #  define UINT32_TYPE unsigned int
7793 # endif
7794 #endif
7795 #ifndef UINT16_TYPE
7796 # ifdef HAVE_UINT16_T
7797 #  define UINT16_TYPE uint16_t
7798 # else
7799 #  define UINT16_TYPE unsigned short int
7800 # endif
7801 #endif
7802 #ifndef INT16_TYPE
7803 # ifdef HAVE_INT16_T
7804 #  define INT16_TYPE int16_t
7805 # else
7806 #  define INT16_TYPE short int
7807 # endif
7808 #endif
7809 #ifndef UINT8_TYPE
7810 # ifdef HAVE_UINT8_T
7811 #  define UINT8_TYPE uint8_t
7812 # else
7813 #  define UINT8_TYPE unsigned char
7814 # endif
7815 #endif
7816 #ifndef INT8_TYPE
7817 # ifdef HAVE_INT8_T
7818 #  define INT8_TYPE int8_t
7819 # else
7820 #  define INT8_TYPE signed char
7821 # endif
7822 #endif
7823 #ifndef LONGDOUBLE_TYPE
7824 # define LONGDOUBLE_TYPE long double
7825 #endif
7826 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7827 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7828 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7829 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7830 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7831 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7832 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7833
7834 /*
7835 ** Macros to determine whether the machine is big or little endian,
7836 ** evaluated at runtime.
7837 */
7838 #ifdef SQLITE_AMALGAMATION
7839 SQLITE_PRIVATE const int sqlite3one = 1;
7840 #else
7841 SQLITE_PRIVATE const int sqlite3one;
7842 #endif
7843 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7844                              || defined(__x86_64) || defined(__x86_64__)
7845 # define SQLITE_BIGENDIAN    0
7846 # define SQLITE_LITTLEENDIAN 1
7847 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7848 #else
7849 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7850 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7851 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7852 #endif
7853
7854 /*
7855 ** Constants for the largest and smallest possible 64-bit signed integers.
7856 ** These macros are designed to work correctly on both 32-bit and 64-bit
7857 ** compilers.
7858 */
7859 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7860 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7861
7862 /*
7863 ** An instance of the following structure is used to store the busy-handler
7864 ** callback for a given sqlite handle. 
7865 **
7866 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7867 ** callback for the database handle. Each pager opened via the sqlite
7868 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7869 ** callback is currently invoked only from within pager.c.
7870 */
7871 typedef struct BusyHandler BusyHandler;
7872 struct BusyHandler {
7873   int (*xFunc)(void *,int);  /* The busy callback */
7874   void *pArg;                /* First arg to busy callback */
7875   int nBusy;                 /* Incremented with each busy call */
7876 };
7877
7878 /*
7879 ** Name of the master database table.  The master database table
7880 ** is a special table that holds the names and attributes of all
7881 ** user tables and indices.
7882 */
7883 #define MASTER_NAME       "sqlite_master"
7884 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7885
7886 /*
7887 ** The root-page of the master database table.
7888 */
7889 #define MASTER_ROOT       1
7890
7891 /*
7892 ** The name of the schema table.
7893 */
7894 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7895
7896 /*
7897 ** A convenience macro that returns the number of elements in
7898 ** an array.
7899 */
7900 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7901
7902 /*
7903 ** The following value as a destructor means to use sqlite3DbFree().
7904 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7905 */
7906 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7907
7908 /*
7909 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7910 ** not support Writable Static Data (WSD) such as global and static variables.
7911 ** All variables must either be on the stack or dynamically allocated from
7912 ** the heap.  When WSD is unsupported, the variable declarations scattered
7913 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7914 ** macro is used for this purpose.  And instead of referencing the variable
7915 ** directly, we use its constant as a key to lookup the run-time allocated
7916 ** buffer that holds real variable.  The constant is also the initializer
7917 ** for the run-time allocated buffer.
7918 **
7919 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7920 ** macros become no-ops and have zero performance impact.
7921 */
7922 #ifdef SQLITE_OMIT_WSD
7923   #define SQLITE_WSD const
7924   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7925   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7926 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7927 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7928 #else
7929   #define SQLITE_WSD 
7930   #define GLOBAL(t,v) v
7931   #define sqlite3GlobalConfig sqlite3Config
7932 #endif
7933
7934 /*
7935 ** The following macros are used to suppress compiler warnings and to
7936 ** make it clear to human readers when a function parameter is deliberately 
7937 ** left unused within the body of a function. This usually happens when
7938 ** a function is called via a function pointer. For example the 
7939 ** implementation of an SQL aggregate step callback may not use the
7940 ** parameter indicating the number of arguments passed to the aggregate,
7941 ** if it knows that this is enforced elsewhere.
7942 **
7943 ** When a function parameter is not used at all within the body of a function,
7944 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7945 ** However, these macros may also be used to suppress warnings related to
7946 ** parameters that may or may not be used depending on compilation options.
7947 ** For example those parameters only used in assert() statements. In these
7948 ** cases the parameters are named as per the usual conventions.
7949 */
7950 #define UNUSED_PARAMETER(x) (void)(x)
7951 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7952
7953 /*
7954 ** Forward references to structures
7955 */
7956 typedef struct AggInfo AggInfo;
7957 typedef struct AuthContext AuthContext;
7958 typedef struct Bitvec Bitvec;
7959 typedef struct RowSet RowSet;
7960 typedef struct CollSeq CollSeq;
7961 typedef struct Column Column;
7962 typedef struct Db Db;
7963 typedef struct Schema Schema;
7964 typedef struct Expr Expr;
7965 typedef struct ExprList ExprList;
7966 typedef struct FKey FKey;
7967 typedef struct FuncDef FuncDef;
7968 typedef struct FuncDefHash FuncDefHash;
7969 typedef struct IdList IdList;
7970 typedef struct Index Index;
7971 typedef struct KeyClass KeyClass;
7972 typedef struct KeyInfo KeyInfo;
7973 typedef struct Lookaside Lookaside;
7974 typedef struct LookasideSlot LookasideSlot;
7975 typedef struct Module Module;
7976 typedef struct NameContext NameContext;
7977 typedef struct Parse Parse;
7978 typedef struct Savepoint Savepoint;
7979 typedef struct Select Select;
7980 typedef struct SrcList SrcList;
7981 typedef struct StrAccum StrAccum;
7982 typedef struct Table Table;
7983 typedef struct TableLock TableLock;
7984 typedef struct Token Token;
7985 typedef struct TriggerStack TriggerStack;
7986 typedef struct TriggerStep TriggerStep;
7987 typedef struct Trigger Trigger;
7988 typedef struct UnpackedRecord UnpackedRecord;
7989 typedef struct Walker Walker;
7990 typedef struct WherePlan WherePlan;
7991 typedef struct WhereInfo WhereInfo;
7992 typedef struct WhereLevel WhereLevel;
7993
7994 /*
7995 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7996 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7997 ** pointer types (i.e. FuncDef) defined above.
7998 */
7999 /************** Include btree.h in the middle of sqliteInt.h *****************/
8000 /************** Begin file btree.h *******************************************/
8001 /*
8002 ** 2001 September 15
8003 **
8004 ** The author disclaims copyright to this source code.  In place of
8005 ** a legal notice, here is a blessing:
8006 **
8007 **    May you do good and not evil.
8008 **    May you find forgiveness for yourself and forgive others.
8009 **    May you share freely, never taking more than you give.
8010 **
8011 *************************************************************************
8012 ** This header file defines the interface that the sqlite B-Tree file
8013 ** subsystem.  See comments in the source code for a detailed description
8014 ** of what each interface routine does.
8015 **
8016 ** @(#) $Id: btree.h,v 1.108 2009/02/03 16:51:25 danielk1977 Exp $
8017 */
8018 #ifndef _BTREE_H_
8019 #define _BTREE_H_
8020
8021 /* TODO: This definition is just included so other modules compile. It
8022 ** needs to be revisited.
8023 */
8024 #define SQLITE_N_BTREE_META 10
8025
8026 /*
8027 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8028 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8029 */
8030 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8031   #define SQLITE_DEFAULT_AUTOVACUUM 0
8032 #endif
8033
8034 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8035 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8036 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8037
8038 /*
8039 ** Forward declarations of structure
8040 */
8041 typedef struct Btree Btree;
8042 typedef struct BtCursor BtCursor;
8043 typedef struct BtShared BtShared;
8044 typedef struct BtreeMutexArray BtreeMutexArray;
8045
8046 /*
8047 ** This structure records all of the Btrees that need to hold
8048 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
8049 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
8050 ** we can always lock and unlock them all quickly.
8051 */
8052 struct BtreeMutexArray {
8053   int nMutex;
8054   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
8055 };
8056
8057
8058 SQLITE_PRIVATE int sqlite3BtreeOpen(
8059   const char *zFilename,   /* Name of database file to open */
8060   sqlite3 *db,             /* Associated database connection */
8061   Btree **,                /* Return open Btree* here */
8062   int flags,               /* Flags */
8063   int vfsFlags             /* Flags passed through to VFS open */
8064 );
8065
8066 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8067 ** following values.
8068 **
8069 ** NOTE:  These values must match the corresponding PAGER_ values in
8070 ** pager.h.
8071 */
8072 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
8073 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
8074 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
8075 #define BTREE_READONLY      8  /* Open the database in read-only mode */
8076 #define BTREE_READWRITE    16  /* Open for both reading and writing */
8077 #define BTREE_CREATE       32  /* Create the database if it does not exist */
8078
8079 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8080 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8081 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
8082 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8083 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
8084 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8085 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8086 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8087 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8088 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8089 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8090 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8091 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
8092 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8093 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
8094 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
8095 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
8096 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
8097 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8098 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8099 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
8100 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8101 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8102 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8103 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
8104 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);
8105 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8106
8107 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8108 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8109 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8110
8111 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8112
8113 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8114 ** of the following flags:
8115 */
8116 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8117 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
8118 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
8119
8120 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8121 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8122 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
8123 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8124 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8125
8126 SQLITE_PRIVATE int sqlite3BtreeCursor(
8127   Btree*,                              /* BTree containing table to open */
8128   int iTable,                          /* Index of root page */
8129   int wrFlag,                          /* 1 for writing.  0 for read-only */
8130   struct KeyInfo*,                     /* First argument to compare function */
8131   BtCursor *pCursor                    /* Space to write cursor structure */
8132 );
8133 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8134
8135 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8136 SQLITE_PRIVATE int sqlite3BtreeMoveto(
8137   BtCursor*,
8138   const void *pKey,
8139   i64 nKey,
8140   int bias,
8141   int *pRes
8142 );
8143 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8144   BtCursor*,
8145   UnpackedRecord *pUnKey,
8146   i64 intKey,
8147   int bias,
8148   int *pRes
8149 );
8150 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8151 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8152 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8153                                   const void *pData, int nData,
8154                                   int nZero, int bias);
8155 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8156 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8157 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8158 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8159 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
8160 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8161 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8162 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8163 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor*);
8164 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8165 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8166 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8167 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8168
8169 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8170 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8171
8172 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8173 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8174 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8175
8176 #ifdef SQLITE_TEST
8177 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8178 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8179 #endif
8180
8181 /*
8182 ** If we are not using shared cache, then there is no need to
8183 ** use mutexes to access the BtShared structures.  So make the
8184 ** Enter and Leave procedures no-ops.
8185 */
8186 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8187 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8188 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8189 #ifndef NDEBUG
8190   /* This routine is used inside assert() statements only. */
8191 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8192 #endif
8193 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8194 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8195 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8196 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8197 #ifndef NDEBUG
8198   /* This routine is used inside assert() statements only. */
8199 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8200 #endif
8201 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
8202 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
8203 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
8204 #else
8205 # define sqlite3BtreeEnter(X)
8206 # define sqlite3BtreeLeave(X)
8207 #ifndef NDEBUG
8208   /* This routine is used inside assert() statements only. */
8209 # define sqlite3BtreeHoldsMutex(X) 1
8210 #endif
8211 # define sqlite3BtreeEnterCursor(X)
8212 # define sqlite3BtreeLeaveCursor(X)
8213 # define sqlite3BtreeEnterAll(X)
8214 # define sqlite3BtreeLeaveAll(X)
8215 #ifndef NDEBUG
8216   /* This routine is used inside assert() statements only. */
8217 # define sqlite3BtreeHoldsAllMutexes(X) 1
8218 #endif
8219 # define sqlite3BtreeMutexArrayEnter(X)
8220 # define sqlite3BtreeMutexArrayLeave(X)
8221 # define sqlite3BtreeMutexArrayInsert(X,Y)
8222 #endif
8223
8224
8225 #endif /* _BTREE_H_ */
8226
8227 /************** End of btree.h ***********************************************/
8228 /************** Continuing where we left off in sqliteInt.h ******************/
8229 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8230 /************** Begin file vdbe.h ********************************************/
8231 /*
8232 ** 2001 September 15
8233 **
8234 ** The author disclaims copyright to this source code.  In place of
8235 ** a legal notice, here is a blessing:
8236 **
8237 **    May you do good and not evil.
8238 **    May you find forgiveness for yourself and forgive others.
8239 **    May you share freely, never taking more than you give.
8240 **
8241 *************************************************************************
8242 ** Header file for the Virtual DataBase Engine (VDBE)
8243 **
8244 ** This header defines the interface to the virtual database engine
8245 ** or VDBE.  The VDBE implements an abstract machine that runs a
8246 ** simple program to access and modify the underlying database.
8247 **
8248 ** $Id: vdbe.h,v 1.139 2008/10/31 10:53:23 danielk1977 Exp $
8249 */
8250 #ifndef _SQLITE_VDBE_H_
8251 #define _SQLITE_VDBE_H_
8252
8253 /*
8254 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8255 ** in the source file sqliteVdbe.c are allowed to see the insides
8256 ** of this structure.
8257 */
8258 typedef struct Vdbe Vdbe;
8259
8260 /*
8261 ** The names of the following types declared in vdbeInt.h are required
8262 ** for the VdbeOp definition.
8263 */
8264 typedef struct VdbeFunc VdbeFunc;
8265 typedef struct Mem Mem;
8266
8267 /*
8268 ** A single instruction of the virtual machine has an opcode
8269 ** and as many as three operands.  The instruction is recorded
8270 ** as an instance of the following structure:
8271 */
8272 struct VdbeOp {
8273   u8 opcode;          /* What operation to perform */
8274   signed char p4type; /* One of the P4_xxx constants for p4 */
8275   u8 opflags;         /* Not currently used */
8276   u8 p5;              /* Fifth parameter is an unsigned character */
8277   int p1;             /* First operand */
8278   int p2;             /* Second parameter (often the jump destination) */
8279   int p3;             /* The third parameter */
8280   union {             /* forth parameter */
8281     int i;                 /* Integer value if p4type==P4_INT32 */
8282     void *p;               /* Generic pointer */
8283     char *z;               /* Pointer to data for string (char array) types */
8284     i64 *pI64;             /* Used when p4type is P4_INT64 */
8285     double *pReal;         /* Used when p4type is P4_REAL */
8286     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8287     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8288     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8289     Mem *pMem;             /* Used when p4type is P4_MEM */
8290     sqlite3_vtab *pVtab;   /* Used when p4type is P4_VTAB */
8291     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8292     int *ai;               /* Used when p4type is P4_INTARRAY */
8293   } p4;
8294 #ifdef SQLITE_DEBUG
8295   char *zComment;          /* Comment to improve readability */
8296 #endif
8297 #ifdef VDBE_PROFILE
8298   int cnt;                 /* Number of times this instruction was executed */
8299   u64 cycles;              /* Total time spent executing this instruction */
8300 #endif
8301 };
8302 typedef struct VdbeOp VdbeOp;
8303
8304 /*
8305 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8306 ** it takes up less space.
8307 */
8308 struct VdbeOpList {
8309   u8 opcode;          /* What operation to perform */
8310   signed char p1;     /* First operand */
8311   signed char p2;     /* Second parameter (often the jump destination) */
8312   signed char p3;     /* Third parameter */
8313 };
8314 typedef struct VdbeOpList VdbeOpList;
8315
8316 /*
8317 ** Allowed values of VdbeOp.p3type
8318 */
8319 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8320 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8321 #define P4_STATIC   (-2)  /* Pointer to a static string */
8322 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8323 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8324 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8325 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8326 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8327 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
8328 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8329 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8330 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8331 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8332 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8333 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8334
8335 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8336 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8337 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8338 ** gets freed when the Vdbe is finalized so it still should be obtained
8339 ** from a single sqliteMalloc().  But no copy is made and the calling
8340 ** function should *not* try to free the KeyInfo.
8341 */
8342 #define P4_KEYINFO_HANDOFF (-16)
8343 #define P4_KEYINFO_STATIC  (-17)
8344
8345 /*
8346 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8347 ** number of columns of data returned by the statement.
8348 */
8349 #define COLNAME_NAME     0
8350 #define COLNAME_DECLTYPE 1
8351 #define COLNAME_DATABASE 2
8352 #define COLNAME_TABLE    3
8353 #define COLNAME_COLUMN   4
8354 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8355 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8356 #else
8357 # ifdef SQLITE_OMIT_DECLTYPE
8358 #   define COLNAME_N      1      /* Store only the name */
8359 # else
8360 #   define COLNAME_N      2      /* Store the name and decltype */
8361 # endif
8362 #endif
8363
8364 /*
8365 ** The following macro converts a relative address in the p2 field
8366 ** of a VdbeOp structure into a negative number so that 
8367 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8368 ** the macro again restores the address.
8369 */
8370 #define ADDR(X)  (-1-(X))
8371
8372 /*
8373 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8374 ** header file that defines a number for each opcode used by the VDBE.
8375 */
8376 /************** Include opcodes.h in the middle of vdbe.h ********************/
8377 /************** Begin file opcodes.h *****************************************/
8378 /* Automatically generated.  Do not edit */
8379 /* See the mkopcodeh.awk script for details */
8380 #define OP_VNext                                1
8381 #define OP_Affinity                             2
8382 #define OP_Column                               3
8383 #define OP_SetCookie                            4
8384 #define OP_Seek                                 5
8385 #define OP_Real                               130   /* same as TK_FLOAT    */
8386 #define OP_Sequence                             6
8387 #define OP_Savepoint                            7
8388 #define OP_Ge                                  77   /* same as TK_GE       */
8389 #define OP_RowKey                               8
8390 #define OP_SCopy                                9
8391 #define OP_Eq                                  73   /* same as TK_EQ       */
8392 #define OP_OpenWrite                           10
8393 #define OP_NotNull                             71   /* same as TK_NOTNULL  */
8394 #define OP_If                                  11
8395 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8396 #define OP_String8                             93   /* same as TK_STRING   */
8397 #define OP_VRowid                              12
8398 #define OP_CollSeq                             13
8399 #define OP_OpenRead                            14
8400 #define OP_Expire                              15
8401 #define OP_AutoCommit                          16
8402 #define OP_Gt                                  74   /* same as TK_GT       */
8403 #define OP_Pagecount                           17
8404 #define OP_IntegrityCk                         18
8405 #define OP_Sort                                20
8406 #define OP_Copy                                21
8407 #define OP_Trace                               22
8408 #define OP_Function                            23
8409 #define OP_IfNeg                               24
8410 #define OP_And                                 66   /* same as TK_AND      */
8411 #define OP_Subtract                            84   /* same as TK_MINUS    */
8412 #define OP_Noop                                25
8413 #define OP_Return                              26
8414 #define OP_Remainder                           87   /* same as TK_REM      */
8415 #define OP_NewRowid                            27
8416 #define OP_Multiply                            85   /* same as TK_STAR     */
8417 #define OP_Variable                            28
8418 #define OP_String                              29
8419 #define OP_RealAffinity                        30
8420 #define OP_VRename                             31
8421 #define OP_ParseSchema                         32
8422 #define OP_VOpen                               33
8423 #define OP_Close                               34
8424 #define OP_CreateIndex                         35
8425 #define OP_IsUnique                            36
8426 #define OP_NotFound                            37
8427 #define OP_Int64                               38
8428 #define OP_MustBeInt                           39
8429 #define OP_Halt                                40
8430 #define OP_Rowid                               41
8431 #define OP_IdxLT                               42
8432 #define OP_AddImm                              43
8433 #define OP_Statement                           44
8434 #define OP_RowData                             45
8435 #define OP_MemMax                              46
8436 #define OP_Or                                  65   /* same as TK_OR       */
8437 #define OP_NotExists                           47
8438 #define OP_Gosub                               48
8439 #define OP_Divide                              86   /* same as TK_SLASH    */
8440 #define OP_Integer                             49
8441 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8442 #define OP_Prev                                50
8443 #define OP_RowSetRead                          51
8444 #define OP_Concat                              88   /* same as TK_CONCAT   */
8445 #define OP_RowSetAdd                           52
8446 #define OP_BitAnd                              79   /* same as TK_BITAND   */
8447 #define OP_VColumn                             53
8448 #define OP_CreateTable                         54
8449 #define OP_Last                                55
8450 #define OP_SeekLe                              56
8451 #define OP_IsNull                              70   /* same as TK_ISNULL   */
8452 #define OP_IncrVacuum                          57
8453 #define OP_IdxRowid                            58
8454 #define OP_ShiftRight                          82   /* same as TK_RSHIFT   */
8455 #define OP_ResetCount                          59
8456 #define OP_ContextPush                         60
8457 #define OP_Yield                               61
8458 #define OP_DropTrigger                         62
8459 #define OP_DropIndex                           63
8460 #define OP_IdxGE                               64
8461 #define OP_IdxDelete                           67
8462 #define OP_Vacuum                              68
8463 #define OP_IfNot                               69
8464 #define OP_DropTable                           78
8465 #define OP_SeekLt                              89
8466 #define OP_MakeRecord                          90
8467 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8468 #define OP_ResultRow                           91
8469 #define OP_Delete                              94
8470 #define OP_AggFinal                            95
8471 #define OP_Compare                             96
8472 #define OP_ShiftLeft                           81   /* same as TK_LSHIFT   */
8473 #define OP_Goto                                97
8474 #define OP_TableLock                           98
8475 #define OP_Clear                               99
8476 #define OP_Le                                  75   /* same as TK_LE       */
8477 #define OP_VerifyCookie                       100
8478 #define OP_AggStep                            101
8479 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8480 #define OP_Not                                 19   /* same as TK_NOT      */
8481 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8482 #define OP_SetNumColumns                      102
8483 #define OP_Transaction                        103
8484 #define OP_VFilter                            104
8485 #define OP_Ne                                  72   /* same as TK_NE       */
8486 #define OP_VDestroy                           105
8487 #define OP_ContextPop                         106
8488 #define OP_BitOr                               80   /* same as TK_BITOR    */
8489 #define OP_Next                               107
8490 #define OP_IdxInsert                          108
8491 #define OP_Lt                                  76   /* same as TK_LT       */
8492 #define OP_SeekGe                             109
8493 #define OP_Insert                             110
8494 #define OP_Destroy                            111
8495 #define OP_ReadCookie                         112
8496 #define OP_LoadAnalysis                       113
8497 #define OP_Explain                            114
8498 #define OP_OpenPseudo                         115
8499 #define OP_OpenEphemeral                      116
8500 #define OP_Null                               117
8501 #define OP_Move                               118
8502 #define OP_Blob                               119
8503 #define OP_Add                                 83   /* same as TK_PLUS     */
8504 #define OP_Rewind                             120
8505 #define OP_SeekGt                             121
8506 #define OP_VBegin                             122
8507 #define OP_VUpdate                            123
8508 #define OP_IfZero                             124
8509 #define OP_BitNot                              92   /* same as TK_BITNOT   */
8510 #define OP_VCreate                            125
8511 #define OP_Found                              126
8512 #define OP_IfPos                              127
8513 #define OP_NullRow                            128
8514 #define OP_Jump                               129
8515 #define OP_Permutation                        131
8516
8517 /* The following opcode values are never used */
8518 #define OP_NotUsed_132                        132
8519 #define OP_NotUsed_133                        133
8520 #define OP_NotUsed_134                        134
8521 #define OP_NotUsed_135                        135
8522 #define OP_NotUsed_136                        136
8523 #define OP_NotUsed_137                        137
8524 #define OP_NotUsed_138                        138
8525 #define OP_NotUsed_139                        139
8526 #define OP_NotUsed_140                        140
8527
8528
8529 /* Properties such as "out2" or "jump" that are specified in
8530 ** comments following the "case" for each opcode in the vdbe.c
8531 ** are encoded into bitvectors as follows:
8532 */
8533 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8534 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8535 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8536 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8537 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8538 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
8539 #define OPFLG_INITIALIZER {\
8540 /*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
8541 /*   8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
8542 /*  16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
8543 /*  24 */ 0x05, 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00,\
8544 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
8545 /*  40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
8546 /*  48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
8547 /*  56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00,\
8548 /*  64 */ 0x11, 0x2c, 0x2c, 0x00, 0x00, 0x05, 0x05, 0x05,\
8549 /*  72 */ 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00, 0x2c,\
8550 /*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
8551 /*  88 */ 0x2c, 0x11, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00,\
8552 /*  96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8553 /* 104 */ 0x01, 0x00, 0x00, 0x01, 0x08, 0x11, 0x00, 0x02,\
8554 /* 112 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02,\
8555 /* 120 */ 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x05,\
8556 /* 128 */ 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8557 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8558 /* 144 */ 0x04, 0x04,}
8559
8560 /************** End of opcodes.h *********************************************/
8561 /************** Continuing where we left off in vdbe.h ***********************/
8562
8563 /*
8564 ** Prototypes for the VDBE interface.  See comments on the implementation
8565 ** for a description of what each of these routines does.
8566 */
8567 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8568 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8569 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8570 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8571 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8572 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8573 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8574 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8575 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8576 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8577 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8578 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8579 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8580 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8581 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8582 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8583 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8584 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8585 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
8586 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8587 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8588 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8589 #ifdef SQLITE_DEBUG
8590 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8591 #endif
8592 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8593 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8594 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8595 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8596 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8597 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8598 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
8599 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8600
8601 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8602 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int);
8603 #endif
8604 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,
8605                                         UnpackedRecord*,int);
8606 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8607 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8608
8609
8610 #ifndef NDEBUG
8611 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8612 # define VdbeComment(X)  sqlite3VdbeComment X
8613 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8614 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8615 #else
8616 # define VdbeComment(X)
8617 # define VdbeNoopComment(X)
8618 #endif
8619
8620 #endif
8621
8622 /************** End of vdbe.h ************************************************/
8623 /************** Continuing where we left off in sqliteInt.h ******************/
8624 /************** Include pager.h in the middle of sqliteInt.h *****************/
8625 /************** Begin file pager.h *******************************************/
8626 /*
8627 ** 2001 September 15
8628 **
8629 ** The author disclaims copyright to this source code.  In place of
8630 ** a legal notice, here is a blessing:
8631 **
8632 **    May you do good and not evil.
8633 **    May you find forgiveness for yourself and forgive others.
8634 **    May you share freely, never taking more than you give.
8635 **
8636 *************************************************************************
8637 ** This header file defines the interface that the sqlite page cache
8638 ** subsystem.  The page cache subsystem reads and writes a file a page
8639 ** at a time and provides a journal for rollback.
8640 **
8641 ** @(#) $Id: pager.h,v 1.100 2009/02/03 16:51:25 danielk1977 Exp $
8642 */
8643
8644 #ifndef _PAGER_H_
8645 #define _PAGER_H_
8646
8647 /*
8648 ** Default maximum size for persistent journal files. A negative 
8649 ** value means no limit. This value may be overridden using the 
8650 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8651 */
8652 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8653   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8654 #endif
8655
8656 /*
8657 ** The type used to represent a page number.  The first page in a file
8658 ** is called page 1.  0 is used to represent "not a page".
8659 */
8660 typedef u32 Pgno;
8661
8662 /*
8663 ** Each open file is managed by a separate instance of the "Pager" structure.
8664 */
8665 typedef struct Pager Pager;
8666
8667 /*
8668 ** Handle type for pages.
8669 */
8670 typedef struct PgHdr DbPage;
8671
8672 /*
8673 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8674 ** reserved for working around a windows/posix incompatibility). It is
8675 ** used in the journal to signify that the remainder of the journal file 
8676 ** is devoted to storing a master journal name - there are no more pages to
8677 ** roll back. See comments for function writeMasterJournal() in pager.c 
8678 ** for details.
8679 */
8680 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8681
8682 /*
8683 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8684 **
8685 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8686 */
8687 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8688 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8689
8690 /*
8691 ** Valid values for the second argument to sqlite3PagerLockingMode().
8692 */
8693 #define PAGER_LOCKINGMODE_QUERY      -1
8694 #define PAGER_LOCKINGMODE_NORMAL      0
8695 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8696
8697 /*
8698 ** Valid values for the second argument to sqlite3PagerJournalMode().
8699 */
8700 #define PAGER_JOURNALMODE_QUERY      -1
8701 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8702 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8703 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8704 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8705 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8706
8707 /*
8708 ** The remainder of this file contains the declarations of the functions
8709 ** that make up the Pager sub-system API. See source code comments for 
8710 ** a detailed description of each routine.
8711 */
8712
8713 /* Open and close a Pager connection. */ 
8714 SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
8715 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8716 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8717
8718 /* Functions used to configure a Pager object. */
8719 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8720 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
8721 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
8722 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8723 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8724 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
8725 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8726 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
8727 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8728 sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8729
8730 /* Functions used to obtain and release page references. */ 
8731 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8732 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8733 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8734 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8735 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8736
8737 /* Operations on page references. */
8738 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8739 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8740 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8741 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8742 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8743 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8744
8745 /* Functions used to manage pager transactions and savepoints. */
8746 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
8747 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag);
8748 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8749 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8750 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8751 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8752 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8753 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8754
8755 /* Functions used to query pager state and configuration. */
8756 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8757 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8758 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8759 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8760 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8761 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8762 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8763 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8764 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8765
8766 /* Functions used to truncate the database file. */
8767 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8768
8769 /* Used by encryption extensions. */
8770 #ifdef SQLITE_HAS_CODEC
8771 SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
8772 #endif
8773
8774 /* Functions to support testing and debugging. */
8775 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8776 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8777 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8778 #endif
8779 #ifdef SQLITE_TEST
8780 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8781 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8782   void disable_simulated_io_errors(void);
8783   void enable_simulated_io_errors(void);
8784 #else
8785 # define disable_simulated_io_errors()
8786 # define enable_simulated_io_errors()
8787 #endif
8788
8789 #endif /* _PAGER_H_ */
8790
8791 /************** End of pager.h ***********************************************/
8792 /************** Continuing where we left off in sqliteInt.h ******************/
8793 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8794 /************** Begin file pcache.h ******************************************/
8795 /*
8796 ** 2008 August 05
8797 **
8798 ** The author disclaims copyright to this source code.  In place of
8799 ** a legal notice, here is a blessing:
8800 **
8801 **    May you do good and not evil.
8802 **    May you find forgiveness for yourself and forgive others.
8803 **    May you share freely, never taking more than you give.
8804 **
8805 *************************************************************************
8806 ** This header file defines the interface that the sqlite page cache
8807 ** subsystem. 
8808 **
8809 ** @(#) $Id: pcache.h,v 1.19 2009/01/20 17:06:27 danielk1977 Exp $
8810 */
8811
8812 #ifndef _PCACHE_H_
8813
8814 typedef struct PgHdr PgHdr;
8815 typedef struct PCache PCache;
8816
8817 /*
8818 ** Every page in the cache is controlled by an instance of the following
8819 ** structure.
8820 */
8821 struct PgHdr {
8822   void *pData;                   /* Content of this page */
8823   void *pExtra;                  /* Extra content */
8824   PgHdr *pDirty;                 /* Transient list of dirty pages */
8825   Pgno pgno;                     /* Page number for this page */
8826   Pager *pPager;                 /* The pager this page is part of */
8827 #ifdef SQLITE_CHECK_PAGES
8828   u32 pageHash;                  /* Hash of page content */
8829 #endif
8830   u16 flags;                     /* PGHDR flags defined below */
8831
8832   /**********************************************************************
8833   ** Elements above are public.  All that follows is private to pcache.c
8834   ** and should not be accessed by other modules.
8835   */
8836   i16 nRef;                      /* Number of users of this page */
8837   PCache *pCache;                /* Cache that owns this page */
8838
8839   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8840   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8841 };
8842
8843 /* Bit values for PgHdr.flags */
8844 #define PGHDR_DIRTY             0x002  /* Page has changed */
8845 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8846                                        ** writing this page to the database */
8847 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8848 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8849 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8850
8851 /* Initialize and shutdown the page cache subsystem */
8852 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8853 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8854
8855 /* Page cache buffer management:
8856 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8857 */
8858 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8859
8860 /* Create a new pager cache.
8861 ** Under memory stress, invoke xStress to try to make pages clean.
8862 ** Only clean and unpinned pages can be reclaimed.
8863 */
8864 SQLITE_PRIVATE void sqlite3PcacheOpen(
8865   int szPage,                    /* Size of every page */
8866   int szExtra,                   /* Extra space associated with each page */
8867   int bPurgeable,                /* True if pages are on backing store */
8868   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8869   void *pStress,                 /* Argument to xStress */
8870   PCache *pToInit                /* Preallocated space for the PCache */
8871 );
8872
8873 /* Modify the page-size after the cache has been created. */
8874 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8875
8876 /* Return the size in bytes of a PCache object.  Used to preallocate
8877 ** storage space.
8878 */
8879 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8880
8881 /* One release per successful fetch.  Page is pinned until released.
8882 ** Reference counted. 
8883 */
8884 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8885 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8886
8887 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8888 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8889 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8890 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8891
8892 /* Change a page number.  Used by incr-vacuum. */
8893 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8894
8895 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8896 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8897
8898 /* Get a list of all dirty pages in the cache, sorted by page number */
8899 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8900
8901 /* Reset and close the cache object */
8902 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8903
8904 /* Clear flags from pages of the page cache */
8905 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8906
8907 /* Discard the contents of the cache */
8908 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8909
8910 /* Return the total number of outstanding page references */
8911 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8912
8913 /* Increment the reference count of an existing page */
8914 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8915
8916 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8917
8918 /* Return the total number of pages stored in the cache */
8919 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8920
8921 #ifdef SQLITE_CHECK_PAGES
8922 /* Iterate through all dirty pages currently stored in the cache. This
8923 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8924 ** library is built.
8925 */
8926 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8927 #endif
8928
8929 /* Set and get the suggested cache-size for the specified pager-cache.
8930 **
8931 ** If no global maximum is configured, then the system attempts to limit
8932 ** the total number of pages cached by purgeable pager-caches to the sum
8933 ** of the suggested cache-sizes.
8934 */
8935 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8936 #ifdef SQLITE_TEST
8937 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8938 #endif
8939
8940 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8941 /* Try to return memory used by the pcache module to the main memory heap */
8942 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8943 #endif
8944
8945 #ifdef SQLITE_TEST
8946 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8947 #endif
8948
8949 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8950
8951 #endif /* _PCACHE_H_ */
8952
8953 /************** End of pcache.h **********************************************/
8954 /************** Continuing where we left off in sqliteInt.h ******************/
8955
8956 /************** Include os.h in the middle of sqliteInt.h ********************/
8957 /************** Begin file os.h **********************************************/
8958 /*
8959 ** 2001 September 16
8960 **
8961 ** The author disclaims copyright to this source code.  In place of
8962 ** a legal notice, here is a blessing:
8963 **
8964 **    May you do good and not evil.
8965 **    May you find forgiveness for yourself and forgive others.
8966 **    May you share freely, never taking more than you give.
8967 **
8968 ******************************************************************************
8969 **
8970 ** This header file (together with is companion C source-code file
8971 ** "os.c") attempt to abstract the underlying operating system so that
8972 ** the SQLite library will work on both POSIX and windows systems.
8973 **
8974 ** This header file is #include-ed by sqliteInt.h and thus ends up
8975 ** being included by every source file.
8976 **
8977 ** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $
8978 */
8979 #ifndef _SQLITE_OS_H_
8980 #define _SQLITE_OS_H_
8981
8982 /*
8983 ** Figure out if we are dealing with Unix, Windows, or some other
8984 ** operating system.  After the following block of preprocess macros,
8985 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8986 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8987 ** three will be 0.
8988 */
8989 #if defined(SQLITE_OS_OTHER)
8990 # if SQLITE_OS_OTHER==1
8991 #   undef SQLITE_OS_UNIX
8992 #   define SQLITE_OS_UNIX 0
8993 #   undef SQLITE_OS_WIN
8994 #   define SQLITE_OS_WIN 0
8995 #   undef SQLITE_OS_OS2
8996 #   define SQLITE_OS_OS2 0
8997 # else
8998 #   undef SQLITE_OS_OTHER
8999 # endif
9000 #endif
9001 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9002 # define SQLITE_OS_OTHER 0
9003 # ifndef SQLITE_OS_WIN
9004 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9005 #     define SQLITE_OS_WIN 1
9006 #     define SQLITE_OS_UNIX 0
9007 #     define SQLITE_OS_OS2 0
9008 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9009 #     define SQLITE_OS_WIN 0
9010 #     define SQLITE_OS_UNIX 0
9011 #     define SQLITE_OS_OS2 1
9012 #   else
9013 #     define SQLITE_OS_WIN 0
9014 #     define SQLITE_OS_UNIX 1
9015 #     define SQLITE_OS_OS2 0
9016 #  endif
9017 # else
9018 #  define SQLITE_OS_UNIX 0
9019 #  define SQLITE_OS_OS2 0
9020 # endif
9021 #else
9022 # ifndef SQLITE_OS_WIN
9023 #  define SQLITE_OS_WIN 0
9024 # endif
9025 #endif
9026
9027 /*
9028 ** Determine if we are dealing with WindowsCE - which has a much
9029 ** reduced API.
9030 */
9031 #if defined(_WIN32_WCE)
9032 # define SQLITE_OS_WINCE 1
9033 #else
9034 # define SQLITE_OS_WINCE 0
9035 #endif
9036
9037
9038 /*
9039 ** Define the maximum size of a temporary filename
9040 */
9041 #if SQLITE_OS_WIN
9042 # include <windows.h>
9043 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
9044 #elif SQLITE_OS_OS2
9045 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9046 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
9047 # endif
9048 # define INCL_DOSDATETIME
9049 # define INCL_DOSFILEMGR
9050 # define INCL_DOSERRORS
9051 # define INCL_DOSMISC
9052 # define INCL_DOSPROCESS
9053 # define INCL_DOSMODULEMGR
9054 # define INCL_DOSSEMAPHORES
9055 # include <os2.h>
9056 # include <uconv.h>
9057 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9058 #else
9059 # define SQLITE_TEMPNAME_SIZE 200
9060 #endif
9061
9062 /* If the SET_FULLSYNC macro is not defined above, then make it
9063 ** a no-op
9064 */
9065 #ifndef SET_FULLSYNC
9066 # define SET_FULLSYNC(x,y)
9067 #endif
9068
9069 /*
9070 ** The default size of a disk sector
9071 */
9072 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9073 # define SQLITE_DEFAULT_SECTOR_SIZE 512
9074 #endif
9075
9076 /*
9077 ** Temporary files are named starting with this prefix followed by 16 random
9078 ** alphanumeric characters, and no file extension. They are stored in the
9079 ** OS's standard temporary file directory, and are deleted prior to exit.
9080 ** If sqlite is being embedded in another program, you may wish to change the
9081 ** prefix to reflect your program's name, so that if your program exits
9082 ** prematurely, old temporary files can be easily identified. This can be done
9083 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9084 **
9085 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9086 ** Mcafee started using SQLite in their anti-virus product and it
9087 ** started putting files with the "sqlite" name in the c:/temp folder.
9088 ** This annoyed many windows users.  Those users would then do a 
9089 ** Google search for "sqlite", find the telephone numbers of the
9090 ** developers and call to wake them up at night and complain.
9091 ** For this reason, the default name prefix is changed to be "sqlite" 
9092 ** spelled backwards.  So the temp files are still identified, but
9093 ** anybody smart enough to figure out the code is also likely smart
9094 ** enough to know that calling the developer will not help get rid
9095 ** of the file.
9096 */
9097 #ifndef SQLITE_TEMP_FILE_PREFIX
9098 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9099 #endif
9100
9101 /*
9102 ** The following values may be passed as the second argument to
9103 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9104 **
9105 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9106 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9107 **            any time. Other processes may hold and obtain new SHARED locks.
9108 ** PENDING:   A single process may hold a PENDING lock on a file at
9109 **            any one time. Existing SHARED locks may persist, but no new
9110 **            SHARED locks may be obtained by other processes.
9111 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9112 **
9113 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9114 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9115 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9116 ** sqlite3OsLock().
9117 */
9118 #define NO_LOCK         0
9119 #define SHARED_LOCK     1
9120 #define RESERVED_LOCK   2
9121 #define PENDING_LOCK    3
9122 #define EXCLUSIVE_LOCK  4
9123
9124 /*
9125 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9126 **
9127 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9128 ** those functions are not available.  So we use only LockFile() and
9129 ** UnlockFile().
9130 **
9131 ** LockFile() prevents not just writing but also reading by other processes.
9132 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9133 ** byte out of a specific range of bytes. The lock byte is obtained at 
9134 ** random so two separate readers can probably access the file at the 
9135 ** same time, unless they are unlucky and choose the same lock byte.
9136 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9137 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9138 ** a single byte of the file that is designated as the reserved lock byte.
9139 ** A PENDING_LOCK is obtained by locking a designated byte different from
9140 ** the RESERVED_LOCK byte.
9141 **
9142 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9143 ** which means we can use reader/writer locks.  When reader/writer locks
9144 ** are used, the lock is placed on the same range of bytes that is used
9145 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9146 ** will support two or more Win95 readers or two or more WinNT readers.
9147 ** But a single Win95 reader will lock out all WinNT readers and a single
9148 ** WinNT reader will lock out all other Win95 readers.
9149 **
9150 ** The following #defines specify the range of bytes used for locking.
9151 ** SHARED_SIZE is the number of bytes available in the pool from which
9152 ** a random byte is selected for a shared lock.  The pool of bytes for
9153 ** shared locks begins at SHARED_FIRST. 
9154 **
9155 ** The same locking strategy and
9156 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9157 ** clients on win95, winNT, and unix all talking to the same shared file
9158 ** and all locking correctly.  To do so would require that samba (or whatever
9159 ** tool is being used for file sharing) implements locks correctly between
9160 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9161 ** using the same locking range we are at least open to the possibility.
9162 **
9163 ** Locking in windows is manditory.  For this reason, we cannot store
9164 ** actual data in the bytes used for locking.  The pager never allocates
9165 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9166 ** that all locks will fit on a single page even at the minimum page size.
9167 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9168 ** is set high so that we don't have to allocate an unused page except
9169 ** for very large databases.  But one should test the page skipping logic 
9170 ** by setting PENDING_BYTE low and running the entire regression suite.
9171 **
9172 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9173 ** file format.  Depending on how it is changed, you might not notice
9174 ** the incompatibility right away, even running a full regression test.
9175 ** The default location of PENDING_BYTE is the first byte past the
9176 ** 1GB boundary.
9177 **
9178 */
9179 #define PENDING_BYTE      sqlite3PendingByte
9180 #define RESERVED_BYTE     (PENDING_BYTE+1)
9181 #define SHARED_FIRST      (PENDING_BYTE+2)
9182 #define SHARED_SIZE       510
9183
9184 /* 
9185 ** Functions for accessing sqlite3_file methods 
9186 */
9187 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9188 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9189 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9190 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9191 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9192 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9193 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9194 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9195 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9196 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9197 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9198 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9199 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9200
9201 /* 
9202 ** Functions for accessing sqlite3_vfs methods 
9203 */
9204 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9205 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9206 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9207 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9208 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9209 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9210 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9211 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9212 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9213 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9214 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9215 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9216 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
9217
9218 /*
9219 ** Convenience functions for opening and closing files using 
9220 ** sqlite3_malloc() to obtain space for the file-handle structure.
9221 */
9222 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9223 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9224
9225 #endif /* _SQLITE_OS_H_ */
9226
9227 /************** End of os.h **************************************************/
9228 /************** Continuing where we left off in sqliteInt.h ******************/
9229 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9230 /************** Begin file mutex.h *******************************************/
9231 /*
9232 ** 2007 August 28
9233 **
9234 ** The author disclaims copyright to this source code.  In place of
9235 ** a legal notice, here is a blessing:
9236 **
9237 **    May you do good and not evil.
9238 **    May you find forgiveness for yourself and forgive others.
9239 **    May you share freely, never taking more than you give.
9240 **
9241 *************************************************************************
9242 **
9243 ** This file contains the common header for all mutex implementations.
9244 ** The sqliteInt.h header #includes this file so that it is available
9245 ** to all source files.  We break it out in an effort to keep the code
9246 ** better organized.
9247 **
9248 ** NOTE:  source files should *not* #include this header file directly.
9249 ** Source files should #include the sqliteInt.h file and let that file
9250 ** include this one indirectly.
9251 **
9252 ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $
9253 */
9254
9255
9256 /*
9257 ** Figure out what version of the code to use.  The choices are
9258 **
9259 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9260 **                             mutexes implemention cannot be overridden
9261 **                             at start-time.
9262 **
9263 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9264 **                             mutual exclusion is provided.  But this
9265 **                             implementation can be overridden at
9266 **                             start-time.
9267 **
9268 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9269 **
9270 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9271 **
9272 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9273 */
9274 #if !SQLITE_THREADSAFE
9275 # define SQLITE_MUTEX_OMIT
9276 #endif
9277 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9278 #  if SQLITE_OS_UNIX
9279 #    define SQLITE_MUTEX_PTHREADS
9280 #  elif SQLITE_OS_WIN
9281 #    define SQLITE_MUTEX_W32
9282 #  elif SQLITE_OS_OS2
9283 #    define SQLITE_MUTEX_OS2
9284 #  else
9285 #    define SQLITE_MUTEX_NOOP
9286 #  endif
9287 #endif
9288
9289 #ifdef SQLITE_MUTEX_OMIT
9290 /*
9291 ** If this is a no-op implementation, implement everything as macros.
9292 */
9293 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9294 #define sqlite3_mutex_free(X)
9295 #define sqlite3_mutex_enter(X)
9296 #define sqlite3_mutex_try(X)      SQLITE_OK
9297 #define sqlite3_mutex_leave(X)
9298 #define sqlite3_mutex_held(X)     1
9299 #define sqlite3_mutex_notheld(X)  1
9300 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9301 #define sqlite3MutexInit()        SQLITE_OK
9302 #define sqlite3MutexEnd()
9303 #endif /* defined(SQLITE_OMIT_MUTEX) */
9304
9305 /************** End of mutex.h ***********************************************/
9306 /************** Continuing where we left off in sqliteInt.h ******************/
9307
9308
9309 /*
9310 ** Each database file to be accessed by the system is an instance
9311 ** of the following structure.  There are normally two of these structures
9312 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9313 ** aDb[1] is the database file used to hold temporary tables.  Additional
9314 ** databases may be attached.
9315 */
9316 struct Db {
9317   char *zName;         /* Name of this database */
9318   Btree *pBt;          /* The B*Tree structure for this database file */
9319   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9320   u8 safety_level;     /* How aggressive at syncing data to disk */
9321   void *pAux;               /* Auxiliary data.  Usually NULL */
9322   void (*xFreeAux)(void*);  /* Routine to free pAux */
9323   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9324 };
9325
9326 /*
9327 ** An instance of the following structure stores a database schema.
9328 **
9329 ** If there are no virtual tables configured in this schema, the
9330 ** Schema.db variable is set to NULL. After the first virtual table
9331 ** has been added, it is set to point to the database connection 
9332 ** used to create the connection. Once a virtual table has been
9333 ** added to the Schema structure and the Schema.db variable populated, 
9334 ** only that database connection may use the Schema to prepare 
9335 ** statements.
9336 */
9337 struct Schema {
9338   int schema_cookie;   /* Database schema version number for this file */
9339   Hash tblHash;        /* All tables indexed by name */
9340   Hash idxHash;        /* All (named) indices indexed by name */
9341   Hash trigHash;       /* All triggers indexed by name */
9342   Hash aFKey;          /* Foreign keys indexed by to-table */
9343   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9344   u8 file_format;      /* Schema format version for this file */
9345   u8 enc;              /* Text encoding used by this database */
9346   u16 flags;           /* Flags associated with this schema */
9347   int cache_size;      /* Number of pages to use in the cache */
9348 #ifndef SQLITE_OMIT_VIRTUALTABLE
9349   sqlite3 *db;         /* "Owner" connection. See comment above */
9350 #endif
9351 };
9352
9353 /*
9354 ** These macros can be used to test, set, or clear bits in the 
9355 ** Db.flags field.
9356 */
9357 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9358 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9359 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9360 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9361
9362 /*
9363 ** Allowed values for the DB.flags field.
9364 **
9365 ** The DB_SchemaLoaded flag is set after the database schema has been
9366 ** read into internal hash tables.
9367 **
9368 ** DB_UnresetViews means that one or more views have column names that
9369 ** have been filled out.  If the schema changes, these column names might
9370 ** changes and so the view will need to be reset.
9371 */
9372 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9373 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9374 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9375
9376 /*
9377 ** The number of different kinds of things that can be limited
9378 ** using the sqlite3_limit() interface.
9379 */
9380 #define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1)
9381
9382 /*
9383 ** Lookaside malloc is a set of fixed-size buffers that can be used
9384 ** to satisfy small transient memory allocation requests for objects
9385 ** associated with a particular database connection.  The use of
9386 ** lookaside malloc provides a significant performance enhancement
9387 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9388 ** SQL statements.
9389 **
9390 ** The Lookaside structure holds configuration information about the
9391 ** lookaside malloc subsystem.  Each available memory allocation in
9392 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9393 ** objects.
9394 */
9395 struct Lookaside {
9396   u16 sz;                 /* Size of each buffer in bytes */
9397   u8 bEnabled;            /* True if use lookaside.  False to ignore it */
9398   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9399   int nOut;               /* Number of buffers currently checked out */
9400   int mxOut;              /* Highwater mark for nOut */
9401   LookasideSlot *pFree;   /* List of available buffers */
9402   void *pStart;           /* First byte of available memory space */
9403   void *pEnd;             /* First byte past end of available space */
9404 };
9405 struct LookasideSlot {
9406   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9407 };
9408
9409 /*
9410 ** A hash table for function definitions.
9411 **
9412 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9413 ** Collisions are on the FuncDef.pHash chain.
9414 */
9415 struct FuncDefHash {
9416   FuncDef *a[23];       /* Hash table for functions */
9417 };
9418
9419 /*
9420 ** Each database is an instance of the following structure.
9421 **
9422 ** The sqlite.lastRowid records the last insert rowid generated by an
9423 ** insert statement.  Inserts on views do not affect its value.  Each
9424 ** trigger has its own context, so that lastRowid can be updated inside
9425 ** triggers as usual.  The previous value will be restored once the trigger
9426 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9427 ** longer (since after version 2.8.12) reset to -1.
9428 **
9429 ** The sqlite.nChange does not count changes within triggers and keeps no
9430 ** context.  It is reset at start of sqlite3_exec.
9431 ** The sqlite.lsChange represents the number of changes made by the last
9432 ** insert, update, or delete statement.  It remains constant throughout the
9433 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9434 ** context stack just like lastRowid so that the count of changes
9435 ** within a trigger is not seen outside the trigger.  Changes to views do not
9436 ** affect the value of lsChange.
9437 ** The sqlite.csChange keeps track of the number of current changes (since
9438 ** the last statement) and is used to update sqlite_lsChange.
9439 **
9440 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9441 ** store the most recent error code and, if applicable, string. The
9442 ** internal function sqlite3Error() is used to set these variables
9443 ** consistently.
9444 */
9445 struct sqlite3 {
9446   sqlite3_vfs *pVfs;            /* OS Interface */
9447   int nDb;                      /* Number of backends currently in use */
9448   Db *aDb;                      /* All backends */
9449   int flags;                    /* Miscellaneous flags. See below */
9450   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
9451   int errCode;                  /* Most recent error code (SQLITE_*) */
9452   int errMask;                  /* & result codes with this before returning */
9453   u8 autoCommit;                /* The auto-commit flag. */
9454   u8 temp_store;                /* 1: file 2: memory 0: default */
9455   u8 mallocFailed;              /* True if we have seen a malloc failure */
9456   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9457   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
9458   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9459   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9460   int nTable;                   /* Number of tables in the database */
9461   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9462   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9463   i64 priorNewRowid;            /* Last randomly generated ROWID */
9464   u32 magic;                    /* Magic number for detect library misuse */
9465   int nChange;                  /* Value returned by sqlite3_changes() */
9466   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9467   sqlite3_mutex *mutex;         /* Connection mutex */
9468   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9469   struct sqlite3InitInfo {      /* Information used during initialization */
9470     int iDb;                    /* When back is being initialized */
9471     int newTnum;                /* Rootpage of table being initialized */
9472     u8 busy;                    /* TRUE if currently initializing */
9473   } init;
9474   int nExtension;               /* Number of loaded extensions */
9475   void **aExtension;            /* Array of shared library handles */
9476   struct Vdbe *pVdbe;           /* List of active virtual machines */
9477   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9478   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9479   void (*xTrace)(void*,const char*);        /* Trace function */
9480   void *pTraceArg;                          /* Argument to the trace function */
9481   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9482   void *pProfileArg;                        /* Argument to profile function */
9483   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9484   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9485   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9486   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9487   void *pUpdateArg;
9488   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9489   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9490   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9491   void *pCollNeededArg;
9492   sqlite3_value *pErr;          /* Most recent error message */
9493   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9494   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9495   union {
9496     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9497     double notUsed1;            /* Spacer */
9498   } u1;
9499   Lookaside lookaside;          /* Lookaside malloc configuration */
9500 #ifndef SQLITE_OMIT_AUTHORIZATION
9501   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9502                                 /* Access authorization function */
9503   void *pAuthArg;               /* 1st argument to the access auth function */
9504 #endif
9505 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9506   int (*xProgress)(void *);     /* The progress callback */
9507   void *pProgressArg;           /* Argument to the progress callback */
9508   int nProgressOps;             /* Number of opcodes for progress callback */
9509 #endif
9510 #ifndef SQLITE_OMIT_VIRTUALTABLE
9511   Hash aModule;                 /* populated by sqlite3_create_module() */
9512   Table *pVTab;                 /* vtab with active Connect/Create method */
9513   sqlite3_vtab **aVTrans;       /* Virtual tables with open transactions */
9514   int nVTrans;                  /* Allocated size of aVTrans */
9515 #endif
9516   FuncDefHash aFunc;            /* Hash table of connection functions */
9517   Hash aCollSeq;                /* All collating sequences */
9518   BusyHandler busyHandler;      /* Busy callback */
9519   int busyTimeout;              /* Busy handler timeout, in msec */
9520   Db aDbStatic[2];              /* Static space for the 2 default backends */
9521 #ifdef SQLITE_SSE
9522   sqlite3_stmt *pFetch;         /* Used by SSE to fetch stored statements */
9523 #endif
9524   Savepoint *pSavepoint;        /* List of active savepoints */
9525   int nSavepoint;               /* Number of non-transaction savepoints */
9526   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9527 };
9528
9529 /*
9530 ** A macro to discover the encoding of a database.
9531 */
9532 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9533
9534 /*
9535 ** Possible values for the sqlite.flags and or Db.flags fields.
9536 **
9537 ** On sqlite.flags, the SQLITE_InTrans value means that we have
9538 ** executed a BEGIN.  On Db.flags, SQLITE_InTrans means a statement
9539 ** transaction is active on that particular database file.
9540 */
9541 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
9542 #define SQLITE_InTrans        0x00000008  /* True if in a transaction */
9543 #define SQLITE_InternChanges  0x00000010  /* Uncommitted Hash table changes */
9544 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
9545 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
9546 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
9547                                           /*   DELETE, or UPDATE and return */
9548                                           /*   the count using a callback. */
9549 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
9550                                           /*   result set is empty */
9551 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
9552 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
9553 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
9554 #define SQLITE_NoReadlock     0x00001000  /* Readlocks are omitted when 
9555                                           ** accessing read-only databases */
9556 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
9557 #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */
9558 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
9559 #define SQLITE_FullFSync      0x00010000  /* Use full fsync on the backend */
9560 #define SQLITE_LoadExtension  0x00020000  /* Enable load_extension */
9561
9562 #define SQLITE_RecoveryMode   0x00040000  /* Ignore schema errors */
9563 #define SQLITE_SharedCache    0x00080000  /* Cache sharing is enabled */
9564 #define SQLITE_Vtab           0x00100000  /* There exists a virtual table */
9565 #define SQLITE_CommitBusy     0x00200000  /* In the process of committing */
9566
9567 /*
9568 ** Possible values for the sqlite.magic field.
9569 ** The numbers are obtained at random and have no special meaning, other
9570 ** than being distinct from one another.
9571 */
9572 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9573 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9574 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9575 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9576 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9577
9578 /*
9579 ** Each SQL function is defined by an instance of the following
9580 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9581 ** hash table.  When multiple functions have the same name, the hash table
9582 ** points to a linked list of these structures.
9583 */
9584 struct FuncDef {
9585   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9586   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9587   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9588   void *pUserData;     /* User data parameter */
9589   FuncDef *pNext;      /* Next function with same name */
9590   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9591   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9592   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9593   char *zName;         /* SQL name of the function. */
9594   FuncDef *pHash;      /* Next with a different name but the same hash */
9595 };
9596
9597 /*
9598 ** Possible values for FuncDef.flags
9599 */
9600 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9601 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9602 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9603 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9604 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9605
9606 /*
9607 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9608 ** used to create the initializers for the FuncDef structures.
9609 **
9610 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9611 **     Used to create a scalar function definition of a function zName 
9612 **     implemented by C function xFunc that accepts nArg arguments. The
9613 **     value passed as iArg is cast to a (void*) and made available
9614 **     as the user-data (sqlite3_user_data()) for the function. If 
9615 **     argument bNC is true, then the FuncDef.needCollate flag is set.
9616 **
9617 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9618 **     Used to create an aggregate function definition implemented by
9619 **     the C functions xStep and xFinal. The first four parameters
9620 **     are interpreted in the same way as the first 4 parameters to
9621 **     FUNCTION().
9622 **
9623 **   LIKEFUNC(zName, nArg, pArg, flags)
9624 **     Used to create a scalar function definition of a function zName 
9625 **     that accepts nArg arguments and is implemented by a call to C 
9626 **     function likeFunc. Argument pArg is cast to a (void *) and made
9627 **     available as the function user-data (sqlite3_user_data()). The
9628 **     FuncDef.flags variable is set to the value passed as the flags
9629 **     parameter.
9630 */
9631 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9632   {nArg, SQLITE_UTF8, bNC*8, SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
9633 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9634   {nArg, SQLITE_UTF8, bNC*8, pArg, 0, xFunc, 0, 0, #zName, 0}
9635 #define LIKEFUNC(zName, nArg, arg, flags) \
9636   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
9637 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9638   {nArg, SQLITE_UTF8, nc*8, SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
9639
9640 /*
9641 ** All current savepoints are stored in a linked list starting at
9642 ** sqlite3.pSavepoint. The first element in the list is the most recently
9643 ** opened savepoint. Savepoints are added to the list by the vdbe
9644 ** OP_Savepoint instruction.
9645 */
9646 struct Savepoint {
9647   char *zName;                        /* Savepoint name (nul-terminated) */
9648   Savepoint *pNext;                   /* Parent savepoint (if any) */
9649 };
9650
9651 /*
9652 ** The following are used as the second parameter to sqlite3Savepoint(),
9653 ** and as the P1 argument to the OP_Savepoint instruction.
9654 */
9655 #define SAVEPOINT_BEGIN      0
9656 #define SAVEPOINT_RELEASE    1
9657 #define SAVEPOINT_ROLLBACK   2
9658
9659
9660 /*
9661 ** Each SQLite module (virtual table definition) is defined by an
9662 ** instance of the following structure, stored in the sqlite3.aModule
9663 ** hash table.
9664 */
9665 struct Module {
9666   const sqlite3_module *pModule;       /* Callback pointers */
9667   const char *zName;                   /* Name passed to create_module() */
9668   void *pAux;                          /* pAux passed to create_module() */
9669   void (*xDestroy)(void *);            /* Module destructor function */
9670 };
9671
9672 /*
9673 ** information about each column of an SQL table is held in an instance
9674 ** of this structure.
9675 */
9676 struct Column {
9677   char *zName;     /* Name of this column */
9678   Expr *pDflt;     /* Default value of this column */
9679   char *zType;     /* Data type for this column */
9680   char *zColl;     /* Collating sequence.  If NULL, use the default */
9681   u8 notNull;      /* True if there is a NOT NULL constraint */
9682   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9683   char affinity;   /* One of the SQLITE_AFF_... values */
9684 #ifndef SQLITE_OMIT_VIRTUALTABLE
9685   u8 isHidden;     /* True if this column is 'hidden' */
9686 #endif
9687 };
9688
9689 /*
9690 ** A "Collating Sequence" is defined by an instance of the following
9691 ** structure. Conceptually, a collating sequence consists of a name and
9692 ** a comparison routine that defines the order of that sequence.
9693 **
9694 ** There may two separate implementations of the collation function, one
9695 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9696 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9697 ** native byte order. When a collation sequence is invoked, SQLite selects
9698 ** the version that will require the least expensive encoding
9699 ** translations, if any.
9700 **
9701 ** The CollSeq.pUser member variable is an extra parameter that passed in
9702 ** as the first argument to the UTF-8 comparison function, xCmp.
9703 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9704 ** xCmp16.
9705 **
9706 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9707 ** collating sequence is undefined.  Indices built on an undefined
9708 ** collating sequence may not be read or written.
9709 */
9710 struct CollSeq {
9711   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9712   u8 enc;               /* Text encoding handled by xCmp() */
9713   u8 type;              /* One of the SQLITE_COLL_... values below */
9714   void *pUser;          /* First argument to xCmp() */
9715   int (*xCmp)(void*,int, const void*, int, const void*);
9716   void (*xDel)(void*);  /* Destructor for pUser */
9717 };
9718
9719 /*
9720 ** Allowed values of CollSeq.type:
9721 */
9722 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9723 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9724 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9725 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9726
9727 /*
9728 ** A sort order can be either ASC or DESC.
9729 */
9730 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9731 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9732
9733 /*
9734 ** Column affinity types.
9735 **
9736 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9737 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9738 ** the speed a little by numbering the values consecutively.  
9739 **
9740 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9741 ** when multiple affinity types are concatenated into a string and
9742 ** used as the P4 operand, they will be more readable.
9743 **
9744 ** Note also that the numeric types are grouped together so that testing
9745 ** for a numeric type is a single comparison.
9746 */
9747 #define SQLITE_AFF_TEXT     'a'
9748 #define SQLITE_AFF_NONE     'b'
9749 #define SQLITE_AFF_NUMERIC  'c'
9750 #define SQLITE_AFF_INTEGER  'd'
9751 #define SQLITE_AFF_REAL     'e'
9752
9753 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9754
9755 /*
9756 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9757 ** affinity value. 
9758 */
9759 #define SQLITE_AFF_MASK     0x67
9760
9761 /*
9762 ** Additional bit values that can be ORed with an affinity without
9763 ** changing the affinity.
9764 */
9765 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9766 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9767
9768 /*
9769 ** Each SQL table is represented in memory by an instance of the
9770 ** following structure.
9771 **
9772 ** Table.zName is the name of the table.  The case of the original
9773 ** CREATE TABLE statement is stored, but case is not significant for
9774 ** comparisons.
9775 **
9776 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9777 ** pointer to an array of Column structures, one for each column.
9778 **
9779 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9780 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9781 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9782 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9783 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9784 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9785 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9786 **
9787 ** Table.tnum is the page number for the root BTree page of the table in the
9788 ** database file.  If Table.iDb is the index of the database table backend
9789 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9790 ** holds temporary tables and indices.  If TF_Ephemeral is set
9791 ** then the table is stored in a file that is automatically deleted
9792 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9793 ** refers VDBE cursor number that holds the table open, not to the root
9794 ** page number.  Transient tables are used to hold the results of a
9795 ** sub-query that appears instead of a real table name in the FROM clause 
9796 ** of a SELECT statement.
9797 */
9798 struct Table {
9799   sqlite3 *db;         /* Associated database connection.  Might be NULL. */
9800   char *zName;         /* Name of the table or view */
9801   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9802   int nCol;            /* Number of columns in this table */
9803   Column *aCol;        /* Information about each column */
9804   Index *pIndex;       /* List of SQL indexes on this table. */
9805   int tnum;            /* Root BTree node for this table (see note above) */
9806   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9807   u16 nRef;            /* Number of pointers to this Table */
9808   u8 tabFlags;         /* Mask of TF_* values */
9809   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9810   Trigger *pTrigger;   /* List of SQL triggers on this table */
9811   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9812   char *zColAff;       /* String defining the affinity of each column */
9813 #ifndef SQLITE_OMIT_CHECK
9814   Expr *pCheck;        /* The AND of all CHECK constraints */
9815 #endif
9816 #ifndef SQLITE_OMIT_ALTERTABLE
9817   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9818 #endif
9819 #ifndef SQLITE_OMIT_VIRTUALTABLE
9820   Module *pMod;        /* Pointer to the implementation of the module */
9821   sqlite3_vtab *pVtab; /* Pointer to the module instance */
9822   int nModuleArg;      /* Number of arguments to the module */
9823   char **azModuleArg;  /* Text of all module args. [0] is module name */
9824 #endif
9825   Schema *pSchema;     /* Schema that contains this table */
9826   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9827 };
9828
9829 /*
9830 ** Allowed values for Tabe.tabFlags.
9831 */
9832 #define TF_Readonly        0x01    /* Read-only system table */
9833 #define TF_Ephemeral       0x02    /* An ephemeral table */
9834 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9835 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9836 #define TF_Virtual         0x10    /* Is a virtual table */
9837 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9838
9839
9840
9841 /*
9842 ** Test to see whether or not a table is a virtual table.  This is
9843 ** done as a macro so that it will be optimized out when virtual
9844 ** table support is omitted from the build.
9845 */
9846 #ifndef SQLITE_OMIT_VIRTUALTABLE
9847 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9848 #  define IsHiddenColumn(X) ((X)->isHidden)
9849 #else
9850 #  define IsVirtual(X)      0
9851 #  define IsHiddenColumn(X) 0
9852 #endif
9853
9854 /*
9855 ** Each foreign key constraint is an instance of the following structure.
9856 **
9857 ** A foreign key is associated with two tables.  The "from" table is
9858 ** the table that contains the REFERENCES clause that creates the foreign
9859 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9860 ** Consider this example:
9861 **
9862 **     CREATE TABLE ex1(
9863 **       a INTEGER PRIMARY KEY,
9864 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9865 **     );
9866 **
9867 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9868 **
9869 ** Each REFERENCES clause generates an instance of the following structure
9870 ** which is attached to the from-table.  The to-table need not exist when
9871 ** the from-table is created.  The existence of the to-table is not checked
9872 ** until an attempt is made to insert data into the from-table.
9873 **
9874 ** The sqlite.aFKey hash table stores pointers to this structure
9875 ** given the name of a to-table.  For each to-table, all foreign keys
9876 ** associated with that table are on a linked list using the FKey.pNextTo
9877 ** field.
9878 */
9879 struct FKey {
9880   Table *pFrom;     /* The table that contains the REFERENCES clause */
9881   FKey *pNextFrom;  /* Next foreign key in pFrom */
9882   char *zTo;        /* Name of table that the key points to */
9883   FKey *pNextTo;    /* Next foreign key that points to zTo */
9884   int nCol;         /* Number of columns in this key */
9885   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9886     int iFrom;         /* Index of column in pFrom */
9887     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9888   } *aCol;          /* One entry for each of nCol column s */
9889   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9890   u8 updateConf;    /* How to resolve conflicts that occur on UPDATE */
9891   u8 deleteConf;    /* How to resolve conflicts that occur on DELETE */
9892   u8 insertConf;    /* How to resolve conflicts that occur on INSERT */
9893 };
9894
9895 /*
9896 ** SQLite supports many different ways to resolve a constraint
9897 ** error.  ROLLBACK processing means that a constraint violation
9898 ** causes the operation in process to fail and for the current transaction
9899 ** to be rolled back.  ABORT processing means the operation in process
9900 ** fails and any prior changes from that one operation are backed out,
9901 ** but the transaction is not rolled back.  FAIL processing means that
9902 ** the operation in progress stops and returns an error code.  But prior
9903 ** changes due to the same operation are not backed out and no rollback
9904 ** occurs.  IGNORE means that the particular row that caused the constraint
9905 ** error is not inserted or updated.  Processing continues and no error
9906 ** is returned.  REPLACE means that preexisting database rows that caused
9907 ** a UNIQUE constraint violation are removed so that the new insert or
9908 ** update can proceed.  Processing continues and no error is reported.
9909 **
9910 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9911 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9912 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9913 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9914 ** referenced table row is propagated into the row that holds the
9915 ** foreign key.
9916 ** 
9917 ** The following symbolic values are used to record which type
9918 ** of action to take.
9919 */
9920 #define OE_None     0   /* There is no constraint to check */
9921 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9922 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9923 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9924 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9925 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9926
9927 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9928 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9929 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9930 #define OE_Cascade  9   /* Cascade the changes */
9931
9932 #define OE_Default  99  /* Do whatever the default action is */
9933
9934
9935 /*
9936 ** An instance of the following structure is passed as the first
9937 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9938 ** comparison of the two index keys.
9939 */
9940 struct KeyInfo {
9941   sqlite3 *db;        /* The database connection */
9942   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
9943   u16 nField;         /* Number of entries in aColl[] */
9944   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
9945   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9946 };
9947
9948 /*
9949 ** An instance of the following structure holds information about a
9950 ** single index record that has already been parsed out into individual
9951 ** values.
9952 **
9953 ** A record is an object that contains one or more fields of data.
9954 ** Records are used to store the content of a table row and to store
9955 ** the key of an index.  A blob encoding of a record is created by
9956 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9957 ** OP_Column opcode.
9958 **
9959 ** This structure holds a record that has already been disassembled
9960 ** into its constituent fields.
9961 */
9962 struct UnpackedRecord {
9963   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9964   u16 nField;         /* Number of entries in apMem[] */
9965   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9966   Mem *aMem;          /* Values */
9967 };
9968
9969 /*
9970 ** Allowed values of UnpackedRecord.flags
9971 */
9972 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9973 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9974 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9975 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9976 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9977
9978 /*
9979 ** Each SQL index is represented in memory by an
9980 ** instance of the following structure.
9981 **
9982 ** The columns of the table that are to be indexed are described
9983 ** by the aiColumn[] field of this structure.  For example, suppose
9984 ** we have the following table and index:
9985 **
9986 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9987 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9988 **
9989 ** In the Table structure describing Ex1, nCol==3 because there are
9990 ** three columns in the table.  In the Index structure describing
9991 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9992 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9993 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9994 ** The second column to be indexed (c1) has an index of 0 in
9995 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9996 **
9997 ** The Index.onError field determines whether or not the indexed columns
9998 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9999 ** it means this is not a unique index.  Otherwise it is a unique index
10000 ** and the value of Index.onError indicate the which conflict resolution 
10001 ** algorithm to employ whenever an attempt is made to insert a non-unique
10002 ** element.
10003 */
10004 struct Index {
10005   char *zName;     /* Name of this index */
10006   int nColumn;     /* Number of columns in the table used by this index */
10007   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10008   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10009   Table *pTable;   /* The SQL table being indexed */
10010   int tnum;        /* Page containing root of this index in database file */
10011   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10012   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10013   char *zColAff;   /* String defining the affinity of each column */
10014   Index *pNext;    /* The next index associated with the same table */
10015   Schema *pSchema; /* Schema containing this index */
10016   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10017   char **azColl;   /* Array of collation sequence names for index */
10018 };
10019
10020 /*
10021 ** Each token coming out of the lexer is an instance of
10022 ** this structure.  Tokens are also used as part of an expression.
10023 **
10024 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10025 ** may contain random values.  Do not make any assumptions about Token.dyn
10026 ** and Token.n when Token.z==0.
10027 */
10028 struct Token {
10029   const unsigned char *z; /* Text of the token.  Not NULL-terminated! */
10030   unsigned dyn  : 1;      /* True for malloced memory, false for static */
10031   unsigned n    : 31;     /* Number of characters in this token */
10032 };
10033
10034 /*
10035 ** An instance of this structure contains information needed to generate
10036 ** code for a SELECT that contains aggregate functions.
10037 **
10038 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10039 ** pointer to this structure.  The Expr.iColumn field is the index in
10040 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10041 ** code for that node.
10042 **
10043 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10044 ** original Select structure that describes the SELECT statement.  These
10045 ** fields do not need to be freed when deallocating the AggInfo structure.
10046 */
10047 struct AggInfo {
10048   u8 directMode;          /* Direct rendering mode means take data directly
10049                           ** from source tables rather than from accumulators */
10050   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10051                           ** than the source table */
10052   int sortingIdx;         /* Cursor number of the sorting index */
10053   ExprList *pGroupBy;     /* The group by clause */
10054   int nSortingColumn;     /* Number of columns in the sorting index */
10055   struct AggInfo_col {    /* For each column used in source tables */
10056     Table *pTab;             /* Source table */
10057     int iTable;              /* Cursor number of the source table */
10058     int iColumn;             /* Column number within the source table */
10059     int iSorterColumn;       /* Column number in the sorting index */
10060     int iMem;                /* Memory location that acts as accumulator */
10061     Expr *pExpr;             /* The original expression */
10062   } *aCol;
10063   int nColumn;            /* Number of used entries in aCol[] */
10064   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
10065   int nAccumulator;       /* Number of columns that show through to the output.
10066                           ** Additional columns are used only as parameters to
10067                           ** aggregate functions */
10068   struct AggInfo_func {   /* For each aggregate function */
10069     Expr *pExpr;             /* Expression encoding the function */
10070     FuncDef *pFunc;          /* The aggregate function implementation */
10071     int iMem;                /* Memory location that acts as accumulator */
10072     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10073   } *aFunc;
10074   int nFunc;              /* Number of entries in aFunc[] */
10075   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
10076 };
10077
10078 /*
10079 ** Each node of an expression in the parse tree is an instance
10080 ** of this structure.
10081 **
10082 ** Expr.op is the opcode.  The integer parser token codes are reused
10083 ** as opcodes here.  For example, the parser defines TK_GE to be an integer
10084 ** code representing the ">=" operator.  This same integer code is reused
10085 ** to represent the greater-than-or-equal-to operator in the expression
10086 ** tree.
10087 **
10088 ** Expr.pRight and Expr.pLeft are subexpressions.  Expr.pList is a list
10089 ** of argument if the expression is a function.
10090 **
10091 ** Expr.token is the operator token for this node.  For some expressions
10092 ** that have subexpressions, Expr.token can be the complete text that gave
10093 ** rise to the Expr.  In the latter case, the token is marked as being
10094 ** a compound token.
10095 **
10096 ** An expression of the form ID or ID.ID refers to a column in a table.
10097 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10098 ** the integer cursor number of a VDBE cursor pointing to that table and
10099 ** Expr.iColumn is the column number for the specific column.  If the
10100 ** expression is used as a result in an aggregate SELECT, then the
10101 ** value is also stored in the Expr.iAgg column in the aggregate so that
10102 ** it can be accessed after all aggregates are computed.
10103 **
10104 ** If the expression is a function, the Expr.iTable is an integer code
10105 ** representing which function.  If the expression is an unbound variable
10106 ** marker (a question mark character '?' in the original SQL) then the
10107 ** Expr.iTable holds the index number for that variable.
10108 **
10109 ** If the expression is a subquery then Expr.iColumn holds an integer
10110 ** register number containing the result of the subquery.  If the
10111 ** subquery gives a constant result, then iTable is -1.  If the subquery
10112 ** gives a different answer at different times during statement processing
10113 ** then iTable is the address of a subroutine that computes the subquery.
10114 **
10115 ** The Expr.pSelect field points to a SELECT statement.  The SELECT might
10116 ** be the right operand of an IN operator.  Or, if a scalar SELECT appears
10117 ** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
10118 ** operand.
10119 **
10120 ** If the Expr is of type OP_Column, and the table it is selecting from
10121 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10122 ** corresponding table definition.
10123 */
10124 struct Expr {
10125   u8 op;                 /* Operation performed by this node */
10126   char affinity;         /* The affinity of the column or 0 if not a column */
10127   u16 flags;             /* Various flags.  See below */
10128   CollSeq *pColl;        /* The collation type of the column or 0 */
10129   Expr *pLeft, *pRight;  /* Left and right subnodes */
10130   ExprList *pList;       /* A list of expressions used as function arguments
10131                          ** or in "<expr> IN (<expr-list)" */
10132   Token token;           /* An operand token */
10133   Token span;            /* Complete text of the expression */
10134   int iTable, iColumn;   /* When op==TK_COLUMN, then this expr node means the
10135                          ** iColumn-th field of the iTable-th table. */
10136   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10137   int iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10138   int iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10139   Select *pSelect;       /* When the expression is a sub-select.  Also the
10140                          ** right side of "<expr> IN (<select>)" */
10141   Table *pTab;           /* Table for TK_COLUMN expressions. */
10142 #if SQLITE_MAX_EXPR_DEPTH>0
10143   int nHeight;           /* Height of the tree headed by this node */
10144 #endif
10145 };
10146
10147 /*
10148 ** The following are the meanings of bits in the Expr.flags field.
10149 */
10150 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10151 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10152 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10153 #define EP_Error      0x0008  /* Expression contains one or more errors */
10154 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10155 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10156 #define EP_Dequoted   0x0040  /* True if the string has been dequoted */
10157 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10158 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10159 #define EP_AnyAff     0x0200  /* Can take a cached column of any affinity */
10160 #define EP_FixedDest  0x0400  /* Result needed in a specific register */
10161 #define EP_IntValue   0x0800  /* Integer value contained in iTable */
10162 /*
10163 ** These macros can be used to test, set, or clear bits in the 
10164 ** Expr.flags field.
10165 */
10166 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10167 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10168 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10169 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10170
10171 /*
10172 ** A list of expressions.  Each expression may optionally have a
10173 ** name.  An expr/name combination can be used in several ways, such
10174 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10175 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10176 ** also be used as the argument to a function, in which case the a.zName
10177 ** field is not used.
10178 */
10179 struct ExprList {
10180   int nExpr;             /* Number of expressions on the list */
10181   int nAlloc;            /* Number of entries allocated below */
10182   int iECursor;          /* VDBE Cursor associated with this ExprList */
10183   struct ExprList_item {
10184     Expr *pExpr;           /* The list of expressions */
10185     char *zName;           /* Token associated with this expression */
10186     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10187     u8 done;               /* A flag to indicate when processing is finished */
10188     u16 iCol;              /* For ORDER BY, column number in result set */
10189     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10190   } *a;                  /* One entry for each expression */
10191 };
10192
10193 /*
10194 ** An instance of this structure can hold a simple list of identifiers,
10195 ** such as the list "a,b,c" in the following statements:
10196 **
10197 **      INSERT INTO t(a,b,c) VALUES ...;
10198 **      CREATE INDEX idx ON t(a,b,c);
10199 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10200 **
10201 ** The IdList.a.idx field is used when the IdList represents the list of
10202 ** column names after a table name in an INSERT statement.  In the statement
10203 **
10204 **     INSERT INTO t(a,b,c) ...
10205 **
10206 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10207 */
10208 struct IdList {
10209   struct IdList_item {
10210     char *zName;      /* Name of the identifier */
10211     int idx;          /* Index in some Table.aCol[] of a column named zName */
10212   } *a;
10213   int nId;         /* Number of identifiers on the list */
10214   int nAlloc;      /* Number of entries allocated for a[] below */
10215 };
10216
10217 /*
10218 ** The bitmask datatype defined below is used for various optimizations.
10219 **
10220 ** Changing this from a 64-bit to a 32-bit type limits the number of
10221 ** tables in a join to 32 instead of 64.  But it also reduces the size
10222 ** of the library by 738 bytes on ix86.
10223 */
10224 typedef u64 Bitmask;
10225
10226 /*
10227 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10228 */
10229 #define BMS  ((int)(sizeof(Bitmask)*8))
10230
10231 /*
10232 ** The following structure describes the FROM clause of a SELECT statement.
10233 ** Each table or subquery in the FROM clause is a separate element of
10234 ** the SrcList.a[] array.
10235 **
10236 ** With the addition of multiple database support, the following structure
10237 ** can also be used to describe a particular table such as the table that
10238 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10239 ** such a table must be a simple name: ID.  But in SQLite, the table can
10240 ** now be identified by a database name, a dot, then the table name: ID.ID.
10241 **
10242 ** The jointype starts out showing the join type between the current table
10243 ** and the next table on the list.  The parser builds the list this way.
10244 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10245 ** jointype expresses the join between the table and the previous table.
10246 */
10247 struct SrcList {
10248   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10249   i16 nAlloc;      /* Number of entries allocated in a[] below */
10250   struct SrcList_item {
10251     char *zDatabase;  /* Name of database holding this table */
10252     char *zName;      /* Name of the table */
10253     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10254     Table *pTab;      /* An SQL table corresponding to zName */
10255     Select *pSelect;  /* A SELECT statement used in place of a table name */
10256     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10257     u8 jointype;      /* Type of join between this able and the previous */
10258     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10259     int iCursor;      /* The VDBE cursor number used to access this table */
10260     Expr *pOn;        /* The ON clause of a join */
10261     IdList *pUsing;   /* The USING clause of a join */
10262     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10263     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10264     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10265   } a[1];             /* One entry for each identifier on the list */
10266 };
10267
10268 /*
10269 ** Permitted values of the SrcList.a.jointype field
10270 */
10271 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10272 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10273 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10274 #define JT_LEFT      0x0008    /* Left outer join */
10275 #define JT_RIGHT     0x0010    /* Right outer join */
10276 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10277 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10278
10279
10280 /*
10281 ** A WherePlan object holds information that describes a lookup
10282 ** strategy.
10283 **
10284 ** This object is intended to be opaque outside of the where.c module.
10285 ** It is included here only so that that compiler will know how big it
10286 ** is.  None of the fields in this object should be used outside of
10287 ** the where.c module.
10288 **
10289 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10290 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10291 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10292 ** case that more than one of these conditions is true.
10293 */
10294 struct WherePlan {
10295   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10296   u32 nEq;                       /* Number of == constraints */
10297   union {
10298     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10299     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10300     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10301   } u;
10302 };
10303
10304 /*
10305 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10306 ** structure contains a single instance of this structure.  This structure
10307 ** is intended to be private the the where.c module and should not be
10308 ** access or modified by other modules.
10309 **
10310 ** The pIdxInfo field is used to help pick the best index on a
10311 ** virtual table.  The pIdxInfo pointer contains indexing
10312 ** information for the i-th table in the FROM clause before reordering.
10313 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10314 ** All other information in the i-th WhereLevel object for the i-th table
10315 ** after FROM clause ordering.
10316 */
10317 struct WhereLevel {
10318   WherePlan plan;       /* query plan for this element of the FROM clause */
10319   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10320   int iTabCur;          /* The VDBE cursor used to access the table */
10321   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10322   int addrBrk;          /* Jump here to break out of the loop */
10323   int addrNxt;          /* Jump here to start the next IN combination */
10324   int addrCont;         /* Jump here to continue with the next loop cycle */
10325   int addrFirst;        /* First instruction of interior of the loop */
10326   u8 iFrom;             /* Which entry in the FROM clause */
10327   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10328   int p1, p2;           /* Operands of the opcode used to ends the loop */
10329   union {               /* Information that depends on plan.wsFlags */
10330     struct {
10331       int nIn;              /* Number of entries in aInLoop[] */
10332       struct InLoop {
10333         int iCur;              /* The VDBE cursor used by this IN operator */
10334         int addrInTop;         /* Top of the IN loop */
10335       } *aInLoop;           /* Information about each nested IN operator */
10336     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10337   } u;
10338
10339   /* The following field is really not part of the current level.  But
10340   ** we need a place to cache virtual table index information for each
10341   ** virtual table in the FROM clause and the WhereLevel structure is
10342   ** a convenient place since there is one WhereLevel for each FROM clause
10343   ** element.
10344   */
10345   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10346 };
10347
10348 /*
10349 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
10350 */
10351 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10352 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10353 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10354 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10355 #define WHERE_FILL_ROWSET      0x0008  /* Save results in a RowSet object */
10356 #define WHERE_OMIT_OPEN        0x0010  /* Table cursor are already open */
10357 #define WHERE_OMIT_CLOSE       0x0020  /* Omit close of table & index cursors */
10358
10359 /*
10360 ** The WHERE clause processing routine has two halves.  The
10361 ** first part does the start of the WHERE loop and the second
10362 ** half does the tail of the WHERE loop.  An instance of
10363 ** this structure is returned by the first half and passed
10364 ** into the second half to give some continuity.
10365 */
10366 struct WhereInfo {
10367   Parse *pParse;       /* Parsing and code generating context */
10368   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10369   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10370   int regRowSet;                 /* Store rowids in this rowset if >=0 */
10371   SrcList *pTabList;             /* List of tables in the join */
10372   int iTop;                      /* The very beginning of the WHERE loop */
10373   int iContinue;                 /* Jump here to continue with next record */
10374   int iBreak;                    /* Jump here to break out of the loop */
10375   int nLevel;                    /* Number of nested loop */
10376   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10377   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10378 };
10379
10380 /*
10381 ** A NameContext defines a context in which to resolve table and column
10382 ** names.  The context consists of a list of tables (the pSrcList) field and
10383 ** a list of named expression (pEList).  The named expression list may
10384 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10385 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10386 ** pEList corresponds to the result set of a SELECT and is NULL for
10387 ** other statements.
10388 **
10389 ** NameContexts can be nested.  When resolving names, the inner-most 
10390 ** context is searched first.  If no match is found, the next outer
10391 ** context is checked.  If there is still no match, the next context
10392 ** is checked.  This process continues until either a match is found
10393 ** or all contexts are check.  When a match is found, the nRef member of
10394 ** the context containing the match is incremented. 
10395 **
10396 ** Each subquery gets a new NameContext.  The pNext field points to the
10397 ** NameContext in the parent query.  Thus the process of scanning the
10398 ** NameContext list corresponds to searching through successively outer
10399 ** subqueries looking for a match.
10400 */
10401 struct NameContext {
10402   Parse *pParse;       /* The parser */
10403   SrcList *pSrcList;   /* One or more tables used to resolve names */
10404   ExprList *pEList;    /* Optional list of named expressions */
10405   int nRef;            /* Number of names resolved by this context */
10406   int nErr;            /* Number of errors encountered while resolving names */
10407   u8 allowAgg;         /* Aggregate functions allowed here */
10408   u8 hasAgg;           /* True if aggregates are seen */
10409   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10410   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10411   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10412   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10413 };
10414
10415 /*
10416 ** An instance of the following structure contains all information
10417 ** needed to generate code for a single SELECT statement.
10418 **
10419 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10420 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10421 ** limit and nOffset to the value of the offset (or 0 if there is not
10422 ** offset).  But later on, nLimit and nOffset become the memory locations
10423 ** in the VDBE that record the limit and offset counters.
10424 **
10425 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10426 ** These addresses must be stored so that we can go back and fill in
10427 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10428 ** the number of columns in P2 can be computed at the same time
10429 ** as the OP_OpenEphm instruction is coded because not
10430 ** enough information about the compound query is known at that point.
10431 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10432 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10433 ** sequences for the ORDER BY clause.
10434 */
10435 struct Select {
10436   ExprList *pEList;      /* The fields of the result */
10437   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10438   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10439   u16 selFlags;          /* Various SF_* values */
10440   SrcList *pSrc;         /* The FROM clause */
10441   Expr *pWhere;          /* The WHERE clause */
10442   ExprList *pGroupBy;    /* The GROUP BY clause */
10443   Expr *pHaving;         /* The HAVING clause */
10444   ExprList *pOrderBy;    /* The ORDER BY clause */
10445   Select *pPrior;        /* Prior select in a compound select statement */
10446   Select *pNext;         /* Next select to the left in a compound */
10447   Select *pRightmost;    /* Right-most select in a compound select statement */
10448   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10449   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10450   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10451   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10452 };
10453
10454 /*
10455 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10456 ** "Select Flag".
10457 */
10458 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10459 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10460 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10461 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10462 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10463 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10464
10465
10466 /*
10467 ** The results of a select can be distributed in several ways.  The
10468 ** "SRT" prefix means "SELECT Result Type".
10469 */
10470 #define SRT_Union        1  /* Store result as keys in an index */
10471 #define SRT_Except       2  /* Remove result from a UNION index */
10472 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10473 #define SRT_Discard      4  /* Do not save the results anywhere */
10474
10475 /* The ORDER BY clause is ignored for all of the above */
10476 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10477
10478 #define SRT_Output       5  /* Output each row of result */
10479 #define SRT_Mem          6  /* Store result in a memory cell */
10480 #define SRT_Set          7  /* Store results as keys in an index */
10481 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10482 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10483 #define SRT_Coroutine   10  /* Generate a single row of result */
10484
10485 /*
10486 ** A structure used to customize the behavior of sqlite3Select(). See
10487 ** comments above sqlite3Select() for details.
10488 */
10489 typedef struct SelectDest SelectDest;
10490 struct SelectDest {
10491   u8 eDest;         /* How to dispose of the results */
10492   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10493   int iParm;        /* A parameter used by the eDest disposal method */
10494   int iMem;         /* Base register where results are written */
10495   int nMem;         /* Number of registers allocated */
10496 };
10497
10498 /*
10499 ** An SQL parser context.  A copy of this structure is passed through
10500 ** the parser and down into all the parser action routine in order to
10501 ** carry around information that is global to the entire parse.
10502 **
10503 ** The structure is divided into two parts.  When the parser and code
10504 ** generate call themselves recursively, the first part of the structure
10505 ** is constant but the second part is reset at the beginning and end of
10506 ** each recursion.
10507 **
10508 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10509 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10510 ** used to store the set of table-locks required by the statement being
10511 ** compiled. Function sqlite3TableLock() is used to add entries to the
10512 ** list.
10513 */
10514 struct Parse {
10515   sqlite3 *db;         /* The main database structure */
10516   int rc;              /* Return code from execution */
10517   char *zErrMsg;       /* An error message */
10518   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10519   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10520   u8 nameClash;        /* A permanent table name clashes with temp table name */
10521   u8 checkSchema;      /* Causes schema cookie check after an error */
10522   u8 nested;           /* Number of nested calls to the parser/code generator */
10523   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10524   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10525   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10526   int aTempReg[8];     /* Holding area for temporary registers */
10527   int nRangeReg;       /* Size of the temporary register block */
10528   int iRangeReg;       /* First register in temporary register block */
10529   int nErr;            /* Number of errors seen */
10530   int nTab;            /* Number of previously allocated VDBE cursors */
10531   int nMem;            /* Number of memory cells used so far */
10532   int nSet;            /* Number of sets used so far */
10533   int ckBase;          /* Base register of data during check constraints */
10534   int disableColCache; /* True to disable adding to column cache */
10535   int nColCache;       /* Number of entries in the column cache */
10536   int iColCache;       /* Next entry of the cache to replace */
10537   struct yColCache {
10538     int iTable;           /* Table cursor number */
10539     int iColumn;          /* Table column number */
10540     char affChange;       /* True if this register has had an affinity change */
10541     int iReg;             /* Register holding value of this column */
10542   } aColCache[10];     /* One for each valid column cache entry */
10543   u32 writeMask;       /* Start a write transaction on these databases */
10544   u32 cookieMask;      /* Bitmask of schema verified databases */
10545   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10546   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10547 #ifndef SQLITE_OMIT_SHARED_CACHE
10548   int nTableLock;        /* Number of locks in aTableLock */
10549   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10550 #endif
10551   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10552   int regRoot;         /* Register holding root page number for new objects */
10553
10554   /* Above is constant between recursions.  Below is reset before and after
10555   ** each recursion */
10556
10557   int nVar;            /* Number of '?' variables seen in the SQL so far */
10558   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10559   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10560   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10561   int nAlias;          /* Number of aliased result set columns */
10562   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10563   int *aAlias;         /* Register used to hold aliased result */
10564   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10565   Token sErrToken;     /* The token at which the error occurred */
10566   Token sNameToken;    /* Token with unqualified schema object name */
10567   Token sLastToken;    /* The last token parsed */
10568   const char *zSql;    /* All SQL text */
10569   const char *zTail;   /* All SQL text past the last semicolon parsed */
10570   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10571   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10572   TriggerStack *trigStack;  /* Trigger actions being coded */
10573   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10574 #ifndef SQLITE_OMIT_VIRTUALTABLE
10575   Token sArg;                /* Complete text of a module argument */
10576   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10577   int nVtabLock;             /* Number of virtual tables to lock */
10578   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10579 #endif
10580   int nHeight;            /* Expression tree height of current sub-select */
10581   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10582 };
10583
10584 #ifdef SQLITE_OMIT_VIRTUALTABLE
10585   #define IN_DECLARE_VTAB 0
10586 #else
10587   #define IN_DECLARE_VTAB (pParse->declareVtab)
10588 #endif
10589
10590 /*
10591 ** An instance of the following structure can be declared on a stack and used
10592 ** to save the Parse.zAuthContext value so that it can be restored later.
10593 */
10594 struct AuthContext {
10595   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10596   Parse *pParse;              /* The Parse structure */
10597 };
10598
10599 /*
10600 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
10601 */
10602 #define OPFLAG_NCHANGE   1    /* Set to update db->nChange */
10603 #define OPFLAG_LASTROWID 2    /* Set to update db->lastRowid */
10604 #define OPFLAG_ISUPDATE  4    /* This OP_Insert is an sql UPDATE */
10605 #define OPFLAG_APPEND    8    /* This is likely to be an append */
10606
10607 /*
10608  * Each trigger present in the database schema is stored as an instance of
10609  * struct Trigger. 
10610  *
10611  * Pointers to instances of struct Trigger are stored in two ways.
10612  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10613  *    database). This allows Trigger structures to be retrieved by name.
10614  * 2. All triggers associated with a single table form a linked list, using the
10615  *    pNext member of struct Trigger. A pointer to the first element of the
10616  *    linked list is stored as the "pTrigger" member of the associated
10617  *    struct Table.
10618  *
10619  * The "step_list" member points to the first element of a linked list
10620  * containing the SQL statements specified as the trigger program.
10621  */
10622 struct Trigger {
10623   char *name;             /* The name of the trigger                        */
10624   char *table;            /* The table or view to which the trigger applies */
10625   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10626   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10627   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10628   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10629                              the <column-list> is stored here */
10630   Token nameToken;        /* Token containing zName. Use during parsing only */
10631   Schema *pSchema;        /* Schema containing the trigger */
10632   Schema *pTabSchema;     /* Schema containing the table */
10633   TriggerStep *step_list; /* Link list of trigger program steps             */
10634   Trigger *pNext;         /* Next trigger associated with the table */
10635 };
10636
10637 /*
10638 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10639 ** determine which. 
10640 **
10641 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10642 ** In that cases, the constants below can be ORed together.
10643 */
10644 #define TRIGGER_BEFORE  1
10645 #define TRIGGER_AFTER   2
10646
10647 /*
10648  * An instance of struct TriggerStep is used to store a single SQL statement
10649  * that is a part of a trigger-program. 
10650  *
10651  * Instances of struct TriggerStep are stored in a singly linked list (linked
10652  * using the "pNext" member) referenced by the "step_list" member of the 
10653  * associated struct Trigger instance. The first element of the linked list is
10654  * the first step of the trigger-program.
10655  * 
10656  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10657  * "SELECT" statement. The meanings of the other members is determined by the 
10658  * value of "op" as follows:
10659  *
10660  * (op == TK_INSERT)
10661  * orconf    -> stores the ON CONFLICT algorithm
10662  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10663  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10664  * target    -> A token holding the name of the table to insert into.
10665  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10666  *              this stores values to be inserted. Otherwise NULL.
10667  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10668  *              statement, then this stores the column-names to be
10669  *              inserted into.
10670  *
10671  * (op == TK_DELETE)
10672  * target    -> A token holding the name of the table to delete from.
10673  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10674  *              Otherwise NULL.
10675  * 
10676  * (op == TK_UPDATE)
10677  * target    -> A token holding the name of the table to update rows of.
10678  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10679  *              Otherwise NULL.
10680  * pExprList -> A list of the columns to update and the expressions to update
10681  *              them to. See sqlite3Update() documentation of "pChanges"
10682  *              argument.
10683  * 
10684  */
10685 struct TriggerStep {
10686   int op;              /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10687   int orconf;          /* OE_Rollback etc. */
10688   Trigger *pTrig;      /* The trigger that this step is a part of */
10689
10690   Select *pSelect;     /* Valid for SELECT and sometimes 
10691                           INSERT steps (when pExprList == 0) */
10692   Token target;        /* Valid for DELETE, UPDATE, INSERT steps */
10693   Expr *pWhere;        /* Valid for DELETE, UPDATE steps */
10694   ExprList *pExprList; /* Valid for UPDATE statements and sometimes 
10695                            INSERT steps (when pSelect == 0)         */
10696   IdList *pIdList;     /* Valid for INSERT statements only */
10697   TriggerStep *pNext;  /* Next in the link-list */
10698   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10699 };
10700
10701 /*
10702  * An instance of struct TriggerStack stores information required during code
10703  * generation of a single trigger program. While the trigger program is being
10704  * coded, its associated TriggerStack instance is pointed to by the
10705  * "pTriggerStack" member of the Parse structure.
10706  *
10707  * The pTab member points to the table that triggers are being coded on. The 
10708  * newIdx member contains the index of the vdbe cursor that points at the temp
10709  * table that stores the new.* references. If new.* references are not valid
10710  * for the trigger being coded (for example an ON DELETE trigger), then newIdx
10711  * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
10712  *
10713  * The ON CONFLICT policy to be used for the trigger program steps is stored 
10714  * as the orconf member. If this is OE_Default, then the ON CONFLICT clause 
10715  * specified for individual triggers steps is used.
10716  *
10717  * struct TriggerStack has a "pNext" member, to allow linked lists to be
10718  * constructed. When coding nested triggers (triggers fired by other triggers)
10719  * each nested trigger stores its parent trigger's TriggerStack as the "pNext" 
10720  * pointer. Once the nested trigger has been coded, the pNext value is restored
10721  * to the pTriggerStack member of the Parse stucture and coding of the parent
10722  * trigger continues.
10723  *
10724  * Before a nested trigger is coded, the linked list pointed to by the 
10725  * pTriggerStack is scanned to ensure that the trigger is not about to be coded
10726  * recursively. If this condition is detected, the nested trigger is not coded.
10727  */
10728 struct TriggerStack {
10729   Table *pTab;         /* Table that triggers are currently being coded on */
10730   int newIdx;          /* Index of vdbe cursor to "new" temp table */
10731   int oldIdx;          /* Index of vdbe cursor to "old" temp table */
10732   u32 newColMask;
10733   u32 oldColMask;
10734   int orconf;          /* Current orconf policy */
10735   int ignoreJump;      /* where to jump to for a RAISE(IGNORE) */
10736   Trigger *pTrigger;   /* The trigger currently being coded */
10737   TriggerStack *pNext; /* Next trigger down on the trigger stack */
10738 };
10739
10740 /*
10741 ** The following structure contains information used by the sqliteFix...
10742 ** routines as they walk the parse tree to make database references
10743 ** explicit.  
10744 */
10745 typedef struct DbFixer DbFixer;
10746 struct DbFixer {
10747   Parse *pParse;      /* The parsing context.  Error messages written here */
10748   const char *zDb;    /* Make sure all objects are contained in this database */
10749   const char *zType;  /* Type of the container - used for error messages */
10750   const Token *pName; /* Name of the container - used for error messages */
10751 };
10752
10753 /*
10754 ** An objected used to accumulate the text of a string where we
10755 ** do not necessarily know how big the string will be in the end.
10756 */
10757 struct StrAccum {
10758   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10759   char *zBase;         /* A base allocation.  Not from malloc. */
10760   char *zText;         /* The string collected so far */
10761   int  nChar;          /* Length of the string so far */
10762   int  nAlloc;         /* Amount of space allocated in zText */
10763   int  mxAlloc;        /* Maximum allowed string length */
10764   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10765   u8   useMalloc;      /* True if zText is enlargeable using realloc */
10766   u8   tooBig;         /* Becomes true if string size exceeds limits */
10767 };
10768
10769 /*
10770 ** A pointer to this structure is used to communicate information
10771 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10772 */
10773 typedef struct {
10774   sqlite3 *db;        /* The database being initialized */
10775   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10776   char **pzErrMsg;    /* Error message stored here */
10777   int rc;             /* Result code stored here */
10778 } InitData;
10779
10780 /*
10781 ** Structure containing global configuration data for the SQLite library.
10782 **
10783 ** This structure also contains some state information.
10784 */
10785 struct Sqlite3Config {
10786   int bMemstat;                     /* True to enable memory status */
10787   int bCoreMutex;                   /* True to enable core mutexing */
10788   int bFullMutex;                   /* True to enable full mutexing */
10789   int mxStrlen;                     /* Maximum string length */
10790   int szLookaside;                  /* Default lookaside buffer size */
10791   int nLookaside;                   /* Default lookaside buffer count */
10792   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10793   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10794   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10795   void *pHeap;                      /* Heap storage space */
10796   int nHeap;                        /* Size of pHeap[] */
10797   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10798   void *pScratch;                   /* Scratch memory */
10799   int szScratch;                    /* Size of each scratch buffer */
10800   int nScratch;                     /* Number of scratch buffers */
10801   void *pPage;                      /* Page cache memory */
10802   int szPage;                       /* Size of each page in pPage[] */
10803   int nPage;                        /* Number of pages in pPage[] */
10804   int mxParserStack;                /* maximum depth of the parser stack */
10805   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10806   /* The above might be initialized to non-zero.  The following need to always
10807   ** initially be zero, however. */
10808   int isInit;                       /* True after initialization has finished */
10809   int inProgress;                   /* True while initialization in progress */
10810   int isMallocInit;                 /* True after malloc is initialized */
10811   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10812   int nRefInitMutex;                /* Number of users of pInitMutex */
10813 };
10814
10815 /*
10816 ** Context pointer passed down through the tree-walk.
10817 */
10818 struct Walker {
10819   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10820   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10821   Parse *pParse;                            /* Parser context.  */
10822   union {                                   /* Extra data for callback */
10823     NameContext *pNC;                          /* Naming context */
10824     int i;                                     /* Integer value */
10825   } u;
10826 };
10827
10828 /* Forward declarations */
10829 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10830 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10831 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10832 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10833 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10834
10835 /*
10836 ** Return code from the parse-tree walking primitives and their
10837 ** callbacks.
10838 */
10839 #define WRC_Continue    0   /* Continue down into children */
10840 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10841 #define WRC_Abort       2   /* Abandon the tree walk */
10842
10843 /*
10844 ** Assuming zIn points to the first byte of a UTF-8 character,
10845 ** advance zIn to point to the first byte of the next UTF-8 character.
10846 */
10847 #define SQLITE_SKIP_UTF8(zIn) {                        \
10848   if( (*(zIn++))>=0xc0 ){                              \
10849     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10850   }                                                    \
10851 }
10852
10853 /*
10854 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
10855 ** builds) or a function call (for debugging).  If it is a function call,
10856 ** it allows the operator to set a breakpoint at the spot where database
10857 ** corruption is first detected.
10858 */
10859 #ifdef SQLITE_DEBUG
10860 SQLITE_PRIVATE   int sqlite3Corrupt(void);
10861 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
10862 #else
10863 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
10864 #endif
10865
10866 /*
10867 ** The following macros mimic the standard library functions toupper(),
10868 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10869 ** sqlite versions only work for ASCII characters, regardless of locale.
10870 */
10871 #ifdef SQLITE_ASCII
10872 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10873 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10874 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10875 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10876 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10877 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10878 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10879 #else
10880 # include <ctype.h>
10881 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10882 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10883 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10884 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10885 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10886 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10887 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10888 #endif
10889
10890 /*
10891 ** Internal function prototypes
10892 */
10893 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10894 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
10895 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10896 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
10897 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10898
10899 SQLITE_PRIVATE int sqlite3MallocInit(void);
10900 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10901 SQLITE_PRIVATE void *sqlite3Malloc(int);
10902 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10903 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10904 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10905 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10906 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10907 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10908 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10909 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10910 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10911 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10912 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10913 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10914 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10915 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10916 SQLITE_PRIVATE void sqlite3PageFree(void*);
10917 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10918 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10919 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10920
10921 #ifdef SQLITE_ENABLE_MEMSYS3
10922 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10923 #endif
10924 #ifdef SQLITE_ENABLE_MEMSYS5
10925 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10926 #endif
10927
10928
10929 #ifndef SQLITE_MUTEX_OMIT
10930 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10931 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10932 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10933 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10934 #endif
10935
10936 SQLITE_PRIVATE int sqlite3StatusValue(int);
10937 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10938 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10939
10940 SQLITE_PRIVATE int sqlite3IsNaN(double);
10941
10942 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10943 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10944 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10945 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10946 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10947 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10948 #endif
10949 #if defined(SQLITE_TEST)
10950 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10951 #endif
10952 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10953 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10954 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10955 SQLITE_PRIVATE void sqlite3Dequote(char*);
10956 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*);
10957 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10958 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10959 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10960 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10961 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10962 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10963 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10964 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*);
10965 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10966 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
10967 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10968 SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
10969 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10970 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10971 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3*, Expr*);
10972 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10973 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*,Token*);
10974 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10975 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10976 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10977 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10978 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10979 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10980 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10981 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10982 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10983 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10984 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10985 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10986 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10987 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10988 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10989 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
10990 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10991 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10992
10993 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10994 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10995 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10996 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
10997 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10998 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10999 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11000
11001 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11002 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11003 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11004 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11005
11006 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11007
11008 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11009 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11010 #else
11011 # define sqlite3ViewGetColumnNames(A,B) 0
11012 #endif
11013
11014 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11015 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
11016 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11017 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11018 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11019 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11020 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11021 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11022 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11023                                       Token*, Select*, Expr*, IdList*);
11024 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11025 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11026 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11027 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11028 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11029 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11030 SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11031                         Token*, int, int);
11032 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11033 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11034 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11035                          Expr*,ExprList*,int,Expr*,Expr*);
11036 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11037 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11038 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11039 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11040 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11041 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11042 #endif
11043 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11044 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11045 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
11046 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11047 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
11048 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11049 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11050 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
11051 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11052 SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse*,int);
11053 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
11054 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11055 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11056 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11057 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11058 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11059 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11060 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11061 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11062 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11063 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11064 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11065 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11066 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11067 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11068 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11069 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11070 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11071 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11072 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11073 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11074 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*);
11075 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11076 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11077 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11078 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11079 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11080 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11081 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11082 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11083 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11084 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11085 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11086 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11087 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11088 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11089 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11090 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
11091 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11092 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11093 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11094                                      int*,int,int,int,int);
11095 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11096 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11097 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11098 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*);
11099 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*);
11100 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*);
11101 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*);
11102 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11103 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*);
11104 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11105 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11106 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11107 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11108 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11109 #ifdef SQLITE_DEBUG
11110 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
11111 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
11112 #else
11113 # define sqlite3SafetyOn(A) 0
11114 # define sqlite3SafetyOff(A) 0
11115 #endif
11116 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11117 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11118 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11119
11120 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11121 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11122 #endif
11123
11124 #ifndef SQLITE_OMIT_TRIGGER
11125 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11126                            Expr*,int, int);
11127 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11128 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11129 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11130 SQLITE_PRIVATE   int sqlite3TriggersExist(Table*, int, ExprList*);
11131 SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
11132                            int, int, u32*, u32*);
11133   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11134 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11135 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11136 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11137                                         ExprList*,Select*,int);
11138 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, int);
11139 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11140 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11141 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11142 #else
11143 # define sqlite3TriggersExist(B,C,D,E,F) 0
11144 # define sqlite3DeleteTrigger(A,B)
11145 # define sqlite3DropTriggerPtr(A,B)
11146 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11147 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0
11148 #endif
11149
11150 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11151 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11152 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11153 #ifndef SQLITE_OMIT_AUTHORIZATION
11154 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11155 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11156 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11157 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11158 #else
11159 # define sqlite3AuthRead(a,b,c,d)
11160 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11161 # define sqlite3AuthContextPush(a,b,c)
11162 # define sqlite3AuthContextPop(a)  ((void)(a))
11163 #endif
11164 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11165 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11166 SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
11167                        int omitJournal, int nCache, int flags, Btree **ppBtree);
11168 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11169 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11170 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11171 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11172 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11173 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11174 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
11175 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11176 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
11177 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11178 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11179 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8*, const u8**);
11180
11181 /*
11182 ** Routines to read and write variable-length integers.  These used to
11183 ** be defined locally, but now we use the varint routines in the util.c
11184 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11185 ** are coded to assume the single byte case is already handled (which 
11186 ** the MACRO form does).
11187 */
11188 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11189 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11190 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11191 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11192 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11193
11194 /*
11195 ** The header of a record consists of a sequence variable-length integers.
11196 ** These integers are almost always small and are encoded as a single byte.
11197 ** The following macros take advantage this fact to provide a fast encode
11198 ** and decode of the integers in a record header.  It is faster for the common
11199 ** case where the integer is a single byte.  It is a little slower when the
11200 ** integer is two or more bytes.  But overall it is faster.
11201 **
11202 ** The following expressions are equivalent:
11203 **
11204 **     x = sqlite3GetVarint32( A, &B );
11205 **     x = sqlite3PutVarint32( A, B );
11206 **
11207 **     x = getVarint32( A, B );
11208 **     x = putVarint32( A, B );
11209 **
11210 */
11211 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11212 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11213 #define getVarint    sqlite3GetVarint
11214 #define putVarint    sqlite3PutVarint
11215
11216
11217 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
11218 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11219 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11220 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11221 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11222 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
11223 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11224 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11225 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11226 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11227 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11228 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
11229 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
11230 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11231 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
11232 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11233 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11234 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11235
11236 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11237 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11238 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11239                         void(*)(void*));
11240 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11241 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11242 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
11243 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11244 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11245 #ifndef SQLITE_AMALGAMATION
11246 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11247 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11248 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11249 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11250 SQLITE_PRIVATE int sqlite3PendingByte;
11251 #endif
11252 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
11253 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11254 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
11255 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11256 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11257 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11258 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11259 SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *, int, int);
11260 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11261 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11262 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11263 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11264 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
11265 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11266 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11267 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
11268 SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
11269 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11270 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11271 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11272 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11273 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11274 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11275 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11276 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11277 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11278 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
11279 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11280 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11281 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11282 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11283   void (*)(sqlite3_context*,int,sqlite3_value **),
11284   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
11285 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11286 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11287
11288 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11289 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11290 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11291 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11292 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11293
11294 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11295 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11296
11297 /*
11298 ** The interface to the LEMON-generated parser
11299 */
11300 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11301 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11302 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11303 #ifdef YYTRACKMAXSTACKDEPTH
11304 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11305 #endif
11306
11307 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3*);
11308 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11309 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11310 #else
11311 # define sqlite3CloseExtensions(X)
11312 #endif
11313
11314 #ifndef SQLITE_OMIT_SHARED_CACHE
11315 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11316 #else
11317   #define sqlite3TableLock(v,w,x,y,z)
11318 #endif
11319
11320 #ifdef SQLITE_TEST
11321 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11322 #endif
11323
11324 #ifdef SQLITE_OMIT_VIRTUALTABLE
11325 #  define sqlite3VtabClear(X)
11326 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11327 #  define sqlite3VtabRollback(X)
11328 #  define sqlite3VtabCommit(X)
11329 #  define sqlite3VtabInSync(db) 0
11330 #else
11331 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
11332 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11333 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11334 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11335 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11336 #endif
11337 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11338 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
11339 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
11340 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11341 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11342 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11343 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11344 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11345 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11346 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11347 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
11348 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11349 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11350 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11351 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11352 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11353 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11354
11355
11356 /*
11357 ** Available fault injectors.  Should be numbered beginning with 0.
11358 */
11359 #define SQLITE_FAULTINJECTOR_MALLOC     0
11360 #define SQLITE_FAULTINJECTOR_COUNT      1
11361
11362 /*
11363 ** The interface to the code in fault.c used for identifying "benign"
11364 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11365 ** is not defined.
11366 */
11367 #ifndef SQLITE_OMIT_BUILTIN_TEST
11368 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11369 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11370 #else
11371   #define sqlite3BeginBenignMalloc()
11372   #define sqlite3EndBenignMalloc()
11373 #endif
11374
11375 #define IN_INDEX_ROWID           1
11376 #define IN_INDEX_EPH             2
11377 #define IN_INDEX_INDEX           3
11378 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11379
11380 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11381 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11382 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11383 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11384 #else
11385   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11386 #endif
11387
11388 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11389 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11390 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11391
11392 #if SQLITE_MAX_EXPR_DEPTH>0
11393 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11394 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11395 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11396 #else
11397   #define sqlite3ExprSetHeight(x,y)
11398   #define sqlite3SelectExprHeight(x) 0
11399   #define sqlite3ExprCheckHeight(x,y)
11400 #endif
11401
11402 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11403 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11404
11405 #ifdef SQLITE_SSE
11406 #include "sseInt.h"
11407 #endif
11408
11409 #ifdef SQLITE_DEBUG
11410 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11411 #endif
11412
11413 /*
11414 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11415 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11416 ** print I/O tracing messages. 
11417 */
11418 #ifdef SQLITE_ENABLE_IOTRACE
11419 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11420 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11421 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11422 #else
11423 # define IOTRACE(A)
11424 # define sqlite3VdbeIOTraceSql(X)
11425 #endif
11426
11427 #endif
11428
11429 /************** End of sqliteInt.h *******************************************/
11430 /************** Begin file global.c ******************************************/
11431 /*
11432 ** 2008 June 13
11433 **
11434 ** The author disclaims copyright to this source code.  In place of
11435 ** a legal notice, here is a blessing:
11436 **
11437 **    May you do good and not evil.
11438 **    May you find forgiveness for yourself and forgive others.
11439 **    May you share freely, never taking more than you give.
11440 **
11441 *************************************************************************
11442 **
11443 ** This file contains definitions of global variables and contants.
11444 **
11445 ** $Id: global.c,v 1.12 2009/02/05 16:31:46 drh Exp $
11446 */
11447
11448
11449 /* An array to map all upper-case characters into their corresponding
11450 ** lower-case character. 
11451 **
11452 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11453 ** handle case conversions for the UTF character set since the tables
11454 ** involved are nearly as big or bigger than SQLite itself.
11455 */
11456 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11457 #ifdef SQLITE_ASCII
11458       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11459      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11460      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11461      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11462     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11463     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11464     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11465     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11466     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11467     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11468     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11469     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11470     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11471     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11472     252,253,254,255
11473 #endif
11474 #ifdef SQLITE_EBCDIC
11475       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11476      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11477      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11478      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11479      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11480      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11481      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11482     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11483     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11484     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11485     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11486     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11487     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11488     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11489     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11490     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11491 #endif
11492 };
11493
11494 /*
11495 ** The following 256 byte lookup table is used to support SQLites built-in
11496 ** equivalents to the following standard library functions:
11497 **
11498 **   isspace()                        0x01
11499 **   isalpha()                        0x02
11500 **   isdigit()                        0x04
11501 **   isalnum()                        0x06
11502 **   isxdigit()                       0x08
11503 **   toupper()                        0x20
11504 **
11505 ** Bit 0x20 is set if the mapped character requires translation to upper
11506 ** case. i.e. if the character is a lower-case ASCII character.
11507 ** If x is a lower-case ASCII character, then its upper-case equivalent
11508 ** is (x - 0x20). Therefore toupper() can be implemented as:
11509 **
11510 **   (x & ~(map[x]&0x20))
11511 **
11512 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11513 ** array. tolower() is used more often than toupper() by SQLite.
11514 **
11515 ** SQLite's versions are identical to the standard versions assuming a
11516 ** locale of "C". They are implemented as macros in sqliteInt.h.
11517 */
11518 #ifdef SQLITE_ASCII
11519 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11520   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11521   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11522   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11523   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11524   0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11525   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11526   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11527   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11528
11529   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11530   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11531   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11532   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 58..5f    XYZ[\]^_ */
11533   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11534   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11535   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11536   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11537
11538   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 80..87    ........ */
11539   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 88..8f    ........ */
11540   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 90..97    ........ */
11541   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 98..9f    ........ */
11542   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a0..a7    ........ */
11543   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a8..af    ........ */
11544   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b0..b7    ........ */
11545   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b8..bf    ........ */
11546
11547   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c0..c7    ........ */
11548   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c8..cf    ........ */
11549   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d0..d7    ........ */
11550   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d8..df    ........ */
11551   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e0..e7    ........ */
11552   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e8..ef    ........ */
11553   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* f0..f7    ........ */
11554   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00   /* f8..ff    ........ */
11555 };
11556 #endif
11557
11558
11559
11560 /*
11561 ** The following singleton contains the global configuration for
11562 ** the SQLite library.
11563 */
11564 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11565    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11566    1,                         /* bCoreMutex */
11567    SQLITE_THREADSAFE==1,      /* bFullMutex */
11568    0x7ffffffe,                /* mxStrlen */
11569    100,                       /* szLookaside */
11570    500,                       /* nLookaside */
11571    {0,0,0,0,0,0,0,0},         /* m */
11572    {0,0,0,0,0,0,0,0,0},       /* mutex */
11573    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11574    (void*)0,                  /* pHeap */
11575    0,                         /* nHeap */
11576    0, 0,                      /* mnHeap, mxHeap */
11577    (void*)0,                  /* pScratch */
11578    0,                         /* szScratch */
11579    0,                         /* nScratch */
11580    (void*)0,                  /* pPage */
11581    0,                         /* szPage */
11582    0,                         /* nPage */
11583    0,                         /* mxParserStack */
11584    0,                         /* sharedCacheEnabled */
11585    /* All the rest need to always be zero */
11586    0,                         /* isInit */
11587    0,                         /* inProgress */
11588    0,                         /* isMallocInit */
11589    0,                         /* pInitMutex */
11590    0,                         /* nRefInitMutex */
11591 };
11592
11593
11594 /*
11595 ** Hash table for global functions - functions common to all
11596 ** database connections.  After initialization, this table is
11597 ** read-only.
11598 */
11599 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11600
11601 /*
11602 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11603 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11604 ** the database page that contains the pending byte.  It never attempts
11605 ** to read or write that page.  The pending byte page is set assign
11606 ** for use by the VFS layers as space for managing file locks.
11607 **
11608 ** During testing, it is often desirable to move the pending byte to
11609 ** a different position in the file.  This allows code that has to
11610 ** deal with the pending byte to run on files that are much smaller
11611 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11612 ** move the pending byte.
11613 **
11614 ** IMPORTANT:  Changing the pending byte to any value other than
11615 ** 0x40000000 results in an incompatible database file format!
11616 ** Changing the pending byte during operating results in undefined
11617 ** and dileterious behavior.
11618 */
11619 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11620
11621 /************** End of global.c **********************************************/
11622 /************** Begin file status.c ******************************************/
11623 /*
11624 ** 2008 June 18
11625 **
11626 ** The author disclaims copyright to this source code.  In place of
11627 ** a legal notice, here is a blessing:
11628 **
11629 **    May you do good and not evil.
11630 **    May you find forgiveness for yourself and forgive others.
11631 **    May you share freely, never taking more than you give.
11632 **
11633 *************************************************************************
11634 **
11635 ** This module implements the sqlite3_status() interface and related
11636 ** functionality.
11637 **
11638 ** $Id: status.c,v 1.9 2008/09/02 00:52:52 drh Exp $
11639 */
11640
11641 /*
11642 ** Variables in which to record status information.
11643 */
11644 typedef struct sqlite3StatType sqlite3StatType;
11645 static SQLITE_WSD struct sqlite3StatType {
11646   int nowValue[9];         /* Current value */
11647   int mxValue[9];          /* Maximum value */
11648 } sqlite3Stat = { {0,}, {0,} };
11649
11650
11651 /* The "wsdStat" macro will resolve to the status information
11652 ** state vector.  If writable static data is unsupported on the target,
11653 ** we have to locate the state vector at run-time.  In the more common
11654 ** case where writable static data is supported, wsdStat can refer directly
11655 ** to the "sqlite3Stat" state vector declared above.
11656 */
11657 #ifdef SQLITE_OMIT_WSD
11658 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11659 # define wsdStat x[0]
11660 #else
11661 # define wsdStatInit
11662 # define wsdStat sqlite3Stat
11663 #endif
11664
11665 /*
11666 ** Return the current value of a status parameter.
11667 */
11668 SQLITE_PRIVATE int sqlite3StatusValue(int op){
11669   wsdStatInit;
11670   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11671   return wsdStat.nowValue[op];
11672 }
11673
11674 /*
11675 ** Add N to the value of a status record.  It is assumed that the
11676 ** caller holds appropriate locks.
11677 */
11678 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11679   wsdStatInit;
11680   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11681   wsdStat.nowValue[op] += N;
11682   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11683     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11684   }
11685 }
11686
11687 /*
11688 ** Set the value of a status to X.
11689 */
11690 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11691   wsdStatInit;
11692   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11693   wsdStat.nowValue[op] = X;
11694   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11695     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11696   }
11697 }
11698
11699 /*
11700 ** Query status information.
11701 **
11702 ** This implementation assumes that reading or writing an aligned
11703 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11704 ** then this routine is not threadsafe.
11705 */
11706 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11707   wsdStatInit;
11708   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11709     return SQLITE_MISUSE;
11710   }
11711   *pCurrent = wsdStat.nowValue[op];
11712   *pHighwater = wsdStat.mxValue[op];
11713   if( resetFlag ){
11714     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11715   }
11716   return SQLITE_OK;
11717 }
11718
11719 /*
11720 ** Query status information for a single database connection
11721 */
11722 SQLITE_API int sqlite3_db_status(
11723   sqlite3 *db,          /* The database connection whose status is desired */
11724   int op,               /* Status verb */
11725   int *pCurrent,        /* Write current value here */
11726   int *pHighwater,      /* Write high-water mark here */
11727   int resetFlag         /* Reset high-water mark if true */
11728 ){
11729   switch( op ){
11730     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11731       *pCurrent = db->lookaside.nOut;
11732       *pHighwater = db->lookaside.mxOut;
11733       if( resetFlag ){
11734         db->lookaside.mxOut = db->lookaside.nOut;
11735       }
11736       break;
11737     }
11738     default: {
11739       return SQLITE_ERROR;
11740     }
11741   }
11742   return SQLITE_OK;
11743 }
11744
11745 /************** End of status.c **********************************************/
11746 /************** Begin file date.c ********************************************/
11747 /*
11748 ** 2003 October 31
11749 **
11750 ** The author disclaims copyright to this source code.  In place of
11751 ** a legal notice, here is a blessing:
11752 **
11753 **    May you do good and not evil.
11754 **    May you find forgiveness for yourself and forgive others.
11755 **    May you share freely, never taking more than you give.
11756 **
11757 *************************************************************************
11758 ** This file contains the C functions that implement date and time
11759 ** functions for SQLite.  
11760 **
11761 ** There is only one exported symbol in this file - the function
11762 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11763 ** All other code has file scope.
11764 **
11765 ** $Id: date.c,v 1.103 2009/02/04 03:59:25 shane Exp $
11766 **
11767 ** SQLite processes all times and dates as Julian Day numbers.  The
11768 ** dates and times are stored as the number of days since noon
11769 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11770 ** calendar system. 
11771 **
11772 ** 1970-01-01 00:00:00 is JD 2440587.5
11773 ** 2000-01-01 00:00:00 is JD 2451544.5
11774 **
11775 ** This implemention requires years to be expressed as a 4-digit number
11776 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11777 ** be represented, even though julian day numbers allow a much wider
11778 ** range of dates.
11779 **
11780 ** The Gregorian calendar system is used for all dates and times,
11781 ** even those that predate the Gregorian calendar.  Historians usually
11782 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11783 ** dates afterwards, depending on locale.  Beware of this difference.
11784 **
11785 ** The conversion algorithms are implemented based on descriptions
11786 ** in the following text:
11787 **
11788 **      Jean Meeus
11789 **      Astronomical Algorithms, 2nd Edition, 1998
11790 **      ISBM 0-943396-61-1
11791 **      Willmann-Bell, Inc
11792 **      Richmond, Virginia (USA)
11793 */
11794 #include <time.h>
11795
11796 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11797
11798 /*
11799 ** On recent Windows platforms, the localtime_s() function is available
11800 ** as part of the "Secure CRT". It is essentially equivalent to 
11801 ** localtime_r() available under most POSIX platforms, except that the 
11802 ** order of the parameters is reversed.
11803 **
11804 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11805 **
11806 ** If the user has not indicated to use localtime_r() or localtime_s()
11807 ** already, check for an MSVC build environment that provides 
11808 ** localtime_s().
11809 */
11810 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11811      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11812 #define HAVE_LOCALTIME_S 1
11813 #endif
11814
11815 /*
11816 ** A structure for holding a single date and time.
11817 */
11818 typedef struct DateTime DateTime;
11819 struct DateTime {
11820   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11821   int Y, M, D;       /* Year, month, and day */
11822   int h, m;          /* Hour and minutes */
11823   int tz;            /* Timezone offset in minutes */
11824   double s;          /* Seconds */
11825   char validYMD;     /* True (1) if Y,M,D are valid */
11826   char validHMS;     /* True (1) if h,m,s are valid */
11827   char validJD;      /* True (1) if iJD is valid */
11828   char validTZ;      /* True (1) if tz is valid */
11829 };
11830
11831
11832 /*
11833 ** Convert zDate into one or more integers.  Additional arguments
11834 ** come in groups of 5 as follows:
11835 **
11836 **       N       number of digits in the integer
11837 **       min     minimum allowed value of the integer
11838 **       max     maximum allowed value of the integer
11839 **       nextC   first character after the integer
11840 **       pVal    where to write the integers value.
11841 **
11842 ** Conversions continue until one with nextC==0 is encountered.
11843 ** The function returns the number of successful conversions.
11844 */
11845 static int getDigits(const char *zDate, ...){
11846   va_list ap;
11847   int val;
11848   int N;
11849   int min;
11850   int max;
11851   int nextC;
11852   int *pVal;
11853   int cnt = 0;
11854   va_start(ap, zDate);
11855   do{
11856     N = va_arg(ap, int);
11857     min = va_arg(ap, int);
11858     max = va_arg(ap, int);
11859     nextC = va_arg(ap, int);
11860     pVal = va_arg(ap, int*);
11861     val = 0;
11862     while( N-- ){
11863       if( !sqlite3Isdigit(*zDate) ){
11864         goto end_getDigits;
11865       }
11866       val = val*10 + *zDate - '0';
11867       zDate++;
11868     }
11869     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11870       goto end_getDigits;
11871     }
11872     *pVal = val;
11873     zDate++;
11874     cnt++;
11875   }while( nextC );
11876 end_getDigits:
11877   va_end(ap);
11878   return cnt;
11879 }
11880
11881 /*
11882 ** Read text from z[] and convert into a floating point number.  Return
11883 ** the number of digits converted.
11884 */
11885 #define getValue sqlite3AtoF
11886
11887 /*
11888 ** Parse a timezone extension on the end of a date-time.
11889 ** The extension is of the form:
11890 **
11891 **        (+/-)HH:MM
11892 **
11893 ** Or the "zulu" notation:
11894 **
11895 **        Z
11896 **
11897 ** If the parse is successful, write the number of minutes
11898 ** of change in p->tz and return 0.  If a parser error occurs,
11899 ** return non-zero.
11900 **
11901 ** A missing specifier is not considered an error.
11902 */
11903 static int parseTimezone(const char *zDate, DateTime *p){
11904   int sgn = 0;
11905   int nHr, nMn;
11906   int c;
11907   while( sqlite3Isspace(*zDate) ){ zDate++; }
11908   p->tz = 0;
11909   c = *zDate;
11910   if( c=='-' ){
11911     sgn = -1;
11912   }else if( c=='+' ){
11913     sgn = +1;
11914   }else if( c=='Z' || c=='z' ){
11915     zDate++;
11916     goto zulu_time;
11917   }else{
11918     return c!=0;
11919   }
11920   zDate++;
11921   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11922     return 1;
11923   }
11924   zDate += 5;
11925   p->tz = sgn*(nMn + nHr*60);
11926 zulu_time:
11927   while( sqlite3Isspace(*zDate) ){ zDate++; }
11928   return *zDate!=0;
11929 }
11930
11931 /*
11932 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11933 ** The HH, MM, and SS must each be exactly 2 digits.  The
11934 ** fractional seconds FFFF can be one or more digits.
11935 **
11936 ** Return 1 if there is a parsing error and 0 on success.
11937 */
11938 static int parseHhMmSs(const char *zDate, DateTime *p){
11939   int h, m, s;
11940   double ms = 0.0;
11941   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11942     return 1;
11943   }
11944   zDate += 5;
11945   if( *zDate==':' ){
11946     zDate++;
11947     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11948       return 1;
11949     }
11950     zDate += 2;
11951     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11952       double rScale = 1.0;
11953       zDate++;
11954       while( sqlite3Isdigit(*zDate) ){
11955         ms = ms*10.0 + *zDate - '0';
11956         rScale *= 10.0;
11957         zDate++;
11958       }
11959       ms /= rScale;
11960     }
11961   }else{
11962     s = 0;
11963   }
11964   p->validJD = 0;
11965   p->validHMS = 1;
11966   p->h = h;
11967   p->m = m;
11968   p->s = s + ms;
11969   if( parseTimezone(zDate, p) ) return 1;
11970   p->validTZ = (p->tz!=0)?1:0;
11971   return 0;
11972 }
11973
11974 /*
11975 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11976 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11977 **
11978 ** Reference:  Meeus page 61
11979 */
11980 static void computeJD(DateTime *p){
11981   int Y, M, D, A, B, X1, X2;
11982
11983   if( p->validJD ) return;
11984   if( p->validYMD ){
11985     Y = p->Y;
11986     M = p->M;
11987     D = p->D;
11988   }else{
11989     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11990     M = 1;
11991     D = 1;
11992   }
11993   if( M<=2 ){
11994     Y--;
11995     M += 12;
11996   }
11997   A = Y/100;
11998   B = 2 - A + (A/4);
11999   X1 = 36525*(Y+4716)/100;
12000   X2 = 306001*(M+1)/10000;
12001   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12002   p->validJD = 1;
12003   if( p->validHMS ){
12004     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12005     if( p->validTZ ){
12006       p->iJD -= p->tz*60000;
12007       p->validYMD = 0;
12008       p->validHMS = 0;
12009       p->validTZ = 0;
12010     }
12011   }
12012 }
12013
12014 /*
12015 ** Parse dates of the form
12016 **
12017 **     YYYY-MM-DD HH:MM:SS.FFF
12018 **     YYYY-MM-DD HH:MM:SS
12019 **     YYYY-MM-DD HH:MM
12020 **     YYYY-MM-DD
12021 **
12022 ** Write the result into the DateTime structure and return 0
12023 ** on success and 1 if the input string is not a well-formed
12024 ** date.
12025 */
12026 static int parseYyyyMmDd(const char *zDate, DateTime *p){
12027   int Y, M, D, neg;
12028
12029   if( zDate[0]=='-' ){
12030     zDate++;
12031     neg = 1;
12032   }else{
12033     neg = 0;
12034   }
12035   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12036     return 1;
12037   }
12038   zDate += 10;
12039   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12040   if( parseHhMmSs(zDate, p)==0 ){
12041     /* We got the time */
12042   }else if( *zDate==0 ){
12043     p->validHMS = 0;
12044   }else{
12045     return 1;
12046   }
12047   p->validJD = 0;
12048   p->validYMD = 1;
12049   p->Y = neg ? -Y : Y;
12050   p->M = M;
12051   p->D = D;
12052   if( p->validTZ ){
12053     computeJD(p);
12054   }
12055   return 0;
12056 }
12057
12058 /*
12059 ** Set the time to the current time reported by the VFS
12060 */
12061 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12062   double r;
12063   sqlite3 *db = sqlite3_context_db_handle(context);
12064   sqlite3OsCurrentTime(db->pVfs, &r);
12065   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12066   p->validJD = 1;
12067 }
12068
12069 /*
12070 ** Attempt to parse the given string into a Julian Day Number.  Return
12071 ** the number of errors.
12072 **
12073 ** The following are acceptable forms for the input string:
12074 **
12075 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12076 **      DDDD.DD 
12077 **      now
12078 **
12079 ** In the first form, the +/-HH:MM is always optional.  The fractional
12080 ** seconds extension (the ".FFF") is optional.  The seconds portion
12081 ** (":SS.FFF") is option.  The year and date can be omitted as long
12082 ** as there is a time string.  The time string can be omitted as long
12083 ** as there is a year and date.
12084 */
12085 static int parseDateOrTime(
12086   sqlite3_context *context, 
12087   const char *zDate, 
12088   DateTime *p
12089 ){
12090   if( parseYyyyMmDd(zDate,p)==0 ){
12091     return 0;
12092   }else if( parseHhMmSs(zDate, p)==0 ){
12093     return 0;
12094   }else if( sqlite3StrICmp(zDate,"now")==0){
12095     setDateTimeToCurrent(context, p);
12096     return 0;
12097   }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
12098     double r;
12099     getValue(zDate, &r);
12100     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12101     p->validJD = 1;
12102     return 0;
12103   }
12104   return 1;
12105 }
12106
12107 /*
12108 ** Compute the Year, Month, and Day from the julian day number.
12109 */
12110 static void computeYMD(DateTime *p){
12111   int Z, A, B, C, D, E, X1;
12112   if( p->validYMD ) return;
12113   if( !p->validJD ){
12114     p->Y = 2000;
12115     p->M = 1;
12116     p->D = 1;
12117   }else{
12118     Z = (int)((p->iJD + 43200000)/86400000);
12119     A = (int)((Z - 1867216.25)/36524.25);
12120     A = Z + 1 + A - (A/4);
12121     B = A + 1524;
12122     C = (int)((B - 122.1)/365.25);
12123     D = (36525*C)/100;
12124     E = (int)((B-D)/30.6001);
12125     X1 = (int)(30.6001*E);
12126     p->D = B - D - X1;
12127     p->M = E<14 ? E-1 : E-13;
12128     p->Y = p->M>2 ? C - 4716 : C - 4715;
12129   }
12130   p->validYMD = 1;
12131 }
12132
12133 /*
12134 ** Compute the Hour, Minute, and Seconds from the julian day number.
12135 */
12136 static void computeHMS(DateTime *p){
12137   int s;
12138   if( p->validHMS ) return;
12139   computeJD(p);
12140   s = (int)((p->iJD + 43200000) % 86400000);
12141   p->s = s/1000.0;
12142   s = (int)p->s;
12143   p->s -= s;
12144   p->h = s/3600;
12145   s -= p->h*3600;
12146   p->m = s/60;
12147   p->s += s - p->m*60;
12148   p->validHMS = 1;
12149 }
12150
12151 /*
12152 ** Compute both YMD and HMS
12153 */
12154 static void computeYMD_HMS(DateTime *p){
12155   computeYMD(p);
12156   computeHMS(p);
12157 }
12158
12159 /*
12160 ** Clear the YMD and HMS and the TZ
12161 */
12162 static void clearYMD_HMS_TZ(DateTime *p){
12163   p->validYMD = 0;
12164   p->validHMS = 0;
12165   p->validTZ = 0;
12166 }
12167
12168 #ifndef SQLITE_OMIT_LOCALTIME
12169 /*
12170 ** Compute the difference (in milliseconds)
12171 ** between localtime and UTC (a.k.a. GMT)
12172 ** for the time value p where p is in UTC.
12173 */
12174 static sqlite3_int64 localtimeOffset(DateTime *p){
12175   DateTime x, y;
12176   time_t t;
12177   x = *p;
12178   computeYMD_HMS(&x);
12179   if( x.Y<1971 || x.Y>=2038 ){
12180     x.Y = 2000;
12181     x.M = 1;
12182     x.D = 1;
12183     x.h = 0;
12184     x.m = 0;
12185     x.s = 0.0;
12186   } else {
12187     int s = (int)(x.s + 0.5);
12188     x.s = s;
12189   }
12190   x.tz = 0;
12191   x.validJD = 0;
12192   computeJD(&x);
12193   t = x.iJD/1000 - 21086676*(i64)10000;
12194 #ifdef HAVE_LOCALTIME_R
12195   {
12196     struct tm sLocal;
12197     localtime_r(&t, &sLocal);
12198     y.Y = sLocal.tm_year + 1900;
12199     y.M = sLocal.tm_mon + 1;
12200     y.D = sLocal.tm_mday;
12201     y.h = sLocal.tm_hour;
12202     y.m = sLocal.tm_min;
12203     y.s = sLocal.tm_sec;
12204   }
12205 #elif defined(HAVE_LOCALTIME_S)
12206   {
12207     struct tm sLocal;
12208     localtime_s(&sLocal, &t);
12209     y.Y = sLocal.tm_year + 1900;
12210     y.M = sLocal.tm_mon + 1;
12211     y.D = sLocal.tm_mday;
12212     y.h = sLocal.tm_hour;
12213     y.m = sLocal.tm_min;
12214     y.s = sLocal.tm_sec;
12215   }
12216 #else
12217   {
12218     struct tm *pTm;
12219     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12220     pTm = localtime(&t);
12221     y.Y = pTm->tm_year + 1900;
12222     y.M = pTm->tm_mon + 1;
12223     y.D = pTm->tm_mday;
12224     y.h = pTm->tm_hour;
12225     y.m = pTm->tm_min;
12226     y.s = pTm->tm_sec;
12227     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12228   }
12229 #endif
12230   y.validYMD = 1;
12231   y.validHMS = 1;
12232   y.validJD = 0;
12233   y.validTZ = 0;
12234   computeJD(&y);
12235   return y.iJD - x.iJD;
12236 }
12237 #endif /* SQLITE_OMIT_LOCALTIME */
12238
12239 /*
12240 ** Process a modifier to a date-time stamp.  The modifiers are
12241 ** as follows:
12242 **
12243 **     NNN days
12244 **     NNN hours
12245 **     NNN minutes
12246 **     NNN.NNNN seconds
12247 **     NNN months
12248 **     NNN years
12249 **     start of month
12250 **     start of year
12251 **     start of week
12252 **     start of day
12253 **     weekday N
12254 **     unixepoch
12255 **     localtime
12256 **     utc
12257 **
12258 ** Return 0 on success and 1 if there is any kind of error.
12259 */
12260 static int parseModifier(const char *zMod, DateTime *p){
12261   int rc = 1;
12262   int n;
12263   double r;
12264   char *z, zBuf[30];
12265   z = zBuf;
12266   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12267     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12268   }
12269   z[n] = 0;
12270   switch( z[0] ){
12271 #ifndef SQLITE_OMIT_LOCALTIME
12272     case 'l': {
12273       /*    localtime
12274       **
12275       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12276       ** show local time.
12277       */
12278       if( strcmp(z, "localtime")==0 ){
12279         computeJD(p);
12280         p->iJD += localtimeOffset(p);
12281         clearYMD_HMS_TZ(p);
12282         rc = 0;
12283       }
12284       break;
12285     }
12286 #endif
12287     case 'u': {
12288       /*
12289       **    unixepoch
12290       **
12291       ** Treat the current value of p->iJD as the number of
12292       ** seconds since 1970.  Convert to a real julian day number.
12293       */
12294       if( strcmp(z, "unixepoch")==0 && p->validJD ){
12295         p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
12296         clearYMD_HMS_TZ(p);
12297         rc = 0;
12298       }
12299 #ifndef SQLITE_OMIT_LOCALTIME
12300       else if( strcmp(z, "utc")==0 ){
12301         sqlite3_int64 c1;
12302         computeJD(p);
12303         c1 = localtimeOffset(p);
12304         p->iJD -= c1;
12305         clearYMD_HMS_TZ(p);
12306         p->iJD += c1 - localtimeOffset(p);
12307         rc = 0;
12308       }
12309 #endif
12310       break;
12311     }
12312     case 'w': {
12313       /*
12314       **    weekday N
12315       **
12316       ** Move the date to the same time on the next occurrence of
12317       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12318       ** date is already on the appropriate weekday, this is a no-op.
12319       */
12320       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12321                  && (n=(int)r)==r && n>=0 && r<7 ){
12322         sqlite3_int64 Z;
12323         computeYMD_HMS(p);
12324         p->validTZ = 0;
12325         p->validJD = 0;
12326         computeJD(p);
12327         Z = ((p->iJD + 129600000)/86400000) % 7;
12328         if( Z>n ) Z -= 7;
12329         p->iJD += (n - Z)*86400000;
12330         clearYMD_HMS_TZ(p);
12331         rc = 0;
12332       }
12333       break;
12334     }
12335     case 's': {
12336       /*
12337       **    start of TTTTT
12338       **
12339       ** Move the date backwards to the beginning of the current day,
12340       ** or month or year.
12341       */
12342       if( strncmp(z, "start of ", 9)!=0 ) break;
12343       z += 9;
12344       computeYMD(p);
12345       p->validHMS = 1;
12346       p->h = p->m = 0;
12347       p->s = 0.0;
12348       p->validTZ = 0;
12349       p->validJD = 0;
12350       if( strcmp(z,"month")==0 ){
12351         p->D = 1;
12352         rc = 0;
12353       }else if( strcmp(z,"year")==0 ){
12354         computeYMD(p);
12355         p->M = 1;
12356         p->D = 1;
12357         rc = 0;
12358       }else if( strcmp(z,"day")==0 ){
12359         rc = 0;
12360       }
12361       break;
12362     }
12363     case '+':
12364     case '-':
12365     case '0':
12366     case '1':
12367     case '2':
12368     case '3':
12369     case '4':
12370     case '5':
12371     case '6':
12372     case '7':
12373     case '8':
12374     case '9': {
12375       double rRounder;
12376       n = getValue(z, &r);
12377       assert( n>=1 );
12378       if( z[n]==':' ){
12379         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12380         ** specified number of hours, minutes, seconds, and fractional seconds
12381         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12382         ** omitted.
12383         */
12384         const char *z2 = z;
12385         DateTime tx;
12386         sqlite3_int64 day;
12387         if( !sqlite3Isdigit(*z2) ) z2++;
12388         memset(&tx, 0, sizeof(tx));
12389         if( parseHhMmSs(z2, &tx) ) break;
12390         computeJD(&tx);
12391         tx.iJD -= 43200000;
12392         day = tx.iJD/86400000;
12393         tx.iJD -= day*86400000;
12394         if( z[0]=='-' ) tx.iJD = -tx.iJD;
12395         computeJD(p);
12396         clearYMD_HMS_TZ(p);
12397         p->iJD += tx.iJD;
12398         rc = 0;
12399         break;
12400       }
12401       z += n;
12402       while( sqlite3Isspace(*z) ) z++;
12403       n = sqlite3Strlen30(z);
12404       if( n>10 || n<3 ) break;
12405       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12406       computeJD(p);
12407       rc = 0;
12408       rRounder = r<0 ? -0.5 : +0.5;
12409       if( n==3 && strcmp(z,"day")==0 ){
12410         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12411       }else if( n==4 && strcmp(z,"hour")==0 ){
12412         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12413       }else if( n==6 && strcmp(z,"minute")==0 ){
12414         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12415       }else if( n==6 && strcmp(z,"second")==0 ){
12416         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12417       }else if( n==5 && strcmp(z,"month")==0 ){
12418         int x, y;
12419         computeYMD_HMS(p);
12420         p->M += (int)r;
12421         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12422         p->Y += x;
12423         p->M -= x*12;
12424         p->validJD = 0;
12425         computeJD(p);
12426         y = (int)r;
12427         if( y!=r ){
12428           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12429         }
12430       }else if( n==4 && strcmp(z,"year")==0 ){
12431         int y = (int)r;
12432         computeYMD_HMS(p);
12433         p->Y += y;
12434         p->validJD = 0;
12435         computeJD(p);
12436         if( y!=r ){
12437           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12438         }
12439       }else{
12440         rc = 1;
12441       }
12442       clearYMD_HMS_TZ(p);
12443       break;
12444     }
12445     default: {
12446       break;
12447     }
12448   }
12449   return rc;
12450 }
12451
12452 /*
12453 ** Process time function arguments.  argv[0] is a date-time stamp.
12454 ** argv[1] and following are modifiers.  Parse them all and write
12455 ** the resulting time into the DateTime structure p.  Return 0
12456 ** on success and 1 if there are any errors.
12457 **
12458 ** If there are zero parameters (if even argv[0] is undefined)
12459 ** then assume a default value of "now" for argv[0].
12460 */
12461 static int isDate(
12462   sqlite3_context *context, 
12463   int argc, 
12464   sqlite3_value **argv, 
12465   DateTime *p
12466 ){
12467   int i;
12468   const unsigned char *z;
12469   int eType;
12470   memset(p, 0, sizeof(*p));
12471   if( argc==0 ){
12472     setDateTimeToCurrent(context, p);
12473   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12474                    || eType==SQLITE_INTEGER ){
12475     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12476     p->validJD = 1;
12477   }else{
12478     z = sqlite3_value_text(argv[0]);
12479     if( !z || parseDateOrTime(context, (char*)z, p) ){
12480       return 1;
12481     }
12482   }
12483   for(i=1; i<argc; i++){
12484     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12485       return 1;
12486     }
12487   }
12488   return 0;
12489 }
12490
12491
12492 /*
12493 ** The following routines implement the various date and time functions
12494 ** of SQLite.
12495 */
12496
12497 /*
12498 **    julianday( TIMESTRING, MOD, MOD, ...)
12499 **
12500 ** Return the julian day number of the date specified in the arguments
12501 */
12502 static void juliandayFunc(
12503   sqlite3_context *context,
12504   int argc,
12505   sqlite3_value **argv
12506 ){
12507   DateTime x;
12508   if( isDate(context, argc, argv, &x)==0 ){
12509     computeJD(&x);
12510     sqlite3_result_double(context, x.iJD/86400000.0);
12511   }
12512 }
12513
12514 /*
12515 **    datetime( TIMESTRING, MOD, MOD, ...)
12516 **
12517 ** Return YYYY-MM-DD HH:MM:SS
12518 */
12519 static void datetimeFunc(
12520   sqlite3_context *context,
12521   int argc,
12522   sqlite3_value **argv
12523 ){
12524   DateTime x;
12525   if( isDate(context, argc, argv, &x)==0 ){
12526     char zBuf[100];
12527     computeYMD_HMS(&x);
12528     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12529                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12530     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12531   }
12532 }
12533
12534 /*
12535 **    time( TIMESTRING, MOD, MOD, ...)
12536 **
12537 ** Return HH:MM:SS
12538 */
12539 static void timeFunc(
12540   sqlite3_context *context,
12541   int argc,
12542   sqlite3_value **argv
12543 ){
12544   DateTime x;
12545   if( isDate(context, argc, argv, &x)==0 ){
12546     char zBuf[100];
12547     computeHMS(&x);
12548     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12549     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12550   }
12551 }
12552
12553 /*
12554 **    date( TIMESTRING, MOD, MOD, ...)
12555 **
12556 ** Return YYYY-MM-DD
12557 */
12558 static void dateFunc(
12559   sqlite3_context *context,
12560   int argc,
12561   sqlite3_value **argv
12562 ){
12563   DateTime x;
12564   if( isDate(context, argc, argv, &x)==0 ){
12565     char zBuf[100];
12566     computeYMD(&x);
12567     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12568     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12569   }
12570 }
12571
12572 /*
12573 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12574 **
12575 ** Return a string described by FORMAT.  Conversions as follows:
12576 **
12577 **   %d  day of month
12578 **   %f  ** fractional seconds  SS.SSS
12579 **   %H  hour 00-24
12580 **   %j  day of year 000-366
12581 **   %J  ** Julian day number
12582 **   %m  month 01-12
12583 **   %M  minute 00-59
12584 **   %s  seconds since 1970-01-01
12585 **   %S  seconds 00-59
12586 **   %w  day of week 0-6  sunday==0
12587 **   %W  week of year 00-53
12588 **   %Y  year 0000-9999
12589 **   %%  %
12590 */
12591 static void strftimeFunc(
12592   sqlite3_context *context,
12593   int argc,
12594   sqlite3_value **argv
12595 ){
12596   DateTime x;
12597   u64 n;
12598   size_t i,j;
12599   char *z;
12600   sqlite3 *db;
12601   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12602   char zBuf[100];
12603   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12604   db = sqlite3_context_db_handle(context);
12605   for(i=0, n=1; zFmt[i]; i++, n++){
12606     if( zFmt[i]=='%' ){
12607       switch( zFmt[i+1] ){
12608         case 'd':
12609         case 'H':
12610         case 'm':
12611         case 'M':
12612         case 'S':
12613         case 'W':
12614           n++;
12615           /* fall thru */
12616         case 'w':
12617         case '%':
12618           break;
12619         case 'f':
12620           n += 8;
12621           break;
12622         case 'j':
12623           n += 3;
12624           break;
12625         case 'Y':
12626           n += 8;
12627           break;
12628         case 's':
12629         case 'J':
12630           n += 50;
12631           break;
12632         default:
12633           return;  /* ERROR.  return a NULL */
12634       }
12635       i++;
12636     }
12637   }
12638   testcase( n==sizeof(zBuf)-1 );
12639   testcase( n==sizeof(zBuf) );
12640   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12641   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12642   if( n<sizeof(zBuf) ){
12643     z = zBuf;
12644   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12645     sqlite3_result_error_toobig(context);
12646     return;
12647   }else{
12648     z = sqlite3DbMallocRaw(db, (int)n);
12649     if( z==0 ){
12650       sqlite3_result_error_nomem(context);
12651       return;
12652     }
12653   }
12654   computeJD(&x);
12655   computeYMD_HMS(&x);
12656   for(i=j=0; zFmt[i]; i++){
12657     if( zFmt[i]!='%' ){
12658       z[j++] = zFmt[i];
12659     }else{
12660       i++;
12661       switch( zFmt[i] ){
12662         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12663         case 'f': {
12664           double s = x.s;
12665           if( s>59.999 ) s = 59.999;
12666           sqlite3_snprintf(7, &z[j],"%06.3f", s);
12667           j += sqlite3Strlen30(&z[j]);
12668           break;
12669         }
12670         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12671         case 'W': /* Fall thru */
12672         case 'j': {
12673           int nDay;             /* Number of days since 1st day of year */
12674           DateTime y = x;
12675           y.validJD = 0;
12676           y.M = 1;
12677           y.D = 1;
12678           computeJD(&y);
12679           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12680           if( zFmt[i]=='W' ){
12681             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12682             wd = (int)(((x.iJD+43200000)/86400000)%7);
12683             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12684             j += 2;
12685           }else{
12686             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12687             j += 3;
12688           }
12689           break;
12690         }
12691         case 'J': {
12692           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12693           j+=sqlite3Strlen30(&z[j]);
12694           break;
12695         }
12696         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12697         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12698         case 's': {
12699           sqlite3_snprintf(30,&z[j],"%d",
12700                            (int)(x.iJD/1000.0 - 210866760000.0));
12701           j += sqlite3Strlen30(&z[j]);
12702           break;
12703         }
12704         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12705         case 'w': {
12706           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12707           break;
12708         }
12709         case 'Y': {
12710           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12711           break;
12712         }
12713         default:   z[j++] = '%'; break;
12714       }
12715     }
12716   }
12717   z[j] = 0;
12718   sqlite3_result_text(context, z, -1,
12719                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12720 }
12721
12722 /*
12723 ** current_time()
12724 **
12725 ** This function returns the same value as time('now').
12726 */
12727 static void ctimeFunc(
12728   sqlite3_context *context,
12729   int NotUsed,
12730   sqlite3_value **NotUsed2
12731 ){
12732   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12733   timeFunc(context, 0, 0);
12734 }
12735
12736 /*
12737 ** current_date()
12738 **
12739 ** This function returns the same value as date('now').
12740 */
12741 static void cdateFunc(
12742   sqlite3_context *context,
12743   int NotUsed,
12744   sqlite3_value **NotUsed2
12745 ){
12746   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12747   dateFunc(context, 0, 0);
12748 }
12749
12750 /*
12751 ** current_timestamp()
12752 **
12753 ** This function returns the same value as datetime('now').
12754 */
12755 static void ctimestampFunc(
12756   sqlite3_context *context,
12757   int NotUsed,
12758   sqlite3_value **NotUsed2
12759 ){
12760   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12761   datetimeFunc(context, 0, 0);
12762 }
12763 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12764
12765 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12766 /*
12767 ** If the library is compiled to omit the full-scale date and time
12768 ** handling (to get a smaller binary), the following minimal version
12769 ** of the functions current_time(), current_date() and current_timestamp()
12770 ** are included instead. This is to support column declarations that
12771 ** include "DEFAULT CURRENT_TIME" etc.
12772 **
12773 ** This function uses the C-library functions time(), gmtime()
12774 ** and strftime(). The format string to pass to strftime() is supplied
12775 ** as the user-data for the function.
12776 */
12777 static void currentTimeFunc(
12778   sqlite3_context *context,
12779   int argc,
12780   sqlite3_value **argv
12781 ){
12782   time_t t;
12783   char *zFormat = (char *)sqlite3_user_data(context);
12784   sqlite3 *db;
12785   double rT;
12786   char zBuf[20];
12787
12788   UNUSED_PARAMETER(argc);
12789   UNUSED_PARAMETER(argv);
12790
12791   db = sqlite3_context_db_handle(context);
12792   sqlite3OsCurrentTime(db->pVfs, &rT);
12793 #ifndef SQLITE_OMIT_FLOATING_POINT
12794   t = 86400.0*(rT - 2440587.5) + 0.5;
12795 #else
12796   /* without floating point support, rT will have
12797   ** already lost fractional day precision.
12798   */
12799   t = 86400 * (rT - 2440587) - 43200;
12800 #endif
12801 #ifdef HAVE_GMTIME_R
12802   {
12803     struct tm sNow;
12804     gmtime_r(&t, &sNow);
12805     strftime(zBuf, 20, zFormat, &sNow);
12806   }
12807 #else
12808   {
12809     struct tm *pTm;
12810     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12811     pTm = gmtime(&t);
12812     strftime(zBuf, 20, zFormat, pTm);
12813     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12814   }
12815 #endif
12816
12817   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12818 }
12819 #endif
12820
12821 /*
12822 ** This function registered all of the above C functions as SQL
12823 ** functions.  This should be the only routine in this file with
12824 ** external linkage.
12825 */
12826 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12827   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12828 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12829     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12830     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12831     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12832     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12833     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12834     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12835     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12836     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12837 #else
12838     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12839     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12840     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12841 #endif
12842   };
12843   int i;
12844   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12845   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12846
12847   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12848     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12849   }
12850 }
12851
12852 /************** End of date.c ************************************************/
12853 /************** Begin file os.c **********************************************/
12854 /*
12855 ** 2005 November 29
12856 **
12857 ** The author disclaims copyright to this source code.  In place of
12858 ** a legal notice, here is a blessing:
12859 **
12860 **    May you do good and not evil.
12861 **    May you find forgiveness for yourself and forgive others.
12862 **    May you share freely, never taking more than you give.
12863 **
12864 ******************************************************************************
12865 **
12866 ** This file contains OS interface code that is common to all
12867 ** architectures.
12868 **
12869 ** $Id: os.c,v 1.125 2008/12/08 18:19:18 drh Exp $
12870 */
12871 #define _SQLITE_OS_C_ 1
12872 #undef _SQLITE_OS_C_
12873
12874 /*
12875 ** The default SQLite sqlite3_vfs implementations do not allocate
12876 ** memory (actually, os_unix.c allocates a small amount of memory
12877 ** from within OsOpen()), but some third-party implementations may.
12878 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12879 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12880 **
12881 ** The following functions are instrumented for malloc() failure 
12882 ** testing:
12883 **
12884 **     sqlite3OsOpen()
12885 **     sqlite3OsRead()
12886 **     sqlite3OsWrite()
12887 **     sqlite3OsSync()
12888 **     sqlite3OsLock()
12889 **
12890 */
12891 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12892   #define DO_OS_MALLOC_TEST if (1) {            \
12893     void *pTstAlloc = sqlite3Malloc(10);       \
12894     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;  \
12895     sqlite3_free(pTstAlloc);                    \
12896   }
12897 #else
12898   #define DO_OS_MALLOC_TEST
12899 #endif
12900
12901 /*
12902 ** The following routines are convenience wrappers around methods
12903 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12904 ** of this would be completely automatic if SQLite were coded using
12905 ** C++ instead of plain old C.
12906 */
12907 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12908   int rc = SQLITE_OK;
12909   if( pId->pMethods ){
12910     rc = pId->pMethods->xClose(pId);
12911     pId->pMethods = 0;
12912   }
12913   return rc;
12914 }
12915 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12916   DO_OS_MALLOC_TEST;
12917   return id->pMethods->xRead(id, pBuf, amt, offset);
12918 }
12919 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12920   DO_OS_MALLOC_TEST;
12921   return id->pMethods->xWrite(id, pBuf, amt, offset);
12922 }
12923 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12924   return id->pMethods->xTruncate(id, size);
12925 }
12926 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12927   DO_OS_MALLOC_TEST;
12928   return id->pMethods->xSync(id, flags);
12929 }
12930 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12931   DO_OS_MALLOC_TEST;
12932   return id->pMethods->xFileSize(id, pSize);
12933 }
12934 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12935   DO_OS_MALLOC_TEST;
12936   return id->pMethods->xLock(id, lockType);
12937 }
12938 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12939   return id->pMethods->xUnlock(id, lockType);
12940 }
12941 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12942   DO_OS_MALLOC_TEST;
12943   return id->pMethods->xCheckReservedLock(id, pResOut);
12944 }
12945 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12946   return id->pMethods->xFileControl(id, op, pArg);
12947 }
12948 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12949   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12950   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12951 }
12952 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12953   return id->pMethods->xDeviceCharacteristics(id);
12954 }
12955
12956 /*
12957 ** The next group of routines are convenience wrappers around the
12958 ** VFS methods.
12959 */
12960 SQLITE_PRIVATE int sqlite3OsOpen(
12961   sqlite3_vfs *pVfs, 
12962   const char *zPath, 
12963   sqlite3_file *pFile, 
12964   int flags, 
12965   int *pFlagsOut
12966 ){
12967   DO_OS_MALLOC_TEST;
12968   return pVfs->xOpen(pVfs, zPath, pFile, flags, pFlagsOut);
12969 }
12970 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12971   return pVfs->xDelete(pVfs, zPath, dirSync);
12972 }
12973 SQLITE_PRIVATE int sqlite3OsAccess(
12974   sqlite3_vfs *pVfs, 
12975   const char *zPath, 
12976   int flags, 
12977   int *pResOut
12978 ){
12979   DO_OS_MALLOC_TEST;
12980   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12981 }
12982 SQLITE_PRIVATE int sqlite3OsFullPathname(
12983   sqlite3_vfs *pVfs, 
12984   const char *zPath, 
12985   int nPathOut, 
12986   char *zPathOut
12987 ){
12988   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12989 }
12990 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12991 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12992   return pVfs->xDlOpen(pVfs, zPath);
12993 }
12994 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12995   pVfs->xDlError(pVfs, nByte, zBufOut);
12996 }
12997 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12998   return pVfs->xDlSym(pVfs, pHdle, zSym);
12999 }
13000 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13001   pVfs->xDlClose(pVfs, pHandle);
13002 }
13003 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13004 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13005   return pVfs->xRandomness(pVfs, nByte, zBufOut);
13006 }
13007 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13008   return pVfs->xSleep(pVfs, nMicro);
13009 }
13010 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
13011   return pVfs->xCurrentTime(pVfs, pTimeOut);
13012 }
13013
13014 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13015   sqlite3_vfs *pVfs, 
13016   const char *zFile, 
13017   sqlite3_file **ppFile, 
13018   int flags,
13019   int *pOutFlags
13020 ){
13021   int rc = SQLITE_NOMEM;
13022   sqlite3_file *pFile;
13023   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13024   if( pFile ){
13025     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13026     if( rc!=SQLITE_OK ){
13027       sqlite3_free(pFile);
13028     }else{
13029       *ppFile = pFile;
13030     }
13031   }
13032   return rc;
13033 }
13034 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13035   int rc = SQLITE_OK;
13036   assert( pFile );
13037   rc = sqlite3OsClose(pFile);
13038   sqlite3_free(pFile);
13039   return rc;
13040 }
13041
13042 /*
13043 ** The list of all registered VFS implementations.
13044 */
13045 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13046 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13047
13048 /*
13049 ** Locate a VFS by name.  If no name is given, simply return the
13050 ** first VFS on the list.
13051 */
13052 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13053   sqlite3_vfs *pVfs = 0;
13054 #if SQLITE_THREADSAFE
13055   sqlite3_mutex *mutex;
13056 #endif
13057 #ifndef SQLITE_OMIT_AUTOINIT
13058   int rc = sqlite3_initialize();
13059   if( rc ) return 0;
13060 #endif
13061 #if SQLITE_THREADSAFE
13062   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13063 #endif
13064   sqlite3_mutex_enter(mutex);
13065   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13066     if( zVfs==0 ) break;
13067     if( strcmp(zVfs, pVfs->zName)==0 ) break;
13068   }
13069   sqlite3_mutex_leave(mutex);
13070   return pVfs;
13071 }
13072
13073 /*
13074 ** Unlink a VFS from the linked list
13075 */
13076 static void vfsUnlink(sqlite3_vfs *pVfs){
13077   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13078   if( pVfs==0 ){
13079     /* No-op */
13080   }else if( vfsList==pVfs ){
13081     vfsList = pVfs->pNext;
13082   }else if( vfsList ){
13083     sqlite3_vfs *p = vfsList;
13084     while( p->pNext && p->pNext!=pVfs ){
13085       p = p->pNext;
13086     }
13087     if( p->pNext==pVfs ){
13088       p->pNext = pVfs->pNext;
13089     }
13090   }
13091 }
13092
13093 /*
13094 ** Register a VFS with the system.  It is harmless to register the same
13095 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
13096 ** true.
13097 */
13098 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13099   sqlite3_mutex *mutex = 0;
13100 #ifndef SQLITE_OMIT_AUTOINIT
13101   int rc = sqlite3_initialize();
13102   if( rc ) return rc;
13103 #endif
13104   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13105   sqlite3_mutex_enter(mutex);
13106   vfsUnlink(pVfs);
13107   if( makeDflt || vfsList==0 ){
13108     pVfs->pNext = vfsList;
13109     vfsList = pVfs;
13110   }else{
13111     pVfs->pNext = vfsList->pNext;
13112     vfsList->pNext = pVfs;
13113   }
13114   assert(vfsList);
13115   sqlite3_mutex_leave(mutex);
13116   return SQLITE_OK;
13117 }
13118
13119 /*
13120 ** Unregister a VFS so that it is no longer accessible.
13121 */
13122 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13123 #if SQLITE_THREADSAFE
13124   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13125 #endif
13126   sqlite3_mutex_enter(mutex);
13127   vfsUnlink(pVfs);
13128   sqlite3_mutex_leave(mutex);
13129   return SQLITE_OK;
13130 }
13131
13132 /************** End of os.c **************************************************/
13133 /************** Begin file fault.c *******************************************/
13134 /*
13135 ** 2008 Jan 22
13136 **
13137 ** The author disclaims copyright to this source code.  In place of
13138 ** a legal notice, here is a blessing:
13139 **
13140 **    May you do good and not evil.
13141 **    May you find forgiveness for yourself and forgive others.
13142 **    May you share freely, never taking more than you give.
13143 **
13144 *************************************************************************
13145 **
13146 ** $Id: fault.c,v 1.11 2008/09/02 00:52:52 drh Exp $
13147 */
13148
13149 /*
13150 ** This file contains code to support the concept of "benign" 
13151 ** malloc failures (when the xMalloc() or xRealloc() method of the
13152 ** sqlite3_mem_methods structure fails to allocate a block of memory
13153 ** and returns 0). 
13154 **
13155 ** Most malloc failures are non-benign. After they occur, SQLite
13156 ** abandons the current operation and returns an error code (usually
13157 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13158 ** fatal. For example, if a malloc fails while resizing a hash table, this 
13159 ** is completely recoverable simply by not carrying out the resize. The 
13160 ** hash table will continue to function normally.  So a malloc failure 
13161 ** during a hash table resize is a benign fault.
13162 */
13163
13164
13165 #ifndef SQLITE_OMIT_BUILTIN_TEST
13166
13167 /*
13168 ** Global variables.
13169 */
13170 typedef struct BenignMallocHooks BenignMallocHooks;
13171 static SQLITE_WSD struct BenignMallocHooks {
13172   void (*xBenignBegin)(void);
13173   void (*xBenignEnd)(void);
13174 } sqlite3Hooks = { 0, 0 };
13175
13176 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13177 ** structure.  If writable static data is unsupported on the target,
13178 ** we have to locate the state vector at run-time.  In the more common
13179 ** case where writable static data is supported, wsdHooks can refer directly
13180 ** to the "sqlite3Hooks" state vector declared above.
13181 */
13182 #ifdef SQLITE_OMIT_WSD
13183 # define wsdHooksInit \
13184   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13185 # define wsdHooks x[0]
13186 #else
13187 # define wsdHooksInit
13188 # define wsdHooks sqlite3Hooks
13189 #endif
13190
13191
13192 /*
13193 ** Register hooks to call when sqlite3BeginBenignMalloc() and
13194 ** sqlite3EndBenignMalloc() are called, respectively.
13195 */
13196 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13197   void (*xBenignBegin)(void),
13198   void (*xBenignEnd)(void)
13199 ){
13200   wsdHooksInit;
13201   wsdHooks.xBenignBegin = xBenignBegin;
13202   wsdHooks.xBenignEnd = xBenignEnd;
13203 }
13204
13205 /*
13206 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13207 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13208 ** indicates that subsequent malloc failures are non-benign.
13209 */
13210 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13211   wsdHooksInit;
13212   if( wsdHooks.xBenignBegin ){
13213     wsdHooks.xBenignBegin();
13214   }
13215 }
13216 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13217   wsdHooksInit;
13218   if( wsdHooks.xBenignEnd ){
13219     wsdHooks.xBenignEnd();
13220   }
13221 }
13222
13223 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13224
13225 /************** End of fault.c ***********************************************/
13226 /************** Begin file mem0.c ********************************************/
13227 /*
13228 ** 2008 October 28
13229 **
13230 ** The author disclaims copyright to this source code.  In place of
13231 ** a legal notice, here is a blessing:
13232 **
13233 **    May you do good and not evil.
13234 **    May you find forgiveness for yourself and forgive others.
13235 **    May you share freely, never taking more than you give.
13236 **
13237 *************************************************************************
13238 **
13239 ** This file contains a no-op memory allocation drivers for use when
13240 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13241 ** here always fail.  SQLite will not operate with these drivers.  These
13242 ** are merely placeholders.  Real drivers must be substituted using
13243 ** sqlite3_config() before SQLite will operate.
13244 **
13245 ** $Id: mem0.c,v 1.1 2008/10/28 18:58:20 drh Exp $
13246 */
13247
13248 /*
13249 ** This version of the memory allocator is the default.  It is
13250 ** used when no other memory allocator is specified using compile-time
13251 ** macros.
13252 */
13253 #ifdef SQLITE_ZERO_MALLOC
13254
13255 /*
13256 ** No-op versions of all memory allocation routines
13257 */
13258 static void *sqlite3MemMalloc(int nByte){ return 0; }
13259 static void sqlite3MemFree(void *pPrior){ return; }
13260 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13261 static int sqlite3MemSize(void *pPrior){ return 0; }
13262 static int sqlite3MemRoundup(int n){ return n; }
13263 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13264 static void sqlite3MemShutdown(void *NotUsed){ return; }
13265
13266 /*
13267 ** This routine is the only routine in this file with external linkage.
13268 **
13269 ** Populate the low-level memory allocation function pointers in
13270 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13271 */
13272 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13273   static const sqlite3_mem_methods defaultMethods = {
13274      sqlite3MemMalloc,
13275      sqlite3MemFree,
13276      sqlite3MemRealloc,
13277      sqlite3MemSize,
13278      sqlite3MemRoundup,
13279      sqlite3MemInit,
13280      sqlite3MemShutdown,
13281      0
13282   };
13283   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13284 }
13285
13286 #endif /* SQLITE_ZERO_MALLOC */
13287
13288 /************** End of mem0.c ************************************************/
13289 /************** Begin file mem1.c ********************************************/
13290 /*
13291 ** 2007 August 14
13292 **
13293 ** The author disclaims copyright to this source code.  In place of
13294 ** a legal notice, here is a blessing:
13295 **
13296 **    May you do good and not evil.
13297 **    May you find forgiveness for yourself and forgive others.
13298 **    May you share freely, never taking more than you give.
13299 **
13300 *************************************************************************
13301 **
13302 ** This file contains low-level memory allocation drivers for when
13303 ** SQLite will use the standard C-library malloc/realloc/free interface
13304 ** to obtain the memory it needs.
13305 **
13306 ** This file contains implementations of the low-level memory allocation
13307 ** routines specified in the sqlite3_mem_methods object.
13308 **
13309 ** $Id: mem1.c,v 1.29 2008/12/10 21:19:57 drh Exp $
13310 */
13311
13312 /*
13313 ** This version of the memory allocator is the default.  It is
13314 ** used when no other memory allocator is specified using compile-time
13315 ** macros.
13316 */
13317 #ifdef SQLITE_SYSTEM_MALLOC
13318
13319 /*
13320 ** Like malloc(), but remember the size of the allocation
13321 ** so that we can find it later using sqlite3MemSize().
13322 **
13323 ** For this low-level routine, we are guaranteed that nByte>0 because
13324 ** cases of nByte<=0 will be intercepted and dealt with by higher level
13325 ** routines.
13326 */
13327 static void *sqlite3MemMalloc(int nByte){
13328   sqlite3_int64 *p;
13329   assert( nByte>0 );
13330   nByte = (nByte+7)&~7;
13331   p = malloc( nByte+8 );
13332   if( p ){
13333     p[0] = nByte;
13334     p++;
13335   }
13336   return (void *)p;
13337 }
13338
13339 /*
13340 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
13341 ** or sqlite3MemRealloc().
13342 **
13343 ** For this low-level routine, we already know that pPrior!=0 since
13344 ** cases where pPrior==0 will have been intecepted and dealt with
13345 ** by higher-level routines.
13346 */
13347 static void sqlite3MemFree(void *pPrior){
13348   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13349   assert( pPrior!=0 );
13350   p--;
13351   free(p);
13352 }
13353
13354 /*
13355 ** Like realloc().  Resize an allocation previously obtained from
13356 ** sqlite3MemMalloc().
13357 **
13358 ** For this low-level interface, we know that pPrior!=0.  Cases where
13359 ** pPrior==0 while have been intercepted by higher-level routine and
13360 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13361 ** cases where nByte<=0 will have been intercepted by higher-level
13362 ** routines and redirected to xFree.
13363 */
13364 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13365   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13366   assert( pPrior!=0 && nByte>0 );
13367   nByte = (nByte+7)&~7;
13368   p = (sqlite3_int64*)pPrior;
13369   p--;
13370   p = realloc(p, nByte+8 );
13371   if( p ){
13372     p[0] = nByte;
13373     p++;
13374   }
13375   return (void*)p;
13376 }
13377
13378 /*
13379 ** Report the allocated size of a prior return from xMalloc()
13380 ** or xRealloc().
13381 */
13382 static int sqlite3MemSize(void *pPrior){
13383   sqlite3_int64 *p;
13384   if( pPrior==0 ) return 0;
13385   p = (sqlite3_int64*)pPrior;
13386   p--;
13387   return (int)p[0];
13388 }
13389
13390 /*
13391 ** Round up a request size to the next valid allocation size.
13392 */
13393 static int sqlite3MemRoundup(int n){
13394   return (n+7) & ~7;
13395 }
13396
13397 /*
13398 ** Initialize this module.
13399 */
13400 static int sqlite3MemInit(void *NotUsed){
13401   UNUSED_PARAMETER(NotUsed);
13402   return SQLITE_OK;
13403 }
13404
13405 /*
13406 ** Deinitialize this module.
13407 */
13408 static void sqlite3MemShutdown(void *NotUsed){
13409   UNUSED_PARAMETER(NotUsed);
13410   return;
13411 }
13412
13413 /*
13414 ** This routine is the only routine in this file with external linkage.
13415 **
13416 ** Populate the low-level memory allocation function pointers in
13417 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13418 */
13419 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13420   static const sqlite3_mem_methods defaultMethods = {
13421      sqlite3MemMalloc,
13422      sqlite3MemFree,
13423      sqlite3MemRealloc,
13424      sqlite3MemSize,
13425      sqlite3MemRoundup,
13426      sqlite3MemInit,
13427      sqlite3MemShutdown,
13428      0
13429   };
13430   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13431 }
13432
13433 #endif /* SQLITE_SYSTEM_MALLOC */
13434
13435 /************** End of mem1.c ************************************************/
13436 /************** Begin file mem2.c ********************************************/
13437 /*
13438 ** 2007 August 15
13439 **
13440 ** The author disclaims copyright to this source code.  In place of
13441 ** a legal notice, here is a blessing:
13442 **
13443 **    May you do good and not evil.
13444 **    May you find forgiveness for yourself and forgive others.
13445 **    May you share freely, never taking more than you give.
13446 **
13447 *************************************************************************
13448 **
13449 ** This file contains low-level memory allocation drivers for when
13450 ** SQLite will use the standard C-library malloc/realloc/free interface
13451 ** to obtain the memory it needs while adding lots of additional debugging
13452 ** information to each allocation in order to help detect and fix memory
13453 ** leaks and memory usage errors.
13454 **
13455 ** This file contains implementations of the low-level memory allocation
13456 ** routines specified in the sqlite3_mem_methods object.
13457 **
13458 ** $Id: mem2.c,v 1.43 2009/02/05 03:00:06 shane Exp $
13459 */
13460
13461 /*
13462 ** This version of the memory allocator is used only if the
13463 ** SQLITE_MEMDEBUG macro is defined
13464 */
13465 #ifdef SQLITE_MEMDEBUG
13466
13467 /*
13468 ** The backtrace functionality is only available with GLIBC
13469 */
13470 #ifdef __GLIBC__
13471   extern int backtrace(void**,int);
13472   extern void backtrace_symbols_fd(void*const*,int,int);
13473 #else
13474 # define backtrace(A,B) 1
13475 # define backtrace_symbols_fd(A,B,C)
13476 #endif
13477
13478 /*
13479 ** Each memory allocation looks like this:
13480 **
13481 **  ------------------------------------------------------------------------
13482 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13483 **  ------------------------------------------------------------------------
13484 **
13485 ** The application code sees only a pointer to the allocation.  We have
13486 ** to back up from the allocation pointer to find the MemBlockHdr.  The
13487 ** MemBlockHdr tells us the size of the allocation and the number of
13488 ** backtrace pointers.  There is also a guard word at the end of the
13489 ** MemBlockHdr.
13490 */
13491 struct MemBlockHdr {
13492   i64 iSize;                          /* Size of this allocation */
13493   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13494   char nBacktrace;                    /* Number of backtraces on this alloc */
13495   char nBacktraceSlots;               /* Available backtrace slots */
13496   short nTitle;                       /* Bytes of title; includes '\0' */
13497   int iForeGuard;                     /* Guard word for sanity */
13498 };
13499
13500 /*
13501 ** Guard words
13502 */
13503 #define FOREGUARD 0x80F5E153
13504 #define REARGUARD 0xE4676B53
13505
13506 /*
13507 ** Number of malloc size increments to track.
13508 */
13509 #define NCSIZE  1000
13510
13511 /*
13512 ** All of the static variables used by this module are collected
13513 ** into a single structure named "mem".  This is to keep the
13514 ** static variables organized and to reduce namespace pollution
13515 ** when this module is combined with other in the amalgamation.
13516 */
13517 static struct {
13518   
13519   /*
13520   ** Mutex to control access to the memory allocation subsystem.
13521   */
13522   sqlite3_mutex *mutex;
13523
13524   /*
13525   ** Head and tail of a linked list of all outstanding allocations
13526   */
13527   struct MemBlockHdr *pFirst;
13528   struct MemBlockHdr *pLast;
13529   
13530   /*
13531   ** The number of levels of backtrace to save in new allocations.
13532   */
13533   int nBacktrace;
13534   void (*xBacktrace)(int, int, void **);
13535
13536   /*
13537   ** Title text to insert in front of each block
13538   */
13539   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13540   char zTitle[100];  /* The title text */
13541
13542   /* 
13543   ** sqlite3MallocDisallow() increments the following counter.
13544   ** sqlite3MallocAllow() decrements it.
13545   */
13546   int disallow; /* Do not allow memory allocation */
13547
13548   /*
13549   ** Gather statistics on the sizes of memory allocations.
13550   ** nAlloc[i] is the number of allocation attempts of i*8
13551   ** bytes.  i==NCSIZE is the number of allocation attempts for
13552   ** sizes more than NCSIZE*8 bytes.
13553   */
13554   int nAlloc[NCSIZE];      /* Total number of allocations */
13555   int nCurrent[NCSIZE];    /* Current number of allocations */
13556   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13557
13558 } mem;
13559
13560
13561 /*
13562 ** Adjust memory usage statistics
13563 */
13564 static void adjustStats(int iSize, int increment){
13565   int i = ((iSize+7)&~7)/8;
13566   if( i>NCSIZE-1 ){
13567     i = NCSIZE - 1;
13568   }
13569   if( increment>0 ){
13570     mem.nAlloc[i]++;
13571     mem.nCurrent[i]++;
13572     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13573       mem.mxCurrent[i] = mem.nCurrent[i];
13574     }
13575   }else{
13576     mem.nCurrent[i]--;
13577     assert( mem.nCurrent[i]>=0 );
13578   }
13579 }
13580
13581 /*
13582 ** Given an allocation, find the MemBlockHdr for that allocation.
13583 **
13584 ** This routine checks the guards at either end of the allocation and
13585 ** if they are incorrect it asserts.
13586 */
13587 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13588   struct MemBlockHdr *p;
13589   int *pInt;
13590   u8 *pU8;
13591   int nReserve;
13592
13593   p = (struct MemBlockHdr*)pAllocation;
13594   p--;
13595   assert( p->iForeGuard==(int)FOREGUARD );
13596   nReserve = (p->iSize+7)&~7;
13597   pInt = (int*)pAllocation;
13598   pU8 = (u8*)pAllocation;
13599   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13600   /* This checks any of the "extra" bytes allocated due
13601   ** to rounding up to an 8 byte boundary to ensure 
13602   ** they haven't been overwritten.
13603   */
13604   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13605   return p;
13606 }
13607
13608 /*
13609 ** Return the number of bytes currently allocated at address p.
13610 */
13611 static int sqlite3MemSize(void *p){
13612   struct MemBlockHdr *pHdr;
13613   if( !p ){
13614     return 0;
13615   }
13616   pHdr = sqlite3MemsysGetHeader(p);
13617   return pHdr->iSize;
13618 }
13619
13620 /*
13621 ** Initialize the memory allocation subsystem.
13622 */
13623 static int sqlite3MemInit(void *NotUsed){
13624   UNUSED_PARAMETER(NotUsed);
13625   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13626   if( !sqlite3GlobalConfig.bMemstat ){
13627     /* If memory status is enabled, then the malloc.c wrapper will already
13628     ** hold the STATIC_MEM mutex when the routines here are invoked. */
13629     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13630   }
13631   return SQLITE_OK;
13632 }
13633
13634 /*
13635 ** Deinitialize the memory allocation subsystem.
13636 */
13637 static void sqlite3MemShutdown(void *NotUsed){
13638   UNUSED_PARAMETER(NotUsed);
13639   mem.mutex = 0;
13640 }
13641
13642 /*
13643 ** Round up a request size to the next valid allocation size.
13644 */
13645 static int sqlite3MemRoundup(int n){
13646   return (n+7) & ~7;
13647 }
13648
13649 /*
13650 ** Allocate nByte bytes of memory.
13651 */
13652 static void *sqlite3MemMalloc(int nByte){
13653   struct MemBlockHdr *pHdr;
13654   void **pBt;
13655   char *z;
13656   int *pInt;
13657   void *p = 0;
13658   int totalSize;
13659   int nReserve;
13660   sqlite3_mutex_enter(mem.mutex);
13661   assert( mem.disallow==0 );
13662   nReserve = (nByte+7)&~7;
13663   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13664                mem.nBacktrace*sizeof(void*) + mem.nTitle;
13665   p = malloc(totalSize);
13666   if( p ){
13667     z = p;
13668     pBt = (void**)&z[mem.nTitle];
13669     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13670     pHdr->pNext = 0;
13671     pHdr->pPrev = mem.pLast;
13672     if( mem.pLast ){
13673       mem.pLast->pNext = pHdr;
13674     }else{
13675       mem.pFirst = pHdr;
13676     }
13677     mem.pLast = pHdr;
13678     pHdr->iForeGuard = FOREGUARD;
13679     pHdr->nBacktraceSlots = mem.nBacktrace;
13680     pHdr->nTitle = mem.nTitle;
13681     if( mem.nBacktrace ){
13682       void *aAddr[40];
13683       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13684       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13685       if( mem.xBacktrace ){
13686         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13687       }
13688     }else{
13689       pHdr->nBacktrace = 0;
13690     }
13691     if( mem.nTitle ){
13692       memcpy(z, mem.zTitle, mem.nTitle);
13693     }
13694     pHdr->iSize = nByte;
13695     adjustStats(nByte, +1);
13696     pInt = (int*)&pHdr[1];
13697     pInt[nReserve/sizeof(int)] = REARGUARD;
13698     memset(pInt, 0x65, nReserve);
13699     p = (void*)pInt;
13700   }
13701   sqlite3_mutex_leave(mem.mutex);
13702   return p; 
13703 }
13704
13705 /*
13706 ** Free memory.
13707 */
13708 static void sqlite3MemFree(void *pPrior){
13709   struct MemBlockHdr *pHdr;
13710   void **pBt;
13711   char *z;
13712   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
13713   pHdr = sqlite3MemsysGetHeader(pPrior);
13714   pBt = (void**)pHdr;
13715   pBt -= pHdr->nBacktraceSlots;
13716   sqlite3_mutex_enter(mem.mutex);
13717   if( pHdr->pPrev ){
13718     assert( pHdr->pPrev->pNext==pHdr );
13719     pHdr->pPrev->pNext = pHdr->pNext;
13720   }else{
13721     assert( mem.pFirst==pHdr );
13722     mem.pFirst = pHdr->pNext;
13723   }
13724   if( pHdr->pNext ){
13725     assert( pHdr->pNext->pPrev==pHdr );
13726     pHdr->pNext->pPrev = pHdr->pPrev;
13727   }else{
13728     assert( mem.pLast==pHdr );
13729     mem.pLast = pHdr->pPrev;
13730   }
13731   z = (char*)pBt;
13732   z -= pHdr->nTitle;
13733   adjustStats(pHdr->iSize, -1);
13734   memset(z, 0x2b, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13735                   pHdr->iSize + sizeof(int) + pHdr->nTitle);
13736   free(z);
13737   sqlite3_mutex_leave(mem.mutex);  
13738 }
13739
13740 /*
13741 ** Change the size of an existing memory allocation.
13742 **
13743 ** For this debugging implementation, we *always* make a copy of the
13744 ** allocation into a new place in memory.  In this way, if the 
13745 ** higher level code is using pointer to the old allocation, it is 
13746 ** much more likely to break and we are much more liking to find
13747 ** the error.
13748 */
13749 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13750   struct MemBlockHdr *pOldHdr;
13751   void *pNew;
13752   assert( mem.disallow==0 );
13753   pOldHdr = sqlite3MemsysGetHeader(pPrior);
13754   pNew = sqlite3MemMalloc(nByte);
13755   if( pNew ){
13756     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13757     if( nByte>pOldHdr->iSize ){
13758       memset(&((char*)pNew)[pOldHdr->iSize], 0x2b, nByte - pOldHdr->iSize);
13759     }
13760     sqlite3MemFree(pPrior);
13761   }
13762   return pNew;
13763 }
13764
13765 /*
13766 ** Populate the low-level memory allocation function pointers in
13767 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13768 */
13769 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13770   static const sqlite3_mem_methods defaultMethods = {
13771      sqlite3MemMalloc,
13772      sqlite3MemFree,
13773      sqlite3MemRealloc,
13774      sqlite3MemSize,
13775      sqlite3MemRoundup,
13776      sqlite3MemInit,
13777      sqlite3MemShutdown,
13778      0
13779   };
13780   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13781 }
13782
13783 /*
13784 ** Set the number of backtrace levels kept for each allocation.
13785 ** A value of zero turns off backtracing.  The number is always rounded
13786 ** up to a multiple of 2.
13787 */
13788 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13789   if( depth<0 ){ depth = 0; }
13790   if( depth>20 ){ depth = 20; }
13791   depth = (depth+1)&0xfe;
13792   mem.nBacktrace = depth;
13793 }
13794
13795 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13796   mem.xBacktrace = xBacktrace;
13797 }
13798
13799 /*
13800 ** Set the title string for subsequent allocations.
13801 */
13802 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13803   unsigned int n = sqlite3Strlen30(zTitle) + 1;
13804   sqlite3_mutex_enter(mem.mutex);
13805   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13806   memcpy(mem.zTitle, zTitle, n);
13807   mem.zTitle[n] = 0;
13808   mem.nTitle = (n+7)&~7;
13809   sqlite3_mutex_leave(mem.mutex);
13810 }
13811
13812 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13813   struct MemBlockHdr *pHdr;
13814   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13815     void **pBt = (void**)pHdr;
13816     pBt -= pHdr->nBacktraceSlots;
13817     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13818   }
13819 }
13820
13821 /*
13822 ** Open the file indicated and write a log of all unfreed memory 
13823 ** allocations into that log.
13824 */
13825 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13826   FILE *out;
13827   struct MemBlockHdr *pHdr;
13828   void **pBt;
13829   int i;
13830   out = fopen(zFilename, "w");
13831   if( out==0 ){
13832     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13833                     zFilename);
13834     return;
13835   }
13836   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13837     char *z = (char*)pHdr;
13838     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13839     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13840             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13841     if( pHdr->nBacktrace ){
13842       fflush(out);
13843       pBt = (void**)pHdr;
13844       pBt -= pHdr->nBacktraceSlots;
13845       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13846       fprintf(out, "\n");
13847     }
13848   }
13849   fprintf(out, "COUNTS:\n");
13850   for(i=0; i<NCSIZE-1; i++){
13851     if( mem.nAlloc[i] ){
13852       fprintf(out, "   %5d: %10d %10d %10d\n", 
13853             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13854     }
13855   }
13856   if( mem.nAlloc[NCSIZE-1] ){
13857     fprintf(out, "   %5d: %10d %10d %10d\n",
13858              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13859              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13860   }
13861   fclose(out);
13862 }
13863
13864 /*
13865 ** Return the number of times sqlite3MemMalloc() has been called.
13866 */
13867 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13868   int i;
13869   int nTotal = 0;
13870   for(i=0; i<NCSIZE; i++){
13871     nTotal += mem.nAlloc[i];
13872   }
13873   return nTotal;
13874 }
13875
13876
13877 #endif /* SQLITE_MEMDEBUG */
13878
13879 /************** End of mem2.c ************************************************/
13880 /************** Begin file mem3.c ********************************************/
13881 /*
13882 ** 2007 October 14
13883 **
13884 ** The author disclaims copyright to this source code.  In place of
13885 ** a legal notice, here is a blessing:
13886 **
13887 **    May you do good and not evil.
13888 **    May you find forgiveness for yourself and forgive others.
13889 **    May you share freely, never taking more than you give.
13890 **
13891 *************************************************************************
13892 ** This file contains the C functions that implement a memory
13893 ** allocation subsystem for use by SQLite. 
13894 **
13895 ** This version of the memory allocation subsystem omits all
13896 ** use of malloc(). The SQLite user supplies a block of memory
13897 ** before calling sqlite3_initialize() from which allocations
13898 ** are made and returned by the xMalloc() and xRealloc() 
13899 ** implementations. Once sqlite3_initialize() has been called,
13900 ** the amount of memory available to SQLite is fixed and cannot
13901 ** be changed.
13902 **
13903 ** This version of the memory allocation subsystem is included
13904 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13905 **
13906 ** $Id: mem3.c,v 1.25 2008/11/19 16:52:44 danielk1977 Exp $
13907 */
13908
13909 /*
13910 ** This version of the memory allocator is only built into the library
13911 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13912 ** mean that the library will use a memory-pool by default, just that
13913 ** it is available. The mempool allocator is activated by calling
13914 ** sqlite3_config().
13915 */
13916 #ifdef SQLITE_ENABLE_MEMSYS3
13917
13918 /*
13919 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13920 */
13921 #define MX_SMALL 10
13922
13923
13924 /*
13925 ** Number of freelist hash slots
13926 */
13927 #define N_HASH  61
13928
13929 /*
13930 ** A memory allocation (also called a "chunk") consists of two or 
13931 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13932 ** a header that is not returned to the user.
13933 **
13934 ** A chunk is two or more blocks that is either checked out or
13935 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13936 ** size of the allocation in blocks if the allocation is free.
13937 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13938 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13939 ** is true if the previous chunk is checked out and false if the
13940 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13941 ** the previous chunk in blocks if the previous chunk is on the
13942 ** freelist. If the previous chunk is checked out, then
13943 ** u.hdr.prevSize can be part of the data for that chunk and should
13944 ** not be read or written.
13945 **
13946 ** We often identify a chunk by its index in mem3.aPool[].  When
13947 ** this is done, the chunk index refers to the second block of
13948 ** the chunk.  In this way, the first chunk has an index of 1.
13949 ** A chunk index of 0 means "no such chunk" and is the equivalent
13950 ** of a NULL pointer.
13951 **
13952 ** The second block of free chunks is of the form u.list.  The
13953 ** two fields form a double-linked list of chunks of related sizes.
13954 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13955 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13956 **
13957 ** The second block of a chunk is user data if the chunk is checked 
13958 ** out.  If a chunk is checked out, the user data may extend into
13959 ** the u.hdr.prevSize value of the following chunk.
13960 */
13961 typedef struct Mem3Block Mem3Block;
13962 struct Mem3Block {
13963   union {
13964     struct {
13965       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13966       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13967     } hdr;
13968     struct {
13969       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13970       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13971     } list;
13972   } u;
13973 };
13974
13975 /*
13976 ** All of the static variables used by this module are collected
13977 ** into a single structure named "mem3".  This is to keep the
13978 ** static variables organized and to reduce namespace pollution
13979 ** when this module is combined with other in the amalgamation.
13980 */
13981 static SQLITE_WSD struct Mem3Global {
13982   /*
13983   ** Memory available for allocation. nPool is the size of the array
13984   ** (in Mem3Blocks) pointed to by aPool less 2.
13985   */
13986   u32 nPool;
13987   Mem3Block *aPool;
13988
13989   /*
13990   ** True if we are evaluating an out-of-memory callback.
13991   */
13992   int alarmBusy;
13993   
13994   /*
13995   ** Mutex to control access to the memory allocation subsystem.
13996   */
13997   sqlite3_mutex *mutex;
13998   
13999   /*
14000   ** The minimum amount of free space that we have seen.
14001   */
14002   u32 mnMaster;
14003
14004   /*
14005   ** iMaster is the index of the master chunk.  Most new allocations
14006   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14007   ** of the current master.  iMaster is 0 if there is not master chunk.
14008   ** The master chunk is not in either the aiHash[] or aiSmall[].
14009   */
14010   u32 iMaster;
14011   u32 szMaster;
14012
14013   /*
14014   ** Array of lists of free blocks according to the block size 
14015   ** for smaller chunks, or a hash on the block size for larger
14016   ** chunks.
14017   */
14018   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14019   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14020 } mem3 = { 97535575 };
14021
14022 #define mem3 GLOBAL(struct Mem3Global, mem3)
14023
14024 /*
14025 ** Unlink the chunk at mem3.aPool[i] from list it is currently
14026 ** on.  *pRoot is the list that i is a member of.
14027 */
14028 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14029   u32 next = mem3.aPool[i].u.list.next;
14030   u32 prev = mem3.aPool[i].u.list.prev;
14031   assert( sqlite3_mutex_held(mem3.mutex) );
14032   if( prev==0 ){
14033     *pRoot = next;
14034   }else{
14035     mem3.aPool[prev].u.list.next = next;
14036   }
14037   if( next ){
14038     mem3.aPool[next].u.list.prev = prev;
14039   }
14040   mem3.aPool[i].u.list.next = 0;
14041   mem3.aPool[i].u.list.prev = 0;
14042 }
14043
14044 /*
14045 ** Unlink the chunk at index i from 
14046 ** whatever list is currently a member of.
14047 */
14048 static void memsys3Unlink(u32 i){
14049   u32 size, hash;
14050   assert( sqlite3_mutex_held(mem3.mutex) );
14051   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14052   assert( i>=1 );
14053   size = mem3.aPool[i-1].u.hdr.size4x/4;
14054   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14055   assert( size>=2 );
14056   if( size <= MX_SMALL ){
14057     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14058   }else{
14059     hash = size % N_HASH;
14060     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14061   }
14062 }
14063
14064 /*
14065 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
14066 ** at *pRoot.
14067 */
14068 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14069   assert( sqlite3_mutex_held(mem3.mutex) );
14070   mem3.aPool[i].u.list.next = *pRoot;
14071   mem3.aPool[i].u.list.prev = 0;
14072   if( *pRoot ){
14073     mem3.aPool[*pRoot].u.list.prev = i;
14074   }
14075   *pRoot = i;
14076 }
14077
14078 /*
14079 ** Link the chunk at index i into either the appropriate
14080 ** small chunk list, or into the large chunk hash table.
14081 */
14082 static void memsys3Link(u32 i){
14083   u32 size, hash;
14084   assert( sqlite3_mutex_held(mem3.mutex) );
14085   assert( i>=1 );
14086   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14087   size = mem3.aPool[i-1].u.hdr.size4x/4;
14088   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14089   assert( size>=2 );
14090   if( size <= MX_SMALL ){
14091     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14092   }else{
14093     hash = size % N_HASH;
14094     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14095   }
14096 }
14097
14098 /*
14099 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14100 ** will already be held (obtained by code in malloc.c) if
14101 ** sqlite3GlobalConfig.bMemStat is true.
14102 */
14103 static void memsys3Enter(void){
14104   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14105     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14106   }
14107   sqlite3_mutex_enter(mem3.mutex);
14108 }
14109 static void memsys3Leave(void){
14110   sqlite3_mutex_leave(mem3.mutex);
14111 }
14112
14113 /*
14114 ** Called when we are unable to satisfy an allocation of nBytes.
14115 */
14116 static void memsys3OutOfMemory(int nByte){
14117   if( !mem3.alarmBusy ){
14118     mem3.alarmBusy = 1;
14119     assert( sqlite3_mutex_held(mem3.mutex) );
14120     sqlite3_mutex_leave(mem3.mutex);
14121     sqlite3_release_memory(nByte);
14122     sqlite3_mutex_enter(mem3.mutex);
14123     mem3.alarmBusy = 0;
14124   }
14125 }
14126
14127
14128 /*
14129 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
14130 ** size parameters for check-out and return a pointer to the 
14131 ** user portion of the chunk.
14132 */
14133 static void *memsys3Checkout(u32 i, u32 nBlock){
14134   u32 x;
14135   assert( sqlite3_mutex_held(mem3.mutex) );
14136   assert( i>=1 );
14137   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14138   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14139   x = mem3.aPool[i-1].u.hdr.size4x;
14140   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14141   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14142   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14143   return &mem3.aPool[i];
14144 }
14145
14146 /*
14147 ** Carve a piece off of the end of the mem3.iMaster free chunk.
14148 ** Return a pointer to the new allocation.  Or, if the master chunk
14149 ** is not large enough, return 0.
14150 */
14151 static void *memsys3FromMaster(u32 nBlock){
14152   assert( sqlite3_mutex_held(mem3.mutex) );
14153   assert( mem3.szMaster>=nBlock );
14154   if( nBlock>=mem3.szMaster-1 ){
14155     /* Use the entire master */
14156     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14157     mem3.iMaster = 0;
14158     mem3.szMaster = 0;
14159     mem3.mnMaster = 0;
14160     return p;
14161   }else{
14162     /* Split the master block.  Return the tail. */
14163     u32 newi, x;
14164     newi = mem3.iMaster + mem3.szMaster - nBlock;
14165     assert( newi > mem3.iMaster+1 );
14166     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14167     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14168     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14169     mem3.szMaster -= nBlock;
14170     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14171     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14172     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14173     if( mem3.szMaster < mem3.mnMaster ){
14174       mem3.mnMaster = mem3.szMaster;
14175     }
14176     return (void*)&mem3.aPool[newi];
14177   }
14178 }
14179
14180 /*
14181 ** *pRoot is the head of a list of free chunks of the same size
14182 ** or same size hash.  In other words, *pRoot is an entry in either
14183 ** mem3.aiSmall[] or mem3.aiHash[].  
14184 **
14185 ** This routine examines all entries on the given list and tries
14186 ** to coalesce each entries with adjacent free chunks.  
14187 **
14188 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
14189 ** the current mem3.iMaster with the new larger chunk.  In order for
14190 ** this mem3.iMaster replacement to work, the master chunk must be
14191 ** linked into the hash tables.  That is not the normal state of
14192 ** affairs, of course.  The calling routine must link the master
14193 ** chunk before invoking this routine, then must unlink the (possibly
14194 ** changed) master chunk once this routine has finished.
14195 */
14196 static void memsys3Merge(u32 *pRoot){
14197   u32 iNext, prev, size, i, x;
14198
14199   assert( sqlite3_mutex_held(mem3.mutex) );
14200   for(i=*pRoot; i>0; i=iNext){
14201     iNext = mem3.aPool[i].u.list.next;
14202     size = mem3.aPool[i-1].u.hdr.size4x;
14203     assert( (size&1)==0 );
14204     if( (size&2)==0 ){
14205       memsys3UnlinkFromList(i, pRoot);
14206       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14207       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14208       if( prev==iNext ){
14209         iNext = mem3.aPool[prev].u.list.next;
14210       }
14211       memsys3Unlink(prev);
14212       size = i + size/4 - prev;
14213       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14214       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14215       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14216       memsys3Link(prev);
14217       i = prev;
14218     }else{
14219       size /= 4;
14220     }
14221     if( size>mem3.szMaster ){
14222       mem3.iMaster = i;
14223       mem3.szMaster = size;
14224     }
14225   }
14226 }
14227
14228 /*
14229 ** Return a block of memory of at least nBytes in size.
14230 ** Return NULL if unable.
14231 **
14232 ** This function assumes that the necessary mutexes, if any, are
14233 ** already held by the caller. Hence "Unsafe".
14234 */
14235 static void *memsys3MallocUnsafe(int nByte){
14236   u32 i;
14237   u32 nBlock;
14238   u32 toFree;
14239
14240   assert( sqlite3_mutex_held(mem3.mutex) );
14241   assert( sizeof(Mem3Block)==8 );
14242   if( nByte<=12 ){
14243     nBlock = 2;
14244   }else{
14245     nBlock = (nByte + 11)/8;
14246   }
14247   assert( nBlock>=2 );
14248
14249   /* STEP 1:
14250   ** Look for an entry of the correct size in either the small
14251   ** chunk table or in the large chunk hash table.  This is
14252   ** successful most of the time (about 9 times out of 10).
14253   */
14254   if( nBlock <= MX_SMALL ){
14255     i = mem3.aiSmall[nBlock-2];
14256     if( i>0 ){
14257       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14258       return memsys3Checkout(i, nBlock);
14259     }
14260   }else{
14261     int hash = nBlock % N_HASH;
14262     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14263       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14264         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14265         return memsys3Checkout(i, nBlock);
14266       }
14267     }
14268   }
14269
14270   /* STEP 2:
14271   ** Try to satisfy the allocation by carving a piece off of the end
14272   ** of the master chunk.  This step usually works if step 1 fails.
14273   */
14274   if( mem3.szMaster>=nBlock ){
14275     return memsys3FromMaster(nBlock);
14276   }
14277
14278
14279   /* STEP 3:  
14280   ** Loop through the entire memory pool.  Coalesce adjacent free
14281   ** chunks.  Recompute the master chunk as the largest free chunk.
14282   ** Then try again to satisfy the allocation by carving a piece off
14283   ** of the end of the master chunk.  This step happens very
14284   ** rarely (we hope!)
14285   */
14286   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14287     memsys3OutOfMemory(toFree);
14288     if( mem3.iMaster ){
14289       memsys3Link(mem3.iMaster);
14290       mem3.iMaster = 0;
14291       mem3.szMaster = 0;
14292     }
14293     for(i=0; i<N_HASH; i++){
14294       memsys3Merge(&mem3.aiHash[i]);
14295     }
14296     for(i=0; i<MX_SMALL-1; i++){
14297       memsys3Merge(&mem3.aiSmall[i]);
14298     }
14299     if( mem3.szMaster ){
14300       memsys3Unlink(mem3.iMaster);
14301       if( mem3.szMaster>=nBlock ){
14302         return memsys3FromMaster(nBlock);
14303       }
14304     }
14305   }
14306
14307   /* If none of the above worked, then we fail. */
14308   return 0;
14309 }
14310
14311 /*
14312 ** Free an outstanding memory allocation.
14313 **
14314 ** This function assumes that the necessary mutexes, if any, are
14315 ** already held by the caller. Hence "Unsafe".
14316 */
14317 void memsys3FreeUnsafe(void *pOld){
14318   Mem3Block *p = (Mem3Block*)pOld;
14319   int i;
14320   u32 size, x;
14321   assert( sqlite3_mutex_held(mem3.mutex) );
14322   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14323   i = p - mem3.aPool;
14324   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14325   size = mem3.aPool[i-1].u.hdr.size4x/4;
14326   assert( i+size<=mem3.nPool+1 );
14327   mem3.aPool[i-1].u.hdr.size4x &= ~1;
14328   mem3.aPool[i+size-1].u.hdr.prevSize = size;
14329   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14330   memsys3Link(i);
14331
14332   /* Try to expand the master using the newly freed chunk */
14333   if( mem3.iMaster ){
14334     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14335       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14336       mem3.iMaster -= size;
14337       mem3.szMaster += size;
14338       memsys3Unlink(mem3.iMaster);
14339       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14340       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14341       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14342     }
14343     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14344     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14345       memsys3Unlink(mem3.iMaster+mem3.szMaster);
14346       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14347       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14348       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14349     }
14350   }
14351 }
14352
14353 /*
14354 ** Return the size of an outstanding allocation, in bytes.  The
14355 ** size returned omits the 8-byte header overhead.  This only
14356 ** works for chunks that are currently checked out.
14357 */
14358 static int memsys3Size(void *p){
14359   Mem3Block *pBlock;
14360   if( p==0 ) return 0;
14361   pBlock = (Mem3Block*)p;
14362   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14363   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14364 }
14365
14366 /*
14367 ** Round up a request size to the next valid allocation size.
14368 */
14369 static int memsys3Roundup(int n){
14370   if( n<=12 ){
14371     return 12;
14372   }else{
14373     return ((n+11)&~7) - 4;
14374   }
14375 }
14376
14377 /*
14378 ** Allocate nBytes of memory.
14379 */
14380 static void *memsys3Malloc(int nBytes){
14381   sqlite3_int64 *p;
14382   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14383   memsys3Enter();
14384   p = memsys3MallocUnsafe(nBytes);
14385   memsys3Leave();
14386   return (void*)p; 
14387 }
14388
14389 /*
14390 ** Free memory.
14391 */
14392 void memsys3Free(void *pPrior){
14393   assert( pPrior );
14394   memsys3Enter();
14395   memsys3FreeUnsafe(pPrior);
14396   memsys3Leave();
14397 }
14398
14399 /*
14400 ** Change the size of an existing memory allocation
14401 */
14402 void *memsys3Realloc(void *pPrior, int nBytes){
14403   int nOld;
14404   void *p;
14405   if( pPrior==0 ){
14406     return sqlite3_malloc(nBytes);
14407   }
14408   if( nBytes<=0 ){
14409     sqlite3_free(pPrior);
14410     return 0;
14411   }
14412   nOld = memsys3Size(pPrior);
14413   if( nBytes<=nOld && nBytes>=nOld-128 ){
14414     return pPrior;
14415   }
14416   memsys3Enter();
14417   p = memsys3MallocUnsafe(nBytes);
14418   if( p ){
14419     if( nOld<nBytes ){
14420       memcpy(p, pPrior, nOld);
14421     }else{
14422       memcpy(p, pPrior, nBytes);
14423     }
14424     memsys3FreeUnsafe(pPrior);
14425   }
14426   memsys3Leave();
14427   return p;
14428 }
14429
14430 /*
14431 ** Initialize this module.
14432 */
14433 static int memsys3Init(void *NotUsed){
14434   UNUSED_PARAMETER(NotUsed);
14435   if( !sqlite3GlobalConfig.pHeap ){
14436     return SQLITE_ERROR;
14437   }
14438
14439   /* Store a pointer to the memory block in global structure mem3. */
14440   assert( sizeof(Mem3Block)==8 );
14441   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14442   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14443
14444   /* Initialize the master block. */
14445   mem3.szMaster = mem3.nPool;
14446   mem3.mnMaster = mem3.szMaster;
14447   mem3.iMaster = 1;
14448   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14449   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14450   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14451
14452   return SQLITE_OK;
14453 }
14454
14455 /*
14456 ** Deinitialize this module.
14457 */
14458 static void memsys3Shutdown(void *NotUsed){
14459   UNUSED_PARAMETER(NotUsed);
14460   return;
14461 }
14462
14463
14464
14465 /*
14466 ** Open the file indicated and write a log of all unfreed memory 
14467 ** allocations into that log.
14468 */
14469 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14470 #ifdef SQLITE_DEBUG
14471   FILE *out;
14472   u32 i, j;
14473   u32 size;
14474   if( zFilename==0 || zFilename[0]==0 ){
14475     out = stdout;
14476   }else{
14477     out = fopen(zFilename, "w");
14478     if( out==0 ){
14479       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14480                       zFilename);
14481       return;
14482     }
14483   }
14484   memsys3Enter();
14485   fprintf(out, "CHUNKS:\n");
14486   for(i=1; i<=mem3.nPool; i+=size/4){
14487     size = mem3.aPool[i-1].u.hdr.size4x;
14488     if( size/4<=1 ){
14489       fprintf(out, "%p size error\n", &mem3.aPool[i]);
14490       assert( 0 );
14491       break;
14492     }
14493     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14494       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14495       assert( 0 );
14496       break;
14497     }
14498     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14499       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14500       assert( 0 );
14501       break;
14502     }
14503     if( size&1 ){
14504       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14505     }else{
14506       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14507                   i==mem3.iMaster ? " **master**" : "");
14508     }
14509   }
14510   for(i=0; i<MX_SMALL-1; i++){
14511     if( mem3.aiSmall[i]==0 ) continue;
14512     fprintf(out, "small(%2d):", i);
14513     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14514       fprintf(out, " %p(%d)", &mem3.aPool[j],
14515               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14516     }
14517     fprintf(out, "\n"); 
14518   }
14519   for(i=0; i<N_HASH; i++){
14520     if( mem3.aiHash[i]==0 ) continue;
14521     fprintf(out, "hash(%2d):", i);
14522     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14523       fprintf(out, " %p(%d)", &mem3.aPool[j],
14524               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14525     }
14526     fprintf(out, "\n"); 
14527   }
14528   fprintf(out, "master=%d\n", mem3.iMaster);
14529   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14530   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14531   sqlite3_mutex_leave(mem3.mutex);
14532   if( out==stdout ){
14533     fflush(stdout);
14534   }else{
14535     fclose(out);
14536   }
14537 #else
14538   UNUSED_PARAMETER(zFilename);
14539 #endif
14540 }
14541
14542 /*
14543 ** This routine is the only routine in this file with external 
14544 ** linkage.
14545 **
14546 ** Populate the low-level memory allocation function pointers in
14547 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14548 ** arguments specify the block of memory to manage.
14549 **
14550 ** This routine is only called by sqlite3_config(), and therefore
14551 ** is not required to be threadsafe (it is not).
14552 */
14553 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14554   static const sqlite3_mem_methods mempoolMethods = {
14555      memsys3Malloc,
14556      memsys3Free,
14557      memsys3Realloc,
14558      memsys3Size,
14559      memsys3Roundup,
14560      memsys3Init,
14561      memsys3Shutdown,
14562      0
14563   };
14564   return &mempoolMethods;
14565 }
14566
14567 #endif /* SQLITE_ENABLE_MEMSYS3 */
14568
14569 /************** End of mem3.c ************************************************/
14570 /************** Begin file mem5.c ********************************************/
14571 /*
14572 ** 2007 October 14
14573 **
14574 ** The author disclaims copyright to this source code.  In place of
14575 ** a legal notice, here is a blessing:
14576 **
14577 **    May you do good and not evil.
14578 **    May you find forgiveness for yourself and forgive others.
14579 **    May you share freely, never taking more than you give.
14580 **
14581 *************************************************************************
14582 ** This file contains the C functions that implement a memory
14583 ** allocation subsystem for use by SQLite. 
14584 **
14585 ** This version of the memory allocation subsystem omits all
14586 ** use of malloc(). The SQLite user supplies a block of memory
14587 ** before calling sqlite3_initialize() from which allocations
14588 ** are made and returned by the xMalloc() and xRealloc() 
14589 ** implementations. Once sqlite3_initialize() has been called,
14590 ** the amount of memory available to SQLite is fixed and cannot
14591 ** be changed.
14592 **
14593 ** This version of the memory allocation subsystem is included
14594 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14595 **
14596 ** $Id: mem5.c,v 1.19 2008/11/19 16:52:44 danielk1977 Exp $
14597 */
14598
14599 /*
14600 ** This version of the memory allocator is used only when 
14601 ** SQLITE_ENABLE_MEMSYS5 is defined.
14602 */
14603 #ifdef SQLITE_ENABLE_MEMSYS5
14604
14605 /*
14606 ** A minimum allocation is an instance of the following structure.
14607 ** Larger allocations are an array of these structures where the
14608 ** size of the array is a power of 2.
14609 */
14610 typedef struct Mem5Link Mem5Link;
14611 struct Mem5Link {
14612   int next;       /* Index of next free chunk */
14613   int prev;       /* Index of previous free chunk */
14614 };
14615
14616 /*
14617 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.nAtom). Since
14618 ** mem5.nAtom is always at least 8, this is not really a practical
14619 ** limitation.
14620 */
14621 #define LOGMAX 30
14622
14623 /*
14624 ** Masks used for mem5.aCtrl[] elements.
14625 */
14626 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block relative to POW2_MIN */
14627 #define CTRL_FREE     0x20    /* True if not checked out */
14628
14629 /*
14630 ** All of the static variables used by this module are collected
14631 ** into a single structure named "mem5".  This is to keep the
14632 ** static variables organized and to reduce namespace pollution
14633 ** when this module is combined with other in the amalgamation.
14634 */
14635 static SQLITE_WSD struct Mem5Global {
14636   /*
14637   ** Memory available for allocation
14638   */
14639   int nAtom;       /* Smallest possible allocation in bytes */
14640   int nBlock;      /* Number of nAtom sized blocks in zPool */
14641   u8 *zPool;
14642   
14643   /*
14644   ** Mutex to control access to the memory allocation subsystem.
14645   */
14646   sqlite3_mutex *mutex;
14647
14648   /*
14649   ** Performance statistics
14650   */
14651   u64 nAlloc;         /* Total number of calls to malloc */
14652   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14653   u64 totalExcess;    /* Total internal fragmentation */
14654   u32 currentOut;     /* Current checkout, including internal fragmentation */
14655   u32 currentCount;   /* Current number of distinct checkouts */
14656   u32 maxOut;         /* Maximum instantaneous currentOut */
14657   u32 maxCount;       /* Maximum instantaneous currentCount */
14658   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14659   
14660   /*
14661   ** Lists of free blocks of various sizes.
14662   */
14663   int aiFreelist[LOGMAX+1];
14664
14665   /*
14666   ** Space for tracking which blocks are checked out and the size
14667   ** of each block.  One byte per block.
14668   */
14669   u8 *aCtrl;
14670
14671 } mem5 = { 19804167 };
14672
14673 #define mem5 GLOBAL(struct Mem5Global, mem5)
14674
14675 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.nAtom]))
14676
14677 /*
14678 ** Unlink the chunk at mem5.aPool[i] from list it is currently
14679 ** on.  It should be found on mem5.aiFreelist[iLogsize].
14680 */
14681 static void memsys5Unlink(int i, int iLogsize){
14682   int next, prev;
14683   assert( i>=0 && i<mem5.nBlock );
14684   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14685   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14686
14687   next = MEM5LINK(i)->next;
14688   prev = MEM5LINK(i)->prev;
14689   if( prev<0 ){
14690     mem5.aiFreelist[iLogsize] = next;
14691   }else{
14692     MEM5LINK(prev)->next = next;
14693   }
14694   if( next>=0 ){
14695     MEM5LINK(next)->prev = prev;
14696   }
14697 }
14698
14699 /*
14700 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14701 ** free list.
14702 */
14703 static void memsys5Link(int i, int iLogsize){
14704   int x;
14705   assert( sqlite3_mutex_held(mem5.mutex) );
14706   assert( i>=0 && i<mem5.nBlock );
14707   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14708   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14709
14710   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14711   MEM5LINK(i)->prev = -1;
14712   if( x>=0 ){
14713     assert( x<mem5.nBlock );
14714     MEM5LINK(x)->prev = i;
14715   }
14716   mem5.aiFreelist[iLogsize] = i;
14717 }
14718
14719 /*
14720 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14721 ** will already be held (obtained by code in malloc.c) if
14722 ** sqlite3GlobalConfig.bMemStat is true.
14723 */
14724 static void memsys5Enter(void){
14725   if( sqlite3GlobalConfig.bMemstat==0 && mem5.mutex==0 ){
14726     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14727   }
14728   sqlite3_mutex_enter(mem5.mutex);
14729 }
14730 static void memsys5Leave(void){
14731   sqlite3_mutex_leave(mem5.mutex);
14732 }
14733
14734 /*
14735 ** Return the size of an outstanding allocation, in bytes.  The
14736 ** size returned omits the 8-byte header overhead.  This only
14737 ** works for chunks that are currently checked out.
14738 */
14739 static int memsys5Size(void *p){
14740   int iSize = 0;
14741   if( p ){
14742     int i = ((u8 *)p-mem5.zPool)/mem5.nAtom;
14743     assert( i>=0 && i<mem5.nBlock );
14744     iSize = mem5.nAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14745   }
14746   return iSize;
14747 }
14748
14749 /*
14750 ** Find the first entry on the freelist iLogsize.  Unlink that
14751 ** entry and return its index. 
14752 */
14753 static int memsys5UnlinkFirst(int iLogsize){
14754   int i;
14755   int iFirst;
14756
14757   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14758   i = iFirst = mem5.aiFreelist[iLogsize];
14759   assert( iFirst>=0 );
14760   while( i>0 ){
14761     if( i<iFirst ) iFirst = i;
14762     i = MEM5LINK(i)->next;
14763   }
14764   memsys5Unlink(iFirst, iLogsize);
14765   return iFirst;
14766 }
14767
14768 /*
14769 ** Return a block of memory of at least nBytes in size.
14770 ** Return NULL if unable.
14771 */
14772 static void *memsys5MallocUnsafe(int nByte){
14773   int i;           /* Index of a mem5.aPool[] slot */
14774   int iBin;        /* Index into mem5.aiFreelist[] */
14775   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14776   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14777
14778   /* Keep track of the maximum allocation request.  Even unfulfilled
14779   ** requests are counted */
14780   if( (u32)nByte>mem5.maxRequest ){
14781     mem5.maxRequest = nByte;
14782   }
14783
14784   /* Round nByte up to the next valid power of two */
14785   for(iFullSz=mem5.nAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14786
14787   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14788   ** block.  If not, then split a block of the next larger power of
14789   ** two in order to create a new free block of size iLogsize.
14790   */
14791   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14792   if( iBin>LOGMAX ) return 0;
14793   i = memsys5UnlinkFirst(iBin);
14794   while( iBin>iLogsize ){
14795     int newSize;
14796
14797     iBin--;
14798     newSize = 1 << iBin;
14799     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14800     memsys5Link(i+newSize, iBin);
14801   }
14802   mem5.aCtrl[i] = iLogsize;
14803
14804   /* Update allocator performance statistics. */
14805   mem5.nAlloc++;
14806   mem5.totalAlloc += iFullSz;
14807   mem5.totalExcess += iFullSz - nByte;
14808   mem5.currentCount++;
14809   mem5.currentOut += iFullSz;
14810   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14811   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14812
14813   /* Return a pointer to the allocated memory. */
14814   return (void*)&mem5.zPool[i*mem5.nAtom];
14815 }
14816
14817 /*
14818 ** Free an outstanding memory allocation.
14819 */
14820 static void memsys5FreeUnsafe(void *pOld){
14821   u32 size, iLogsize;
14822   int iBlock;             
14823
14824   /* Set iBlock to the index of the block pointed to by pOld in 
14825   ** the array of mem5.nAtom byte blocks pointed to by mem5.zPool.
14826   */
14827   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.nAtom;
14828
14829   /* Check that the pointer pOld points to a valid, non-free block. */
14830   assert( iBlock>=0 && iBlock<mem5.nBlock );
14831   assert( ((u8 *)pOld-mem5.zPool)%mem5.nAtom==0 );
14832   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14833
14834   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14835   size = 1<<iLogsize;
14836   assert( iBlock+size-1<(u32)mem5.nBlock );
14837
14838   mem5.aCtrl[iBlock] |= CTRL_FREE;
14839   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14840   assert( mem5.currentCount>0 );
14841   assert( mem5.currentOut>=(size*mem5.nAtom) );
14842   mem5.currentCount--;
14843   mem5.currentOut -= size*mem5.nAtom;
14844   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14845   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14846
14847   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14848   while( iLogsize<LOGMAX ){
14849     int iBuddy;
14850     if( (iBlock>>iLogsize) & 1 ){
14851       iBuddy = iBlock - size;
14852     }else{
14853       iBuddy = iBlock + size;
14854     }
14855     assert( iBuddy>=0 );
14856     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14857     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14858     memsys5Unlink(iBuddy, iLogsize);
14859     iLogsize++;
14860     if( iBuddy<iBlock ){
14861       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14862       mem5.aCtrl[iBlock] = 0;
14863       iBlock = iBuddy;
14864     }else{
14865       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14866       mem5.aCtrl[iBuddy] = 0;
14867     }
14868     size *= 2;
14869   }
14870   memsys5Link(iBlock, iLogsize);
14871 }
14872
14873 /*
14874 ** Allocate nBytes of memory
14875 */
14876 static void *memsys5Malloc(int nBytes){
14877   sqlite3_int64 *p = 0;
14878   if( nBytes>0 ){
14879     memsys5Enter();
14880     p = memsys5MallocUnsafe(nBytes);
14881     memsys5Leave();
14882   }
14883   return (void*)p; 
14884 }
14885
14886 /*
14887 ** Free memory.
14888 */
14889 static void memsys5Free(void *pPrior){
14890   if( pPrior==0 ){
14891 assert(0);
14892     return;
14893   }
14894   memsys5Enter();
14895   memsys5FreeUnsafe(pPrior);
14896   memsys5Leave();  
14897 }
14898
14899 /*
14900 ** Change the size of an existing memory allocation
14901 */
14902 static void *memsys5Realloc(void *pPrior, int nBytes){
14903   int nOld;
14904   void *p;
14905   if( pPrior==0 ){
14906     return memsys5Malloc(nBytes);
14907   }
14908   if( nBytes<=0 ){
14909     memsys5Free(pPrior);
14910     return 0;
14911   }
14912   nOld = memsys5Size(pPrior);
14913   if( nBytes<=nOld ){
14914     return pPrior;
14915   }
14916   memsys5Enter();
14917   p = memsys5MallocUnsafe(nBytes);
14918   if( p ){
14919     memcpy(p, pPrior, nOld);
14920     memsys5FreeUnsafe(pPrior);
14921   }
14922   memsys5Leave();
14923   return p;
14924 }
14925
14926 /*
14927 ** Round up a request size to the next valid allocation size.
14928 */
14929 static int memsys5Roundup(int n){
14930   int iFullSz;
14931   for(iFullSz=mem5.nAtom; iFullSz<n; iFullSz *= 2);
14932   return iFullSz;
14933 }
14934
14935 static int memsys5Log(int iValue){
14936   int iLog;
14937   for(iLog=0; (1<<iLog)<iValue; iLog++);
14938   return iLog;
14939 }
14940
14941 /*
14942 ** Initialize this module.
14943 */
14944 static int memsys5Init(void *NotUsed){
14945   int ii;
14946   int nByte = sqlite3GlobalConfig.nHeap;
14947   u8 *zByte = (u8 *)sqlite3GlobalConfig.pHeap;
14948   int nMinLog;                 /* Log of minimum allocation size in bytes*/
14949   int iOffset;
14950
14951   UNUSED_PARAMETER(NotUsed);
14952
14953   if( !zByte ){
14954     return SQLITE_ERROR;
14955   }
14956
14957   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14958   mem5.nAtom = (1<<nMinLog);
14959   while( (int)sizeof(Mem5Link)>mem5.nAtom ){
14960     mem5.nAtom = mem5.nAtom << 1;
14961   }
14962
14963   mem5.nBlock = (nByte / (mem5.nAtom+sizeof(u8)));
14964   mem5.zPool = zByte;
14965   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.nAtom];
14966
14967   for(ii=0; ii<=LOGMAX; ii++){
14968     mem5.aiFreelist[ii] = -1;
14969   }
14970
14971   iOffset = 0;
14972   for(ii=LOGMAX; ii>=0; ii--){
14973     int nAlloc = (1<<ii);
14974     if( (iOffset+nAlloc)<=mem5.nBlock ){
14975       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14976       memsys5Link(iOffset, ii);
14977       iOffset += nAlloc;
14978     }
14979     assert((iOffset+nAlloc)>mem5.nBlock);
14980   }
14981
14982   return SQLITE_OK;
14983 }
14984
14985 /*
14986 ** Deinitialize this module.
14987 */
14988 static void memsys5Shutdown(void *NotUsed){
14989   UNUSED_PARAMETER(NotUsed);
14990   return;
14991 }
14992
14993 /*
14994 ** Open the file indicated and write a log of all unfreed memory 
14995 ** allocations into that log.
14996 */
14997 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14998 #ifdef SQLITE_DEBUG
14999   FILE *out;
15000   int i, j, n;
15001   int nMinLog;
15002
15003   if( zFilename==0 || zFilename[0]==0 ){
15004     out = stdout;
15005   }else{
15006     out = fopen(zFilename, "w");
15007     if( out==0 ){
15008       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15009                       zFilename);
15010       return;
15011     }
15012   }
15013   memsys5Enter();
15014   nMinLog = memsys5Log(mem5.nAtom);
15015   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15016     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15017     fprintf(out, "freelist items of size %d: %d\n", mem5.nAtom << i, n);
15018   }
15019   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15020   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15021   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15022   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15023   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15024   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15025   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15026   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15027   memsys5Leave();
15028   if( out==stdout ){
15029     fflush(stdout);
15030   }else{
15031     fclose(out);
15032   }
15033 #else
15034   UNUSED_PARAMETER(zFilename);
15035 #endif
15036 }
15037
15038 /*
15039 ** This routine is the only routine in this file with external 
15040 ** linkage. It returns a pointer to a static sqlite3_mem_methods
15041 ** struct populated with the memsys5 methods.
15042 */
15043 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15044   static const sqlite3_mem_methods memsys5Methods = {
15045      memsys5Malloc,
15046      memsys5Free,
15047      memsys5Realloc,
15048      memsys5Size,
15049      memsys5Roundup,
15050      memsys5Init,
15051      memsys5Shutdown,
15052      0
15053   };
15054   return &memsys5Methods;
15055 }
15056
15057 #endif /* SQLITE_ENABLE_MEMSYS5 */
15058
15059 /************** End of mem5.c ************************************************/
15060 /************** Begin file mutex.c *******************************************/
15061 /*
15062 ** 2007 August 14
15063 **
15064 ** The author disclaims copyright to this source code.  In place of
15065 ** a legal notice, here is a blessing:
15066 **
15067 **    May you do good and not evil.
15068 **    May you find forgiveness for yourself and forgive others.
15069 **    May you share freely, never taking more than you give.
15070 **
15071 *************************************************************************
15072 ** This file contains the C functions that implement mutexes.
15073 **
15074 ** This file contains code that is common across all mutex implementations.
15075
15076 **
15077 ** $Id: mutex.c,v 1.30 2009/02/17 16:29:11 danielk1977 Exp $
15078 */
15079
15080 #ifndef SQLITE_MUTEX_OMIT
15081 /*
15082 ** Initialize the mutex system.
15083 */
15084 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
15085   int rc = SQLITE_OK;
15086   if( sqlite3GlobalConfig.bCoreMutex ){
15087     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15088       /* If the xMutexAlloc method has not been set, then the user did not
15089       ** install a mutex implementation via sqlite3_config() prior to 
15090       ** sqlite3_initialize() being called. This block copies pointers to
15091       ** the default implementation into the sqlite3GlobalConfig structure.
15092       **
15093       ** The danger is that although sqlite3_config() is not a threadsafe
15094       ** API, sqlite3_initialize() is, and so multiple threads may be
15095       ** attempting to run this function simultaneously. To guard write
15096       ** access to the sqlite3GlobalConfig structure, the 'MASTER' static mutex
15097       ** is obtained before modifying it.
15098       */
15099       sqlite3_mutex_methods *p = sqlite3DefaultMutex();
15100       sqlite3_mutex *pMaster = 0;
15101   
15102       rc = p->xMutexInit();
15103       if( rc==SQLITE_OK ){
15104         pMaster = p->xMutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15105         assert(pMaster);
15106         p->xMutexEnter(pMaster);
15107         assert( sqlite3GlobalConfig.mutex.xMutexAlloc==0 
15108              || sqlite3GlobalConfig.mutex.xMutexAlloc==p->xMutexAlloc
15109         );
15110         if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15111           sqlite3GlobalConfig.mutex = *p;
15112         }
15113         p->xMutexLeave(pMaster);
15114       }
15115     }else{
15116       rc = sqlite3GlobalConfig.mutex.xMutexInit();
15117     }
15118   }
15119
15120   return rc;
15121 }
15122
15123 /*
15124 ** Shutdown the mutex system. This call frees resources allocated by
15125 ** sqlite3MutexInit().
15126 */
15127 SQLITE_PRIVATE int sqlite3MutexEnd(void){
15128   int rc = SQLITE_OK;
15129   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15130     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15131   }
15132   return rc;
15133 }
15134
15135 /*
15136 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15137 */
15138 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15139 #ifndef SQLITE_OMIT_AUTOINIT
15140   if( sqlite3_initialize() ) return 0;
15141 #endif
15142   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15143 }
15144
15145 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15146   if( !sqlite3GlobalConfig.bCoreMutex ){
15147     return 0;
15148   }
15149   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15150 }
15151
15152 /*
15153 ** Free a dynamic mutex.
15154 */
15155 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15156   if( p ){
15157     sqlite3GlobalConfig.mutex.xMutexFree(p);
15158   }
15159 }
15160
15161 /*
15162 ** Obtain the mutex p. If some other thread already has the mutex, block
15163 ** until it can be obtained.
15164 */
15165 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15166   if( p ){
15167     sqlite3GlobalConfig.mutex.xMutexEnter(p);
15168   }
15169 }
15170
15171 /*
15172 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15173 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15174 */
15175 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15176   int rc = SQLITE_OK;
15177   if( p ){
15178     return sqlite3GlobalConfig.mutex.xMutexTry(p);
15179   }
15180   return rc;
15181 }
15182
15183 /*
15184 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
15185 ** entered by the same thread.  The behavior is undefined if the mutex 
15186 ** is not currently entered. If a NULL pointer is passed as an argument
15187 ** this function is a no-op.
15188 */
15189 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15190   if( p ){
15191     sqlite3GlobalConfig.mutex.xMutexLeave(p);
15192   }
15193 }
15194
15195 #ifndef NDEBUG
15196 /*
15197 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15198 ** intended for use inside assert() statements.
15199 */
15200 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15201   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15202 }
15203 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15204   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15205 }
15206 #endif
15207
15208 #endif /* SQLITE_OMIT_MUTEX */
15209
15210 /************** End of mutex.c ***********************************************/
15211 /************** Begin file mutex_noop.c **************************************/
15212 /*
15213 ** 2008 October 07
15214 **
15215 ** The author disclaims copyright to this source code.  In place of
15216 ** a legal notice, here is a blessing:
15217 **
15218 **    May you do good and not evil.
15219 **    May you find forgiveness for yourself and forgive others.
15220 **    May you share freely, never taking more than you give.
15221 **
15222 *************************************************************************
15223 ** This file contains the C functions that implement mutexes.
15224 **
15225 ** This implementation in this file does not provide any mutual
15226 ** exclusion and is thus suitable for use only in applications
15227 ** that use SQLite in a single thread.  The routines defined
15228 ** here are place-holders.  Applications can substitute working
15229 ** mutex routines at start-time using the
15230 **
15231 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15232 **
15233 ** interface.
15234 **
15235 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
15236 ** that does error checking on mutexes to make sure they are being
15237 ** called correctly.
15238 **
15239 ** $Id: mutex_noop.c,v 1.3 2008/12/05 17:17:08 drh Exp $
15240 */
15241
15242
15243 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
15244 /*
15245 ** Stub routines for all mutex methods.
15246 **
15247 ** This routines provide no mutual exclusion or error checking.
15248 */
15249 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
15250 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
15251 static int noopMutexInit(void){ return SQLITE_OK; }
15252 static int noopMutexEnd(void){ return SQLITE_OK; }
15253 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
15254 static void noopMutexFree(sqlite3_mutex *p){ return; }
15255 static void noopMutexEnter(sqlite3_mutex *p){ return; }
15256 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
15257 static void noopMutexLeave(sqlite3_mutex *p){ return; }
15258
15259 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15260   static sqlite3_mutex_methods sMutex = {
15261     noopMutexInit,
15262     noopMutexEnd,
15263     noopMutexAlloc,
15264     noopMutexFree,
15265     noopMutexEnter,
15266     noopMutexTry,
15267     noopMutexLeave,
15268
15269     noopMutexHeld,
15270     noopMutexNotheld
15271   };
15272
15273   return &sMutex;
15274 }
15275 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
15276
15277 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
15278 /*
15279 ** In this implementation, error checking is provided for testing
15280 ** and debugging purposes.  The mutexes still do not provide any
15281 ** mutual exclusion.
15282 */
15283
15284 /*
15285 ** The mutex object
15286 */
15287 struct sqlite3_mutex {
15288   int id;     /* The mutex type */
15289   int cnt;    /* Number of entries without a matching leave */
15290 };
15291
15292 /*
15293 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15294 ** intended for use inside assert() statements.
15295 */
15296 static int debugMutexHeld(sqlite3_mutex *p){
15297   return p==0 || p->cnt>0;
15298 }
15299 static int debugMutexNotheld(sqlite3_mutex *p){
15300   return p==0 || p->cnt==0;
15301 }
15302
15303 /*
15304 ** Initialize and deinitialize the mutex subsystem.
15305 */
15306 static int debugMutexInit(void){ return SQLITE_OK; }
15307 static int debugMutexEnd(void){ return SQLITE_OK; }
15308
15309 /*
15310 ** The sqlite3_mutex_alloc() routine allocates a new
15311 ** mutex and returns a pointer to it.  If it returns NULL
15312 ** that means that a mutex could not be allocated. 
15313 */
15314 static sqlite3_mutex *debugMutexAlloc(int id){
15315   static sqlite3_mutex aStatic[6];
15316   sqlite3_mutex *pNew = 0;
15317   switch( id ){
15318     case SQLITE_MUTEX_FAST:
15319     case SQLITE_MUTEX_RECURSIVE: {
15320       pNew = sqlite3Malloc(sizeof(*pNew));
15321       if( pNew ){
15322         pNew->id = id;
15323         pNew->cnt = 0;
15324       }
15325       break;
15326     }
15327     default: {
15328       assert( id-2 >= 0 );
15329       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15330       pNew = &aStatic[id-2];
15331       pNew->id = id;
15332       break;
15333     }
15334   }
15335   return pNew;
15336 }
15337
15338 /*
15339 ** This routine deallocates a previously allocated mutex.
15340 */
15341 static void debugMutexFree(sqlite3_mutex *p){
15342   assert( p->cnt==0 );
15343   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15344   sqlite3_free(p);
15345 }
15346
15347 /*
15348 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15349 ** to enter a mutex.  If another thread is already within the mutex,
15350 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15351 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15352 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15353 ** be entered multiple times by the same thread.  In such cases the,
15354 ** mutex must be exited an equal number of times before another thread
15355 ** can enter.  If the same thread tries to enter any other kind of mutex
15356 ** more than once, the behavior is undefined.
15357 */
15358 static void debugMutexEnter(sqlite3_mutex *p){
15359   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15360   p->cnt++;
15361 }
15362 static int debugMutexTry(sqlite3_mutex *p){
15363   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15364   p->cnt++;
15365   return SQLITE_OK;
15366 }
15367
15368 /*
15369 ** The sqlite3_mutex_leave() routine exits a mutex that was
15370 ** previously entered by the same thread.  The behavior
15371 ** is undefined if the mutex is not currently entered or
15372 ** is not currently allocated.  SQLite will never do either.
15373 */
15374 static void debugMutexLeave(sqlite3_mutex *p){
15375   assert( debugMutexHeld(p) );
15376   p->cnt--;
15377   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15378 }
15379
15380 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15381   static sqlite3_mutex_methods sMutex = {
15382     debugMutexInit,
15383     debugMutexEnd,
15384     debugMutexAlloc,
15385     debugMutexFree,
15386     debugMutexEnter,
15387     debugMutexTry,
15388     debugMutexLeave,
15389
15390     debugMutexHeld,
15391     debugMutexNotheld
15392   };
15393
15394   return &sMutex;
15395 }
15396 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
15397
15398 /************** End of mutex_noop.c ******************************************/
15399 /************** Begin file mutex_os2.c ***************************************/
15400 /*
15401 ** 2007 August 28
15402 **
15403 ** The author disclaims copyright to this source code.  In place of
15404 ** a legal notice, here is a blessing:
15405 **
15406 **    May you do good and not evil.
15407 **    May you find forgiveness for yourself and forgive others.
15408 **    May you share freely, never taking more than you give.
15409 **
15410 *************************************************************************
15411 ** This file contains the C functions that implement mutexes for OS/2
15412 **
15413 ** $Id: mutex_os2.c,v 1.11 2008/11/22 19:50:54 pweilbacher Exp $
15414 */
15415
15416 /*
15417 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15418 ** See the mutex.h file for details.
15419 */
15420 #ifdef SQLITE_MUTEX_OS2
15421
15422 /********************** OS/2 Mutex Implementation **********************
15423 **
15424 ** This implementation of mutexes is built using the OS/2 API.
15425 */
15426
15427 /*
15428 ** The mutex object
15429 ** Each recursive mutex is an instance of the following structure.
15430 */
15431 struct sqlite3_mutex {
15432   HMTX mutex;       /* Mutex controlling the lock */
15433   int  id;          /* Mutex type */
15434   int  nRef;        /* Number of references */
15435   TID  owner;       /* Thread holding this mutex */
15436 };
15437
15438 #define OS2_MUTEX_INITIALIZER   0,0,0,0
15439
15440 /*
15441 ** Initialize and deinitialize the mutex subsystem.
15442 */
15443 static int os2MutexInit(void){ return SQLITE_OK; }
15444 static int os2MutexEnd(void){ return SQLITE_OK; }
15445
15446 /*
15447 ** The sqlite3_mutex_alloc() routine allocates a new
15448 ** mutex and returns a pointer to it.  If it returns NULL
15449 ** that means that a mutex could not be allocated. 
15450 ** SQLite will unwind its stack and return an error.  The argument
15451 ** to sqlite3_mutex_alloc() is one of these integer constants:
15452 **
15453 ** <ul>
15454 ** <li>  SQLITE_MUTEX_FAST               0
15455 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15456 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15457 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15458 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15459 ** </ul>
15460 **
15461 ** The first two constants cause sqlite3_mutex_alloc() to create
15462 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15463 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15464 ** The mutex implementation does not need to make a distinction
15465 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15466 ** not want to.  But SQLite will only request a recursive mutex in
15467 ** cases where it really needs one.  If a faster non-recursive mutex
15468 ** implementation is available on the host platform, the mutex subsystem
15469 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15470 **
15471 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15472 ** a pointer to a static preexisting mutex.  Three static mutexes are
15473 ** used by the current version of SQLite.  Future versions of SQLite
15474 ** may add additional static mutexes.  Static mutexes are for internal
15475 ** use by SQLite only.  Applications that use SQLite mutexes should
15476 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15477 ** SQLITE_MUTEX_RECURSIVE.
15478 **
15479 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15480 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15481 ** returns a different mutex on every call.  But for the static
15482 ** mutex types, the same mutex is returned on every call that has
15483 ** the same type number.
15484 */
15485 static sqlite3_mutex *os2MutexAlloc(int iType){
15486   sqlite3_mutex *p = NULL;
15487   switch( iType ){
15488     case SQLITE_MUTEX_FAST:
15489     case SQLITE_MUTEX_RECURSIVE: {
15490       p = sqlite3MallocZero( sizeof(*p) );
15491       if( p ){
15492         p->id = iType;
15493         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15494           sqlite3_free( p );
15495           p = NULL;
15496         }
15497       }
15498       break;
15499     }
15500     default: {
15501       static volatile int isInit = 0;
15502       static sqlite3_mutex staticMutexes[] = {
15503         { OS2_MUTEX_INITIALIZER, },
15504         { OS2_MUTEX_INITIALIZER, },
15505         { OS2_MUTEX_INITIALIZER, },
15506         { OS2_MUTEX_INITIALIZER, },
15507         { OS2_MUTEX_INITIALIZER, },
15508         { OS2_MUTEX_INITIALIZER, },
15509       };
15510       if ( !isInit ){
15511         APIRET rc;
15512         PTIB ptib;
15513         PPIB ppib;
15514         HMTX mutex;
15515         char name[32];
15516         DosGetInfoBlocks( &ptib, &ppib );
15517         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15518                           ppib->pib_ulpid );
15519         while( !isInit ){
15520           mutex = 0;
15521           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15522           if( rc == NO_ERROR ){
15523             unsigned int i;
15524             if( !isInit ){
15525               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15526                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15527               }
15528               isInit = 1;
15529             }
15530             DosCloseMutexSem( mutex );
15531           }else if( rc == ERROR_DUPLICATE_NAME ){
15532             DosSleep( 1 );
15533           }else{
15534             return p;
15535           }
15536         }
15537       }
15538       assert( iType-2 >= 0 );
15539       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15540       p = &staticMutexes[iType-2];
15541       p->id = iType;
15542       break;
15543     }
15544   }
15545   return p;
15546 }
15547
15548
15549 /*
15550 ** This routine deallocates a previously allocated mutex.
15551 ** SQLite is careful to deallocate every mutex that it allocates.
15552 */
15553 static void os2MutexFree(sqlite3_mutex *p){
15554   if( p==0 ) return;
15555   assert( p->nRef==0 );
15556   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15557   DosCloseMutexSem( p->mutex );
15558   sqlite3_free( p );
15559 }
15560
15561 /*
15562 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15563 ** to enter a mutex.  If another thread is already within the mutex,
15564 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15565 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15566 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15567 ** be entered multiple times by the same thread.  In such cases the,
15568 ** mutex must be exited an equal number of times before another thread
15569 ** can enter.  If the same thread tries to enter any other kind of mutex
15570 ** more than once, the behavior is undefined.
15571 */
15572 static void os2MutexEnter(sqlite3_mutex *p){
15573   TID tid;
15574   PID holder1;
15575   ULONG holder2;
15576   if( p==0 ) return;
15577   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15578   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15579   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15580   p->owner = tid;
15581   p->nRef++;
15582 }
15583 static int os2MutexTry(sqlite3_mutex *p){
15584   int rc;
15585   TID tid;
15586   PID holder1;
15587   ULONG holder2;
15588   if( p==0 ) return SQLITE_OK;
15589   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15590   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15591     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15592     p->owner = tid;
15593     p->nRef++;
15594     rc = SQLITE_OK;
15595   } else {
15596     rc = SQLITE_BUSY;
15597   }
15598
15599   return rc;
15600 }
15601
15602 /*
15603 ** The sqlite3_mutex_leave() routine exits a mutex that was
15604 ** previously entered by the same thread.  The behavior
15605 ** is undefined if the mutex is not currently entered or
15606 ** is not currently allocated.  SQLite will never do either.
15607 */
15608 static void os2MutexLeave(sqlite3_mutex *p){
15609   TID tid;
15610   PID holder1;
15611   ULONG holder2;
15612   if( p==0 ) return;
15613   assert( p->nRef>0 );
15614   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15615   assert( p->owner==tid );
15616   p->nRef--;
15617   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15618   DosReleaseMutexSem(p->mutex);
15619 }
15620
15621 #ifdef SQLITE_DEBUG
15622 /*
15623 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15624 ** intended for use inside assert() statements.
15625 */
15626 static int os2MutexHeld(sqlite3_mutex *p){
15627   TID tid;
15628   PID pid;
15629   ULONG ulCount;
15630   PTIB ptib;
15631   if( p!=0 ) {
15632     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15633   } else {
15634     DosGetInfoBlocks(&ptib, NULL);
15635     tid = ptib->tib_ptib2->tib2_ultid;
15636   }
15637   return p==0 || (p->nRef!=0 && p->owner==tid);
15638 }
15639 static int os2MutexNotheld(sqlite3_mutex *p){
15640   TID tid;
15641   PID pid;
15642   ULONG ulCount;
15643   PTIB ptib;
15644   if( p!= 0 ) {
15645     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15646   } else {
15647     DosGetInfoBlocks(&ptib, NULL);
15648     tid = ptib->tib_ptib2->tib2_ultid;
15649   }
15650   return p==0 || p->nRef==0 || p->owner!=tid;
15651 }
15652 #endif
15653
15654 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15655   static sqlite3_mutex_methods sMutex = {
15656     os2MutexInit,
15657     os2MutexEnd,
15658     os2MutexAlloc,
15659     os2MutexFree,
15660     os2MutexEnter,
15661     os2MutexTry,
15662     os2MutexLeave,
15663 #ifdef SQLITE_DEBUG
15664     os2MutexHeld,
15665     os2MutexNotheld
15666 #endif
15667   };
15668
15669   return &sMutex;
15670 }
15671 #endif /* SQLITE_MUTEX_OS2 */
15672
15673 /************** End of mutex_os2.c *******************************************/
15674 /************** Begin file mutex_unix.c **************************************/
15675 /*
15676 ** 2007 August 28
15677 **
15678 ** The author disclaims copyright to this source code.  In place of
15679 ** a legal notice, here is a blessing:
15680 **
15681 **    May you do good and not evil.
15682 **    May you find forgiveness for yourself and forgive others.
15683 **    May you share freely, never taking more than you give.
15684 **
15685 *************************************************************************
15686 ** This file contains the C functions that implement mutexes for pthreads
15687 **
15688 ** $Id: mutex_unix.c,v 1.16 2008/12/08 18:19:18 drh Exp $
15689 */
15690
15691 /*
15692 ** The code in this file is only used if we are compiling threadsafe
15693 ** under unix with pthreads.
15694 **
15695 ** Note that this implementation requires a version of pthreads that
15696 ** supports recursive mutexes.
15697 */
15698 #ifdef SQLITE_MUTEX_PTHREADS
15699
15700 #include <pthread.h>
15701
15702
15703 /*
15704 ** Each recursive mutex is an instance of the following structure.
15705 */
15706 struct sqlite3_mutex {
15707   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15708   int id;                    /* Mutex type */
15709   int nRef;                  /* Number of entrances */
15710   pthread_t owner;           /* Thread that is within this mutex */
15711 #ifdef SQLITE_DEBUG
15712   int trace;                 /* True to trace changes */
15713 #endif
15714 };
15715 #ifdef SQLITE_DEBUG
15716 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15717 #else
15718 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15719 #endif
15720
15721 /*
15722 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15723 ** intended for use only inside assert() statements.  On some platforms,
15724 ** there might be race conditions that can cause these routines to
15725 ** deliver incorrect results.  In particular, if pthread_equal() is
15726 ** not an atomic operation, then these routines might delivery
15727 ** incorrect results.  On most platforms, pthread_equal() is a 
15728 ** comparison of two integers and is therefore atomic.  But we are
15729 ** told that HPUX is not such a platform.  If so, then these routines
15730 ** will not always work correctly on HPUX.
15731 **
15732 ** On those platforms where pthread_equal() is not atomic, SQLite
15733 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15734 ** make sure no assert() statements are evaluated and hence these
15735 ** routines are never called.
15736 */
15737 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15738 static int pthreadMutexHeld(sqlite3_mutex *p){
15739   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15740 }
15741 static int pthreadMutexNotheld(sqlite3_mutex *p){
15742   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15743 }
15744 #endif
15745
15746 /*
15747 ** Initialize and deinitialize the mutex subsystem.
15748 */
15749 static int pthreadMutexInit(void){ return SQLITE_OK; }
15750 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15751
15752 /*
15753 ** The sqlite3_mutex_alloc() routine allocates a new
15754 ** mutex and returns a pointer to it.  If it returns NULL
15755 ** that means that a mutex could not be allocated.  SQLite
15756 ** will unwind its stack and return an error.  The argument
15757 ** to sqlite3_mutex_alloc() is one of these integer constants:
15758 **
15759 ** <ul>
15760 ** <li>  SQLITE_MUTEX_FAST
15761 ** <li>  SQLITE_MUTEX_RECURSIVE
15762 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15763 ** <li>  SQLITE_MUTEX_STATIC_MEM
15764 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15765 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15766 ** <li>  SQLITE_MUTEX_STATIC_LRU
15767 ** </ul>
15768 **
15769 ** The first two constants cause sqlite3_mutex_alloc() to create
15770 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15771 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15772 ** The mutex implementation does not need to make a distinction
15773 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15774 ** not want to.  But SQLite will only request a recursive mutex in
15775 ** cases where it really needs one.  If a faster non-recursive mutex
15776 ** implementation is available on the host platform, the mutex subsystem
15777 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15778 **
15779 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15780 ** a pointer to a static preexisting mutex.  Three static mutexes are
15781 ** used by the current version of SQLite.  Future versions of SQLite
15782 ** may add additional static mutexes.  Static mutexes are for internal
15783 ** use by SQLite only.  Applications that use SQLite mutexes should
15784 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15785 ** SQLITE_MUTEX_RECURSIVE.
15786 **
15787 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15788 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15789 ** returns a different mutex on every call.  But for the static 
15790 ** mutex types, the same mutex is returned on every call that has
15791 ** the same type number.
15792 */
15793 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15794   static sqlite3_mutex staticMutexes[] = {
15795     SQLITE3_MUTEX_INITIALIZER,
15796     SQLITE3_MUTEX_INITIALIZER,
15797     SQLITE3_MUTEX_INITIALIZER,
15798     SQLITE3_MUTEX_INITIALIZER,
15799     SQLITE3_MUTEX_INITIALIZER,
15800     SQLITE3_MUTEX_INITIALIZER
15801   };
15802   sqlite3_mutex *p;
15803   switch( iType ){
15804     case SQLITE_MUTEX_RECURSIVE: {
15805       p = sqlite3MallocZero( sizeof(*p) );
15806       if( p ){
15807 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15808         /* If recursive mutexes are not available, we will have to
15809         ** build our own.  See below. */
15810         pthread_mutex_init(&p->mutex, 0);
15811 #else
15812         /* Use a recursive mutex if it is available */
15813         pthread_mutexattr_t recursiveAttr;
15814         pthread_mutexattr_init(&recursiveAttr);
15815         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15816         pthread_mutex_init(&p->mutex, &recursiveAttr);
15817         pthread_mutexattr_destroy(&recursiveAttr);
15818 #endif
15819         p->id = iType;
15820       }
15821       break;
15822     }
15823     case SQLITE_MUTEX_FAST: {
15824       p = sqlite3MallocZero( sizeof(*p) );
15825       if( p ){
15826         p->id = iType;
15827         pthread_mutex_init(&p->mutex, 0);
15828       }
15829       break;
15830     }
15831     default: {
15832       assert( iType-2 >= 0 );
15833       assert( iType-2 < ArraySize(staticMutexes) );
15834       p = &staticMutexes[iType-2];
15835       p->id = iType;
15836       break;
15837     }
15838   }
15839   return p;
15840 }
15841
15842
15843 /*
15844 ** This routine deallocates a previously
15845 ** allocated mutex.  SQLite is careful to deallocate every
15846 ** mutex that it allocates.
15847 */
15848 static void pthreadMutexFree(sqlite3_mutex *p){
15849   assert( p->nRef==0 );
15850   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15851   pthread_mutex_destroy(&p->mutex);
15852   sqlite3_free(p);
15853 }
15854
15855 /*
15856 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15857 ** to enter a mutex.  If another thread is already within the mutex,
15858 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15859 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15860 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15861 ** be entered multiple times by the same thread.  In such cases the,
15862 ** mutex must be exited an equal number of times before another thread
15863 ** can enter.  If the same thread tries to enter any other kind of mutex
15864 ** more than once, the behavior is undefined.
15865 */
15866 static void pthreadMutexEnter(sqlite3_mutex *p){
15867   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15868
15869 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15870   /* If recursive mutexes are not available, then we have to grow
15871   ** our own.  This implementation assumes that pthread_equal()
15872   ** is atomic - that it cannot be deceived into thinking self
15873   ** and p->owner are equal if p->owner changes between two values
15874   ** that are not equal to self while the comparison is taking place.
15875   ** This implementation also assumes a coherent cache - that 
15876   ** separate processes cannot read different values from the same
15877   ** address at the same time.  If either of these two conditions
15878   ** are not met, then the mutexes will fail and problems will result.
15879   */
15880   {
15881     pthread_t self = pthread_self();
15882     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15883       p->nRef++;
15884     }else{
15885       pthread_mutex_lock(&p->mutex);
15886       assert( p->nRef==0 );
15887       p->owner = self;
15888       p->nRef = 1;
15889     }
15890   }
15891 #else
15892   /* Use the built-in recursive mutexes if they are available.
15893   */
15894   pthread_mutex_lock(&p->mutex);
15895   p->owner = pthread_self();
15896   p->nRef++;
15897 #endif
15898
15899 #ifdef SQLITE_DEBUG
15900   if( p->trace ){
15901     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15902   }
15903 #endif
15904 }
15905 static int pthreadMutexTry(sqlite3_mutex *p){
15906   int rc;
15907   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15908
15909 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15910   /* If recursive mutexes are not available, then we have to grow
15911   ** our own.  This implementation assumes that pthread_equal()
15912   ** is atomic - that it cannot be deceived into thinking self
15913   ** and p->owner are equal if p->owner changes between two values
15914   ** that are not equal to self while the comparison is taking place.
15915   ** This implementation also assumes a coherent cache - that 
15916   ** separate processes cannot read different values from the same
15917   ** address at the same time.  If either of these two conditions
15918   ** are not met, then the mutexes will fail and problems will result.
15919   */
15920   {
15921     pthread_t self = pthread_self();
15922     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15923       p->nRef++;
15924       rc = SQLITE_OK;
15925     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15926       assert( p->nRef==0 );
15927       p->owner = self;
15928       p->nRef = 1;
15929       rc = SQLITE_OK;
15930     }else{
15931       rc = SQLITE_BUSY;
15932     }
15933   }
15934 #else
15935   /* Use the built-in recursive mutexes if they are available.
15936   */
15937   if( pthread_mutex_trylock(&p->mutex)==0 ){
15938     p->owner = pthread_self();
15939     p->nRef++;
15940     rc = SQLITE_OK;
15941   }else{
15942     rc = SQLITE_BUSY;
15943   }
15944 #endif
15945
15946 #ifdef SQLITE_DEBUG
15947   if( rc==SQLITE_OK && p->trace ){
15948     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15949   }
15950 #endif
15951   return rc;
15952 }
15953
15954 /*
15955 ** The sqlite3_mutex_leave() routine exits a mutex that was
15956 ** previously entered by the same thread.  The behavior
15957 ** is undefined if the mutex is not currently entered or
15958 ** is not currently allocated.  SQLite will never do either.
15959 */
15960 static void pthreadMutexLeave(sqlite3_mutex *p){
15961   assert( pthreadMutexHeld(p) );
15962   p->nRef--;
15963   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15964
15965 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15966   if( p->nRef==0 ){
15967     pthread_mutex_unlock(&p->mutex);
15968   }
15969 #else
15970   pthread_mutex_unlock(&p->mutex);
15971 #endif
15972
15973 #ifdef SQLITE_DEBUG
15974   if( p->trace ){
15975     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15976   }
15977 #endif
15978 }
15979
15980 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15981   static sqlite3_mutex_methods sMutex = {
15982     pthreadMutexInit,
15983     pthreadMutexEnd,
15984     pthreadMutexAlloc,
15985     pthreadMutexFree,
15986     pthreadMutexEnter,
15987     pthreadMutexTry,
15988     pthreadMutexLeave,
15989 #ifdef SQLITE_DEBUG
15990     pthreadMutexHeld,
15991     pthreadMutexNotheld
15992 #else
15993     0,
15994     0
15995 #endif
15996   };
15997
15998   return &sMutex;
15999 }
16000
16001 #endif /* SQLITE_MUTEX_PTHREAD */
16002
16003 /************** End of mutex_unix.c ******************************************/
16004 /************** Begin file mutex_w32.c ***************************************/
16005 /*
16006 ** 2007 August 14
16007 **
16008 ** The author disclaims copyright to this source code.  In place of
16009 ** a legal notice, here is a blessing:
16010 **
16011 **    May you do good and not evil.
16012 **    May you find forgiveness for yourself and forgive others.
16013 **    May you share freely, never taking more than you give.
16014 **
16015 *************************************************************************
16016 ** This file contains the C functions that implement mutexes for win32
16017 **
16018 ** $Id: mutex_w32.c,v 1.15 2009/01/30 16:09:23 shane Exp $
16019 */
16020
16021 /*
16022 ** The code in this file is only used if we are compiling multithreaded
16023 ** on a win32 system.
16024 */
16025 #ifdef SQLITE_MUTEX_W32
16026
16027 /*
16028 ** Each recursive mutex is an instance of the following structure.
16029 */
16030 struct sqlite3_mutex {
16031   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16032   int id;                    /* Mutex type */
16033   int nRef;                  /* Number of enterances */
16034   DWORD owner;               /* Thread holding this mutex */
16035 };
16036
16037 /*
16038 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16039 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16040 **
16041 ** Here is an interesting observation:  Win95, Win98, and WinME lack
16042 ** the LockFileEx() API.  But we can still statically link against that
16043 ** API as long as we don't call it win running Win95/98/ME.  A call to
16044 ** this routine is used to determine if the host is Win95/98/ME or
16045 ** WinNT/2K/XP so that we will know whether or not we can safely call
16046 ** the LockFileEx() API.
16047 **
16048 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16049 ** which is only available if your application was compiled with 
16050 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16051 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
16052 ** this out as well.
16053 */
16054 #if 0
16055 #if SQLITE_OS_WINCE
16056 # define mutexIsNT()  (1)
16057 #else
16058   static int mutexIsNT(void){
16059     static int osType = 0;
16060     if( osType==0 ){
16061       OSVERSIONINFO sInfo;
16062       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16063       GetVersionEx(&sInfo);
16064       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16065     }
16066     return osType==2;
16067   }
16068 #endif /* SQLITE_OS_WINCE */
16069 #endif
16070
16071 #ifdef SQLITE_DEBUG
16072 /*
16073 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16074 ** intended for use only inside assert() statements.
16075 */
16076 static int winMutexHeld(sqlite3_mutex *p){
16077   return p->nRef!=0 && p->owner==GetCurrentThreadId();
16078 }
16079 static int winMutexNotheld(sqlite3_mutex *p){
16080   return p->nRef==0 || p->owner!=GetCurrentThreadId();
16081 }
16082 #endif
16083
16084
16085 /*
16086 ** Initialize and deinitialize the mutex subsystem.
16087 */
16088 static int winMutexInit(void){ return SQLITE_OK; }
16089 static int winMutexEnd(void){ return SQLITE_OK; }
16090
16091 /*
16092 ** The sqlite3_mutex_alloc() routine allocates a new
16093 ** mutex and returns a pointer to it.  If it returns NULL
16094 ** that means that a mutex could not be allocated.  SQLite
16095 ** will unwind its stack and return an error.  The argument
16096 ** to sqlite3_mutex_alloc() is one of these integer constants:
16097 **
16098 ** <ul>
16099 ** <li>  SQLITE_MUTEX_FAST               0
16100 ** <li>  SQLITE_MUTEX_RECURSIVE          1
16101 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16102 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
16103 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16104 ** </ul>
16105 **
16106 ** The first two constants cause sqlite3_mutex_alloc() to create
16107 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16108 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16109 ** The mutex implementation does not need to make a distinction
16110 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16111 ** not want to.  But SQLite will only request a recursive mutex in
16112 ** cases where it really needs one.  If a faster non-recursive mutex
16113 ** implementation is available on the host platform, the mutex subsystem
16114 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16115 **
16116 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16117 ** a pointer to a static preexisting mutex.  Three static mutexes are
16118 ** used by the current version of SQLite.  Future versions of SQLite
16119 ** may add additional static mutexes.  Static mutexes are for internal
16120 ** use by SQLite only.  Applications that use SQLite mutexes should
16121 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16122 ** SQLITE_MUTEX_RECURSIVE.
16123 **
16124 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16125 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16126 ** returns a different mutex on every call.  But for the static 
16127 ** mutex types, the same mutex is returned on every call that has
16128 ** the same type number.
16129 */
16130 static sqlite3_mutex *winMutexAlloc(int iType){
16131   sqlite3_mutex *p;
16132
16133   switch( iType ){
16134     case SQLITE_MUTEX_FAST:
16135     case SQLITE_MUTEX_RECURSIVE: {
16136       p = sqlite3MallocZero( sizeof(*p) );
16137       if( p ){
16138         p->id = iType;
16139         InitializeCriticalSection(&p->mutex);
16140       }
16141       break;
16142     }
16143     default: {
16144       static sqlite3_mutex staticMutexes[6];
16145       static int isInit = 0;
16146       while( !isInit ){
16147         static long lock = 0;
16148         if( InterlockedIncrement(&lock)==1 ){
16149           int i;
16150           for(i=0; i<sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++){
16151             InitializeCriticalSection(&staticMutexes[i].mutex);
16152           }
16153           isInit = 1;
16154         }else{
16155           Sleep(1);
16156         }
16157       }
16158       assert( iType-2 >= 0 );
16159       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16160       p = &staticMutexes[iType-2];
16161       p->id = iType;
16162       break;
16163     }
16164   }
16165   return p;
16166 }
16167
16168
16169 /*
16170 ** This routine deallocates a previously
16171 ** allocated mutex.  SQLite is careful to deallocate every
16172 ** mutex that it allocates.
16173 */
16174 static void winMutexFree(sqlite3_mutex *p){
16175   assert( p );
16176   assert( p->nRef==0 );
16177   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16178   DeleteCriticalSection(&p->mutex);
16179   sqlite3_free(p);
16180 }
16181
16182 /*
16183 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16184 ** to enter a mutex.  If another thread is already within the mutex,
16185 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16186 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16187 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16188 ** be entered multiple times by the same thread.  In such cases the,
16189 ** mutex must be exited an equal number of times before another thread
16190 ** can enter.  If the same thread tries to enter any other kind of mutex
16191 ** more than once, the behavior is undefined.
16192 */
16193 static void winMutexEnter(sqlite3_mutex *p){
16194   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
16195   EnterCriticalSection(&p->mutex);
16196   p->owner = GetCurrentThreadId(); 
16197   p->nRef++;
16198 }
16199 static int winMutexTry(sqlite3_mutex *p){
16200   int rc = SQLITE_BUSY;
16201   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
16202   /*
16203   ** The sqlite3_mutex_try() routine is very rarely used, and when it
16204   ** is used it is merely an optimization.  So it is OK for it to always
16205   ** fail.  
16206   **
16207   ** The TryEnterCriticalSection() interface is only available on WinNT.
16208   ** And some windows compilers complain if you try to use it without
16209   ** first doing some #defines that prevent SQLite from building on Win98.
16210   ** For that reason, we will omit this optimization for now.  See
16211   ** ticket #2685.
16212   */
16213 #if 0
16214   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16215     p->owner = GetCurrentThreadId();
16216     p->nRef++;
16217     rc = SQLITE_OK;
16218   }
16219 #else
16220   UNUSED_PARAMETER(p);
16221 #endif
16222   return rc;
16223 }
16224
16225 /*
16226 ** The sqlite3_mutex_leave() routine exits a mutex that was
16227 ** previously entered by the same thread.  The behavior
16228 ** is undefined if the mutex is not currently entered or
16229 ** is not currently allocated.  SQLite will never do either.
16230 */
16231 static void winMutexLeave(sqlite3_mutex *p){
16232   assert( p->nRef>0 );
16233   assert( p->owner==GetCurrentThreadId() );
16234   p->nRef--;
16235   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16236   LeaveCriticalSection(&p->mutex);
16237 }
16238
16239 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
16240   static sqlite3_mutex_methods sMutex = {
16241     winMutexInit,
16242     winMutexEnd,
16243     winMutexAlloc,
16244     winMutexFree,
16245     winMutexEnter,
16246     winMutexTry,
16247     winMutexLeave,
16248 #ifdef SQLITE_DEBUG
16249     winMutexHeld,
16250     winMutexNotheld
16251 #else
16252     0,
16253     0
16254 #endif
16255   };
16256
16257   return &sMutex;
16258 }
16259 #endif /* SQLITE_MUTEX_W32 */
16260
16261 /************** End of mutex_w32.c *******************************************/
16262 /************** Begin file malloc.c ******************************************/
16263 /*
16264 ** 2001 September 15
16265 **
16266 ** The author disclaims copyright to this source code.  In place of
16267 ** a legal notice, here is a blessing:
16268 **
16269 **    May you do good and not evil.
16270 **    May you find forgiveness for yourself and forgive others.
16271 **    May you share freely, never taking more than you give.
16272 **
16273 *************************************************************************
16274 **
16275 ** Memory allocation functions used throughout sqlite.
16276 **
16277 ** $Id: malloc.c,v 1.56 2009/02/17 18:37:29 drh Exp $
16278 */
16279
16280 /*
16281 ** This routine runs when the memory allocator sees that the
16282 ** total memory allocation is about to exceed the soft heap
16283 ** limit.
16284 */
16285 static void softHeapLimitEnforcer(
16286   void *NotUsed, 
16287   sqlite3_int64 NotUsed2,
16288   int allocSize
16289 ){
16290   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16291   sqlite3_release_memory(allocSize);
16292 }
16293
16294 /*
16295 ** Set the soft heap-size limit for the library. Passing a zero or 
16296 ** negative value indicates no limit.
16297 */
16298 SQLITE_API void sqlite3_soft_heap_limit(int n){
16299   sqlite3_uint64 iLimit;
16300   int overage;
16301   if( n<0 ){
16302     iLimit = 0;
16303   }else{
16304     iLimit = n;
16305   }
16306   sqlite3_initialize();
16307   if( iLimit>0 ){
16308     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16309   }else{
16310     sqlite3MemoryAlarm(0, 0, 0);
16311   }
16312   overage = (int)(sqlite3_memory_used() - (i64)n);
16313   if( overage>0 ){
16314     sqlite3_release_memory(overage);
16315   }
16316 }
16317
16318 /*
16319 ** Attempt to release up to n bytes of non-essential memory currently
16320 ** held by SQLite. An example of non-essential memory is memory used to
16321 ** cache database pages that are not currently in use.
16322 */
16323 SQLITE_API int sqlite3_release_memory(int n){
16324 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16325   int nRet = 0;
16326 #if 0
16327   nRet += sqlite3VdbeReleaseMemory(n);
16328 #endif
16329   nRet += sqlite3PcacheReleaseMemory(n-nRet);
16330   return nRet;
16331 #else
16332   UNUSED_PARAMETER(n);
16333   return SQLITE_OK;
16334 #endif
16335 }
16336
16337 /*
16338 ** State information local to the memory allocation subsystem.
16339 */
16340 static SQLITE_WSD struct Mem0Global {
16341   /* Number of free pages for scratch and page-cache memory */
16342   u32 nScratchFree;
16343   u32 nPageFree;
16344
16345   sqlite3_mutex *mutex;         /* Mutex to serialize access */
16346
16347   /*
16348   ** The alarm callback and its arguments.  The mem0.mutex lock will
16349   ** be held while the callback is running.  Recursive calls into
16350   ** the memory subsystem are allowed, but no new callbacks will be
16351   ** issued.  The alarmBusy variable is set to prevent recursive
16352   ** callbacks.
16353   */
16354   sqlite3_int64 alarmThreshold;
16355   void (*alarmCallback)(void*, sqlite3_int64,int);
16356   void *alarmArg;
16357   int alarmBusy;
16358
16359   /*
16360   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16361   ** sqlite3GlobalConfig.pPage to a block of memory that records
16362   ** which pages are available.
16363   */
16364   u32 *aScratchFree;
16365   u32 *aPageFree;
16366 } mem0 = { 62560955, 0, 0, 0, 0, 0, 0, 0, 0 };
16367
16368 #define mem0 GLOBAL(struct Mem0Global, mem0)
16369
16370 /*
16371 ** Initialize the memory allocation subsystem.
16372 */
16373 SQLITE_PRIVATE int sqlite3MallocInit(void){
16374   if( sqlite3GlobalConfig.m.xMalloc==0 ){
16375     sqlite3MemSetDefault();
16376   }
16377   memset(&mem0, 0, sizeof(mem0));
16378   if( sqlite3GlobalConfig.bCoreMutex ){
16379     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16380   }
16381   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16382       && sqlite3GlobalConfig.nScratch>=0 ){
16383     int i;
16384     sqlite3GlobalConfig.szScratch = (sqlite3GlobalConfig.szScratch - 4) & ~7;
16385     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16386                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16387     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16388     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16389   }else{
16390     sqlite3GlobalConfig.pScratch = 0;
16391     sqlite3GlobalConfig.szScratch = 0;
16392   }
16393   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16394       && sqlite3GlobalConfig.nPage>=1 ){
16395     int i;
16396     int overhead;
16397     int sz = sqlite3GlobalConfig.szPage & ~7;
16398     int n = sqlite3GlobalConfig.nPage;
16399     overhead = (4*n + sz - 1)/sz;
16400     sqlite3GlobalConfig.nPage -= overhead;
16401     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16402                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16403     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16404     mem0.nPageFree = sqlite3GlobalConfig.nPage;
16405   }else{
16406     sqlite3GlobalConfig.pPage = 0;
16407     sqlite3GlobalConfig.szPage = 0;
16408   }
16409   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16410 }
16411
16412 /*
16413 ** Deinitialize the memory allocation subsystem.
16414 */
16415 SQLITE_PRIVATE void sqlite3MallocEnd(void){
16416   if( sqlite3GlobalConfig.m.xShutdown ){
16417     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16418   }
16419   memset(&mem0, 0, sizeof(mem0));
16420 }
16421
16422 /*
16423 ** Return the amount of memory currently checked out.
16424 */
16425 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16426   int n, mx;
16427   sqlite3_int64 res;
16428   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16429   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16430   return res;
16431 }
16432
16433 /*
16434 ** Return the maximum amount of memory that has ever been
16435 ** checked out since either the beginning of this process
16436 ** or since the most recent reset.
16437 */
16438 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16439   int n, mx;
16440   sqlite3_int64 res;
16441   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16442   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16443   return res;
16444 }
16445
16446 /*
16447 ** Change the alarm callback
16448 */
16449 SQLITE_PRIVATE int sqlite3MemoryAlarm(
16450   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16451   void *pArg,
16452   sqlite3_int64 iThreshold
16453 ){
16454   sqlite3_mutex_enter(mem0.mutex);
16455   mem0.alarmCallback = xCallback;
16456   mem0.alarmArg = pArg;
16457   mem0.alarmThreshold = iThreshold;
16458   sqlite3_mutex_leave(mem0.mutex);
16459   return SQLITE_OK;
16460 }
16461
16462 #ifndef SQLITE_OMIT_DEPRECATED
16463 /*
16464 ** Deprecated external interface.  Internal/core SQLite code
16465 ** should call sqlite3MemoryAlarm.
16466 */
16467 SQLITE_API int sqlite3_memory_alarm(
16468   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16469   void *pArg,
16470   sqlite3_int64 iThreshold
16471 ){
16472   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16473 }
16474 #endif
16475
16476 /*
16477 ** Trigger the alarm 
16478 */
16479 static void sqlite3MallocAlarm(int nByte){
16480   void (*xCallback)(void*,sqlite3_int64,int);
16481   sqlite3_int64 nowUsed;
16482   void *pArg;
16483   if( mem0.alarmCallback==0 || mem0.alarmBusy  ) return;
16484   mem0.alarmBusy = 1;
16485   xCallback = mem0.alarmCallback;
16486   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16487   pArg = mem0.alarmArg;
16488   sqlite3_mutex_leave(mem0.mutex);
16489   xCallback(pArg, nowUsed, nByte);
16490   sqlite3_mutex_enter(mem0.mutex);
16491   mem0.alarmBusy = 0;
16492 }
16493
16494 /*
16495 ** Do a memory allocation with statistics and alarms.  Assume the
16496 ** lock is already held.
16497 */
16498 static int mallocWithAlarm(int n, void **pp){
16499   int nFull;
16500   void *p;
16501   assert( sqlite3_mutex_held(mem0.mutex) );
16502   nFull = sqlite3GlobalConfig.m.xRoundup(n);
16503   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16504   if( mem0.alarmCallback!=0 ){
16505     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16506     if( nUsed+nFull >= mem0.alarmThreshold ){
16507       sqlite3MallocAlarm(nFull);
16508     }
16509   }
16510   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16511   if( p==0 && mem0.alarmCallback ){
16512     sqlite3MallocAlarm(nFull);
16513     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16514   }
16515   if( p ){
16516     nFull = sqlite3MallocSize(p);
16517     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16518   }
16519   *pp = p;
16520   return nFull;
16521 }
16522
16523 /*
16524 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16525 ** assumes the memory subsystem has already been initialized.
16526 */
16527 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16528   void *p;
16529   if( n<=0 || NEVER(n>=0x7fffff00) ){
16530     /* The NEVER(n>=0x7fffff00) term is added out of paranoia.  We want to make
16531     ** absolutely sure that there is nothing within SQLite that can cause a
16532     ** memory allocation of a number of bytes which is near the maximum signed
16533     ** integer value and thus cause an integer overflow inside of the xMalloc()
16534     ** implementation.  The n>=0x7fffff00 gives us 255 bytes of headroom.  The
16535     ** test should never be true because SQLITE_MAX_LENGTH should be much
16536     ** less than 0x7fffff00 and it should catch large memory allocations
16537     ** before they reach this point. */
16538     p = 0;
16539   }else if( sqlite3GlobalConfig.bMemstat ){
16540     sqlite3_mutex_enter(mem0.mutex);
16541     mallocWithAlarm(n, &p);
16542     sqlite3_mutex_leave(mem0.mutex);
16543   }else{
16544     p = sqlite3GlobalConfig.m.xMalloc(n);
16545   }
16546   return p;
16547 }
16548
16549 /*
16550 ** This version of the memory allocation is for use by the application.
16551 ** First make sure the memory subsystem is initialized, then do the
16552 ** allocation.
16553 */
16554 SQLITE_API void *sqlite3_malloc(int n){
16555 #ifndef SQLITE_OMIT_AUTOINIT
16556   if( sqlite3_initialize() ) return 0;
16557 #endif
16558   return sqlite3Malloc(n);
16559 }
16560
16561 /*
16562 ** Each thread may only have a single outstanding allocation from
16563 ** xScratchMalloc().  We verify this constraint in the single-threaded
16564 ** case by setting scratchAllocOut to 1 when an allocation
16565 ** is outstanding clearing it when the allocation is freed.
16566 */
16567 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16568 static int scratchAllocOut = 0;
16569 #endif
16570
16571
16572 /*
16573 ** Allocate memory that is to be used and released right away.
16574 ** This routine is similar to alloca() in that it is not intended
16575 ** for situations where the memory might be held long-term.  This
16576 ** routine is intended to get memory to old large transient data
16577 ** structures that would not normally fit on the stack of an
16578 ** embedded processor.
16579 */
16580 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16581   void *p;
16582   assert( n>0 );
16583
16584 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16585   /* Verify that no more than one scratch allocation per thread
16586   ** is outstanding at one time.  (This is only checked in the
16587   ** single-threaded case since checking in the multi-threaded case
16588   ** would be much more complicated.) */
16589   assert( scratchAllocOut==0 );
16590 #endif
16591
16592   if( sqlite3GlobalConfig.szScratch<n ){
16593     goto scratch_overflow;
16594   }else{  
16595     sqlite3_mutex_enter(mem0.mutex);
16596     if( mem0.nScratchFree==0 ){
16597       sqlite3_mutex_leave(mem0.mutex);
16598       goto scratch_overflow;
16599     }else{
16600       int i;
16601       i = mem0.aScratchFree[--mem0.nScratchFree];
16602       i *= sqlite3GlobalConfig.szScratch;
16603       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16604       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16605       sqlite3_mutex_leave(mem0.mutex);
16606       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16607       assert(  (((u8*)p - (u8*)0) & 7)==0 );
16608     }
16609   }
16610 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16611   scratchAllocOut = p!=0;
16612 #endif
16613
16614   return p;
16615
16616 scratch_overflow:
16617   if( sqlite3GlobalConfig.bMemstat ){
16618     sqlite3_mutex_enter(mem0.mutex);
16619     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16620     n = mallocWithAlarm(n, &p);
16621     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16622     sqlite3_mutex_leave(mem0.mutex);
16623   }else{
16624     p = sqlite3GlobalConfig.m.xMalloc(n);
16625   }
16626 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16627   scratchAllocOut = p!=0;
16628 #endif
16629   return p;    
16630 }
16631 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16632   if( p ){
16633
16634 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16635     /* Verify that no more than one scratch allocation per thread
16636     ** is outstanding at one time.  (This is only checked in the
16637     ** single-threaded case since checking in the multi-threaded case
16638     ** would be much more complicated.) */
16639     assert( scratchAllocOut==1 );
16640     scratchAllocOut = 0;
16641 #endif
16642
16643     if( sqlite3GlobalConfig.pScratch==0
16644            || p<sqlite3GlobalConfig.pScratch
16645            || p>=(void*)mem0.aScratchFree ){
16646       if( sqlite3GlobalConfig.bMemstat ){
16647         int iSize = sqlite3MallocSize(p);
16648         sqlite3_mutex_enter(mem0.mutex);
16649         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16650         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16651         sqlite3GlobalConfig.m.xFree(p);
16652         sqlite3_mutex_leave(mem0.mutex);
16653       }else{
16654         sqlite3GlobalConfig.m.xFree(p);
16655       }
16656     }else{
16657       int i;
16658       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16659       i /= sqlite3GlobalConfig.szScratch;
16660       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16661       sqlite3_mutex_enter(mem0.mutex);
16662       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16663       mem0.aScratchFree[mem0.nScratchFree++] = i;
16664       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16665       sqlite3_mutex_leave(mem0.mutex);
16666     }
16667   }
16668 }
16669
16670 /*
16671 ** Allocate memory to be used by the page cache.  Make use of the
16672 ** memory buffer provided by SQLITE_CONFIG_PAGECACHE if there is one
16673 ** and that memory is of the right size and is not completely
16674 ** consumed.  Otherwise, failover to sqlite3Malloc().
16675 */
16676 #if 0
16677 SQLITE_PRIVATE void *sqlite3PageMalloc(int n){
16678   void *p;
16679   assert( n>0 );
16680   assert( (n & (n-1))==0 );
16681   assert( n>=512 && n<=32768 );
16682
16683   if( sqlite3GlobalConfig.szPage<n ){
16684     goto page_overflow;
16685   }else{  
16686     sqlite3_mutex_enter(mem0.mutex);
16687     if( mem0.nPageFree==0 ){
16688       sqlite3_mutex_leave(mem0.mutex);
16689       goto page_overflow;
16690     }else{
16691       int i;
16692       i = mem0.aPageFree[--mem0.nPageFree];
16693       sqlite3_mutex_leave(mem0.mutex);
16694       i *= sqlite3GlobalConfig.szPage;
16695       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16696       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
16697       p = (void*)&((char*)sqlite3GlobalConfig.pPage)[i];
16698     }
16699   }
16700   return p;
16701
16702 page_overflow:
16703   if( sqlite3GlobalConfig.bMemstat ){
16704     sqlite3_mutex_enter(mem0.mutex);
16705     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, n);
16706     n = mallocWithAlarm(n, &p);
16707     if( p ) sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, n);
16708     sqlite3_mutex_leave(mem0.mutex);
16709   }else{
16710     p = sqlite3GlobalConfig.m.xMalloc(n);
16711   }
16712   return p;    
16713 }
16714 SQLITE_PRIVATE void sqlite3PageFree(void *p){
16715   if( p ){
16716     if( sqlite3GlobalConfig.pPage==0
16717            || p<sqlite3GlobalConfig.pPage
16718            || p>=(void*)mem0.aPageFree ){
16719       /* In this case, the page allocation was obtained from a regular 
16720       ** call to sqlite3_mem_methods.xMalloc() (a page-cache-memory 
16721       ** "overflow"). Free the block with sqlite3_mem_methods.xFree().
16722       */
16723       if( sqlite3GlobalConfig.bMemstat ){
16724         int iSize = sqlite3MallocSize(p);
16725         sqlite3_mutex_enter(mem0.mutex);
16726         sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
16727         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16728         sqlite3GlobalConfig.m.xFree(p);
16729         sqlite3_mutex_leave(mem0.mutex);
16730       }else{
16731         sqlite3GlobalConfig.m.xFree(p);
16732       }
16733     }else{
16734       /* The page allocation was allocated from the sqlite3GlobalConfig.pPage
16735       ** buffer. In this case all that is add the index of the page in
16736       ** the sqlite3GlobalConfig.pPage array to the set of free indexes stored
16737       ** in the mem0.aPageFree[] array.
16738       */
16739       int i;
16740       i = (u8 *)p - (u8 *)sqlite3GlobalConfig.pPage;
16741       i /= sqlite3GlobalConfig.szPage;
16742       assert( i>=0 && i<sqlite3GlobalConfig.nPage );
16743       sqlite3_mutex_enter(mem0.mutex);
16744       assert( mem0.nPageFree<sqlite3GlobalConfig.nPage );
16745       mem0.aPageFree[mem0.nPageFree++] = i;
16746       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
16747       sqlite3_mutex_leave(mem0.mutex);
16748 #if !defined(NDEBUG) && 0
16749       /* Assert that a duplicate was not just inserted into aPageFree[]. */
16750       for(i=0; i<mem0.nPageFree-1; i++){
16751         assert( mem0.aPageFree[i]!=mem0.aPageFree[mem0.nPageFree-1] );
16752       }
16753 #endif
16754     }
16755   }
16756 }
16757 #endif
16758
16759 /*
16760 ** TRUE if p is a lookaside memory allocation from db
16761 */
16762 #ifndef SQLITE_OMIT_LOOKASIDE
16763 static int isLookaside(sqlite3 *db, void *p){
16764   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16765 }
16766 #else
16767 #define isLookaside(A,B) 0
16768 #endif
16769
16770 /*
16771 ** Return the size of a memory allocation previously obtained from
16772 ** sqlite3Malloc() or sqlite3_malloc().
16773 */
16774 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16775   return sqlite3GlobalConfig.m.xSize(p);
16776 }
16777 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16778   if( p==0 ){
16779     return 0;
16780   }else if( isLookaside(db, p) ){
16781     return db->lookaside.sz;
16782   }else{
16783     return sqlite3GlobalConfig.m.xSize(p);
16784   }
16785 }
16786
16787 /*
16788 ** Free memory previously obtained from sqlite3Malloc().
16789 */
16790 SQLITE_API void sqlite3_free(void *p){
16791   if( p==0 ) return;
16792   if( sqlite3GlobalConfig.bMemstat ){
16793     sqlite3_mutex_enter(mem0.mutex);
16794     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16795     sqlite3GlobalConfig.m.xFree(p);
16796     sqlite3_mutex_leave(mem0.mutex);
16797   }else{
16798     sqlite3GlobalConfig.m.xFree(p);
16799   }
16800 }
16801
16802 /*
16803 ** Free memory that might be associated with a particular database
16804 ** connection.
16805 */
16806 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16807   if( isLookaside(db, p) ){
16808     LookasideSlot *pBuf = (LookasideSlot*)p;
16809     pBuf->pNext = db->lookaside.pFree;
16810     db->lookaside.pFree = pBuf;
16811     db->lookaside.nOut--;
16812   }else{
16813     sqlite3_free(p);
16814   }
16815 }
16816
16817 /*
16818 ** Change the size of an existing memory allocation
16819 */
16820 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16821   int nOld, nNew;
16822   void *pNew;
16823   if( pOld==0 ){
16824     return sqlite3Malloc(nBytes);
16825   }
16826   if( nBytes<=0 || NEVER(nBytes>=0x7fffff00) ){
16827     /* The NEVER(...) term is explained in comments on sqlite3Malloc() */
16828     sqlite3_free(pOld);
16829     return 0;
16830   }
16831   nOld = sqlite3MallocSize(pOld);
16832   if( sqlite3GlobalConfig.bMemstat ){
16833     sqlite3_mutex_enter(mem0.mutex);
16834     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16835     nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16836     if( nOld==nNew ){
16837       pNew = pOld;
16838     }else{
16839       if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16840             mem0.alarmThreshold ){
16841         sqlite3MallocAlarm(nNew-nOld);
16842       }
16843       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16844       if( pNew==0 && mem0.alarmCallback ){
16845         sqlite3MallocAlarm(nBytes);
16846         pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16847       }
16848       if( pNew ){
16849         nNew = sqlite3MallocSize(pNew);
16850         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16851       }
16852     }
16853     sqlite3_mutex_leave(mem0.mutex);
16854   }else{
16855     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nBytes);
16856   }
16857   return pNew;
16858 }
16859
16860 /*
16861 ** The public interface to sqlite3Realloc.  Make sure that the memory
16862 ** subsystem is initialized prior to invoking sqliteRealloc.
16863 */
16864 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16865 #ifndef SQLITE_OMIT_AUTOINIT
16866   if( sqlite3_initialize() ) return 0;
16867 #endif
16868   return sqlite3Realloc(pOld, n);
16869 }
16870
16871
16872 /*
16873 ** Allocate and zero memory.
16874 */ 
16875 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16876   void *p = sqlite3Malloc(n);
16877   if( p ){
16878     memset(p, 0, n);
16879   }
16880   return p;
16881 }
16882
16883 /*
16884 ** Allocate and zero memory.  If the allocation fails, make
16885 ** the mallocFailed flag in the connection pointer.
16886 */
16887 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16888   void *p = sqlite3DbMallocRaw(db, n);
16889   if( p ){
16890     memset(p, 0, n);
16891   }
16892   return p;
16893 }
16894
16895 /*
16896 ** Allocate and zero memory.  If the allocation fails, make
16897 ** the mallocFailed flag in the connection pointer.
16898 **
16899 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16900 ** failure on the same database connection) then always return 0.
16901 ** Hence for a particular database connection, once malloc starts
16902 ** failing, it fails consistently until mallocFailed is reset.
16903 ** This is an important assumption.  There are many places in the
16904 ** code that do things like this:
16905 **
16906 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16907 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16908 **         if( b ) a[10] = 9;
16909 **
16910 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16911 ** that all prior mallocs (ex: "a") worked too.
16912 */
16913 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16914   void *p;
16915 #ifndef SQLITE_OMIT_LOOKASIDE
16916   if( db ){
16917     LookasideSlot *pBuf;
16918     if( db->mallocFailed ){
16919       return 0;
16920     }
16921     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16922          && (pBuf = db->lookaside.pFree)!=0 ){
16923       db->lookaside.pFree = pBuf->pNext;
16924       db->lookaside.nOut++;
16925       if( db->lookaside.nOut>db->lookaside.mxOut ){
16926         db->lookaside.mxOut = db->lookaside.nOut;
16927       }
16928       return (void*)pBuf;
16929     }
16930   }
16931 #else
16932   if( db && db->mallocFailed ){
16933     return 0;
16934   }
16935 #endif
16936   p = sqlite3Malloc(n);
16937   if( !p && db ){
16938     db->mallocFailed = 1;
16939   }
16940   return p;
16941 }
16942
16943 /*
16944 ** Resize the block of memory pointed to by p to n bytes. If the
16945 ** resize fails, set the mallocFailed flag in the connection object.
16946 */
16947 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16948   void *pNew = 0;
16949   if( db->mallocFailed==0 ){
16950     if( p==0 ){
16951       return sqlite3DbMallocRaw(db, n);
16952     }
16953     if( isLookaside(db, p) ){
16954       if( n<=db->lookaside.sz ){
16955         return p;
16956       }
16957       pNew = sqlite3DbMallocRaw(db, n);
16958       if( pNew ){
16959         memcpy(pNew, p, db->lookaside.sz);
16960         sqlite3DbFree(db, p);
16961       }
16962     }else{
16963       pNew = sqlite3_realloc(p, n);
16964       if( !pNew ){
16965         db->mallocFailed = 1;
16966       }
16967     }
16968   }
16969   return pNew;
16970 }
16971
16972 /*
16973 ** Attempt to reallocate p.  If the reallocation fails, then free p
16974 ** and set the mallocFailed flag in the database connection.
16975 */
16976 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16977   void *pNew;
16978   pNew = sqlite3DbRealloc(db, p, n);
16979   if( !pNew ){
16980     sqlite3DbFree(db, p);
16981   }
16982   return pNew;
16983 }
16984
16985 /*
16986 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16987 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16988 ** is because when memory debugging is turned on, these two functions are 
16989 ** called via macros that record the current file and line number in the
16990 ** ThreadData structure.
16991 */
16992 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16993   char *zNew;
16994   size_t n;
16995   if( z==0 ){
16996     return 0;
16997   }
16998   n = (db ? sqlite3Strlen(db, z) : sqlite3Strlen30(z))+1;
16999   assert( (n&0x7fffffff)==n );
17000   zNew = sqlite3DbMallocRaw(db, (int)n);
17001   if( zNew ){
17002     memcpy(zNew, z, n);
17003   }
17004   return zNew;
17005 }
17006 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17007   char *zNew;
17008   if( z==0 ){
17009     return 0;
17010   }
17011   assert( (n&0x7fffffff)==n );
17012   zNew = sqlite3DbMallocRaw(db, n+1);
17013   if( zNew ){
17014     memcpy(zNew, z, n);
17015     zNew[n] = 0;
17016   }
17017   return zNew;
17018 }
17019
17020 /*
17021 ** Create a string from the zFromat argument and the va_list that follows.
17022 ** Store the string in memory obtained from sqliteMalloc() and make *pz
17023 ** point to that string.
17024 */
17025 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17026   va_list ap;
17027   char *z;
17028
17029   va_start(ap, zFormat);
17030   z = sqlite3VMPrintf(db, zFormat, ap);
17031   va_end(ap);
17032   sqlite3DbFree(db, *pz);
17033   *pz = z;
17034 }
17035
17036
17037 /*
17038 ** This function must be called before exiting any API function (i.e. 
17039 ** returning control to the user) that has called sqlite3_malloc or
17040 ** sqlite3_realloc.
17041 **
17042 ** The returned value is normally a copy of the second argument to this
17043 ** function. However, if a malloc() failure has occured since the previous
17044 ** invocation SQLITE_NOMEM is returned instead. 
17045 **
17046 ** If the first argument, db, is not NULL and a malloc() error has occured,
17047 ** then the connection error-code (the value returned by sqlite3_errcode())
17048 ** is set to SQLITE_NOMEM.
17049 */
17050 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17051   /* If the db handle is not NULL, then we must hold the connection handle
17052   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
17053   ** is unsafe, as is the call to sqlite3Error().
17054   */
17055   assert( !db || sqlite3_mutex_held(db->mutex) );
17056   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17057     sqlite3Error(db, SQLITE_NOMEM, 0);
17058     db->mallocFailed = 0;
17059     rc = SQLITE_NOMEM;
17060   }
17061   return rc & (db ? db->errMask : 0xff);
17062 }
17063
17064 /************** End of malloc.c **********************************************/
17065 /************** Begin file printf.c ******************************************/
17066 /*
17067 ** The "printf" code that follows dates from the 1980's.  It is in
17068 ** the public domain.  The original comments are included here for
17069 ** completeness.  They are very out-of-date but might be useful as
17070 ** an historical reference.  Most of the "enhancements" have been backed
17071 ** out so that the functionality is now the same as standard printf().
17072 **
17073 ** $Id: printf.c,v 1.99 2008/12/10 19:26:24 drh Exp $
17074 **
17075 **************************************************************************
17076 **
17077 ** The following modules is an enhanced replacement for the "printf" subroutines
17078 ** found in the standard C library.  The following enhancements are
17079 ** supported:
17080 **
17081 **      +  Additional functions.  The standard set of "printf" functions
17082 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17083 **         vsprintf.  This module adds the following:
17084 **
17085 **           *  snprintf -- Works like sprintf, but has an extra argument
17086 **                          which is the size of the buffer written to.
17087 **
17088 **           *  mprintf --  Similar to sprintf.  Writes output to memory
17089 **                          obtained from malloc.
17090 **
17091 **           *  xprintf --  Calls a function to dispose of output.
17092 **
17093 **           *  nprintf --  No output, but returns the number of characters
17094 **                          that would have been output by printf.
17095 **
17096 **           *  A v- version (ex: vsnprintf) of every function is also
17097 **              supplied.
17098 **
17099 **      +  A few extensions to the formatting notation are supported:
17100 **
17101 **           *  The "=" flag (similar to "-") causes the output to be
17102 **              be centered in the appropriately sized field.
17103 **
17104 **           *  The %b field outputs an integer in binary notation.
17105 **
17106 **           *  The %c field now accepts a precision.  The character output
17107 **              is repeated by the number of times the precision specifies.
17108 **
17109 **           *  The %' field works like %c, but takes as its character the
17110 **              next character of the format string, instead of the next
17111 **              argument.  For example,  printf("%.78'-")  prints 78 minus
17112 **              signs, the same as  printf("%.78c",'-').
17113 **
17114 **      +  When compiled using GCC on a SPARC, this version of printf is
17115 **         faster than the library printf for SUN OS 4.1.
17116 **
17117 **      +  All functions are fully reentrant.
17118 **
17119 */
17120
17121 /*
17122 ** Conversion types fall into various categories as defined by the
17123 ** following enumeration.
17124 */
17125 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17126 #define etFLOAT       2 /* Floating point.  %f */
17127 #define etEXP         3 /* Exponentional notation. %e and %E */
17128 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17129 #define etSIZE        5 /* Return number of characters processed so far. %n */
17130 #define etSTRING      6 /* Strings. %s */
17131 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17132 #define etPERCENT     8 /* Percent symbol. %% */
17133 #define etCHARX       9 /* Characters. %c */
17134 /* The rest are extensions, not normally found in printf() */
17135 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17136 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17137                           NULL pointers replaced by SQL NULL.  %Q */
17138 #define etTOKEN      12 /* a pointer to a Token structure */
17139 #define etSRCLIST    13 /* a pointer to a SrcList */
17140 #define etPOINTER    14 /* The %p conversion */
17141 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17142 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17143
17144
17145 /*
17146 ** An "etByte" is an 8-bit unsigned value.
17147 */
17148 typedef unsigned char etByte;
17149
17150 /*
17151 ** Each builtin conversion character (ex: the 'd' in "%d") is described
17152 ** by an instance of the following structure
17153 */
17154 typedef struct et_info {   /* Information about each format field */
17155   char fmttype;            /* The format field code letter */
17156   etByte base;             /* The base for radix conversion */
17157   etByte flags;            /* One or more of FLAG_ constants below */
17158   etByte type;             /* Conversion paradigm */
17159   etByte charset;          /* Offset into aDigits[] of the digits string */
17160   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17161 } et_info;
17162
17163 /*
17164 ** Allowed values for et_info.flags
17165 */
17166 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
17167 #define FLAG_INTERN  2     /* True if for internal use only */
17168 #define FLAG_STRING  4     /* Allow infinity precision */
17169
17170
17171 /*
17172 ** The following table is searched linearly, so it is good to put the
17173 ** most frequently used conversion types first.
17174 */
17175 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17176 static const char aPrefix[] = "-x0\000X0";
17177 static const et_info fmtinfo[] = {
17178   {  'd', 10, 1, etRADIX,      0,  0 },
17179   {  's',  0, 4, etSTRING,     0,  0 },
17180   {  'g',  0, 1, etGENERIC,    30, 0 },
17181   {  'z',  0, 4, etDYNSTRING,  0,  0 },
17182   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17183   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17184   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17185   {  'c',  0, 0, etCHARX,      0,  0 },
17186   {  'o',  8, 0, etRADIX,      0,  2 },
17187   {  'u', 10, 0, etRADIX,      0,  0 },
17188   {  'x', 16, 0, etRADIX,      16, 1 },
17189   {  'X', 16, 0, etRADIX,      0,  4 },
17190 #ifndef SQLITE_OMIT_FLOATING_POINT
17191   {  'f',  0, 1, etFLOAT,      0,  0 },
17192   {  'e',  0, 1, etEXP,        30, 0 },
17193   {  'E',  0, 1, etEXP,        14, 0 },
17194   {  'G',  0, 1, etGENERIC,    14, 0 },
17195 #endif
17196   {  'i', 10, 1, etRADIX,      0,  0 },
17197   {  'n',  0, 0, etSIZE,       0,  0 },
17198   {  '%',  0, 0, etPERCENT,    0,  0 },
17199   {  'p', 16, 0, etPOINTER,    0,  1 },
17200   {  'T',  0, 2, etTOKEN,      0,  0 },
17201   {  'S',  0, 2, etSRCLIST,    0,  0 },
17202   {  'r', 10, 3, etORDINAL,    0,  0 },
17203 };
17204
17205 /*
17206 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17207 ** conversions will work.
17208 */
17209 #ifndef SQLITE_OMIT_FLOATING_POINT
17210 /*
17211 ** "*val" is a double such that 0.1 <= *val < 10.0
17212 ** Return the ascii code for the leading digit of *val, then
17213 ** multiply "*val" by 10.0 to renormalize.
17214 **
17215 ** Example:
17216 **     input:     *val = 3.14159
17217 **     output:    *val = 1.4159    function return = '3'
17218 **
17219 ** The counter *cnt is incremented each time.  After counter exceeds
17220 ** 16 (the number of significant digits in a 64-bit float) '0' is
17221 ** always returned.
17222 */
17223 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17224   int digit;
17225   LONGDOUBLE_TYPE d;
17226   if( (*cnt)++ >= 16 ) return '0';
17227   digit = (int)*val;
17228   d = digit;
17229   digit += '0';
17230   *val = (*val - d)*10.0;
17231   return (char)digit;
17232 }
17233 #endif /* SQLITE_OMIT_FLOATING_POINT */
17234
17235 /*
17236 ** Append N space characters to the given string buffer.
17237 */
17238 static void appendSpace(StrAccum *pAccum, int N){
17239   static const char zSpaces[] = "                             ";
17240   while( N>=(int)sizeof(zSpaces)-1 ){
17241     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
17242     N -= sizeof(zSpaces)-1;
17243   }
17244   if( N>0 ){
17245     sqlite3StrAccumAppend(pAccum, zSpaces, N);
17246   }
17247 }
17248
17249 /*
17250 ** On machines with a small stack size, you can redefine the
17251 ** SQLITE_PRINT_BUF_SIZE to be less than 350.  But beware - for
17252 ** smaller values some %f conversions may go into an infinite loop.
17253 */
17254 #ifndef SQLITE_PRINT_BUF_SIZE
17255 # define SQLITE_PRINT_BUF_SIZE 350
17256 #endif
17257 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17258
17259 /*
17260 ** The root program.  All variations call this core.
17261 **
17262 ** INPUTS:
17263 **   func   This is a pointer to a function taking three arguments
17264 **            1. A pointer to anything.  Same as the "arg" parameter.
17265 **            2. A pointer to the list of characters to be output
17266 **               (Note, this list is NOT null terminated.)
17267 **            3. An integer number of characters to be output.
17268 **               (Note: This number might be zero.)
17269 **
17270 **   arg    This is the pointer to anything which will be passed as the
17271 **          first argument to "func".  Use it for whatever you like.
17272 **
17273 **   fmt    This is the format string, as in the usual print.
17274 **
17275 **   ap     This is a pointer to a list of arguments.  Same as in
17276 **          vfprint.
17277 **
17278 ** OUTPUTS:
17279 **          The return value is the total number of characters sent to
17280 **          the function "func".  Returns -1 on a error.
17281 **
17282 ** Note that the order in which automatic variables are declared below
17283 ** seems to make a big difference in determining how fast this beast
17284 ** will run.
17285 */
17286 SQLITE_PRIVATE void sqlite3VXPrintf(
17287   StrAccum *pAccum,                  /* Accumulate results here */
17288   int useExtended,                   /* Allow extended %-conversions */
17289   const char *fmt,                   /* Format string */
17290   va_list ap                         /* arguments */
17291 ){
17292   int c;                     /* Next character in the format string */
17293   char *bufpt;               /* Pointer to the conversion buffer */
17294   int precision;             /* Precision of the current field */
17295   int length;                /* Length of the field */
17296   int idx;                   /* A general purpose loop counter */
17297   int width;                 /* Width of the current field */
17298   etByte flag_leftjustify;   /* True if "-" flag is present */
17299   etByte flag_plussign;      /* True if "+" flag is present */
17300   etByte flag_blanksign;     /* True if " " flag is present */
17301   etByte flag_alternateform; /* True if "#" flag is present */
17302   etByte flag_altform2;      /* True if "!" flag is present */
17303   etByte flag_zeropad;       /* True if field width constant starts with zero */
17304   etByte flag_long;          /* True if "l" flag is present */
17305   etByte flag_longlong;      /* True if the "ll" flag is present */
17306   etByte done;               /* Loop termination flag */
17307   sqlite_uint64 longvalue;   /* Value for integer types */
17308   LONGDOUBLE_TYPE realvalue; /* Value for real types */
17309   const et_info *infop;      /* Pointer to the appropriate info structure */
17310   char buf[etBUFSIZE];       /* Conversion buffer */
17311   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17312   etByte xtype = 0;          /* Conversion paradigm */
17313   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17314 #ifndef SQLITE_OMIT_FLOATING_POINT
17315   int  exp, e2;              /* exponent of real numbers */
17316   double rounder;            /* Used for rounding floating point values */
17317   etByte flag_dp;            /* True if decimal point should be shown */
17318   etByte flag_rtz;           /* True if trailing zeros should be removed */
17319   etByte flag_exp;           /* True to force display of the exponent */
17320   int nsd;                   /* Number of significant digits returned */
17321 #endif
17322
17323   length = 0;
17324   bufpt = 0;
17325   for(; (c=(*fmt))!=0; ++fmt){
17326     if( c!='%' ){
17327       int amt;
17328       bufpt = (char *)fmt;
17329       amt = 1;
17330       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17331       sqlite3StrAccumAppend(pAccum, bufpt, amt);
17332       if( c==0 ) break;
17333     }
17334     if( (c=(*++fmt))==0 ){
17335       sqlite3StrAccumAppend(pAccum, "%", 1);
17336       break;
17337     }
17338     /* Find out what flags are present */
17339     flag_leftjustify = flag_plussign = flag_blanksign = 
17340      flag_alternateform = flag_altform2 = flag_zeropad = 0;
17341     done = 0;
17342     do{
17343       switch( c ){
17344         case '-':   flag_leftjustify = 1;     break;
17345         case '+':   flag_plussign = 1;        break;
17346         case ' ':   flag_blanksign = 1;       break;
17347         case '#':   flag_alternateform = 1;   break;
17348         case '!':   flag_altform2 = 1;        break;
17349         case '0':   flag_zeropad = 1;         break;
17350         default:    done = 1;                 break;
17351       }
17352     }while( !done && (c=(*++fmt))!=0 );
17353     /* Get the field width */
17354     width = 0;
17355     if( c=='*' ){
17356       width = va_arg(ap,int);
17357       if( width<0 ){
17358         flag_leftjustify = 1;
17359         width = -width;
17360       }
17361       c = *++fmt;
17362     }else{
17363       while( c>='0' && c<='9' ){
17364         width = width*10 + c - '0';
17365         c = *++fmt;
17366       }
17367     }
17368     if( width > etBUFSIZE-10 ){
17369       width = etBUFSIZE-10;
17370     }
17371     /* Get the precision */
17372     if( c=='.' ){
17373       precision = 0;
17374       c = *++fmt;
17375       if( c=='*' ){
17376         precision = va_arg(ap,int);
17377         if( precision<0 ) precision = -precision;
17378         c = *++fmt;
17379       }else{
17380         while( c>='0' && c<='9' ){
17381           precision = precision*10 + c - '0';
17382           c = *++fmt;
17383         }
17384       }
17385     }else{
17386       precision = -1;
17387     }
17388     /* Get the conversion type modifier */
17389     if( c=='l' ){
17390       flag_long = 1;
17391       c = *++fmt;
17392       if( c=='l' ){
17393         flag_longlong = 1;
17394         c = *++fmt;
17395       }else{
17396         flag_longlong = 0;
17397       }
17398     }else{
17399       flag_long = flag_longlong = 0;
17400     }
17401     /* Fetch the info entry for the field */
17402     infop = 0;
17403     for(idx=0; idx<ArraySize(fmtinfo); idx++){
17404       if( c==fmtinfo[idx].fmttype ){
17405         infop = &fmtinfo[idx];
17406         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17407           xtype = infop->type;
17408         }else{
17409           return;
17410         }
17411         break;
17412       }
17413     }
17414     zExtra = 0;
17415     if( infop==0 ){
17416       return;
17417     }
17418
17419
17420     /* Limit the precision to prevent overflowing buf[] during conversion */
17421     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17422       precision = etBUFSIZE-40;
17423     }
17424
17425     /*
17426     ** At this point, variables are initialized as follows:
17427     **
17428     **   flag_alternateform          TRUE if a '#' is present.
17429     **   flag_altform2               TRUE if a '!' is present.
17430     **   flag_plussign               TRUE if a '+' is present.
17431     **   flag_leftjustify            TRUE if a '-' is present or if the
17432     **                               field width was negative.
17433     **   flag_zeropad                TRUE if the width began with 0.
17434     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17435     **                               the conversion character.
17436     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17437     **                               the conversion character.
17438     **   flag_blanksign              TRUE if a ' ' is present.
17439     **   width                       The specified field width.  This is
17440     **                               always non-negative.  Zero is the default.
17441     **   precision                   The specified precision.  The default
17442     **                               is -1.
17443     **   xtype                       The class of the conversion.
17444     **   infop                       Pointer to the appropriate info struct.
17445     */
17446     switch( xtype ){
17447       case etPOINTER:
17448         flag_longlong = sizeof(char*)==sizeof(i64);
17449         flag_long = sizeof(char*)==sizeof(long int);
17450         /* Fall through into the next case */
17451       case etORDINAL:
17452       case etRADIX:
17453         if( infop->flags & FLAG_SIGNED ){
17454           i64 v;
17455           if( flag_longlong )   v = va_arg(ap,i64);
17456           else if( flag_long )  v = va_arg(ap,long int);
17457           else                  v = va_arg(ap,int);
17458           if( v<0 ){
17459             longvalue = -v;
17460             prefix = '-';
17461           }else{
17462             longvalue = v;
17463             if( flag_plussign )        prefix = '+';
17464             else if( flag_blanksign )  prefix = ' ';
17465             else                       prefix = 0;
17466           }
17467         }else{
17468           if( flag_longlong )   longvalue = va_arg(ap,u64);
17469           else if( flag_long )  longvalue = va_arg(ap,unsigned long int);
17470           else                  longvalue = va_arg(ap,unsigned int);
17471           prefix = 0;
17472         }
17473         if( longvalue==0 ) flag_alternateform = 0;
17474         if( flag_zeropad && precision<width-(prefix!=0) ){
17475           precision = width-(prefix!=0);
17476         }
17477         bufpt = &buf[etBUFSIZE-1];
17478         if( xtype==etORDINAL ){
17479           static const char zOrd[] = "thstndrd";
17480           int x = (int)(longvalue % 10);
17481           if( x>=4 || (longvalue/10)%10==1 ){
17482             x = 0;
17483           }
17484           buf[etBUFSIZE-3] = zOrd[x*2];
17485           buf[etBUFSIZE-2] = zOrd[x*2+1];
17486           bufpt -= 2;
17487         }
17488         {
17489           register const char *cset;      /* Use registers for speed */
17490           register int base;
17491           cset = &aDigits[infop->charset];
17492           base = infop->base;
17493           do{                                           /* Convert to ascii */
17494             *(--bufpt) = cset[longvalue%base];
17495             longvalue = longvalue/base;
17496           }while( longvalue>0 );
17497         }
17498         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17499         for(idx=precision-length; idx>0; idx--){
17500           *(--bufpt) = '0';                             /* Zero pad */
17501         }
17502         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17503         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17504           const char *pre;
17505           char x;
17506           pre = &aPrefix[infop->prefix];
17507           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17508         }
17509         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17510         break;
17511       case etFLOAT:
17512       case etEXP:
17513       case etGENERIC:
17514         realvalue = va_arg(ap,double);
17515 #ifndef SQLITE_OMIT_FLOATING_POINT
17516         if( precision<0 ) precision = 6;         /* Set default precision */
17517         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17518         if( realvalue<0.0 ){
17519           realvalue = -realvalue;
17520           prefix = '-';
17521         }else{
17522           if( flag_plussign )          prefix = '+';
17523           else if( flag_blanksign )    prefix = ' ';
17524           else                         prefix = 0;
17525         }
17526         if( xtype==etGENERIC && precision>0 ) precision--;
17527 #if 0
17528         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17529         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17530 #else
17531         /* It makes more sense to use 0.5 */
17532         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17533 #endif
17534         if( xtype==etFLOAT ) realvalue += rounder;
17535         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17536         exp = 0;
17537         if( sqlite3IsNaN((double)realvalue) ){
17538           bufpt = "NaN";
17539           length = 3;
17540           break;
17541         }
17542         if( realvalue>0.0 ){
17543           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17544           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17545           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17546           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17547           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17548           if( exp>350 ){
17549             if( prefix=='-' ){
17550               bufpt = "-Inf";
17551             }else if( prefix=='+' ){
17552               bufpt = "+Inf";
17553             }else{
17554               bufpt = "Inf";
17555             }
17556             length = sqlite3Strlen30(bufpt);
17557             break;
17558           }
17559         }
17560         bufpt = buf;
17561         /*
17562         ** If the field type is etGENERIC, then convert to either etEXP
17563         ** or etFLOAT, as appropriate.
17564         */
17565         flag_exp = xtype==etEXP;
17566         if( xtype!=etFLOAT ){
17567           realvalue += rounder;
17568           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17569         }
17570         if( xtype==etGENERIC ){
17571           flag_rtz = !flag_alternateform;
17572           if( exp<-4 || exp>precision ){
17573             xtype = etEXP;
17574           }else{
17575             precision = precision - exp;
17576             xtype = etFLOAT;
17577           }
17578         }else{
17579           flag_rtz = 0;
17580         }
17581         if( xtype==etEXP ){
17582           e2 = 0;
17583         }else{
17584           e2 = exp;
17585         }
17586         nsd = 0;
17587         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17588         /* The sign in front of the number */
17589         if( prefix ){
17590           *(bufpt++) = prefix;
17591         }
17592         /* Digits prior to the decimal point */
17593         if( e2<0 ){
17594           *(bufpt++) = '0';
17595         }else{
17596           for(; e2>=0; e2--){
17597             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17598           }
17599         }
17600         /* The decimal point */
17601         if( flag_dp ){
17602           *(bufpt++) = '.';
17603         }
17604         /* "0" digits after the decimal point but before the first
17605         ** significant digit of the number */
17606         for(e2++; e2<0; precision--, e2++){
17607           assert( precision>0 );
17608           *(bufpt++) = '0';
17609         }
17610         /* Significant digits after the decimal point */
17611         while( (precision--)>0 ){
17612           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17613         }
17614         /* Remove trailing zeros and the "." if no digits follow the "." */
17615         if( flag_rtz && flag_dp ){
17616           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17617           assert( bufpt>buf );
17618           if( bufpt[-1]=='.' ){
17619             if( flag_altform2 ){
17620               *(bufpt++) = '0';
17621             }else{
17622               *(--bufpt) = 0;
17623             }
17624           }
17625         }
17626         /* Add the "eNNN" suffix */
17627         if( flag_exp || xtype==etEXP ){
17628           *(bufpt++) = aDigits[infop->charset];
17629           if( exp<0 ){
17630             *(bufpt++) = '-'; exp = -exp;
17631           }else{
17632             *(bufpt++) = '+';
17633           }
17634           if( exp>=100 ){
17635             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17636             exp %= 100;
17637           }
17638           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17639           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17640         }
17641         *bufpt = 0;
17642
17643         /* The converted number is in buf[] and zero terminated. Output it.
17644         ** Note that the number is in the usual order, not reversed as with
17645         ** integer conversions. */
17646         length = (int)(bufpt-buf);
17647         bufpt = buf;
17648
17649         /* Special case:  Add leading zeros if the flag_zeropad flag is
17650         ** set and we are not left justified */
17651         if( flag_zeropad && !flag_leftjustify && length < width){
17652           int i;
17653           int nPad = width - length;
17654           for(i=width; i>=nPad; i--){
17655             bufpt[i] = bufpt[i-nPad];
17656           }
17657           i = prefix!=0;
17658           while( nPad-- ) bufpt[i++] = '0';
17659           length = width;
17660         }
17661 #endif
17662         break;
17663       case etSIZE:
17664         *(va_arg(ap,int*)) = pAccum->nChar;
17665         length = width = 0;
17666         break;
17667       case etPERCENT:
17668         buf[0] = '%';
17669         bufpt = buf;
17670         length = 1;
17671         break;
17672       case etCHARX:
17673         c = va_arg(ap,int);
17674         buf[0] = (char)c;
17675         if( precision>=0 ){
17676           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17677           length = precision;
17678         }else{
17679           length =1;
17680         }
17681         bufpt = buf;
17682         break;
17683       case etSTRING:
17684       case etDYNSTRING:
17685         bufpt = va_arg(ap,char*);
17686         if( bufpt==0 ){
17687           bufpt = "";
17688         }else if( xtype==etDYNSTRING ){
17689           zExtra = bufpt;
17690         }
17691         if( precision>=0 ){
17692           for(length=0; length<precision && bufpt[length]; length++){}
17693         }else{
17694           length = sqlite3Strlen30(bufpt);
17695         }
17696         break;
17697       case etSQLESCAPE:
17698       case etSQLESCAPE2:
17699       case etSQLESCAPE3: {
17700         int i, j, n, isnull;
17701         int needQuote;
17702         char ch;
17703         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17704         char *escarg = va_arg(ap,char*);
17705         isnull = escarg==0;
17706         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17707         for(i=n=0; (ch=escarg[i])!=0; i++){
17708           if( ch==q )  n++;
17709         }
17710         needQuote = !isnull && xtype==etSQLESCAPE2;
17711         n += i + 1 + needQuote*2;
17712         if( n>etBUFSIZE ){
17713           bufpt = zExtra = sqlite3Malloc( n );
17714           if( bufpt==0 ){
17715             pAccum->mallocFailed = 1;
17716             return;
17717           }
17718         }else{
17719           bufpt = buf;
17720         }
17721         j = 0;
17722         if( needQuote ) bufpt[j++] = q;
17723         for(i=0; (ch=escarg[i])!=0; i++){
17724           bufpt[j++] = ch;
17725           if( ch==q ) bufpt[j++] = ch;
17726         }
17727         if( needQuote ) bufpt[j++] = q;
17728         bufpt[j] = 0;
17729         length = j;
17730         /* The precision is ignored on %q and %Q */
17731         /* if( precision>=0 && precision<length ) length = precision; */
17732         break;
17733       }
17734       case etTOKEN: {
17735         Token *pToken = va_arg(ap, Token*);
17736         if( pToken ){
17737           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17738         }
17739         length = width = 0;
17740         break;
17741       }
17742       case etSRCLIST: {
17743         SrcList *pSrc = va_arg(ap, SrcList*);
17744         int k = va_arg(ap, int);
17745         struct SrcList_item *pItem = &pSrc->a[k];
17746         assert( k>=0 && k<pSrc->nSrc );
17747         if( pItem->zDatabase ){
17748           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17749           sqlite3StrAccumAppend(pAccum, ".", 1);
17750         }
17751         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17752         length = width = 0;
17753         break;
17754       }
17755     }/* End switch over the format type */
17756     /*
17757     ** The text of the conversion is pointed to by "bufpt" and is
17758     ** "length" characters long.  The field width is "width".  Do
17759     ** the output.
17760     */
17761     if( !flag_leftjustify ){
17762       register int nspace;
17763       nspace = width-length;
17764       if( nspace>0 ){
17765         appendSpace(pAccum, nspace);
17766       }
17767     }
17768     if( length>0 ){
17769       sqlite3StrAccumAppend(pAccum, bufpt, length);
17770     }
17771     if( flag_leftjustify ){
17772       register int nspace;
17773       nspace = width-length;
17774       if( nspace>0 ){
17775         appendSpace(pAccum, nspace);
17776       }
17777     }
17778     if( zExtra ){
17779       sqlite3_free(zExtra);
17780     }
17781   }/* End for loop over the format string */
17782 } /* End of function */
17783
17784 /*
17785 ** Append N bytes of text from z to the StrAccum object.
17786 */
17787 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17788   if( p->tooBig | p->mallocFailed ){
17789     return;
17790   }
17791   if( N<0 ){
17792     N = sqlite3Strlen30(z);
17793   }
17794   if( N==0 || z==0 ){
17795     return;
17796   }
17797   if( p->nChar+N >= p->nAlloc ){
17798     char *zNew;
17799     if( !p->useMalloc ){
17800       p->tooBig = 1;
17801       N = p->nAlloc - p->nChar - 1;
17802       if( N<=0 ){
17803         return;
17804       }
17805     }else{
17806       i64 szNew = p->nChar;
17807       szNew += N + 1;
17808       if( szNew > p->mxAlloc ){
17809         sqlite3StrAccumReset(p);
17810         p->tooBig = 1;
17811         return;
17812       }else{
17813         p->nAlloc = (int)szNew;
17814       }
17815       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17816       if( zNew ){
17817         memcpy(zNew, p->zText, p->nChar);
17818         sqlite3StrAccumReset(p);
17819         p->zText = zNew;
17820       }else{
17821         p->mallocFailed = 1;
17822         sqlite3StrAccumReset(p);
17823         return;
17824       }
17825     }
17826   }
17827   memcpy(&p->zText[p->nChar], z, N);
17828   p->nChar += N;
17829 }
17830
17831 /*
17832 ** Finish off a string by making sure it is zero-terminated.
17833 ** Return a pointer to the resulting string.  Return a NULL
17834 ** pointer if any kind of error was encountered.
17835 */
17836 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17837   if( p->zText ){
17838     p->zText[p->nChar] = 0;
17839     if( p->useMalloc && p->zText==p->zBase ){
17840       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17841       if( p->zText ){
17842         memcpy(p->zText, p->zBase, p->nChar+1);
17843       }else{
17844         p->mallocFailed = 1;
17845       }
17846     }
17847   }
17848   return p->zText;
17849 }
17850
17851 /*
17852 ** Reset an StrAccum string.  Reclaim all malloced memory.
17853 */
17854 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17855   if( p->zText!=p->zBase ){
17856     sqlite3DbFree(p->db, p->zText);
17857   }
17858   p->zText = 0;
17859 }
17860
17861 /*
17862 ** Initialize a string accumulator
17863 */
17864 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17865   p->zText = p->zBase = zBase;
17866   p->db = 0;
17867   p->nChar = 0;
17868   p->nAlloc = n;
17869   p->mxAlloc = mx;
17870   p->useMalloc = 1;
17871   p->tooBig = 0;
17872   p->mallocFailed = 0;
17873 }
17874
17875 /*
17876 ** Print into memory obtained from sqliteMalloc().  Use the internal
17877 ** %-conversion extensions.
17878 */
17879 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17880   char *z;
17881   char zBase[SQLITE_PRINT_BUF_SIZE];
17882   StrAccum acc;
17883   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17884                       db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
17885   acc.db = db;
17886   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17887   z = sqlite3StrAccumFinish(&acc);
17888   if( acc.mallocFailed && db ){
17889     db->mallocFailed = 1;
17890   }
17891   return z;
17892 }
17893
17894 /*
17895 ** Print into memory obtained from sqliteMalloc().  Use the internal
17896 ** %-conversion extensions.
17897 */
17898 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17899   va_list ap;
17900   char *z;
17901   va_start(ap, zFormat);
17902   z = sqlite3VMPrintf(db, zFormat, ap);
17903   va_end(ap);
17904   return z;
17905 }
17906
17907 /*
17908 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17909 ** the string and before returnning.  This routine is intended to be used
17910 ** to modify an existing string.  For example:
17911 **
17912 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17913 **
17914 */
17915 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17916   va_list ap;
17917   char *z;
17918   va_start(ap, zFormat);
17919   z = sqlite3VMPrintf(db, zFormat, ap);
17920   va_end(ap);
17921   sqlite3DbFree(db, zStr);
17922   return z;
17923 }
17924
17925 /*
17926 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17927 ** %-conversion extensions.
17928 */
17929 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17930   char *z;
17931   char zBase[SQLITE_PRINT_BUF_SIZE];
17932   StrAccum acc;
17933 #ifndef SQLITE_OMIT_AUTOINIT
17934   if( sqlite3_initialize() ) return 0;
17935 #endif
17936   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17937   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17938   z = sqlite3StrAccumFinish(&acc);
17939   return z;
17940 }
17941
17942 /*
17943 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17944 ** %-conversion extensions.
17945 */
17946 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17947   va_list ap;
17948   char *z;
17949 #ifndef SQLITE_OMIT_AUTOINIT
17950   if( sqlite3_initialize() ) return 0;
17951 #endif
17952   va_start(ap, zFormat);
17953   z = sqlite3_vmprintf(zFormat, ap);
17954   va_end(ap);
17955   return z;
17956 }
17957
17958 /*
17959 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17960 ** current locale settings.  This is important for SQLite because we
17961 ** are not able to use a "," as the decimal point in place of "." as
17962 ** specified by some locales.
17963 */
17964 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17965   char *z;
17966   va_list ap;
17967   StrAccum acc;
17968
17969   if( n<=0 ){
17970     return zBuf;
17971   }
17972   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17973   acc.useMalloc = 0;
17974   va_start(ap,zFormat);
17975   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17976   va_end(ap);
17977   z = sqlite3StrAccumFinish(&acc);
17978   return z;
17979 }
17980
17981 #if defined(SQLITE_DEBUG)
17982 /*
17983 ** A version of printf() that understands %lld.  Used for debugging.
17984 ** The printf() built into some versions of windows does not understand %lld
17985 ** and segfaults if you give it a long long int.
17986 */
17987 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17988   va_list ap;
17989   StrAccum acc;
17990   char zBuf[500];
17991   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17992   acc.useMalloc = 0;
17993   va_start(ap,zFormat);
17994   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17995   va_end(ap);
17996   sqlite3StrAccumFinish(&acc);
17997   fprintf(stdout,"%s", zBuf);
17998   fflush(stdout);
17999 }
18000 #endif
18001
18002 /************** End of printf.c **********************************************/
18003 /************** Begin file random.c ******************************************/
18004 /*
18005 ** 2001 September 15
18006 **
18007 ** The author disclaims copyright to this source code.  In place of
18008 ** a legal notice, here is a blessing:
18009 **
18010 **    May you do good and not evil.
18011 **    May you find forgiveness for yourself and forgive others.
18012 **    May you share freely, never taking more than you give.
18013 **
18014 *************************************************************************
18015 ** This file contains code to implement a pseudo-random number
18016 ** generator (PRNG) for SQLite.
18017 **
18018 ** Random numbers are used by some of the database backends in order
18019 ** to generate random integer keys for tables or random filenames.
18020 **
18021 ** $Id: random.c,v 1.29 2008/12/10 19:26:24 drh Exp $
18022 */
18023
18024
18025 /* All threads share a single random number generator.
18026 ** This structure is the current state of the generator.
18027 */
18028 static SQLITE_WSD struct sqlite3PrngType {
18029   unsigned char isInit;          /* True if initialized */
18030   unsigned char i, j;            /* State variables */
18031   unsigned char s[256];          /* State variables */
18032 } sqlite3Prng;
18033
18034 /*
18035 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18036 ** must be held while executing this routine.
18037 **
18038 ** Why not just use a library random generator like lrand48() for this?
18039 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
18040 ** good source of random numbers.  The lrand48() library function may
18041 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
18042 ** subtle problems on some systems that could cause problems.  It is hard
18043 ** to know.  To minimize the risk of problems due to bad lrand48()
18044 ** implementations, SQLite uses this random number generator based
18045 ** on RC4, which we know works very well.
18046 **
18047 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
18048 ** randomness any more.  But we will leave this code in all the same.
18049 */
18050 static u8 randomByte(void){
18051   unsigned char t;
18052
18053
18054   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18055   ** state vector.  If writable static data is unsupported on the target,
18056   ** we have to locate the state vector at run-time.  In the more common
18057   ** case where writable static data is supported, wsdPrng can refer directly
18058   ** to the "sqlite3Prng" state vector declared above.
18059   */
18060 #ifdef SQLITE_OMIT_WSD
18061   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18062 # define wsdPrng p[0]
18063 #else
18064 # define wsdPrng sqlite3Prng
18065 #endif
18066
18067
18068   /* Initialize the state of the random number generator once,
18069   ** the first time this routine is called.  The seed value does
18070   ** not need to contain a lot of randomness since we are not
18071   ** trying to do secure encryption or anything like that...
18072   **
18073   ** Nothing in this file or anywhere else in SQLite does any kind of
18074   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18075   ** number generator) not as an encryption device.
18076   */
18077   if( !wsdPrng.isInit ){
18078     int i;
18079     char k[256];
18080     wsdPrng.j = 0;
18081     wsdPrng.i = 0;
18082     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18083     for(i=0; i<256; i++){
18084       wsdPrng.s[i] = (u8)i;
18085     }
18086     for(i=0; i<256; i++){
18087       wsdPrng.j += wsdPrng.s[i] + k[i];
18088       t = wsdPrng.s[wsdPrng.j];
18089       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18090       wsdPrng.s[i] = t;
18091     }
18092     wsdPrng.isInit = 1;
18093   }
18094
18095   /* Generate and return single random byte
18096   */
18097   wsdPrng.i++;
18098   t = wsdPrng.s[wsdPrng.i];
18099   wsdPrng.j += t;
18100   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18101   wsdPrng.s[wsdPrng.j] = t;
18102   t += wsdPrng.s[wsdPrng.i];
18103   return wsdPrng.s[t];
18104 }
18105
18106 /*
18107 ** Return N random bytes.
18108 */
18109 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18110   unsigned char *zBuf = pBuf;
18111 #if SQLITE_THREADSAFE
18112   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18113 #endif
18114   sqlite3_mutex_enter(mutex);
18115   while( N-- ){
18116     *(zBuf++) = randomByte();
18117   }
18118   sqlite3_mutex_leave(mutex);
18119 }
18120
18121 #ifndef SQLITE_OMIT_BUILTIN_TEST
18122 /*
18123 ** For testing purposes, we sometimes want to preserve the state of
18124 ** PRNG and restore the PRNG to its saved state at a later time, or
18125 ** to reset the PRNG to its initial state.  These routines accomplish
18126 ** those tasks.
18127 **
18128 ** The sqlite3_test_control() interface calls these routines to
18129 ** control the PRNG.
18130 */
18131 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18132 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18133   memcpy(
18134     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18135     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18136     sizeof(sqlite3Prng)
18137   );
18138 }
18139 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18140   memcpy(
18141     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18142     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18143     sizeof(sqlite3Prng)
18144   );
18145 }
18146 SQLITE_PRIVATE void sqlite3PrngResetState(void){
18147   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18148 }
18149 #endif /* SQLITE_OMIT_BUILTIN_TEST */
18150
18151 /************** End of random.c **********************************************/
18152 /************** Begin file utf.c *********************************************/
18153 /*
18154 ** 2004 April 13
18155 **
18156 ** The author disclaims copyright to this source code.  In place of
18157 ** a legal notice, here is a blessing:
18158 **
18159 **    May you do good and not evil.
18160 **    May you find forgiveness for yourself and forgive others.
18161 **    May you share freely, never taking more than you give.
18162 **
18163 *************************************************************************
18164 ** This file contains routines used to translate between UTF-8, 
18165 ** UTF-16, UTF-16BE, and UTF-16LE.
18166 **
18167 ** $Id: utf.c,v 1.70 2008/12/10 22:30:25 shane Exp $
18168 **
18169 ** Notes on UTF-8:
18170 **
18171 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
18172 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
18173 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
18174 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
18175 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
18176 **
18177 **
18178 ** Notes on UTF-16:  (with wwww+1==uuuuu)
18179 **
18180 **      Word-0               Word-1          Value
18181 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
18182 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
18183 **
18184 **
18185 ** BOM or Byte Order Mark:
18186 **     0xff 0xfe   little-endian utf-16 follows
18187 **     0xfe 0xff   big-endian utf-16 follows
18188 **
18189 */
18190 /************** Include vdbeInt.h in the middle of utf.c *********************/
18191 /************** Begin file vdbeInt.h *****************************************/
18192 /*
18193 ** 2003 September 6
18194 **
18195 ** The author disclaims copyright to this source code.  In place of
18196 ** a legal notice, here is a blessing:
18197 **
18198 **    May you do good and not evil.
18199 **    May you find forgiveness for yourself and forgive others.
18200 **    May you share freely, never taking more than you give.
18201 **
18202 *************************************************************************
18203 ** This is the header file for information that is private to the
18204 ** VDBE.  This information used to all be at the top of the single
18205 ** source code file "vdbe.c".  When that file became too big (over
18206 ** 6000 lines long) it was split up into several smaller files and
18207 ** this header information was factored out.
18208 **
18209 ** $Id: vdbeInt.h,v 1.162 2009/02/03 15:39:01 drh Exp $
18210 */
18211 #ifndef _VDBEINT_H_
18212 #define _VDBEINT_H_
18213
18214 /*
18215 ** intToKey() and keyToInt() used to transform the rowid.  But with
18216 ** the latest versions of the design they are no-ops.
18217 */
18218 #define keyToInt(X)   (X)
18219 #define intToKey(X)   (X)
18220
18221
18222 /*
18223 ** SQL is translated into a sequence of instructions to be
18224 ** executed by a virtual machine.  Each instruction is an instance
18225 ** of the following structure.
18226 */
18227 typedef struct VdbeOp Op;
18228
18229 /*
18230 ** Boolean values
18231 */
18232 typedef unsigned char Bool;
18233
18234 /*
18235 ** A cursor is a pointer into a single BTree within a database file.
18236 ** The cursor can seek to a BTree entry with a particular key, or
18237 ** loop over all entries of the Btree.  You can also insert new BTree
18238 ** entries or retrieve the key or data from the entry that the cursor
18239 ** is currently pointing to.
18240 ** 
18241 ** Every cursor that the virtual machine has open is represented by an
18242 ** instance of the following structure.
18243 **
18244 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
18245 ** really a single row that represents the NEW or OLD pseudo-table of
18246 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
18247 ** the rowid is in VdbeCursor.iKey.
18248 */
18249 struct VdbeCursor {
18250   BtCursor *pCursor;    /* The cursor structure of the backend */
18251   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
18252   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
18253   i64 nextRowid;        /* Next rowid returned by OP_NewRowid */
18254   Bool zeroed;          /* True if zeroed out and ready for reuse */
18255   Bool rowidIsValid;    /* True if lastRowid is valid */
18256   Bool atFirst;         /* True if pointing to first entry */
18257   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
18258   Bool nullRow;         /* True if pointing to a row with no data */
18259   Bool nextRowidValid;  /* True if the nextRowid field is valid */
18260   Bool pseudoTable;     /* This is a NEW or OLD pseudo-tables of a trigger */
18261   Bool ephemPseudoTable;
18262   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
18263   Bool isTable;         /* True if a table requiring integer keys */
18264   Bool isIndex;         /* True if an index containing keys only - no data */
18265   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
18266   Btree *pBt;           /* Separate file holding temporary table */
18267   int nData;            /* Number of bytes in pData */
18268   char *pData;          /* Data for a NEW or OLD pseudo-table */
18269   i64 iKey;             /* Key for the NEW or OLD pseudo-table row */
18270   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
18271   int nField;           /* Number of fields in the header */
18272   i64 seqCount;         /* Sequence counter */
18273   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
18274   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
18275
18276   /* Cached information about the header for the data record that the
18277   ** cursor is currently pointing to.  Only valid if cacheValid is true.
18278   ** aRow might point to (ephemeral) data for the current row, or it might
18279   ** be NULL.
18280   */
18281   int cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
18282   int payloadSize;      /* Total number of bytes in the record */
18283   u32 *aType;           /* Type values for all entries in the record */
18284   u32 *aOffset;         /* Cached offsets to the start of each columns data */
18285   u8 *aRow;             /* Data for the current row, if all on one page */
18286 };
18287 typedef struct VdbeCursor VdbeCursor;
18288
18289 /*
18290 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
18291 */
18292 #define CACHE_STALE 0
18293
18294 /*
18295 ** Internally, the vdbe manipulates nearly all SQL values as Mem
18296 ** structures. Each Mem struct may cache multiple representations (string,
18297 ** integer etc.) of the same value.  A value (and therefore Mem structure)
18298 ** has the following properties:
18299 **
18300 ** Each value has a manifest type. The manifest type of the value stored
18301 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
18302 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
18303 ** SQLITE_BLOB.
18304 */
18305 struct Mem {
18306   union {
18307     i64 i;              /* Integer value. */
18308     int nZero;          /* Used when bit MEM_Zero is set in flags */
18309     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18310     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18311   } u;
18312   double r;           /* Real value */
18313   sqlite3 *db;        /* The associated database connection */
18314   char *z;            /* String or BLOB value */
18315   int n;              /* Number of characters in string value, excluding '\0' */
18316   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18317   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18318   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18319   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18320   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18321 };
18322
18323 /* One or more of the following flags are set to indicate the validOK
18324 ** representations of the value stored in the Mem struct.
18325 **
18326 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18327 ** No other flags may be set in this case.
18328 **
18329 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18330 ** Usually this is encoded in the same unicode encoding as the main
18331 ** database (see below for exceptions). If the MEM_Term flag is also
18332 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
18333 ** flags may coexist with the MEM_Str flag.
18334 **
18335 ** Multiple of these values can appear in Mem.flags.  But only one
18336 ** at a time can appear in Mem.type.
18337 */
18338 #define MEM_Null      0x0001   /* Value is NULL */
18339 #define MEM_Str       0x0002   /* Value is a string */
18340 #define MEM_Int       0x0004   /* Value is an integer */
18341 #define MEM_Real      0x0008   /* Value is a real number */
18342 #define MEM_Blob      0x0010   /* Value is a BLOB */
18343 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
18344 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
18345
18346 /* Whenever Mem contains a valid string or blob representation, one of
18347 ** the following flags must be set to determine the memory management
18348 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18349 ** string is \000 or \u0000 terminated
18350 */
18351 #define MEM_Term      0x0200   /* String rep is nul terminated */
18352 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
18353 #define MEM_Static    0x0800   /* Mem.z points to a static string */
18354 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18355 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18356 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18357
18358 #ifdef SQLITE_OMIT_INCRBLOB
18359   #undef MEM_Zero
18360   #define MEM_Zero 0x0000
18361 #endif
18362
18363
18364 /*
18365 ** Clear any existing type flags from a Mem and replace them with f
18366 */
18367 #define MemSetTypeFlag(p, f) \
18368    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18369
18370
18371 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18372 ** additional information about auxiliary information bound to arguments
18373 ** of the function.  This is used to implement the sqlite3_get_auxdata()
18374 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18375 ** that can be associated with a constant argument to a function.  This
18376 ** allows functions such as "regexp" to compile their constant regular
18377 ** expression argument once and reused the compiled code for multiple
18378 ** invocations.
18379 */
18380 struct VdbeFunc {
18381   FuncDef *pFunc;               /* The definition of the function */
18382   int nAux;                     /* Number of entries allocated for apAux[] */
18383   struct AuxData {
18384     void *pAux;                   /* Aux data for the i-th argument */
18385     void (*xDelete)(void *);      /* Destructor for the aux data */
18386   } apAux[1];                   /* One slot for each function argument */
18387 };
18388
18389 /*
18390 ** The "context" argument for a installable function.  A pointer to an
18391 ** instance of this structure is the first argument to the routines used
18392 ** implement the SQL functions.
18393 **
18394 ** There is a typedef for this structure in sqlite.h.  So all routines,
18395 ** even the public interface to SQLite, can use a pointer to this structure.
18396 ** But this file is the only place where the internal details of this
18397 ** structure are known.
18398 **
18399 ** This structure is defined inside of vdbeInt.h because it uses substructures
18400 ** (Mem) which are only defined there.
18401 */
18402 struct sqlite3_context {
18403   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18404   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18405   Mem s;                /* The return value is stored here */
18406   Mem *pMem;            /* Memory cell used to store aggregate context */
18407   int isError;          /* Error code returned by the function. */
18408   CollSeq *pColl;       /* Collating sequence */
18409 };
18410
18411 /*
18412 ** A Set structure is used for quick testing to see if a value
18413 ** is part of a small set.  Sets are used to implement code like
18414 ** this:
18415 **            x.y IN ('hi','hoo','hum')
18416 */
18417 typedef struct Set Set;
18418 struct Set {
18419   Hash hash;             /* A set is just a hash table */
18420   HashElem *prev;        /* Previously accessed hash elemen */
18421 };
18422
18423 /*
18424 ** A Context stores the last insert rowid, the last statement change count,
18425 ** and the current statement change count (i.e. changes since last statement).
18426 ** The current keylist is also stored in the context.
18427 ** Elements of Context structure type make up the ContextStack, which is
18428 ** updated by the ContextPush and ContextPop opcodes (used by triggers).
18429 ** The context is pushed before executing a trigger a popped when the
18430 ** trigger finishes.
18431 */
18432 typedef struct Context Context;
18433 struct Context {
18434   i64 lastRowid;    /* Last insert rowid (sqlite3.lastRowid) */
18435   int nChange;      /* Statement changes (Vdbe.nChanges)     */
18436 };
18437
18438 /*
18439 ** An instance of the virtual machine.  This structure contains the complete
18440 ** state of the virtual machine.
18441 **
18442 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18443 ** is really a pointer to an instance of this structure.
18444 **
18445 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18446 ** any virtual table method invocations made by the vdbe program. It is
18447 ** set to 2 for xDestroy method calls and 1 for all other methods. This
18448 ** variable is used for two purposes: to allow xDestroy methods to execute
18449 ** "DROP TABLE" statements and to prevent some nasty side effects of
18450 ** malloc failure when SQLite is invoked recursively by a virtual table 
18451 ** method function.
18452 */
18453 struct Vdbe {
18454   sqlite3 *db;        /* The whole database */
18455   Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
18456   int nOp;            /* Number of instructions in the program */
18457   int nOpAlloc;       /* Number of slots allocated for aOp[] */
18458   Op *aOp;            /* Space to hold the virtual machine's program */
18459   int nLabel;         /* Number of labels used */
18460   int nLabelAlloc;    /* Number of slots allocated in aLabel[] */
18461   int *aLabel;        /* Space to hold the labels */
18462   Mem **apArg;        /* Arguments to currently executing user function */
18463   Mem *aColName;      /* Column names to return */
18464   int nCursor;        /* Number of slots in apCsr[] */
18465   VdbeCursor **apCsr; /* One element of this array for each open cursor */
18466   int nVar;           /* Number of entries in aVar[] */
18467   Mem *aVar;          /* Values for the OP_Variable opcode. */
18468   char **azVar;       /* Name of variables */
18469   int okVar;          /* True if azVar[] has been initialized */
18470   u32 magic;              /* Magic number for sanity checking */
18471   int nMem;               /* Number of memory locations currently allocated */
18472   Mem *aMem;              /* The memory locations */
18473   int nCallback;          /* Number of callbacks invoked so far */
18474   int cacheCtr;           /* VdbeCursor row cache generation counter */
18475   int contextStackTop;    /* Index of top element in the context stack */
18476   int contextStackDepth;  /* The size of the "context" stack */
18477   Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
18478   int pc;                 /* The program counter */
18479   int rc;                 /* Value to return */
18480   unsigned uniqueCnt;     /* Used by OP_MakeRecord when P2!=0 */
18481   int errorAction;        /* Recovery action to do in case of an error */
18482   int inTempTrans;        /* True if temp database is transactioned */
18483   int nResColumn;         /* Number of columns in one row of the result set */
18484   char **azResColumn;     /* Values for one row of result */ 
18485   char *zErrMsg;          /* Error message written here */
18486   Mem *pResultSet;        /* Pointer to an array of results */
18487   u8 explain;             /* True if EXPLAIN present on SQL command */
18488   u8 changeCntOn;         /* True to update the change-counter */
18489   u8 expired;             /* True if the VM needs to be recompiled */
18490   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18491   u8 inVtabMethod;        /* See comments above */
18492   u8 usesStmtJournal;     /* True if uses a statement journal */
18493   u8 readOnly;            /* True for read-only statements */
18494   int nChange;            /* Number of db changes made since last reset */
18495   i64 startTime;          /* Time when query started - used for profiling */
18496   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18497   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18498   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
18499   int nSql;             /* Number of bytes in zSql */
18500   char *zSql;           /* Text of the SQL statement that generated this */
18501 #ifdef SQLITE_DEBUG
18502   FILE *trace;          /* Write an execution trace here, if not NULL */
18503 #endif
18504   int openedStatement;  /* True if this VM has opened a statement journal */
18505 #ifdef SQLITE_SSE
18506   int fetchId;          /* Statement number used by sqlite3_fetch_statement */
18507   int lru;              /* Counter used for LRU cache replacement */
18508 #endif
18509 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18510   Vdbe *pLruPrev;
18511   Vdbe *pLruNext;
18512 #endif
18513 };
18514
18515 /*
18516 ** The following are allowed values for Vdbe.magic
18517 */
18518 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18519 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18520 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18521 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18522
18523 /*
18524 ** Function prototypes
18525 */
18526 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18527 void sqliteVdbePopStack(Vdbe*,int);
18528 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18529 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18530 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18531 #endif
18532 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
18533 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18534 SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18535 SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18536 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18537
18538 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18539 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18540 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
18541 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18542 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18543 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18544 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18545 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18546 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18547 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18548 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18549 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18550 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18551 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18552 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18553 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
18554 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18555 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18556 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18557 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18558 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18559 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18560 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18561 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18562 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18563 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18564 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18565 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18566 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18567 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18568 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18569 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18570 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
18571 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18572 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18573 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
18574 #endif
18575
18576 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18577 #ifdef SQLITE_DEBUG
18578 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18579 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18580 #endif
18581 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18582
18583 #ifndef SQLITE_OMIT_INCRBLOB
18584 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18585 #else
18586   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18587 #endif
18588
18589 #endif /* !defined(_VDBEINT_H_) */
18590
18591 /************** End of vdbeInt.h *********************************************/
18592 /************** Continuing where we left off in utf.c ************************/
18593
18594 #ifndef SQLITE_AMALGAMATION
18595 /*
18596 ** The following constant value is used by the SQLITE_BIGENDIAN and
18597 ** SQLITE_LITTLEENDIAN macros.
18598 */
18599 SQLITE_PRIVATE const int sqlite3one = 1;
18600 #endif /* SQLITE_AMALGAMATION */
18601
18602 /*
18603 ** This lookup table is used to help decode the first byte of
18604 ** a multi-byte UTF8 character.
18605 */
18606 static const unsigned char sqlite3Utf8Trans1[] = {
18607   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18608   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18609   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18610   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18611   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18612   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18613   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18614   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18615 };
18616
18617
18618 #define WRITE_UTF8(zOut, c) {                          \
18619   if( c<0x00080 ){                                     \
18620     *zOut++ = (u8)(c&0xFF);                            \
18621   }                                                    \
18622   else if( c<0x00800 ){                                \
18623     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
18624     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18625   }                                                    \
18626   else if( c<0x10000 ){                                \
18627     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
18628     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18629     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18630   }else{                                               \
18631     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
18632     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
18633     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18634     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18635   }                                                    \
18636 }
18637
18638 #define WRITE_UTF16LE(zOut, c) {                                    \
18639   if( c<=0xFFFF ){                                                  \
18640     *zOut++ = (u8)(c&0x00FF);                                       \
18641     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18642   }else{                                                            \
18643     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18644     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18645     *zOut++ = (u8)(c&0x00FF);                                       \
18646     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18647   }                                                                 \
18648 }
18649
18650 #define WRITE_UTF16BE(zOut, c) {                                    \
18651   if( c<=0xFFFF ){                                                  \
18652     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18653     *zOut++ = (u8)(c&0x00FF);                                       \
18654   }else{                                                            \
18655     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18656     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18657     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18658     *zOut++ = (u8)(c&0x00FF);                                       \
18659   }                                                                 \
18660 }
18661
18662 #define READ_UTF16LE(zIn, c){                                         \
18663   c = (*zIn++);                                                       \
18664   c += ((*zIn++)<<8);                                                 \
18665   if( c>=0xD800 && c<0xE000 ){                                       \
18666     int c2 = (*zIn++);                                                \
18667     c2 += ((*zIn++)<<8);                                              \
18668     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18669     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18670   }                                                                   \
18671 }
18672
18673 #define READ_UTF16BE(zIn, c){                                         \
18674   c = ((*zIn++)<<8);                                                  \
18675   c += (*zIn++);                                                      \
18676   if( c>=0xD800 && c<0xE000 ){                                       \
18677     int c2 = ((*zIn++)<<8);                                           \
18678     c2 += (*zIn++);                                                   \
18679     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18680     if( (c & 0xFFFF0000)==0 ) c = 0xFFFD;                             \
18681   }                                                                   \
18682 }
18683
18684 /*
18685 ** Translate a single UTF-8 character.  Return the unicode value.
18686 **
18687 ** During translation, assume that the byte that zTerm points
18688 ** is a 0x00.
18689 **
18690 ** Write a pointer to the next unread byte back into *pzNext.
18691 **
18692 ** Notes On Invalid UTF-8:
18693 **
18694 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18695 **     be encoded as a multi-byte character.  Any multi-byte character that
18696 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18697 **
18698 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18699 **     If a multi-byte character attempts to encode a value between
18700 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18701 **
18702 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18703 **     byte of a character are interpreted as single-byte characters
18704 **     and rendered as themselves even though they are technically
18705 **     invalid characters.
18706 **
18707 **  *  This routine accepts an infinite number of different UTF8 encodings
18708 **     for unicode values 0x80 and greater.  It do not change over-length
18709 **     encodings to 0xfffd as some systems recommend.
18710 */
18711 #define READ_UTF8(zIn, zTerm, c)                           \
18712   c = *(zIn++);                                            \
18713   if( c>=0xc0 ){                                           \
18714     c = sqlite3Utf8Trans1[c-0xc0];                         \
18715     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18716       c = (c<<6) + (0x3f & *(zIn++));                      \
18717     }                                                      \
18718     if( c<0x80                                             \
18719         || (c&0xFFFFF800)==0xD800                          \
18720         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18721   }
18722 SQLITE_PRIVATE int sqlite3Utf8Read(
18723   const unsigned char *z,         /* First byte of UTF-8 character */
18724   const unsigned char *zTerm,     /* Pretend this byte is 0x00 */
18725   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18726 ){
18727   int c;
18728   READ_UTF8(z, zTerm, c);
18729   *pzNext = z;
18730   return c;
18731 }
18732
18733
18734
18735
18736 /*
18737 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18738 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18739 */ 
18740 /* #define TRANSLATE_TRACE 1 */
18741
18742 #ifndef SQLITE_OMIT_UTF16
18743 /*
18744 ** This routine transforms the internal text encoding used by pMem to
18745 ** desiredEnc. It is an error if the string is already of the desired
18746 ** encoding, or if *pMem does not contain a string value.
18747 */
18748 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18749   int len;                    /* Maximum length of output string in bytes */
18750   unsigned char *zOut;                  /* Output buffer */
18751   unsigned char *zIn;                   /* Input iterator */
18752   unsigned char *zTerm;                 /* End of input */
18753   unsigned char *z;                     /* Output iterator */
18754   unsigned int c;
18755
18756   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18757   assert( pMem->flags&MEM_Str );
18758   assert( pMem->enc!=desiredEnc );
18759   assert( pMem->enc!=0 );
18760   assert( pMem->n>=0 );
18761
18762 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18763   {
18764     char zBuf[100];
18765     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18766     fprintf(stderr, "INPUT:  %s\n", zBuf);
18767   }
18768 #endif
18769
18770   /* If the translation is between UTF-16 little and big endian, then 
18771   ** all that is required is to swap the byte order. This case is handled
18772   ** differently from the others.
18773   */
18774   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18775     u8 temp;
18776     int rc;
18777     rc = sqlite3VdbeMemMakeWriteable(pMem);
18778     if( rc!=SQLITE_OK ){
18779       assert( rc==SQLITE_NOMEM );
18780       return SQLITE_NOMEM;
18781     }
18782     zIn = (u8*)pMem->z;
18783     zTerm = &zIn[pMem->n&~1];
18784     while( zIn<zTerm ){
18785       temp = *zIn;
18786       *zIn = *(zIn+1);
18787       zIn++;
18788       *zIn++ = temp;
18789     }
18790     pMem->enc = desiredEnc;
18791     goto translate_out;
18792   }
18793
18794   /* Set len to the maximum number of bytes required in the output buffer. */
18795   if( desiredEnc==SQLITE_UTF8 ){
18796     /* When converting from UTF-16, the maximum growth results from
18797     ** translating a 2-byte character to a 4-byte UTF-8 character.
18798     ** A single byte is required for the output string
18799     ** nul-terminator.
18800     */
18801     pMem->n &= ~1;
18802     len = pMem->n * 2 + 1;
18803   }else{
18804     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18805     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18806     ** character. Two bytes are required in the output buffer for the
18807     ** nul-terminator.
18808     */
18809     len = pMem->n * 2 + 2;
18810   }
18811
18812   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18813   ** byte past the end.
18814   **
18815   ** Variable zOut is set to point at the output buffer, space obtained
18816   ** from sqlite3_malloc().
18817   */
18818   zIn = (u8*)pMem->z;
18819   zTerm = &zIn[pMem->n];
18820   zOut = sqlite3DbMallocRaw(pMem->db, len);
18821   if( !zOut ){
18822     return SQLITE_NOMEM;
18823   }
18824   z = zOut;
18825
18826   if( pMem->enc==SQLITE_UTF8 ){
18827     if( desiredEnc==SQLITE_UTF16LE ){
18828       /* UTF-8 -> UTF-16 Little-endian */
18829       while( zIn<zTerm ){
18830         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18831         READ_UTF8(zIn, zTerm, c);
18832         WRITE_UTF16LE(z, c);
18833       }
18834     }else{
18835       assert( desiredEnc==SQLITE_UTF16BE );
18836       /* UTF-8 -> UTF-16 Big-endian */
18837       while( zIn<zTerm ){
18838         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18839         READ_UTF8(zIn, zTerm, c);
18840         WRITE_UTF16BE(z, c);
18841       }
18842     }
18843     pMem->n = (int)(z - zOut);
18844     *z++ = 0;
18845   }else{
18846     assert( desiredEnc==SQLITE_UTF8 );
18847     if( pMem->enc==SQLITE_UTF16LE ){
18848       /* UTF-16 Little-endian -> UTF-8 */
18849       while( zIn<zTerm ){
18850         READ_UTF16LE(zIn, c); 
18851         WRITE_UTF8(z, c);
18852       }
18853     }else{
18854       /* UTF-16 Big-endian -> UTF-8 */
18855       while( zIn<zTerm ){
18856         READ_UTF16BE(zIn, c); 
18857         WRITE_UTF8(z, c);
18858       }
18859     }
18860     pMem->n = (int)(z - zOut);
18861   }
18862   *z = 0;
18863   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18864
18865   sqlite3VdbeMemRelease(pMem);
18866   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18867   pMem->enc = desiredEnc;
18868   pMem->flags |= (MEM_Term|MEM_Dyn);
18869   pMem->z = (char*)zOut;
18870   pMem->zMalloc = pMem->z;
18871
18872 translate_out:
18873 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18874   {
18875     char zBuf[100];
18876     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18877     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18878   }
18879 #endif
18880   return SQLITE_OK;
18881 }
18882
18883 /*
18884 ** This routine checks for a byte-order mark at the beginning of the 
18885 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18886 ** the encoding of the Mem adjusted. This routine does not do any
18887 ** byte-swapping, it just sets Mem.enc appropriately.
18888 **
18889 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18890 ** changed by this function.
18891 */
18892 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18893   int rc = SQLITE_OK;
18894   u8 bom = 0;
18895
18896   if( pMem->n<0 || pMem->n>1 ){
18897     u8 b1 = *(u8 *)pMem->z;
18898     u8 b2 = *(((u8 *)pMem->z) + 1);
18899     if( b1==0xFE && b2==0xFF ){
18900       bom = SQLITE_UTF16BE;
18901     }
18902     if( b1==0xFF && b2==0xFE ){
18903       bom = SQLITE_UTF16LE;
18904     }
18905   }
18906   
18907   if( bom ){
18908     rc = sqlite3VdbeMemMakeWriteable(pMem);
18909     if( rc==SQLITE_OK ){
18910       pMem->n -= 2;
18911       memmove(pMem->z, &pMem->z[2], pMem->n);
18912       pMem->z[pMem->n] = '\0';
18913       pMem->z[pMem->n+1] = '\0';
18914       pMem->flags |= MEM_Term;
18915       pMem->enc = bom;
18916     }
18917   }
18918   return rc;
18919 }
18920 #endif /* SQLITE_OMIT_UTF16 */
18921
18922 /*
18923 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18924 ** return the number of unicode characters in pZ up to (but not including)
18925 ** the first 0x00 byte. If nByte is not less than zero, return the
18926 ** number of unicode characters in the first nByte of pZ (or up to 
18927 ** the first 0x00, whichever comes first).
18928 */
18929 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18930   int r = 0;
18931   const u8 *z = (const u8*)zIn;
18932   const u8 *zTerm;
18933   if( nByte>=0 ){
18934     zTerm = &z[nByte];
18935   }else{
18936     zTerm = (const u8*)(-1);
18937   }
18938   assert( z<=zTerm );
18939   while( *z!=0 && z<zTerm ){
18940     SQLITE_SKIP_UTF8(z);
18941     r++;
18942   }
18943   return r;
18944 }
18945
18946 /* This test function is not currently used by the automated test-suite. 
18947 ** Hence it is only available in debug builds.
18948 */
18949 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18950 /*
18951 ** Translate UTF-8 to UTF-8.
18952 **
18953 ** This has the effect of making sure that the string is well-formed
18954 ** UTF-8.  Miscoded characters are removed.
18955 **
18956 ** The translation is done in-place (since it is impossible for the
18957 ** correct UTF-8 encoding to be longer than a malformed encoding).
18958 */
18959 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18960   unsigned char *zOut = zIn;
18961   unsigned char *zStart = zIn;
18962   unsigned char *zTerm = &zIn[sqlite3Strlen30((char *)zIn)];
18963   u32 c;
18964
18965   while( zIn[0] ){
18966     c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn);
18967     if( c!=0xfffd ){
18968       WRITE_UTF8(zOut, c);
18969     }
18970   }
18971   *zOut = 0;
18972   return zOut - zStart;
18973 }
18974 #endif
18975
18976 #ifndef SQLITE_OMIT_UTF16
18977 /*
18978 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18979 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18980 ** be freed by the calling function.
18981 **
18982 ** NULL is returned if there is an allocation error.
18983 */
18984 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18985   Mem m;
18986   memset(&m, 0, sizeof(m));
18987   m.db = db;
18988   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18989   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18990   if( db->mallocFailed ){
18991     sqlite3VdbeMemRelease(&m);
18992     m.z = 0;
18993   }
18994   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18995   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18996   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18997 }
18998
18999 /*
19000 ** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
19001 ** return the number of bytes up to (but not including), the first pair
19002 ** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
19003 ** then return the number of bytes in the first nChar unicode characters
19004 ** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
19005 */
19006 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19007   unsigned int c = 1;
19008   char const *z = zIn;
19009   int n = 0;
19010   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19011     /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
19012     ** and in other parts of this file means that at one branch will
19013     ** not be covered by coverage testing on any single host. But coverage
19014     ** will be complete if the tests are run on both a little-endian and 
19015     ** big-endian host. Because both the UTF16NATIVE and SQLITE_UTF16BE
19016     ** macros are constant at compile time the compiler can determine
19017     ** which branch will be followed. It is therefore assumed that no runtime
19018     ** penalty is paid for this "if" statement.
19019     */
19020     while( c && ((nChar<0) || n<nChar) ){
19021       READ_UTF16BE(z, c);
19022       n++;
19023     }
19024   }else{
19025     while( c && ((nChar<0) || n<nChar) ){
19026       READ_UTF16LE(z, c);
19027       n++;
19028     }
19029   }
19030   return (int)(z-(char const *)zIn)-((c==0)?2:0);
19031 }
19032
19033 #if defined(SQLITE_TEST)
19034 /*
19035 ** This routine is called from the TCL test function "translate_selftest".
19036 ** It checks that the primitives for serializing and deserializing
19037 ** characters in each encoding are inverses of each other.
19038 */
19039 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19040   unsigned int i, t;
19041   unsigned char zBuf[20];
19042   unsigned char *z;
19043   unsigned char *zTerm;
19044   int n;
19045   unsigned int c;
19046
19047   for(i=0; i<0x00110000; i++){
19048     z = zBuf;
19049     WRITE_UTF8(z, i);
19050     n = (int)(z-zBuf);
19051     assert( n>0 && n<=4 );
19052     z[0] = 0;
19053     zTerm = z;
19054     z = zBuf;
19055     c = sqlite3Utf8Read(z, zTerm, (const u8**)&z);
19056     t = i;
19057     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19058     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19059     assert( c==t );
19060     assert( (z-zBuf)==n );
19061   }
19062   for(i=0; i<0x00110000; i++){
19063     if( i>=0xD800 && i<0xE000 ) continue;
19064     z = zBuf;
19065     WRITE_UTF16LE(z, i);
19066     n = (int)(z-zBuf);
19067     assert( n>0 && n<=4 );
19068     z[0] = 0;
19069     z = zBuf;
19070     READ_UTF16LE(z, c);
19071     assert( c==i );
19072     assert( (z-zBuf)==n );
19073   }
19074   for(i=0; i<0x00110000; i++){
19075     if( i>=0xD800 && i<0xE000 ) continue;
19076     z = zBuf;
19077     WRITE_UTF16BE(z, i);
19078     n = (int)(z-zBuf);
19079     assert( n>0 && n<=4 );
19080     z[0] = 0;
19081     z = zBuf;
19082     READ_UTF16BE(z, c);
19083     assert( c==i );
19084     assert( (z-zBuf)==n );
19085   }
19086 }
19087 #endif /* SQLITE_TEST */
19088 #endif /* SQLITE_OMIT_UTF16 */
19089
19090 /************** End of utf.c *************************************************/
19091 /************** Begin file util.c ********************************************/
19092 /*
19093 ** 2001 September 15
19094 **
19095 ** The author disclaims copyright to this source code.  In place of
19096 ** a legal notice, here is a blessing:
19097 **
19098 **    May you do good and not evil.
19099 **    May you find forgiveness for yourself and forgive others.
19100 **    May you share freely, never taking more than you give.
19101 **
19102 *************************************************************************
19103 ** Utility functions used throughout sqlite.
19104 **
19105 ** This file contains functions for allocating memory, comparing
19106 ** strings, and stuff like that.
19107 **
19108 ** $Id: util.c,v 1.248 2009/02/04 03:59:25 shane Exp $
19109 */
19110
19111 /*
19112 ** Routine needed to support the testcase() macro.
19113 */
19114 #ifdef SQLITE_COVERAGE_TEST
19115 SQLITE_PRIVATE void sqlite3Coverage(int x){
19116   static int dummy = 0;
19117   dummy += x;
19118 }
19119 #endif
19120
19121 /*
19122 ** Routine needed to support the ALWAYS() and NEVER() macros.
19123 **
19124 ** The argument to ALWAYS() should always be true and the argument
19125 ** to NEVER() should always be false.  If either is not the case
19126 ** then this routine is called in order to throw an error.
19127 **
19128 ** This routine only exists if assert() is operational.  It always
19129 ** throws an assert on its first invocation.  The variable has a long
19130 ** name to help the assert() message be more readable.  The variable
19131 ** is used to prevent a too-clever optimizer from optimizing out the
19132 ** entire call.
19133 */
19134 #ifndef NDEBUG
19135 SQLITE_PRIVATE int sqlite3Assert(void){
19136   static volatile int ALWAYS_was_false_or_NEVER_was_true = 0;
19137   assert( ALWAYS_was_false_or_NEVER_was_true );      /* Always fails */
19138   return ALWAYS_was_false_or_NEVER_was_true++;       /* Not Reached */
19139 }
19140 #endif
19141
19142 /*
19143 ** Return true if the floating point value is Not a Number (NaN).
19144 */
19145 SQLITE_PRIVATE int sqlite3IsNaN(double x){
19146   /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
19147   ** On the other hand, the use of -ffast-math comes with the following
19148   ** warning:
19149   **
19150   **      This option [-ffast-math] should never be turned on by any
19151   **      -O option since it can result in incorrect output for programs
19152   **      which depend on an exact implementation of IEEE or ISO 
19153   **      rules/specifications for math functions.
19154   **
19155   ** Under MSVC, this NaN test may fail if compiled with a floating-
19156   ** point precision mode other than /fp:precise.  From the MSDN 
19157   ** documentation:
19158   **
19159   **      The compiler [with /fp:precise] will properly handle comparisons 
19160   **      involving NaN. For example, x != x evaluates to true if x is NaN 
19161   **      ...
19162   */
19163 #ifdef __FAST_MATH__
19164 # error SQLite will not work correctly with the -ffast-math option of GCC.
19165 #endif
19166   volatile double y = x;
19167   volatile double z = y;
19168   return y!=z;
19169 }
19170
19171 /*
19172 ** Compute a string length that is limited to what can be stored in
19173 ** lower 30 bits of a 32-bit signed integer.
19174 */
19175 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19176   const char *z2 = z;
19177   while( *z2 ){ z2++; }
19178   return 0x3fffffff & (int)(z2 - z);
19179 }
19180
19181 /*
19182 ** Return the length of a string, except do not allow the string length
19183 ** to exceed the SQLITE_LIMIT_LENGTH setting.
19184 */
19185 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
19186   const char *z2 = z;
19187   int len;
19188   int x;
19189   while( *z2 ){ z2++; }
19190   x = (int)(z2 - z);
19191   len = 0x7fffffff & x;
19192   if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
19193     return db->aLimit[SQLITE_LIMIT_LENGTH];
19194   }else{
19195     return len;
19196   }
19197 }
19198
19199 /*
19200 ** Set the most recent error code and error string for the sqlite
19201 ** handle "db". The error code is set to "err_code".
19202 **
19203 ** If it is not NULL, string zFormat specifies the format of the
19204 ** error string in the style of the printf functions: The following
19205 ** format characters are allowed:
19206 **
19207 **      %s      Insert a string
19208 **      %z      A string that should be freed after use
19209 **      %d      Insert an integer
19210 **      %T      Insert a token
19211 **      %S      Insert the first element of a SrcList
19212 **
19213 ** zFormat and any string tokens that follow it are assumed to be
19214 ** encoded in UTF-8.
19215 **
19216 ** To clear the most recent error for sqlite handle "db", sqlite3Error
19217 ** should be called with err_code set to SQLITE_OK and zFormat set
19218 ** to NULL.
19219 */
19220 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19221   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19222     db->errCode = err_code;
19223     if( zFormat ){
19224       char *z;
19225       va_list ap;
19226       va_start(ap, zFormat);
19227       z = sqlite3VMPrintf(db, zFormat, ap);
19228       va_end(ap);
19229       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19230     }else{
19231       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19232     }
19233   }
19234 }
19235
19236 /*
19237 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19238 ** The following formatting characters are allowed:
19239 **
19240 **      %s      Insert a string
19241 **      %z      A string that should be freed after use
19242 **      %d      Insert an integer
19243 **      %T      Insert a token
19244 **      %S      Insert the first element of a SrcList
19245 **
19246 ** This function should be used to report any error that occurs whilst
19247 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19248 ** last thing the sqlite3_prepare() function does is copy the error
19249 ** stored by this function into the database handle using sqlite3Error().
19250 ** Function sqlite3Error() should be used during statement execution
19251 ** (sqlite3_step() etc.).
19252 */
19253 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19254   va_list ap;
19255   sqlite3 *db = pParse->db;
19256   pParse->nErr++;
19257   sqlite3DbFree(db, pParse->zErrMsg);
19258   va_start(ap, zFormat);
19259   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
19260   va_end(ap);
19261   if( pParse->rc==SQLITE_OK ){
19262     pParse->rc = SQLITE_ERROR;
19263   }
19264 }
19265
19266 /*
19267 ** Clear the error message in pParse, if any
19268 */
19269 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
19270   sqlite3DbFree(pParse->db, pParse->zErrMsg);
19271   pParse->zErrMsg = 0;
19272   pParse->nErr = 0;
19273 }
19274
19275 /*
19276 ** Convert an SQL-style quoted string into a normal string by removing
19277 ** the quote characters.  The conversion is done in-place.  If the
19278 ** input does not begin with a quote character, then this routine
19279 ** is a no-op.
19280 **
19281 ** 2002-Feb-14: This routine is extended to remove MS-Access style
19282 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
19283 ** "a-b-c".
19284 */
19285 SQLITE_PRIVATE void sqlite3Dequote(char *z){
19286   char quote;
19287   int i, j;
19288   if( z==0 ) return;
19289   quote = z[0];
19290   switch( quote ){
19291     case '\'':  break;
19292     case '"':   break;
19293     case '`':   break;                /* For MySQL compatibility */
19294     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19295     default:    return;
19296   }
19297   for(i=1, j=0; z[i]; i++){
19298     if( z[i]==quote ){
19299       if( z[i+1]==quote ){
19300         z[j++] = quote;
19301         i++;
19302       }else{
19303         z[j++] = 0;
19304         break;
19305       }
19306     }else{
19307       z[j++] = z[i];
19308     }
19309   }
19310 }
19311
19312 /* Convenient short-hand */
19313 #define UpperToLower sqlite3UpperToLower
19314
19315 /*
19316 ** Some systems have stricmp().  Others have strcasecmp().  Because
19317 ** there is no consistency, we will define our own.
19318 */
19319 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19320   register unsigned char *a, *b;
19321   a = (unsigned char *)zLeft;
19322   b = (unsigned char *)zRight;
19323   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19324   return UpperToLower[*a] - UpperToLower[*b];
19325 }
19326 SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
19327   register unsigned char *a, *b;
19328   a = (unsigned char *)zLeft;
19329   b = (unsigned char *)zRight;
19330   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19331   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19332 }
19333
19334 /*
19335 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
19336 ** string contains any character which is not part of a number. If
19337 ** the string is numeric and contains the '.' character, set *realnum
19338 ** to TRUE (otherwise FALSE).
19339 **
19340 ** An empty string is considered non-numeric.
19341 */
19342 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19343   int incr = (enc==SQLITE_UTF8?1:2);
19344   if( enc==SQLITE_UTF16BE ) z++;
19345   if( *z=='-' || *z=='+' ) z += incr;
19346   if( !sqlite3Isdigit(*z) ){
19347     return 0;
19348   }
19349   z += incr;
19350   if( realnum ) *realnum = 0;
19351   while( sqlite3Isdigit(*z) ){ z += incr; }
19352   if( *z=='.' ){
19353     z += incr;
19354     if( !sqlite3Isdigit(*z) ) return 0;
19355     while( sqlite3Isdigit(*z) ){ z += incr; }
19356     if( realnum ) *realnum = 1;
19357   }
19358   if( *z=='e' || *z=='E' ){
19359     z += incr;
19360     if( *z=='+' || *z=='-' ) z += incr;
19361     if( !sqlite3Isdigit(*z) ) return 0;
19362     while( sqlite3Isdigit(*z) ){ z += incr; }
19363     if( realnum ) *realnum = 1;
19364   }
19365   return *z==0;
19366 }
19367
19368 /*
19369 ** The string z[] is an ascii representation of a real number.
19370 ** Convert this string to a double.
19371 **
19372 ** This routine assumes that z[] really is a valid number.  If it
19373 ** is not, the result is undefined.
19374 **
19375 ** This routine is used instead of the library atof() function because
19376 ** the library atof() might want to use "," as the decimal point instead
19377 ** of "." depending on how locale is set.  But that would cause problems
19378 ** for SQL.  So this routine always uses "." regardless of locale.
19379 */
19380 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19381 #ifndef SQLITE_OMIT_FLOATING_POINT
19382   int sign = 1;
19383   const char *zBegin = z;
19384   LONGDOUBLE_TYPE v1 = 0.0;
19385   int nSignificant = 0;
19386   while( sqlite3Isspace(*z) ) z++;
19387   if( *z=='-' ){
19388     sign = -1;
19389     z++;
19390   }else if( *z=='+' ){
19391     z++;
19392   }
19393   while( z[0]=='0' ){
19394     z++;
19395   }
19396   while( sqlite3Isdigit(*z) ){
19397     v1 = v1*10.0 + (*z - '0');
19398     z++;
19399     nSignificant++;
19400   }
19401   if( *z=='.' ){
19402     LONGDOUBLE_TYPE divisor = 1.0;
19403     z++;
19404     if( nSignificant==0 ){
19405       while( z[0]=='0' ){
19406         divisor *= 10.0;
19407         z++;
19408       }
19409     }
19410     while( sqlite3Isdigit(*z) ){
19411       if( nSignificant<18 ){
19412         v1 = v1*10.0 + (*z - '0');
19413         divisor *= 10.0;
19414         nSignificant++;
19415       }
19416       z++;
19417     }
19418     v1 /= divisor;
19419   }
19420   if( *z=='e' || *z=='E' ){
19421     int esign = 1;
19422     int eval = 0;
19423     LONGDOUBLE_TYPE scale = 1.0;
19424     z++;
19425     if( *z=='-' ){
19426       esign = -1;
19427       z++;
19428     }else if( *z=='+' ){
19429       z++;
19430     }
19431     while( sqlite3Isdigit(*z) ){
19432       eval = eval*10 + *z - '0';
19433       z++;
19434     }
19435     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
19436     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
19437     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
19438     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
19439     if( esign<0 ){
19440       v1 /= scale;
19441     }else{
19442       v1 *= scale;
19443     }
19444   }
19445   *pResult = (double)(sign<0 ? -v1 : v1);
19446   return (int)(z - zBegin);
19447 #else
19448   return sqlite3Atoi64(z, pResult);
19449 #endif /* SQLITE_OMIT_FLOATING_POINT */
19450 }
19451
19452 /*
19453 ** Compare the 19-character string zNum against the text representation
19454 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19455 ** if zNum is less than, equal to, or greater than the string.
19456 **
19457 ** Unlike memcmp() this routine is guaranteed to return the difference
19458 ** in the values of the last digit if the only difference is in the
19459 ** last digit.  So, for example,
19460 **
19461 **      compare2pow63("9223372036854775800")
19462 **
19463 ** will return -8.
19464 */
19465 static int compare2pow63(const char *zNum){
19466   int c;
19467   c = memcmp(zNum,"922337203685477580",18);
19468   if( c==0 ){
19469     c = zNum[18] - '8';
19470   }
19471   return c;
19472 }
19473
19474
19475 /*
19476 ** Return TRUE if zNum is a 64-bit signed integer and write
19477 ** the value of the integer into *pNum.  If zNum is not an integer
19478 ** or is an integer that is too large to be expressed with 64 bits,
19479 ** then return false.
19480 **
19481 ** When this routine was originally written it dealt with only
19482 ** 32-bit numbers.  At that time, it was much faster than the
19483 ** atoi() library routine in RedHat 7.2.
19484 */
19485 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19486   i64 v = 0;
19487   int neg;
19488   int i, c;
19489   const char *zStart;
19490   while( sqlite3Isspace(*zNum) ) zNum++;
19491   if( *zNum=='-' ){
19492     neg = 1;
19493     zNum++;
19494   }else if( *zNum=='+' ){
19495     neg = 0;
19496     zNum++;
19497   }else{
19498     neg = 0;
19499   }
19500   zStart = zNum;
19501   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19502   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19503     v = v*10 + c - '0';
19504   }
19505   *pNum = neg ? -v : v;
19506   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19507     /* zNum is empty or contains non-numeric text or is longer
19508     ** than 19 digits (thus guaranting that it is too large) */
19509     return 0;
19510   }else if( i<19 ){
19511     /* Less than 19 digits, so we know that it fits in 64 bits */
19512     return 1;
19513   }else{
19514     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19515     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19516     ** is 2^63. */
19517     return compare2pow63(zNum)<neg;
19518   }
19519 }
19520
19521 /*
19522 ** The string zNum represents an integer.  There might be some other
19523 ** information following the integer too, but that part is ignored.
19524 ** If the integer that the prefix of zNum represents will fit in a
19525 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19526 **
19527 ** This routine returns FALSE for the string -9223372036854775808 even that
19528 ** that number will, in theory fit in a 64-bit integer.  Positive
19529 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
19530 ** false.
19531 */
19532 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19533   int i, c;
19534   int neg = 0;
19535   if( *zNum=='-' ){
19536     neg = 1;
19537     zNum++;
19538   }else if( *zNum=='+' ){
19539     zNum++;
19540   }
19541   if( negFlag ) neg = 1-neg;
19542   while( *zNum=='0' ){
19543     zNum++;   /* Skip leading zeros.  Ticket #2454 */
19544   }
19545   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
19546   if( i<19 ){
19547     /* Guaranteed to fit if less than 19 digits */
19548     return 1;
19549   }else if( i>19 ){
19550     /* Guaranteed to be too big if greater than 19 digits */
19551     return 0;
19552   }else{
19553     /* Compare against 2^63. */
19554     return compare2pow63(zNum)<neg;
19555   }
19556 }
19557
19558 /*
19559 ** If zNum represents an integer that will fit in 32-bits, then set
19560 ** *pValue to that integer and return true.  Otherwise return false.
19561 **
19562 ** Any non-numeric characters that following zNum are ignored.
19563 ** This is different from sqlite3Atoi64() which requires the
19564 ** input number to be zero-terminated.
19565 */
19566 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19567   sqlite_int64 v = 0;
19568   int i, c;
19569   int neg = 0;
19570   if( zNum[0]=='-' ){
19571     neg = 1;
19572     zNum++;
19573   }else if( zNum[0]=='+' ){
19574     zNum++;
19575   }
19576   while( zNum[0]=='0' ) zNum++;
19577   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19578     v = v*10 + c;
19579   }
19580
19581   /* The longest decimal representation of a 32 bit integer is 10 digits:
19582   **
19583   **             1234567890
19584   **     2^31 -> 2147483648
19585   */
19586   if( i>10 ){
19587     return 0;
19588   }
19589   if( v-neg>2147483647 ){
19590     return 0;
19591   }
19592   if( neg ){
19593     v = -v;
19594   }
19595   *pValue = (int)v;
19596   return 1;
19597 }
19598
19599 /*
19600 ** The variable-length integer encoding is as follows:
19601 **
19602 ** KEY:
19603 **         A = 0xxxxxxx    7 bits of data and one flag bit
19604 **         B = 1xxxxxxx    7 bits of data and one flag bit
19605 **         C = xxxxxxxx    8 bits of data
19606 **
19607 **  7 bits - A
19608 ** 14 bits - BA
19609 ** 21 bits - BBA
19610 ** 28 bits - BBBA
19611 ** 35 bits - BBBBA
19612 ** 42 bits - BBBBBA
19613 ** 49 bits - BBBBBBA
19614 ** 56 bits - BBBBBBBA
19615 ** 64 bits - BBBBBBBBC
19616 */
19617
19618 /*
19619 ** Write a 64-bit variable-length integer to memory starting at p[0].
19620 ** The length of data write will be between 1 and 9 bytes.  The number
19621 ** of bytes written is returned.
19622 **
19623 ** A variable-length integer consists of the lower 7 bits of each byte
19624 ** for all bytes that have the 8th bit set and one byte with the 8th
19625 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19626 ** 8 bits and is the last byte.
19627 */
19628 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19629   int i, j, n;
19630   u8 buf[10];
19631   if( v & (((u64)0xff000000)<<32) ){
19632     p[8] = (u8)v;
19633     v >>= 8;
19634     for(i=7; i>=0; i--){
19635       p[i] = (u8)((v & 0x7f) | 0x80);
19636       v >>= 7;
19637     }
19638     return 9;
19639   }    
19640   n = 0;
19641   do{
19642     buf[n++] = (u8)((v & 0x7f) | 0x80);
19643     v >>= 7;
19644   }while( v!=0 );
19645   buf[0] &= 0x7f;
19646   assert( n<=9 );
19647   for(i=0, j=n-1; j>=0; j--, i++){
19648     p[i] = buf[j];
19649   }
19650   return n;
19651 }
19652
19653 /*
19654 ** This routine is a faster version of sqlite3PutVarint() that only
19655 ** works for 32-bit positive integers and which is optimized for
19656 ** the common case of small integers.  A MACRO version, putVarint32,
19657 ** is provided which inlines the single-byte case.  All code should use
19658 ** the MACRO version as this function assumes the single-byte case has
19659 ** already been handled.
19660 */
19661 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19662 #ifndef putVarint32
19663   if( (v & ~0x7f)==0 ){
19664     p[0] = v;
19665     return 1;
19666   }
19667 #endif
19668   if( (v & ~0x3fff)==0 ){
19669     p[0] = (u8)((v>>7) | 0x80);
19670     p[1] = (u8)(v & 0x7f);
19671     return 2;
19672   }
19673   return sqlite3PutVarint(p, v);
19674 }
19675
19676 /*
19677 ** Read a 64-bit variable-length integer from memory starting at p[0].
19678 ** Return the number of bytes read.  The value is stored in *v.
19679 */
19680 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19681   u32 a,b,s;
19682
19683   a = *p;
19684   /* a: p0 (unmasked) */
19685   if (!(a&0x80))
19686   {
19687     *v = a;
19688     return 1;
19689   }
19690
19691   p++;
19692   b = *p;
19693   /* b: p1 (unmasked) */
19694   if (!(b&0x80))
19695   {
19696     a &= 0x7f;
19697     a = a<<7;
19698     a |= b;
19699     *v = a;
19700     return 2;
19701   }
19702
19703   p++;
19704   a = a<<14;
19705   a |= *p;
19706   /* a: p0<<14 | p2 (unmasked) */
19707   if (!(a&0x80))
19708   {
19709     a &= (0x7f<<14)|(0x7f);
19710     b &= 0x7f;
19711     b = b<<7;
19712     a |= b;
19713     *v = a;
19714     return 3;
19715   }
19716
19717   /* CSE1 from below */
19718   a &= (0x7f<<14)|(0x7f);
19719   p++;
19720   b = b<<14;
19721   b |= *p;
19722   /* b: p1<<14 | p3 (unmasked) */
19723   if (!(b&0x80))
19724   {
19725     b &= (0x7f<<14)|(0x7f);
19726     /* moved CSE1 up */
19727     /* a &= (0x7f<<14)|(0x7f); */
19728     a = a<<7;
19729     a |= b;
19730     *v = a;
19731     return 4;
19732   }
19733
19734   /* a: p0<<14 | p2 (masked) */
19735   /* b: p1<<14 | p3 (unmasked) */
19736   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19737   /* moved CSE1 up */
19738   /* a &= (0x7f<<14)|(0x7f); */
19739   b &= (0x7f<<14)|(0x7f);
19740   s = a;
19741   /* s: p0<<14 | p2 (masked) */
19742
19743   p++;
19744   a = a<<14;
19745   a |= *p;
19746   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19747   if (!(a&0x80))
19748   {
19749     /* we can skip these cause they were (effectively) done above in calc'ing s */
19750     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19751     /* b &= (0x7f<<14)|(0x7f); */
19752     b = b<<7;
19753     a |= b;
19754     s = s>>18;
19755     *v = ((u64)s)<<32 | a;
19756     return 5;
19757   }
19758
19759   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19760   s = s<<7;
19761   s |= b;
19762   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19763
19764   p++;
19765   b = b<<14;
19766   b |= *p;
19767   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19768   if (!(b&0x80))
19769   {
19770     /* we can skip this cause it was (effectively) done above in calc'ing s */
19771     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19772     a &= (0x7f<<14)|(0x7f);
19773     a = a<<7;
19774     a |= b;
19775     s = s>>18;
19776     *v = ((u64)s)<<32 | a;
19777     return 6;
19778   }
19779
19780   p++;
19781   a = a<<14;
19782   a |= *p;
19783   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19784   if (!(a&0x80))
19785   {
19786     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19787     b &= (0x7f<<14)|(0x7f);
19788     b = b<<7;
19789     a |= b;
19790     s = s>>11;
19791     *v = ((u64)s)<<32 | a;
19792     return 7;
19793   }
19794
19795   /* CSE2 from below */
19796   a &= (0x7f<<14)|(0x7f);
19797   p++;
19798   b = b<<14;
19799   b |= *p;
19800   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19801   if (!(b&0x80))
19802   {
19803     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19804     /* moved CSE2 up */
19805     /* a &= (0x7f<<14)|(0x7f); */
19806     a = a<<7;
19807     a |= b;
19808     s = s>>4;
19809     *v = ((u64)s)<<32 | a;
19810     return 8;
19811   }
19812
19813   p++;
19814   a = a<<15;
19815   a |= *p;
19816   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19817
19818   /* moved CSE2 up */
19819   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19820   b &= (0x7f<<14)|(0x7f);
19821   b = b<<8;
19822   a |= b;
19823
19824   s = s<<4;
19825   b = p[-4];
19826   b &= 0x7f;
19827   b = b>>3;
19828   s |= b;
19829
19830   *v = ((u64)s)<<32 | a;
19831
19832   return 9;
19833 }
19834
19835 /*
19836 ** Read a 32-bit variable-length integer from memory starting at p[0].
19837 ** Return the number of bytes read.  The value is stored in *v.
19838 ** A MACRO version, getVarint32, is provided which inlines the 
19839 ** single-byte case.  All code should use the MACRO version as 
19840 ** this function assumes the single-byte case has already been handled.
19841 */
19842 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19843   u32 a,b;
19844
19845   a = *p;
19846   /* a: p0 (unmasked) */
19847 #ifndef getVarint32
19848   if (!(a&0x80))
19849   {
19850     *v = a;
19851     return 1;
19852   }
19853 #endif
19854
19855   p++;
19856   b = *p;
19857   /* b: p1 (unmasked) */
19858   if (!(b&0x80))
19859   {
19860     a &= 0x7f;
19861     a = a<<7;
19862     *v = a | b;
19863     return 2;
19864   }
19865
19866   p++;
19867   a = a<<14;
19868   a |= *p;
19869   /* a: p0<<14 | p2 (unmasked) */
19870   if (!(a&0x80))
19871   {
19872     a &= (0x7f<<14)|(0x7f);
19873     b &= 0x7f;
19874     b = b<<7;
19875     *v = a | b;
19876     return 3;
19877   }
19878
19879   p++;
19880   b = b<<14;
19881   b |= *p;
19882   /* b: p1<<14 | p3 (unmasked) */
19883   if (!(b&0x80))
19884   {
19885     b &= (0x7f<<14)|(0x7f);
19886     a &= (0x7f<<14)|(0x7f);
19887     a = a<<7;
19888     *v = a | b;
19889     return 4;
19890   }
19891
19892   p++;
19893   a = a<<14;
19894   a |= *p;
19895   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19896   if (!(a&0x80))
19897   {
19898     a &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19899     b &= (0x7f<<28)|(0x7f<<14)|(0x7f);
19900     b = b<<7;
19901     *v = a | b;
19902     return 5;
19903   }
19904
19905   /* We can only reach this point when reading a corrupt database
19906   ** file.  In that case we are not in any hurry.  Use the (relatively
19907   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19908   ** value. */
19909   {
19910     u64 v64;
19911     u8 n;
19912
19913     p -= 4;
19914     n = sqlite3GetVarint(p, &v64);
19915     assert( n>5 && n<=9 );
19916     *v = (u32)v64;
19917     return n;
19918   }
19919 }
19920
19921 /*
19922 ** Return the number of bytes that will be needed to store the given
19923 ** 64-bit integer.
19924 */
19925 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19926   int i = 0;
19927   do{
19928     i++;
19929     v >>= 7;
19930   }while( v!=0 && i<9 );
19931   return i;
19932 }
19933
19934
19935 /*
19936 ** Read or write a four-byte big-endian integer value.
19937 */
19938 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19939   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19940 }
19941 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19942   p[0] = (u8)(v>>24);
19943   p[1] = (u8)(v>>16);
19944   p[2] = (u8)(v>>8);
19945   p[3] = (u8)v;
19946 }
19947
19948
19949
19950 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19951 /*
19952 ** Translate a single byte of Hex into an integer.
19953 ** This routinen only works if h really is a valid hexadecimal
19954 ** character:  0..9a..fA..F
19955 */
19956 static u8 hexToInt(int h){
19957   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19958 #ifdef SQLITE_ASCII
19959   h += 9*(1&(h>>6));
19960 #endif
19961 #ifdef SQLITE_EBCDIC
19962   h += 9*(1&~(h>>4));
19963 #endif
19964   return (u8)(h & 0xf);
19965 }
19966 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19967
19968 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19969 /*
19970 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19971 ** value.  Return a pointer to its binary value.  Space to hold the
19972 ** binary value has been obtained from malloc and must be freed by
19973 ** the calling routine.
19974 */
19975 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19976   char *zBlob;
19977   int i;
19978
19979   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19980   n--;
19981   if( zBlob ){
19982     for(i=0; i<n; i+=2){
19983       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19984     }
19985     zBlob[i/2] = 0;
19986   }
19987   return zBlob;
19988 }
19989 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19990
19991
19992 /*
19993 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19994 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19995 ** when this routine is called.
19996 **
19997 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19998 ** value indicates that the database connection passed into the API is
19999 ** open and is not being used by another thread.  By changing the value
20000 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
20001 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
20002 ** when the API exits. 
20003 **
20004 ** This routine is a attempt to detect if two threads use the
20005 ** same sqlite* pointer at the same time.  There is a race 
20006 ** condition so it is possible that the error is not detected.
20007 ** But usually the problem will be seen.  The result will be an
20008 ** error which can be used to debug the application that is
20009 ** using SQLite incorrectly.
20010 **
20011 ** Ticket #202:  If db->magic is not a valid open value, take care not
20012 ** to modify the db structure at all.  It could be that db is a stale
20013 ** pointer.  In other words, it could be that there has been a prior
20014 ** call to sqlite3_close(db) and db has been deallocated.  And we do
20015 ** not want to write into deallocated memory.
20016 */
20017 #ifdef SQLITE_DEBUG
20018 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
20019   if( db->magic==SQLITE_MAGIC_OPEN ){
20020     db->magic = SQLITE_MAGIC_BUSY;
20021     assert( sqlite3_mutex_held(db->mutex) );
20022     return 0;
20023   }else if( db->magic==SQLITE_MAGIC_BUSY ){
20024     db->magic = SQLITE_MAGIC_ERROR;
20025     db->u1.isInterrupted = 1;
20026   }
20027   return 1;
20028 }
20029 #endif
20030
20031 /*
20032 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
20033 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
20034 ** when this routine is called.
20035 */
20036 #ifdef SQLITE_DEBUG
20037 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
20038   if( db->magic==SQLITE_MAGIC_BUSY ){
20039     db->magic = SQLITE_MAGIC_OPEN;
20040     assert( sqlite3_mutex_held(db->mutex) );
20041     return 0;
20042   }else{
20043     db->magic = SQLITE_MAGIC_ERROR;
20044     db->u1.isInterrupted = 1;
20045     return 1;
20046   }
20047 }
20048 #endif
20049
20050 /*
20051 ** Check to make sure we have a valid db pointer.  This test is not
20052 ** foolproof but it does provide some measure of protection against
20053 ** misuse of the interface such as passing in db pointers that are
20054 ** NULL or which have been previously closed.  If this routine returns
20055 ** 1 it means that the db pointer is valid and 0 if it should not be
20056 ** dereferenced for any reason.  The calling function should invoke
20057 ** SQLITE_MISUSE immediately.
20058 **
20059 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20060 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20061 ** open properly and is not fit for general use but which can be
20062 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
20063 */
20064 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20065   u32 magic;
20066   if( db==0 ) return 0;
20067   magic = db->magic;
20068   if( magic!=SQLITE_MAGIC_OPEN &&
20069       magic!=SQLITE_MAGIC_BUSY ) return 0;
20070   return 1;
20071 }
20072 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20073   u32 magic;
20074   if( db==0 ) return 0;
20075   magic = db->magic;
20076   if( magic!=SQLITE_MAGIC_SICK &&
20077       magic!=SQLITE_MAGIC_OPEN &&
20078       magic!=SQLITE_MAGIC_BUSY ) return 0;
20079   return 1;
20080 }
20081
20082 /************** End of util.c ************************************************/
20083 /************** Begin file hash.c ********************************************/
20084 /*
20085 ** 2001 September 22
20086 **
20087 ** The author disclaims copyright to this source code.  In place of
20088 ** a legal notice, here is a blessing:
20089 **
20090 **    May you do good and not evil.
20091 **    May you find forgiveness for yourself and forgive others.
20092 **    May you share freely, never taking more than you give.
20093 **
20094 *************************************************************************
20095 ** This is the implementation of generic hash-tables
20096 ** used in SQLite.
20097 **
20098 ** $Id: hash.c,v 1.33 2009/01/09 01:12:28 drh Exp $
20099 */
20100
20101 /* Turn bulk memory into a hash table object by initializing the
20102 ** fields of the Hash structure.
20103 **
20104 ** "pNew" is a pointer to the hash table that is to be initialized.
20105 ** "copyKey" is true if the hash table should make its own private
20106 ** copy of keys and false if it should just use the supplied pointer.
20107 */
20108 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
20109   assert( pNew!=0 );
20110   pNew->copyKey = copyKey!=0;
20111   pNew->first = 0;
20112   pNew->count = 0;
20113   pNew->htsize = 0;
20114   pNew->ht = 0;
20115 }
20116
20117 /* Remove all entries from a hash table.  Reclaim all memory.
20118 ** Call this routine to delete a hash table or to reset a hash table
20119 ** to the empty state.
20120 */
20121 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20122   HashElem *elem;         /* For looping over all elements of the table */
20123
20124   assert( pH!=0 );
20125   elem = pH->first;
20126   pH->first = 0;
20127   sqlite3_free(pH->ht);
20128   pH->ht = 0;
20129   pH->htsize = 0;
20130   while( elem ){
20131     HashElem *next_elem = elem->next;
20132     if( pH->copyKey ){
20133       sqlite3_free(elem->pKey);
20134     }
20135     sqlite3_free(elem);
20136     elem = next_elem;
20137   }
20138   pH->count = 0;
20139 }
20140
20141 /*
20142 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
20143 */
20144 static int strHash(const void *pKey, int nKey){
20145   const char *z = (const char *)pKey;
20146   int h = 0;
20147   if( nKey<=0 ) nKey = sqlite3Strlen30(z);
20148   while( nKey > 0  ){
20149     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20150     nKey--;
20151   }
20152   return h & 0x7fffffff;
20153 }
20154 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
20155   if( n1!=n2 ) return 1;
20156   return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
20157 }
20158
20159
20160 /* Link an element into the hash table
20161 */
20162 static void insertElement(
20163   Hash *pH,              /* The complete hash table */
20164   struct _ht *pEntry,    /* The entry into which pNew is inserted */
20165   HashElem *pNew         /* The element to be inserted */
20166 ){
20167   HashElem *pHead;       /* First element already in pEntry */
20168   pHead = pEntry->chain;
20169   if( pHead ){
20170     pNew->next = pHead;
20171     pNew->prev = pHead->prev;
20172     if( pHead->prev ){ pHead->prev->next = pNew; }
20173     else             { pH->first = pNew; }
20174     pHead->prev = pNew;
20175   }else{
20176     pNew->next = pH->first;
20177     if( pH->first ){ pH->first->prev = pNew; }
20178     pNew->prev = 0;
20179     pH->first = pNew;
20180   }
20181   pEntry->count++;
20182   pEntry->chain = pNew;
20183 }
20184
20185
20186 /* Resize the hash table so that it cantains "new_size" buckets.
20187 ** "new_size" must be a power of 2.  The hash table might fail 
20188 ** to resize if sqlite3_malloc() fails.
20189 */
20190 static void rehash(Hash *pH, int new_size){
20191   struct _ht *new_ht;            /* The new hash table */
20192   HashElem *elem, *next_elem;    /* For looping over existing elements */
20193
20194 #ifdef SQLITE_MALLOC_SOFT_LIMIT
20195   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20196     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20197   }
20198   if( new_size==pH->htsize ) return;
20199 #endif
20200
20201   /* There is a call to sqlite3_malloc() inside rehash(). If there is
20202   ** already an allocation at pH->ht, then if this malloc() fails it
20203   ** is benign (since failing to resize a hash table is a performance
20204   ** hit only, not a fatal error).
20205   */
20206   if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
20207   new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
20208   if( pH->htsize>0 ) sqlite3EndBenignMalloc();
20209
20210   if( new_ht==0 ) return;
20211   sqlite3_free(pH->ht);
20212   pH->ht = new_ht;
20213   pH->htsize = new_size;
20214   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20215     int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
20216     next_elem = elem->next;
20217     insertElement(pH, &new_ht[h], elem);
20218   }
20219 }
20220
20221 /* This function (for internal use only) locates an element in an
20222 ** hash table that matches the given key.  The hash for this key has
20223 ** already been computed and is passed as the 4th parameter.
20224 */
20225 static HashElem *findElementGivenHash(
20226   const Hash *pH,     /* The pH to be searched */
20227   const void *pKey,   /* The key we are searching for */
20228   int nKey,
20229   int h               /* The hash for this key. */
20230 ){
20231   HashElem *elem;                /* Used to loop thru the element list */
20232   int count;                     /* Number of elements left to test */
20233
20234   if( pH->ht ){
20235     struct _ht *pEntry = &pH->ht[h];
20236     elem = pEntry->chain;
20237     count = pEntry->count;
20238     while( count-- && elem ){
20239       if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
20240         return elem;
20241       }
20242       elem = elem->next;
20243     }
20244   }
20245   return 0;
20246 }
20247
20248 /* Remove a single entry from the hash table given a pointer to that
20249 ** element and a hash on the element's key.
20250 */
20251 static void removeElementGivenHash(
20252   Hash *pH,         /* The pH containing "elem" */
20253   HashElem* elem,   /* The element to be removed from the pH */
20254   int h             /* Hash value for the element */
20255 ){
20256   struct _ht *pEntry;
20257   if( elem->prev ){
20258     elem->prev->next = elem->next; 
20259   }else{
20260     pH->first = elem->next;
20261   }
20262   if( elem->next ){
20263     elem->next->prev = elem->prev;
20264   }
20265   pEntry = &pH->ht[h];
20266   if( pEntry->chain==elem ){
20267     pEntry->chain = elem->next;
20268   }
20269   pEntry->count--;
20270   if( pEntry->count<=0 ){
20271     pEntry->chain = 0;
20272   }
20273   if( pH->copyKey ){
20274     sqlite3_free(elem->pKey);
20275   }
20276   sqlite3_free( elem );
20277   pH->count--;
20278   if( pH->count<=0 ){
20279     assert( pH->first==0 );
20280     assert( pH->count==0 );
20281     sqlite3HashClear(pH);
20282   }
20283 }
20284
20285 /* Attempt to locate an element of the hash table pH with a key
20286 ** that matches pKey,nKey.  Return a pointer to the corresponding 
20287 ** HashElem structure for this element if it is found, or NULL
20288 ** otherwise.
20289 */
20290 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
20291   int h;             /* A hash on key */
20292   HashElem *elem;    /* The element that matches key */
20293
20294   if( pH==0 || pH->ht==0 ) return 0;
20295   h = strHash(pKey,nKey);
20296   elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
20297   return elem;
20298 }
20299
20300 /* Attempt to locate an element of the hash table pH with a key
20301 ** that matches pKey,nKey.  Return the data for this element if it is
20302 ** found, or NULL if there is no match.
20303 */
20304 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
20305   HashElem *elem;    /* The element that matches key */
20306   elem = sqlite3HashFindElem(pH, pKey, nKey);
20307   return elem ? elem->data : 0;
20308 }
20309
20310 /* Insert an element into the hash table pH.  The key is pKey,nKey
20311 ** and the data is "data".
20312 **
20313 ** If no element exists with a matching key, then a new
20314 ** element is created.  A copy of the key is made if the copyKey
20315 ** flag is set.  NULL is returned.
20316 **
20317 ** If another element already exists with the same key, then the
20318 ** new data replaces the old data and the old data is returned.
20319 ** The key is not copied in this instance.  If a malloc fails, then
20320 ** the new data is returned and the hash table is unchanged.
20321 **
20322 ** If the "data" parameter to this function is NULL, then the
20323 ** element corresponding to "key" is removed from the hash table.
20324 */
20325 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
20326   int hraw;             /* Raw hash value of the key */
20327   int h;                /* the hash of the key modulo hash table size */
20328   HashElem *elem;       /* Used to loop thru the element list */
20329   HashElem *new_elem;   /* New element added to the pH */
20330
20331   assert( pH!=0 );
20332   hraw = strHash(pKey, nKey);
20333   if( pH->htsize ){
20334     h = hraw % pH->htsize;
20335     elem = findElementGivenHash(pH,pKey,nKey,h);
20336     if( elem ){
20337       void *old_data = elem->data;
20338       if( data==0 ){
20339         removeElementGivenHash(pH,elem,h);
20340       }else{
20341         elem->data = data;
20342         if( !pH->copyKey ){
20343           elem->pKey = (void *)pKey;
20344         }
20345         assert(nKey==elem->nKey);
20346       }
20347       return old_data;
20348     }
20349   }
20350   if( data==0 ) return 0;
20351   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20352   if( new_elem==0 ) return data;
20353   if( pH->copyKey && pKey!=0 ){
20354     new_elem->pKey = sqlite3Malloc( nKey );
20355     if( new_elem->pKey==0 ){
20356       sqlite3_free(new_elem);
20357       return data;
20358     }
20359     memcpy((void*)new_elem->pKey, pKey, nKey);
20360   }else{
20361     new_elem->pKey = (void*)pKey;
20362   }
20363   new_elem->nKey = nKey;
20364   pH->count++;
20365   if( pH->htsize==0 ){
20366     rehash(pH, 128/sizeof(pH->ht[0]));
20367     if( pH->htsize==0 ){
20368       pH->count = 0;
20369       if( pH->copyKey ){
20370         sqlite3_free(new_elem->pKey);
20371       }
20372       sqlite3_free(new_elem);
20373       return data;
20374     }
20375   }
20376   if( pH->count > pH->htsize ){
20377     rehash(pH,pH->htsize*2);
20378   }
20379   assert( pH->htsize>0 );
20380   h = hraw % pH->htsize;
20381   insertElement(pH, &pH->ht[h], new_elem);
20382   new_elem->data = data;
20383   return 0;
20384 }
20385
20386 /************** End of hash.c ************************************************/
20387 /************** Begin file opcodes.c *****************************************/
20388 /* Automatically generated.  Do not edit */
20389 /* See the mkopcodec.awk script for details. */
20390 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20391 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20392  static const char *const azName[] = { "?",
20393      /*   1 */ "VNext",
20394      /*   2 */ "Affinity",
20395      /*   3 */ "Column",
20396      /*   4 */ "SetCookie",
20397      /*   5 */ "Seek",
20398      /*   6 */ "Sequence",
20399      /*   7 */ "Savepoint",
20400      /*   8 */ "RowKey",
20401      /*   9 */ "SCopy",
20402      /*  10 */ "OpenWrite",
20403      /*  11 */ "If",
20404      /*  12 */ "VRowid",
20405      /*  13 */ "CollSeq",
20406      /*  14 */ "OpenRead",
20407      /*  15 */ "Expire",
20408      /*  16 */ "AutoCommit",
20409      /*  17 */ "Pagecount",
20410      /*  18 */ "IntegrityCk",
20411      /*  19 */ "Not",
20412      /*  20 */ "Sort",
20413      /*  21 */ "Copy",
20414      /*  22 */ "Trace",
20415      /*  23 */ "Function",
20416      /*  24 */ "IfNeg",
20417      /*  25 */ "Noop",
20418      /*  26 */ "Return",
20419      /*  27 */ "NewRowid",
20420      /*  28 */ "Variable",
20421      /*  29 */ "String",
20422      /*  30 */ "RealAffinity",
20423      /*  31 */ "VRename",
20424      /*  32 */ "ParseSchema",
20425      /*  33 */ "VOpen",
20426      /*  34 */ "Close",
20427      /*  35 */ "CreateIndex",
20428      /*  36 */ "IsUnique",
20429      /*  37 */ "NotFound",
20430      /*  38 */ "Int64",
20431      /*  39 */ "MustBeInt",
20432      /*  40 */ "Halt",
20433      /*  41 */ "Rowid",
20434      /*  42 */ "IdxLT",
20435      /*  43 */ "AddImm",
20436      /*  44 */ "Statement",
20437      /*  45 */ "RowData",
20438      /*  46 */ "MemMax",
20439      /*  47 */ "NotExists",
20440      /*  48 */ "Gosub",
20441      /*  49 */ "Integer",
20442      /*  50 */ "Prev",
20443      /*  51 */ "RowSetRead",
20444      /*  52 */ "RowSetAdd",
20445      /*  53 */ "VColumn",
20446      /*  54 */ "CreateTable",
20447      /*  55 */ "Last",
20448      /*  56 */ "SeekLe",
20449      /*  57 */ "IncrVacuum",
20450      /*  58 */ "IdxRowid",
20451      /*  59 */ "ResetCount",
20452      /*  60 */ "ContextPush",
20453      /*  61 */ "Yield",
20454      /*  62 */ "DropTrigger",
20455      /*  63 */ "DropIndex",
20456      /*  64 */ "IdxGE",
20457      /*  65 */ "Or",
20458      /*  66 */ "And",
20459      /*  67 */ "IdxDelete",
20460      /*  68 */ "Vacuum",
20461      /*  69 */ "IfNot",
20462      /*  70 */ "IsNull",
20463      /*  71 */ "NotNull",
20464      /*  72 */ "Ne",
20465      /*  73 */ "Eq",
20466      /*  74 */ "Gt",
20467      /*  75 */ "Le",
20468      /*  76 */ "Lt",
20469      /*  77 */ "Ge",
20470      /*  78 */ "DropTable",
20471      /*  79 */ "BitAnd",
20472      /*  80 */ "BitOr",
20473      /*  81 */ "ShiftLeft",
20474      /*  82 */ "ShiftRight",
20475      /*  83 */ "Add",
20476      /*  84 */ "Subtract",
20477      /*  85 */ "Multiply",
20478      /*  86 */ "Divide",
20479      /*  87 */ "Remainder",
20480      /*  88 */ "Concat",
20481      /*  89 */ "SeekLt",
20482      /*  90 */ "MakeRecord",
20483      /*  91 */ "ResultRow",
20484      /*  92 */ "BitNot",
20485      /*  93 */ "String8",
20486      /*  94 */ "Delete",
20487      /*  95 */ "AggFinal",
20488      /*  96 */ "Compare",
20489      /*  97 */ "Goto",
20490      /*  98 */ "TableLock",
20491      /*  99 */ "Clear",
20492      /* 100 */ "VerifyCookie",
20493      /* 101 */ "AggStep",
20494      /* 102 */ "SetNumColumns",
20495      /* 103 */ "Transaction",
20496      /* 104 */ "VFilter",
20497      /* 105 */ "VDestroy",
20498      /* 106 */ "ContextPop",
20499      /* 107 */ "Next",
20500      /* 108 */ "IdxInsert",
20501      /* 109 */ "SeekGe",
20502      /* 110 */ "Insert",
20503      /* 111 */ "Destroy",
20504      /* 112 */ "ReadCookie",
20505      /* 113 */ "LoadAnalysis",
20506      /* 114 */ "Explain",
20507      /* 115 */ "OpenPseudo",
20508      /* 116 */ "OpenEphemeral",
20509      /* 117 */ "Null",
20510      /* 118 */ "Move",
20511      /* 119 */ "Blob",
20512      /* 120 */ "Rewind",
20513      /* 121 */ "SeekGt",
20514      /* 122 */ "VBegin",
20515      /* 123 */ "VUpdate",
20516      /* 124 */ "IfZero",
20517      /* 125 */ "VCreate",
20518      /* 126 */ "Found",
20519      /* 127 */ "IfPos",
20520      /* 128 */ "NullRow",
20521      /* 129 */ "Jump",
20522      /* 130 */ "Real",
20523      /* 131 */ "Permutation",
20524      /* 132 */ "NotUsed_132",
20525      /* 133 */ "NotUsed_133",
20526      /* 134 */ "NotUsed_134",
20527      /* 135 */ "NotUsed_135",
20528      /* 136 */ "NotUsed_136",
20529      /* 137 */ "NotUsed_137",
20530      /* 138 */ "NotUsed_138",
20531      /* 139 */ "NotUsed_139",
20532      /* 140 */ "NotUsed_140",
20533      /* 141 */ "ToText",
20534      /* 142 */ "ToBlob",
20535      /* 143 */ "ToNumeric",
20536      /* 144 */ "ToInt",
20537      /* 145 */ "ToReal",
20538   };
20539   return azName[i];
20540 }
20541 #endif
20542
20543 /************** End of opcodes.c *********************************************/
20544 /************** Begin file os_os2.c ******************************************/
20545 /*
20546 ** 2006 Feb 14
20547 **
20548 ** The author disclaims copyright to this source code.  In place of
20549 ** a legal notice, here is a blessing:
20550 **
20551 **    May you do good and not evil.
20552 **    May you find forgiveness for yourself and forgive others.
20553 **    May you share freely, never taking more than you give.
20554 **
20555 ******************************************************************************
20556 **
20557 ** This file contains code that is specific to OS/2.
20558 **
20559 ** $Id: os_os2.c,v 1.63 2008/12/10 19:26:24 drh Exp $
20560 */
20561
20562
20563 #if SQLITE_OS_OS2
20564
20565 /*
20566 ** A Note About Memory Allocation:
20567 **
20568 ** This driver uses malloc()/free() directly rather than going through
20569 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20570 ** are designed for use on embedded systems where memory is scarce and
20571 ** malloc failures happen frequently.  OS/2 does not typically run on
20572 ** embedded systems, and when it does the developers normally have bigger
20573 ** problems to worry about than running out of memory.  So there is not
20574 ** a compelling need to use the wrappers.
20575 **
20576 ** But there is a good reason to not use the wrappers.  If we use the
20577 ** wrappers then we will get simulated malloc() failures within this
20578 ** driver.  And that causes all kinds of problems for our tests.  We
20579 ** could enhance SQLite to deal with simulated malloc failures within
20580 ** the OS driver, but the code to deal with those failure would not
20581 ** be exercised on Linux (which does not need to malloc() in the driver)
20582 ** and so we would have difficulty writing coverage tests for that
20583 ** code.  Better to leave the code out, we think.
20584 **
20585 ** The point of this discussion is as follows:  When creating a new
20586 ** OS layer for an embedded system, if you use this file as an example,
20587 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20588 ** desktops but not so well in embedded systems.
20589 */
20590
20591 /*
20592 ** Macros used to determine whether or not to use threads.
20593 */
20594 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20595 # define SQLITE_OS2_THREADS 1
20596 #endif
20597
20598 /*
20599 ** Include code that is common to all os_*.c files
20600 */
20601 /************** Include os_common.h in the middle of os_os2.c ****************/
20602 /************** Begin file os_common.h ***************************************/
20603 /*
20604 ** 2004 May 22
20605 **
20606 ** The author disclaims copyright to this source code.  In place of
20607 ** a legal notice, here is a blessing:
20608 **
20609 **    May you do good and not evil.
20610 **    May you find forgiveness for yourself and forgive others.
20611 **    May you share freely, never taking more than you give.
20612 **
20613 ******************************************************************************
20614 **
20615 ** This file contains macros and a little bit of code that is common to
20616 ** all of the platform-specific files (os_*.c) and is #included into those
20617 ** files.
20618 **
20619 ** This file should be #included by the os_*.c files only.  It is not a
20620 ** general purpose header file.
20621 **
20622 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
20623 */
20624 #ifndef _OS_COMMON_H_
20625 #define _OS_COMMON_H_
20626
20627 /*
20628 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20629 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20630 ** switch.  The following code should catch this problem at compile-time.
20631 */
20632 #ifdef MEMORY_DEBUG
20633 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20634 #endif
20635
20636
20637 /*
20638  * When testing, this global variable stores the location of the
20639  * pending-byte in the database file.
20640  */
20641 #ifdef SQLITE_TEST
20642 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
20643 #endif
20644
20645 #ifdef SQLITE_DEBUG
20646 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20647 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20648 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20649 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20650 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20651 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20652 #define OSTRACE6(X,Y,Z,A,B,C) \
20653     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20654 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20655     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20656 #else
20657 #define OSTRACE1(X)
20658 #define OSTRACE2(X,Y)
20659 #define OSTRACE3(X,Y,Z)
20660 #define OSTRACE4(X,Y,Z,A)
20661 #define OSTRACE5(X,Y,Z,A,B)
20662 #define OSTRACE6(X,Y,Z,A,B,C)
20663 #define OSTRACE7(X,Y,Z,A,B,C,D)
20664 #endif
20665
20666 /*
20667 ** Macros for performance tracing.  Normally turned off.  Only works
20668 ** on i486 hardware.
20669 */
20670 #ifdef SQLITE_PERFORMANCE_TRACE
20671
20672 /* 
20673 ** hwtime.h contains inline assembler code for implementing 
20674 ** high-performance timing routines.
20675 */
20676 /************** Include hwtime.h in the middle of os_common.h ****************/
20677 /************** Begin file hwtime.h ******************************************/
20678 /*
20679 ** 2008 May 27
20680 **
20681 ** The author disclaims copyright to this source code.  In place of
20682 ** a legal notice, here is a blessing:
20683 **
20684 **    May you do good and not evil.
20685 **    May you find forgiveness for yourself and forgive others.
20686 **    May you share freely, never taking more than you give.
20687 **
20688 ******************************************************************************
20689 **
20690 ** This file contains inline asm code for retrieving "high-performance"
20691 ** counters for x86 class CPUs.
20692 **
20693 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
20694 */
20695 #ifndef _HWTIME_H_
20696 #define _HWTIME_H_
20697
20698 /*
20699 ** The following routine only works on pentium-class (or newer) processors.
20700 ** It uses the RDTSC opcode to read the cycle count value out of the
20701 ** processor and returns that value.  This can be used for high-res
20702 ** profiling.
20703 */
20704 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20705       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20706
20707   #if defined(__GNUC__)
20708
20709   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20710      unsigned int lo, hi;
20711      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20712      return (sqlite_uint64)hi << 32 | lo;
20713   }
20714
20715   #elif defined(_MSC_VER)
20716
20717   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20718      __asm {
20719         rdtsc
20720         ret       ; return value at EDX:EAX
20721      }
20722   }
20723
20724   #endif
20725
20726 #elif (defined(__GNUC__) && defined(__x86_64__))
20727
20728   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20729       unsigned long val;
20730       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20731       return val;
20732   }
20733  
20734 #elif (defined(__GNUC__) && defined(__ppc__))
20735
20736   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20737       unsigned long long retval;
20738       unsigned long junk;
20739       __asm__ __volatile__ ("\n\
20740           1:      mftbu   %1\n\
20741                   mftb    %L0\n\
20742                   mftbu   %0\n\
20743                   cmpw    %0,%1\n\
20744                   bne     1b"
20745                   : "=r" (retval), "=r" (junk));
20746       return retval;
20747   }
20748
20749 #else
20750
20751   #error Need implementation of sqlite3Hwtime() for your platform.
20752
20753   /*
20754   ** To compile without implementing sqlite3Hwtime() for your platform,
20755   ** you can remove the above #error and use the following
20756   ** stub function.  You will lose timing support for many
20757   ** of the debugging and testing utilities, but it should at
20758   ** least compile and run.
20759   */
20760 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20761
20762 #endif
20763
20764 #endif /* !defined(_HWTIME_H_) */
20765
20766 /************** End of hwtime.h **********************************************/
20767 /************** Continuing where we left off in os_common.h ******************/
20768
20769 static sqlite_uint64 g_start;
20770 static sqlite_uint64 g_elapsed;
20771 #define TIMER_START       g_start=sqlite3Hwtime()
20772 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20773 #define TIMER_ELAPSED     g_elapsed
20774 #else
20775 #define TIMER_START
20776 #define TIMER_END
20777 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20778 #endif
20779
20780 /*
20781 ** If we compile with the SQLITE_TEST macro set, then the following block
20782 ** of code will give us the ability to simulate a disk I/O error.  This
20783 ** is used for testing the I/O recovery logic.
20784 */
20785 #ifdef SQLITE_TEST
20786 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20787 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20788 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20789 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20790 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20791 SQLITE_API int sqlite3_diskfull_pending = 0;
20792 SQLITE_API int sqlite3_diskfull = 0;
20793 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20794 #define SimulateIOError(CODE)  \
20795   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20796        || sqlite3_io_error_pending-- == 1 )  \
20797               { local_ioerr(); CODE; }
20798 static void local_ioerr(){
20799   IOTRACE(("IOERR\n"));
20800   sqlite3_io_error_hit++;
20801   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20802 }
20803 #define SimulateDiskfullError(CODE) \
20804    if( sqlite3_diskfull_pending ){ \
20805      if( sqlite3_diskfull_pending == 1 ){ \
20806        local_ioerr(); \
20807        sqlite3_diskfull = 1; \
20808        sqlite3_io_error_hit = 1; \
20809        CODE; \
20810      }else{ \
20811        sqlite3_diskfull_pending--; \
20812      } \
20813    }
20814 #else
20815 #define SimulateIOErrorBenign(X)
20816 #define SimulateIOError(A)
20817 #define SimulateDiskfullError(A)
20818 #endif
20819
20820 /*
20821 ** When testing, keep a count of the number of open files.
20822 */
20823 #ifdef SQLITE_TEST
20824 SQLITE_API int sqlite3_open_file_count = 0;
20825 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20826 #else
20827 #define OpenCounter(X)
20828 #endif
20829
20830 #endif /* !defined(_OS_COMMON_H_) */
20831
20832 /************** End of os_common.h *******************************************/
20833 /************** Continuing where we left off in os_os2.c *********************/
20834
20835 /*
20836 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20837 ** protability layer.
20838 */
20839 typedef struct os2File os2File;
20840 struct os2File {
20841   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20842   HFILE h;                  /* Handle for accessing the file */
20843   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20844   unsigned char locktype;   /* Type of lock currently held on this file */
20845 };
20846
20847 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20848
20849 /*****************************************************************************
20850 ** The next group of routines implement the I/O methods specified
20851 ** by the sqlite3_io_methods object.
20852 ******************************************************************************/
20853
20854 /*
20855 ** Close a file.
20856 */
20857 static int os2Close( sqlite3_file *id ){
20858   APIRET rc = NO_ERROR;
20859   os2File *pFile;
20860   if( id && (pFile = (os2File*)id) != 0 ){
20861     OSTRACE2( "CLOSE %d\n", pFile->h );
20862     rc = DosClose( pFile->h );
20863     pFile->locktype = NO_LOCK;
20864     if( pFile->pathToDel != NULL ){
20865       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20866       free( pFile->pathToDel );
20867       pFile->pathToDel = NULL;
20868     }
20869     id = 0;
20870     OpenCounter( -1 );
20871   }
20872
20873   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20874 }
20875
20876 /*
20877 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20878 ** bytes were read successfully and SQLITE_IOERR if anything goes
20879 ** wrong.
20880 */
20881 static int os2Read(
20882   sqlite3_file *id,               /* File to read from */
20883   void *pBuf,                     /* Write content into this buffer */
20884   int amt,                        /* Number of bytes to read */
20885   sqlite3_int64 offset            /* Begin reading at this offset */
20886 ){
20887   ULONG fileLocation = 0L;
20888   ULONG got;
20889   os2File *pFile = (os2File*)id;
20890   assert( id!=0 );
20891   SimulateIOError( return SQLITE_IOERR_READ );
20892   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20893   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20894     return SQLITE_IOERR;
20895   }
20896   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20897     return SQLITE_IOERR_READ;
20898   }
20899   if( got == (ULONG)amt )
20900     return SQLITE_OK;
20901   else {
20902     /* Unread portions of the input buffer must be zero-filled */
20903     memset(&((char*)pBuf)[got], 0, amt-got);
20904     return SQLITE_IOERR_SHORT_READ;
20905   }
20906 }
20907
20908 /*
20909 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20910 ** or some other error code on failure.
20911 */
20912 static int os2Write(
20913   sqlite3_file *id,               /* File to write into */
20914   const void *pBuf,               /* The bytes to be written */
20915   int amt,                        /* Number of bytes to write */
20916   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20917 ){
20918   ULONG fileLocation = 0L;
20919   APIRET rc = NO_ERROR;
20920   ULONG wrote;
20921   os2File *pFile = (os2File*)id;
20922   assert( id!=0 );
20923   SimulateIOError( return SQLITE_IOERR_WRITE );
20924   SimulateDiskfullError( return SQLITE_FULL );
20925   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20926   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20927     return SQLITE_IOERR;
20928   }
20929   assert( amt>0 );
20930   while( amt > 0 &&
20931          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20932          wrote > 0
20933   ){
20934     amt -= wrote;
20935     pBuf = &((char*)pBuf)[wrote];
20936   }
20937
20938   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20939 }
20940
20941 /*
20942 ** Truncate an open file to a specified size
20943 */
20944 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20945   APIRET rc = NO_ERROR;
20946   os2File *pFile = (os2File*)id;
20947   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20948   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20949   rc = DosSetFileSize( pFile->h, nByte );
20950   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20951 }
20952
20953 #ifdef SQLITE_TEST
20954 /*
20955 ** Count the number of fullsyncs and normal syncs.  This is used to test
20956 ** that syncs and fullsyncs are occuring at the right times.
20957 */
20958 SQLITE_API int sqlite3_sync_count = 0;
20959 SQLITE_API int sqlite3_fullsync_count = 0;
20960 #endif
20961
20962 /*
20963 ** Make sure all writes to a particular file are committed to disk.
20964 */
20965 static int os2Sync( sqlite3_file *id, int flags ){
20966   os2File *pFile = (os2File*)id;
20967   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20968 #ifdef SQLITE_TEST
20969   if( flags & SQLITE_SYNC_FULL){
20970     sqlite3_fullsync_count++;
20971   }
20972   sqlite3_sync_count++;
20973 #endif
20974   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20975   ** no-op
20976   */
20977 #ifdef SQLITE_NO_SYNC
20978   UNUSED_PARAMETER(pFile);
20979   return SQLITE_OK;
20980 #else
20981   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20982 #endif
20983 }
20984
20985 /*
20986 ** Determine the current size of a file in bytes
20987 */
20988 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20989   APIRET rc = NO_ERROR;
20990   FILESTATUS3 fsts3FileInfo;
20991   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20992   assert( id!=0 );
20993   SimulateIOError( return SQLITE_IOERR_FSTAT );
20994   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20995   if( rc == NO_ERROR ){
20996     *pSize = fsts3FileInfo.cbFile;
20997     return SQLITE_OK;
20998   }else{
20999     return SQLITE_IOERR_FSTAT;
21000   }
21001 }
21002
21003 /*
21004 ** Acquire a reader lock.
21005 */
21006 static int getReadLock( os2File *pFile ){
21007   FILELOCK  LockArea,
21008             UnlockArea;
21009   APIRET res;
21010   memset(&LockArea, 0, sizeof(LockArea));
21011   memset(&UnlockArea, 0, sizeof(UnlockArea));
21012   LockArea.lOffset = SHARED_FIRST;
21013   LockArea.lRange = SHARED_SIZE;
21014   UnlockArea.lOffset = 0L;
21015   UnlockArea.lRange = 0L;
21016   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21017   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
21018   return res;
21019 }
21020
21021 /*
21022 ** Undo a readlock
21023 */
21024 static int unlockReadLock( os2File *id ){
21025   FILELOCK  LockArea,
21026             UnlockArea;
21027   APIRET res;
21028   memset(&LockArea, 0, sizeof(LockArea));
21029   memset(&UnlockArea, 0, sizeof(UnlockArea));
21030   LockArea.lOffset = 0L;
21031   LockArea.lRange = 0L;
21032   UnlockArea.lOffset = SHARED_FIRST;
21033   UnlockArea.lRange = SHARED_SIZE;
21034   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21035   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
21036   return res;
21037 }
21038
21039 /*
21040 ** Lock the file with the lock specified by parameter locktype - one
21041 ** of the following:
21042 **
21043 **     (1) SHARED_LOCK
21044 **     (2) RESERVED_LOCK
21045 **     (3) PENDING_LOCK
21046 **     (4) EXCLUSIVE_LOCK
21047 **
21048 ** Sometimes when requesting one lock state, additional lock states
21049 ** are inserted in between.  The locking might fail on one of the later
21050 ** transitions leaving the lock state different from what it started but
21051 ** still short of its goal.  The following chart shows the allowed
21052 ** transitions and the inserted intermediate states:
21053 **
21054 **    UNLOCKED -> SHARED
21055 **    SHARED -> RESERVED
21056 **    SHARED -> (PENDING) -> EXCLUSIVE
21057 **    RESERVED -> (PENDING) -> EXCLUSIVE
21058 **    PENDING -> EXCLUSIVE
21059 **
21060 ** This routine will only increase a lock.  The os2Unlock() routine
21061 ** erases all locks at once and returns us immediately to locking level 0.
21062 ** It is not possible to lower the locking level one step at a time.  You
21063 ** must go straight to locking level 0.
21064 */
21065 static int os2Lock( sqlite3_file *id, int locktype ){
21066   int rc = SQLITE_OK;       /* Return code from subroutines */
21067   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21068   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21069   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21070   FILELOCK  LockArea,
21071             UnlockArea;
21072   os2File *pFile = (os2File*)id;
21073   memset(&LockArea, 0, sizeof(LockArea));
21074   memset(&UnlockArea, 0, sizeof(UnlockArea));
21075   assert( pFile!=0 );
21076   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
21077
21078   /* If there is already a lock of this type or more restrictive on the
21079   ** os2File, do nothing. Don't use the end_lock: exit path, as
21080   ** sqlite3_mutex_enter() hasn't been called yet.
21081   */
21082   if( pFile->locktype>=locktype ){
21083     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
21084     return SQLITE_OK;
21085   }
21086
21087   /* Make sure the locking sequence is correct
21088   */
21089   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21090   assert( locktype!=PENDING_LOCK );
21091   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21092
21093   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21094   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21095   ** the PENDING_LOCK byte is temporary.
21096   */
21097   newLocktype = pFile->locktype;
21098   if( pFile->locktype==NO_LOCK
21099       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21100   ){
21101     LockArea.lOffset = PENDING_BYTE;
21102     LockArea.lRange = 1L;
21103     UnlockArea.lOffset = 0L;
21104     UnlockArea.lRange = 0L;
21105
21106     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21107     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21108     if( res == NO_ERROR ){
21109       gotPendingLock = 1;
21110       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
21111     }
21112   }
21113
21114   /* Acquire a shared lock
21115   */
21116   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21117     assert( pFile->locktype==NO_LOCK );
21118     res = getReadLock(pFile);
21119     if( res == NO_ERROR ){
21120       newLocktype = SHARED_LOCK;
21121     }
21122     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
21123   }
21124
21125   /* Acquire a RESERVED lock
21126   */
21127   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21128     assert( pFile->locktype==SHARED_LOCK );
21129     LockArea.lOffset = RESERVED_BYTE;
21130     LockArea.lRange = 1L;
21131     UnlockArea.lOffset = 0L;
21132     UnlockArea.lRange = 0L;
21133     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21134     if( res == NO_ERROR ){
21135       newLocktype = RESERVED_LOCK;
21136     }
21137     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
21138   }
21139
21140   /* Acquire a PENDING lock
21141   */
21142   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21143     newLocktype = PENDING_LOCK;
21144     gotPendingLock = 0;
21145     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
21146   }
21147
21148   /* Acquire an EXCLUSIVE lock
21149   */
21150   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21151     assert( pFile->locktype>=SHARED_LOCK );
21152     res = unlockReadLock(pFile);
21153     OSTRACE2( "unreadlock = %d\n", res );
21154     LockArea.lOffset = SHARED_FIRST;
21155     LockArea.lRange = SHARED_SIZE;
21156     UnlockArea.lOffset = 0L;
21157     UnlockArea.lRange = 0L;
21158     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21159     if( res == NO_ERROR ){
21160       newLocktype = EXCLUSIVE_LOCK;
21161     }else{
21162       OSTRACE2( "OS/2 error-code = %d\n", res );
21163       getReadLock(pFile);
21164     }
21165     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
21166   }
21167
21168   /* If we are holding a PENDING lock that ought to be released, then
21169   ** release it now.
21170   */
21171   if( gotPendingLock && locktype==SHARED_LOCK ){
21172     int r;
21173     LockArea.lOffset = 0L;
21174     LockArea.lRange = 0L;
21175     UnlockArea.lOffset = PENDING_BYTE;
21176     UnlockArea.lRange = 1L;
21177     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21178     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
21179   }
21180
21181   /* Update the state of the lock has held in the file descriptor then
21182   ** return the appropriate result code.
21183   */
21184   if( res == NO_ERROR ){
21185     rc = SQLITE_OK;
21186   }else{
21187     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21188               locktype, newLocktype );
21189     rc = SQLITE_BUSY;
21190   }
21191   pFile->locktype = newLocktype;
21192   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
21193   return rc;
21194 }
21195
21196 /*
21197 ** This routine checks if there is a RESERVED lock held on the specified
21198 ** file by this or any other process. If such a lock is held, return
21199 ** non-zero, otherwise zero.
21200 */
21201 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21202   int r = 0;
21203   os2File *pFile = (os2File*)id;
21204   assert( pFile!=0 );
21205   if( pFile->locktype>=RESERVED_LOCK ){
21206     r = 1;
21207     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
21208   }else{
21209     FILELOCK  LockArea,
21210               UnlockArea;
21211     APIRET rc = NO_ERROR;
21212     memset(&LockArea, 0, sizeof(LockArea));
21213     memset(&UnlockArea, 0, sizeof(UnlockArea));
21214     LockArea.lOffset = RESERVED_BYTE;
21215     LockArea.lRange = 1L;
21216     UnlockArea.lOffset = 0L;
21217     UnlockArea.lRange = 0L;
21218     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21219     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
21220     if( rc == NO_ERROR ){
21221       APIRET rcu = NO_ERROR; /* return code for unlocking */
21222       LockArea.lOffset = 0L;
21223       LockArea.lRange = 0L;
21224       UnlockArea.lOffset = RESERVED_BYTE;
21225       UnlockArea.lRange = 1L;
21226       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21227       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
21228     }
21229     r = !(rc == NO_ERROR);
21230     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
21231   }
21232   *pOut = r;
21233   return SQLITE_OK;
21234 }
21235
21236 /*
21237 ** Lower the locking level on file descriptor id to locktype.  locktype
21238 ** must be either NO_LOCK or SHARED_LOCK.
21239 **
21240 ** If the locking level of the file descriptor is already at or below
21241 ** the requested locking level, this routine is a no-op.
21242 **
21243 ** It is not possible for this routine to fail if the second argument
21244 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21245 ** might return SQLITE_IOERR;
21246 */
21247 static int os2Unlock( sqlite3_file *id, int locktype ){
21248   int type;
21249   os2File *pFile = (os2File*)id;
21250   APIRET rc = SQLITE_OK;
21251   APIRET res = NO_ERROR;
21252   FILELOCK  LockArea,
21253             UnlockArea;
21254   memset(&LockArea, 0, sizeof(LockArea));
21255   memset(&UnlockArea, 0, sizeof(UnlockArea));
21256   assert( pFile!=0 );
21257   assert( locktype<=SHARED_LOCK );
21258   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
21259   type = pFile->locktype;
21260   if( type>=EXCLUSIVE_LOCK ){
21261     LockArea.lOffset = 0L;
21262     LockArea.lRange = 0L;
21263     UnlockArea.lOffset = SHARED_FIRST;
21264     UnlockArea.lRange = SHARED_SIZE;
21265     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21266     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
21267     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21268       /* This should never happen.  We should always be able to
21269       ** reacquire the read lock */
21270       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
21271       rc = SQLITE_IOERR_UNLOCK;
21272     }
21273   }
21274   if( type>=RESERVED_LOCK ){
21275     LockArea.lOffset = 0L;
21276     LockArea.lRange = 0L;
21277     UnlockArea.lOffset = RESERVED_BYTE;
21278     UnlockArea.lRange = 1L;
21279     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21280     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
21281   }
21282   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21283     res = unlockReadLock(pFile);
21284     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
21285   }
21286   if( type>=PENDING_LOCK ){
21287     LockArea.lOffset = 0L;
21288     LockArea.lRange = 0L;
21289     UnlockArea.lOffset = PENDING_BYTE;
21290     UnlockArea.lRange = 1L;
21291     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21292     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
21293   }
21294   pFile->locktype = locktype;
21295   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
21296   return rc;
21297 }
21298
21299 /*
21300 ** Control and query of the open file handle.
21301 */
21302 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21303   switch( op ){
21304     case SQLITE_FCNTL_LOCKSTATE: {
21305       *(int*)pArg = ((os2File*)id)->locktype;
21306       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
21307       return SQLITE_OK;
21308     }
21309   }
21310   return SQLITE_ERROR;
21311 }
21312
21313 /*
21314 ** Return the sector size in bytes of the underlying block device for
21315 ** the specified file. This is almost always 512 bytes, but may be
21316 ** larger for some devices.
21317 **
21318 ** SQLite code assumes this function cannot fail. It also assumes that
21319 ** if two files are created in the same file-system directory (i.e.
21320 ** a database and its journal file) that the sector size will be the
21321 ** same for both.
21322 */
21323 static int os2SectorSize(sqlite3_file *id){
21324   return SQLITE_DEFAULT_SECTOR_SIZE;
21325 }
21326
21327 /*
21328 ** Return a vector of device characteristics.
21329 */
21330 static int os2DeviceCharacteristics(sqlite3_file *id){
21331   return 0;
21332 }
21333
21334
21335 /*
21336 ** Character set conversion objects used by conversion routines.
21337 */
21338 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21339 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21340
21341 /*
21342 ** Helper function to initialize the conversion objects from and to UTF-8.
21343 */
21344 static void initUconvObjects( void ){
21345   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21346     ucUtf8 = NULL;
21347   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21348     uclCp = NULL;
21349 }
21350
21351 /*
21352 ** Helper function to free the conversion objects from and to UTF-8.
21353 */
21354 static void freeUconvObjects( void ){
21355   if ( ucUtf8 )
21356     UniFreeUconvObject( ucUtf8 );
21357   if ( uclCp )
21358     UniFreeUconvObject( uclCp );
21359   ucUtf8 = NULL;
21360   uclCp = NULL;
21361 }
21362
21363 /*
21364 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21365 ** The two-step process: first convert the incoming UTF-8 string
21366 ** into UCS-2 and then from UCS-2 to the current codepage.
21367 ** The returned char pointer has to be freed.
21368 */
21369 static char *convertUtf8PathToCp( const char *in ){
21370   UniChar tempPath[CCHMAXPATH];
21371   char *out = (char *)calloc( CCHMAXPATH, 1 );
21372
21373   if( !out )
21374     return NULL;
21375
21376   if( !ucUtf8 || !uclCp )
21377     initUconvObjects();
21378
21379   /* determine string for the conversion of UTF-8 which is CP1208 */
21380   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21381     return out; /* if conversion fails, return the empty string */
21382
21383   /* conversion for current codepage which can be used for paths */
21384   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21385
21386   return out;
21387 }
21388
21389 /*
21390 ** Helper function to convert filenames from local codepage to UTF-8.
21391 ** The two-step process: first convert the incoming codepage-specific
21392 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21393 ** The returned char pointer has to be freed.
21394 **
21395 ** This function is non-static to be able to use this in shell.c and
21396 ** similar applications that take command line arguments.
21397 */
21398 char *convertCpPathToUtf8( const char *in ){
21399   UniChar tempPath[CCHMAXPATH];
21400   char *out = (char *)calloc( CCHMAXPATH, 1 );
21401
21402   if( !out )
21403     return NULL;
21404
21405   if( !ucUtf8 || !uclCp )
21406     initUconvObjects();
21407
21408   /* conversion for current codepage which can be used for paths */
21409   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21410     return out; /* if conversion fails, return the empty string */
21411
21412   /* determine string for the conversion of UTF-8 which is CP1208 */
21413   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21414
21415   return out;
21416 }
21417
21418 /*
21419 ** This vector defines all the methods that can operate on an
21420 ** sqlite3_file for os2.
21421 */
21422 static const sqlite3_io_methods os2IoMethod = {
21423   1,                        /* iVersion */
21424   os2Close,
21425   os2Read,
21426   os2Write,
21427   os2Truncate,
21428   os2Sync,
21429   os2FileSize,
21430   os2Lock,
21431   os2Unlock,
21432   os2CheckReservedLock,
21433   os2FileControl,
21434   os2SectorSize,
21435   os2DeviceCharacteristics
21436 };
21437
21438 /***************************************************************************
21439 ** Here ends the I/O methods that form the sqlite3_io_methods object.
21440 **
21441 ** The next block of code implements the VFS methods.
21442 ****************************************************************************/
21443
21444 /*
21445 ** Create a temporary file name in zBuf.  zBuf must be big enough to
21446 ** hold at pVfs->mxPathname characters.
21447 */
21448 static int getTempname(int nBuf, char *zBuf ){
21449   static const unsigned char zChars[] =
21450     "abcdefghijklmnopqrstuvwxyz"
21451     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21452     "0123456789";
21453   int i, j;
21454   char zTempPathBuf[3];
21455   PSZ zTempPath = (PSZ)&zTempPathBuf;
21456   if( sqlite3_temp_directory ){
21457     zTempPath = sqlite3_temp_directory;
21458   }else{
21459     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21460       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21461         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21462            ULONG ulDriveNum = 0, ulDriveMap = 0;
21463            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21464            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21465         }
21466       }
21467     }
21468   }
21469   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21470    * multiple (back)slashes which causes DosOpen() to fail.              *
21471    * Trailing spaces are not allowed, either.                            */
21472   j = sqlite3Strlen30(zTempPath);
21473   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21474                     || zTempPath[j-1] == ' ' ) ){
21475     j--;
21476   }
21477   zTempPath[j] = '\0';
21478   if( !sqlite3_temp_directory ){
21479     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21480     sqlite3_snprintf( nBuf-30, zBuf,
21481                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21482     free( zTempPathUTF );
21483   }else{
21484     sqlite3_snprintf( nBuf-30, zBuf,
21485                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21486   }
21487   j = sqlite3Strlen30( zBuf );
21488   sqlite3_randomness( 20, &zBuf[j] );
21489   for( i = 0; i < 20; i++, j++ ){
21490     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21491   }
21492   zBuf[j] = 0;
21493   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
21494   return SQLITE_OK;
21495 }
21496
21497
21498 /*
21499 ** Turn a relative pathname into a full pathname.  Write the full
21500 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21501 ** bytes in size.
21502 */
21503 static int os2FullPathname(
21504   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21505   const char *zRelative,      /* Possibly relative input path */
21506   int nFull,                  /* Size of output buffer in bytes */
21507   char *zFull                 /* Output buffer */
21508 ){
21509   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21510   char zFullCp[CCHMAXPATH] = "\0";
21511   char *zFullUTF;
21512   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21513                                 CCHMAXPATH );
21514   free( zRelativeCp );
21515   zFullUTF = convertCpPathToUtf8( zFullCp );
21516   sqlite3_snprintf( nFull, zFull, zFullUTF );
21517   free( zFullUTF );
21518   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21519 }
21520
21521
21522 /*
21523 ** Open a file.
21524 */
21525 static int os2Open(
21526   sqlite3_vfs *pVfs,            /* Not used */
21527   const char *zName,            /* Name of the file */
21528   sqlite3_file *id,             /* Write the SQLite file handle here */
21529   int flags,                    /* Open mode flags */
21530   int *pOutFlags                /* Status return flags */
21531 ){
21532   HFILE h;
21533   ULONG ulFileAttribute = FILE_NORMAL;
21534   ULONG ulOpenFlags = 0;
21535   ULONG ulOpenMode = 0;
21536   os2File *pFile = (os2File*)id;
21537   APIRET rc = NO_ERROR;
21538   ULONG ulAction;
21539   char *zNameCp;
21540   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21541
21542   /* If the second argument to this function is NULL, generate a 
21543   ** temporary file name to use 
21544   */
21545   if( !zName ){
21546     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21547     if( rc!=SQLITE_OK ){
21548       return rc;
21549     }
21550     zName = zTmpname;
21551   }
21552
21553
21554   memset( pFile, 0, sizeof(*pFile) );
21555
21556   OSTRACE2( "OPEN want %d\n", flags );
21557
21558   if( flags & SQLITE_OPEN_READWRITE ){
21559     ulOpenMode |= OPEN_ACCESS_READWRITE;
21560     OSTRACE1( "OPEN read/write\n" );
21561   }else{
21562     ulOpenMode |= OPEN_ACCESS_READONLY;
21563     OSTRACE1( "OPEN read only\n" );
21564   }
21565
21566   if( flags & SQLITE_OPEN_CREATE ){
21567     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21568     OSTRACE1( "OPEN open new/create\n" );
21569   }else{
21570     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21571     OSTRACE1( "OPEN open existing\n" );
21572   }
21573
21574   if( flags & SQLITE_OPEN_MAIN_DB ){
21575     ulOpenMode |= OPEN_SHARE_DENYNONE;
21576     OSTRACE1( "OPEN share read/write\n" );
21577   }else{
21578     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21579     OSTRACE1( "OPEN share read only\n" );
21580   }
21581
21582   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21583     char pathUtf8[CCHMAXPATH];
21584 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21585     ulFileAttribute = FILE_HIDDEN;
21586 #endif
21587     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21588     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21589     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21590   }else{
21591     pFile->pathToDel = NULL;
21592     OSTRACE1( "OPEN normal file attribute\n" );
21593   }
21594
21595   /* always open in random access mode for possibly better speed */
21596   ulOpenMode |= OPEN_FLAGS_RANDOM;
21597   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21598   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21599
21600   zNameCp = convertUtf8PathToCp( zName );
21601   rc = DosOpen( (PSZ)zNameCp,
21602                 &h,
21603                 &ulAction,
21604                 0L,
21605                 ulFileAttribute,
21606                 ulOpenFlags,
21607                 ulOpenMode,
21608                 (PEAOP2)NULL );
21609   free( zNameCp );
21610   if( rc != NO_ERROR ){
21611     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21612               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21613     if( pFile->pathToDel )
21614       free( pFile->pathToDel );
21615     pFile->pathToDel = NULL;
21616     if( flags & SQLITE_OPEN_READWRITE ){
21617       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21618       return os2Open( pVfs, zName, id,
21619                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21620                       pOutFlags );
21621     }else{
21622       return SQLITE_CANTOPEN;
21623     }
21624   }
21625
21626   if( pOutFlags ){
21627     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21628   }
21629
21630   pFile->pMethod = &os2IoMethod;
21631   pFile->h = h;
21632   OpenCounter(+1);
21633   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21634   return SQLITE_OK;
21635 }
21636
21637 /*
21638 ** Delete the named file.
21639 */
21640 static int os2Delete(
21641   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21642   const char *zFilename,                 /* Name of file to delete */
21643   int syncDir                            /* Not used on os2 */
21644 ){
21645   APIRET rc = NO_ERROR;
21646   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21647   SimulateIOError( return SQLITE_IOERR_DELETE );
21648   rc = DosDelete( (PSZ)zFilenameCp );
21649   free( zFilenameCp );
21650   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21651   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21652 }
21653
21654 /*
21655 ** Check the existance and status of a file.
21656 */
21657 static int os2Access(
21658   sqlite3_vfs *pVfs,        /* Not used on os2 */
21659   const char *zFilename,    /* Name of file to check */
21660   int flags,                /* Type of test to make on this file */
21661   int *pOut                 /* Write results here */
21662 ){
21663   FILESTATUS3 fsts3ConfigInfo;
21664   APIRET rc = NO_ERROR;
21665   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21666
21667   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21668   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21669                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21670   free( zFilenameCp );
21671   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21672             fsts3ConfigInfo.attrFile, flags, rc );
21673   switch( flags ){
21674     case SQLITE_ACCESS_READ:
21675     case SQLITE_ACCESS_EXISTS:
21676       rc = (rc == NO_ERROR);
21677       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21678       break;
21679     case SQLITE_ACCESS_READWRITE:
21680       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21681       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21682       break;
21683     default:
21684       assert( !"Invalid flags argument" );
21685   }
21686   *pOut = rc;
21687   return SQLITE_OK;
21688 }
21689
21690
21691 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21692 /*
21693 ** Interfaces for opening a shared library, finding entry points
21694 ** within the shared library, and closing the shared library.
21695 */
21696 /*
21697 ** Interfaces for opening a shared library, finding entry points
21698 ** within the shared library, and closing the shared library.
21699 */
21700 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21701   UCHAR loadErr[256];
21702   HMODULE hmod;
21703   APIRET rc;
21704   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21705   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21706   free(zFilenameCp);
21707   return rc != NO_ERROR ? 0 : (void*)hmod;
21708 }
21709 /*
21710 ** A no-op since the error code is returned on the DosLoadModule call.
21711 ** os2Dlopen returns zero if DosLoadModule is not successful.
21712 */
21713 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21714 /* no-op */
21715 }
21716 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21717   PFN pfn;
21718   APIRET rc;
21719   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21720   if( rc != NO_ERROR ){
21721     /* if the symbol itself was not found, search again for the same
21722      * symbol with an extra underscore, that might be needed depending
21723      * on the calling convention */
21724     char _zSymbol[256] = "_";
21725     strncat(_zSymbol, zSymbol, 255);
21726     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21727   }
21728   return rc != NO_ERROR ? 0 : (void*)pfn;
21729 }
21730 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21731   DosFreeModule((HMODULE)pHandle);
21732 }
21733 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21734   #define os2DlOpen 0
21735   #define os2DlError 0
21736   #define os2DlSym 0
21737   #define os2DlClose 0
21738 #endif
21739
21740
21741 /*
21742 ** Write up to nBuf bytes of randomness into zBuf.
21743 */
21744 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21745   int n = 0;
21746 #if defined(SQLITE_TEST)
21747   n = nBuf;
21748   memset(zBuf, 0, nBuf);
21749 #else
21750   int sizeofULong = sizeof(ULONG);
21751   if( (int)sizeof(DATETIME) <= nBuf - n ){
21752     DATETIME x;
21753     DosGetDateTime(&x);
21754     memcpy(&zBuf[n], &x, sizeof(x));
21755     n += sizeof(x);
21756   }
21757
21758   if( sizeofULong <= nBuf - n ){
21759     PPIB ppib;
21760     DosGetInfoBlocks(NULL, &ppib);
21761     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21762     n += sizeofULong;
21763   }
21764
21765   if( sizeofULong <= nBuf - n ){
21766     PTIB ptib;
21767     DosGetInfoBlocks(&ptib, NULL);
21768     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21769     n += sizeofULong;
21770   }
21771
21772   /* if we still haven't filled the buffer yet the following will */
21773   /* grab everything once instead of making several calls for a single item */
21774   if( sizeofULong <= nBuf - n ){
21775     ULONG ulSysInfo[QSV_MAX];
21776     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21777
21778     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21779     n += sizeofULong;
21780
21781     if( sizeofULong <= nBuf - n ){
21782       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21783       n += sizeofULong;
21784     }
21785     if( sizeofULong <= nBuf - n ){
21786       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21787       n += sizeofULong;
21788     }
21789     if( sizeofULong <= nBuf - n ){
21790       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21791       n += sizeofULong;
21792     }
21793     if( sizeofULong <= nBuf - n ){
21794       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21795       n += sizeofULong;
21796     }
21797   }
21798 #endif
21799
21800   return n;
21801 }
21802
21803 /*
21804 ** Sleep for a little while.  Return the amount of time slept.
21805 ** The argument is the number of microseconds we want to sleep.
21806 ** The return value is the number of microseconds of sleep actually
21807 ** requested from the underlying operating system, a number which
21808 ** might be greater than or equal to the argument, but not less
21809 ** than the argument.
21810 */
21811 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21812   DosSleep( (microsec/1000) );
21813   return microsec;
21814 }
21815
21816 /*
21817 ** The following variable, if set to a non-zero value, becomes the result
21818 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21819 */
21820 #ifdef SQLITE_TEST
21821 SQLITE_API int sqlite3_current_time = 0;
21822 #endif
21823
21824 /*
21825 ** Find the current time (in Universal Coordinated Time).  Write the
21826 ** current time and date as a Julian Day number into *prNow and
21827 ** return 0.  Return 1 if the time and date cannot be found.
21828 */
21829 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21830   double now;
21831   SHORT minute; /* needs to be able to cope with negative timezone offset */
21832   USHORT second, hour,
21833          day, month, year;
21834   DATETIME dt;
21835   DosGetDateTime( &dt );
21836   second = (USHORT)dt.seconds;
21837   minute = (SHORT)dt.minutes + dt.timezone;
21838   hour = (USHORT)dt.hours;
21839   day = (USHORT)dt.day;
21840   month = (USHORT)dt.month;
21841   year = (USHORT)dt.year;
21842
21843   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21844      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21845   /* Calculate the Julian days */
21846   now = day - 32076 +
21847     1461*(year + 4800 + (month - 14)/12)/4 +
21848     367*(month - 2 - (month - 14)/12*12)/12 -
21849     3*((year + 4900 + (month - 14)/12)/100)/4;
21850
21851   /* Add the fractional hours, mins and seconds */
21852   now += (hour + 12.0)/24.0;
21853   now += minute/1440.0;
21854   now += second/86400.0;
21855   *prNow = now;
21856 #ifdef SQLITE_TEST
21857   if( sqlite3_current_time ){
21858     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21859   }
21860 #endif
21861   return 0;
21862 }
21863
21864 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21865   return 0;
21866 }
21867
21868 /*
21869 ** Initialize and deinitialize the operating system interface.
21870 */
21871 SQLITE_API int sqlite3_os_init(void){
21872   static sqlite3_vfs os2Vfs = {
21873     1,                 /* iVersion */
21874     sizeof(os2File),   /* szOsFile */
21875     CCHMAXPATH,        /* mxPathname */
21876     0,                 /* pNext */
21877     "os2",             /* zName */
21878     0,                 /* pAppData */
21879
21880     os2Open,           /* xOpen */
21881     os2Delete,         /* xDelete */
21882     os2Access,         /* xAccess */
21883     os2FullPathname,   /* xFullPathname */
21884     os2DlOpen,         /* xDlOpen */
21885     os2DlError,        /* xDlError */
21886     os2DlSym,          /* xDlSym */
21887     os2DlClose,        /* xDlClose */
21888     os2Randomness,     /* xRandomness */
21889     os2Sleep,          /* xSleep */
21890     os2CurrentTime,    /* xCurrentTime */
21891     os2GetLastError    /* xGetLastError */
21892   };
21893   sqlite3_vfs_register(&os2Vfs, 1);
21894   initUconvObjects();
21895   return SQLITE_OK;
21896 }
21897 SQLITE_API int sqlite3_os_end(void){
21898   freeUconvObjects();
21899   return SQLITE_OK;
21900 }
21901
21902 #endif /* SQLITE_OS_OS2 */
21903
21904 /************** End of os_os2.c **********************************************/
21905 /************** Begin file os_unix.c *****************************************/
21906 /*
21907 ** 2004 May 22
21908 **
21909 ** The author disclaims copyright to this source code.  In place of
21910 ** a legal notice, here is a blessing:
21911 **
21912 **    May you do good and not evil.
21913 **    May you find forgiveness for yourself and forgive others.
21914 **    May you share freely, never taking more than you give.
21915 **
21916 ******************************************************************************
21917 **
21918 ** This file contains the VFS implementation for unix-like operating systems
21919 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21920 **
21921 ** There are actually several different VFS implementations in this file.
21922 ** The differences are in the way that file locking is done.  The default
21923 ** implementation uses Posix Advisory Locks.  Alternative implementations
21924 ** use flock(), dot-files, various proprietary locking schemas, or simply
21925 ** skip locking all together.
21926 **
21927 ** This source file is organized into divisions where the logic for various
21928 ** subfunctions is contained within the appropriate division.  PLEASE
21929 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21930 ** in the correct division and should be clearly labeled.
21931 **
21932 ** The layout of divisions is as follows:
21933 **
21934 **   *  General-purpose declarations and utility functions.
21935 **   *  Unique file ID logic used by VxWorks.
21936 **   *  Various locking primitive implementations (all except proxy locking):
21937 **      + for Posix Advisory Locks
21938 **      + for no-op locks
21939 **      + for dot-file locks
21940 **      + for flock() locking
21941 **      + for named semaphore locks (VxWorks only)
21942 **      + for AFP filesystem locks (MacOSX only)
21943 **   *  sqlite3_file methods not associated with locking.
21944 **   *  Definitions of sqlite3_io_methods objects for all locking
21945 **      methods plus "finder" functions for each locking method.
21946 **   *  sqlite3_vfs method implementations.
21947 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21948 **   *  Definitions of sqlite3_vfs objects for all locking methods
21949 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21950 **
21951 ** $Id: os_unix.c,v 1.241 2009/02/09 17:34:07 drh Exp $
21952 */
21953 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21954
21955 /*
21956 ** There are various methods for file locking used for concurrency
21957 ** control:
21958 **
21959 **   1. POSIX locking (the default),
21960 **   2. No locking,
21961 **   3. Dot-file locking,
21962 **   4. flock() locking,
21963 **   5. AFP locking (OSX only),
21964 **   6. Named POSIX semaphores (VXWorks only),
21965 **   7. proxy locking. (OSX only)
21966 **
21967 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21968 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21969 ** selection of the appropriate locking style based on the filesystem
21970 ** where the database is located.  
21971 */
21972 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21973 #  if defined(__APPLE__)
21974 #    define SQLITE_ENABLE_LOCKING_STYLE 1
21975 #  else
21976 #    define SQLITE_ENABLE_LOCKING_STYLE 0
21977 #  endif
21978 #endif
21979
21980 /*
21981 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
21982 ** vxworks, or 0 otherwise.
21983 */
21984 #ifndef OS_VXWORKS
21985 #  if defined(__RTP__) || defined(_WRS_KERNEL)
21986 #    define OS_VXWORKS 1
21987 #  else
21988 #    define OS_VXWORKS 0
21989 #  endif
21990 #endif
21991
21992 /*
21993 ** These #defines should enable >2GB file support on Posix if the
21994 ** underlying operating system supports it.  If the OS lacks
21995 ** large file support, these should be no-ops.
21996 **
21997 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21998 ** on the compiler command line.  This is necessary if you are compiling
21999 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22000 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22001 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22002 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22003 ** portability you should omit LFS.
22004 **
22005 ** The previous paragraph was written in 2005.  (This paragraph is written
22006 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22007 ** you should probably leave LFS enabled.  But some embedded platforms might
22008 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22009 */
22010 #ifndef SQLITE_DISABLE_LFS
22011 # define _LARGE_FILE       1
22012 # ifndef _FILE_OFFSET_BITS
22013 #   define _FILE_OFFSET_BITS 64
22014 # endif
22015 # define _LARGEFILE_SOURCE 1
22016 #endif
22017
22018 /*
22019 ** standard include files.
22020 */
22021 #include <sys/types.h>
22022 #include <sys/stat.h>
22023 #include <fcntl.h>
22024 #include <unistd.h>
22025 #include <sys/time.h>
22026 #include <errno.h>
22027
22028 #if SQLITE_ENABLE_LOCKING_STYLE
22029 # include <sys/ioctl.h>
22030 # if OS_VXWORKS
22031 #  include <semaphore.h>
22032 #  include <limits.h>
22033 # else
22034 #  include <sys/file.h>
22035 #  include <sys/param.h>
22036 #  include <sys/mount.h>
22037 # endif
22038 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22039
22040 /*
22041 ** If we are to be thread-safe, include the pthreads header and define
22042 ** the SQLITE_UNIX_THREADS macro.
22043 */
22044 #if SQLITE_THREADSAFE
22045 # define SQLITE_UNIX_THREADS 1
22046 #endif
22047
22048 /*
22049 ** Default permissions when creating a new file
22050 */
22051 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22052 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22053 #endif
22054
22055 /*
22056  ** Default permissions when creating auto proxy dir
22057  */
22058 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22059 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22060 #endif
22061
22062 /*
22063 ** Maximum supported path-length.
22064 */
22065 #define MAX_PATHNAME 512
22066
22067 /*
22068 ** Only set the lastErrno if the error code is a real error and not 
22069 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22070 */
22071 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22072
22073
22074 /*
22075 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22076 ** VFS implementations.
22077 */
22078 typedef struct unixFile unixFile;
22079 struct unixFile {
22080   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22081   struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
22082   struct unixLockInfo *pLock;      /* Info about locks on this inode */
22083   int h;                           /* The file descriptor */
22084   int dirfd;                       /* File descriptor for the directory */
22085   unsigned char locktype;          /* The type of lock held on this fd */
22086   int lastErrno;                   /* The unix errno from the last I/O error */
22087   void *lockingContext;            /* Locking style specific state */
22088 #if SQLITE_ENABLE_LOCKING_STYLE
22089   int openFlags;                   /* The flags specified at open() */
22090 #endif
22091 #if SQLITE_THREADSAFE && defined(__linux__)
22092   pthread_t tid;                   /* The thread that "owns" this unixFile */
22093 #endif
22094 #if OS_VXWORKS
22095   int isDelete;                    /* Delete on close if true */
22096   struct vxworksFileId *pId;       /* Unique file ID */
22097 #endif
22098 #ifndef NDEBUG
22099   /* The next group of variables are used to track whether or not the
22100   ** transaction counter in bytes 24-27 of database files are updated
22101   ** whenever any part of the database changes.  An assertion fault will
22102   ** occur if a file is updated without also updating the transaction
22103   ** counter.  This test is made to avoid new problems similar to the
22104   ** one described by ticket #3584. 
22105   */
22106   unsigned char transCntrChng;   /* True if the transaction counter changed */
22107   unsigned char dbUpdate;        /* True if any part of database file changed */
22108   unsigned char inNormalWrite;   /* True if in a normal write operation */
22109
22110   /* If true, that means we are dealing with a database file that has
22111   ** a range of locking bytes from PENDING_BYTE through PENDING_BYTE+511
22112   ** which should never be read or written.  Asserts() will verify this */
22113   unsigned char isLockable;      /* True if file might be locked */
22114 #endif
22115 #ifdef SQLITE_TEST
22116   /* In test mode, increase the size of this structure a bit so that 
22117   ** it is larger than the struct CrashFile defined in test6.c.
22118   */
22119   char aPadding[32];
22120 #endif
22121 };
22122
22123 /*
22124 ** Include code that is common to all os_*.c files
22125 */
22126 /************** Include os_common.h in the middle of os_unix.c ***************/
22127 /************** Begin file os_common.h ***************************************/
22128 /*
22129 ** 2004 May 22
22130 **
22131 ** The author disclaims copyright to this source code.  In place of
22132 ** a legal notice, here is a blessing:
22133 **
22134 **    May you do good and not evil.
22135 **    May you find forgiveness for yourself and forgive others.
22136 **    May you share freely, never taking more than you give.
22137 **
22138 ******************************************************************************
22139 **
22140 ** This file contains macros and a little bit of code that is common to
22141 ** all of the platform-specific files (os_*.c) and is #included into those
22142 ** files.
22143 **
22144 ** This file should be #included by the os_*.c files only.  It is not a
22145 ** general purpose header file.
22146 **
22147 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
22148 */
22149 #ifndef _OS_COMMON_H_
22150 #define _OS_COMMON_H_
22151
22152 /*
22153 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22154 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22155 ** switch.  The following code should catch this problem at compile-time.
22156 */
22157 #ifdef MEMORY_DEBUG
22158 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22159 #endif
22160
22161
22162 /*
22163  * When testing, this global variable stores the location of the
22164  * pending-byte in the database file.
22165  */
22166 #ifdef SQLITE_TEST
22167 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
22168 #endif
22169
22170 #ifdef SQLITE_DEBUG
22171 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22172 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
22173 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
22174 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
22175 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
22176 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
22177 #define OSTRACE6(X,Y,Z,A,B,C) \
22178     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
22179 #define OSTRACE7(X,Y,Z,A,B,C,D) \
22180     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
22181 #else
22182 #define OSTRACE1(X)
22183 #define OSTRACE2(X,Y)
22184 #define OSTRACE3(X,Y,Z)
22185 #define OSTRACE4(X,Y,Z,A)
22186 #define OSTRACE5(X,Y,Z,A,B)
22187 #define OSTRACE6(X,Y,Z,A,B,C)
22188 #define OSTRACE7(X,Y,Z,A,B,C,D)
22189 #endif
22190
22191 /*
22192 ** Macros for performance tracing.  Normally turned off.  Only works
22193 ** on i486 hardware.
22194 */
22195 #ifdef SQLITE_PERFORMANCE_TRACE
22196
22197 /* 
22198 ** hwtime.h contains inline assembler code for implementing 
22199 ** high-performance timing routines.
22200 */
22201 /************** Include hwtime.h in the middle of os_common.h ****************/
22202 /************** Begin file hwtime.h ******************************************/
22203 /*
22204 ** 2008 May 27
22205 **
22206 ** The author disclaims copyright to this source code.  In place of
22207 ** a legal notice, here is a blessing:
22208 **
22209 **    May you do good and not evil.
22210 **    May you find forgiveness for yourself and forgive others.
22211 **    May you share freely, never taking more than you give.
22212 **
22213 ******************************************************************************
22214 **
22215 ** This file contains inline asm code for retrieving "high-performance"
22216 ** counters for x86 class CPUs.
22217 **
22218 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
22219 */
22220 #ifndef _HWTIME_H_
22221 #define _HWTIME_H_
22222
22223 /*
22224 ** The following routine only works on pentium-class (or newer) processors.
22225 ** It uses the RDTSC opcode to read the cycle count value out of the
22226 ** processor and returns that value.  This can be used for high-res
22227 ** profiling.
22228 */
22229 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22230       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22231
22232   #if defined(__GNUC__)
22233
22234   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22235      unsigned int lo, hi;
22236      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22237      return (sqlite_uint64)hi << 32 | lo;
22238   }
22239
22240   #elif defined(_MSC_VER)
22241
22242   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22243      __asm {
22244         rdtsc
22245         ret       ; return value at EDX:EAX
22246      }
22247   }
22248
22249   #endif
22250
22251 #elif (defined(__GNUC__) && defined(__x86_64__))
22252
22253   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22254       unsigned long val;
22255       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22256       return val;
22257   }
22258  
22259 #elif (defined(__GNUC__) && defined(__ppc__))
22260
22261   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22262       unsigned long long retval;
22263       unsigned long junk;
22264       __asm__ __volatile__ ("\n\
22265           1:      mftbu   %1\n\
22266                   mftb    %L0\n\
22267                   mftbu   %0\n\
22268                   cmpw    %0,%1\n\
22269                   bne     1b"
22270                   : "=r" (retval), "=r" (junk));
22271       return retval;
22272   }
22273
22274 #else
22275
22276   #error Need implementation of sqlite3Hwtime() for your platform.
22277
22278   /*
22279   ** To compile without implementing sqlite3Hwtime() for your platform,
22280   ** you can remove the above #error and use the following
22281   ** stub function.  You will lose timing support for many
22282   ** of the debugging and testing utilities, but it should at
22283   ** least compile and run.
22284   */
22285 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22286
22287 #endif
22288
22289 #endif /* !defined(_HWTIME_H_) */
22290
22291 /************** End of hwtime.h **********************************************/
22292 /************** Continuing where we left off in os_common.h ******************/
22293
22294 static sqlite_uint64 g_start;
22295 static sqlite_uint64 g_elapsed;
22296 #define TIMER_START       g_start=sqlite3Hwtime()
22297 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22298 #define TIMER_ELAPSED     g_elapsed
22299 #else
22300 #define TIMER_START
22301 #define TIMER_END
22302 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22303 #endif
22304
22305 /*
22306 ** If we compile with the SQLITE_TEST macro set, then the following block
22307 ** of code will give us the ability to simulate a disk I/O error.  This
22308 ** is used for testing the I/O recovery logic.
22309 */
22310 #ifdef SQLITE_TEST
22311 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22312 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22313 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22314 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22315 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22316 SQLITE_API int sqlite3_diskfull_pending = 0;
22317 SQLITE_API int sqlite3_diskfull = 0;
22318 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22319 #define SimulateIOError(CODE)  \
22320   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22321        || sqlite3_io_error_pending-- == 1 )  \
22322               { local_ioerr(); CODE; }
22323 static void local_ioerr(){
22324   IOTRACE(("IOERR\n"));
22325   sqlite3_io_error_hit++;
22326   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22327 }
22328 #define SimulateDiskfullError(CODE) \
22329    if( sqlite3_diskfull_pending ){ \
22330      if( sqlite3_diskfull_pending == 1 ){ \
22331        local_ioerr(); \
22332        sqlite3_diskfull = 1; \
22333        sqlite3_io_error_hit = 1; \
22334        CODE; \
22335      }else{ \
22336        sqlite3_diskfull_pending--; \
22337      } \
22338    }
22339 #else
22340 #define SimulateIOErrorBenign(X)
22341 #define SimulateIOError(A)
22342 #define SimulateDiskfullError(A)
22343 #endif
22344
22345 /*
22346 ** When testing, keep a count of the number of open files.
22347 */
22348 #ifdef SQLITE_TEST
22349 SQLITE_API int sqlite3_open_file_count = 0;
22350 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22351 #else
22352 #define OpenCounter(X)
22353 #endif
22354
22355 #endif /* !defined(_OS_COMMON_H_) */
22356
22357 /************** End of os_common.h *******************************************/
22358 /************** Continuing where we left off in os_unix.c ********************/
22359
22360 /*
22361 ** Define various macros that are missing from some systems.
22362 */
22363 #ifndef O_LARGEFILE
22364 # define O_LARGEFILE 0
22365 #endif
22366 #ifdef SQLITE_DISABLE_LFS
22367 # undef O_LARGEFILE
22368 # define O_LARGEFILE 0
22369 #endif
22370 #ifndef O_NOFOLLOW
22371 # define O_NOFOLLOW 0
22372 #endif
22373 #ifndef O_BINARY
22374 # define O_BINARY 0
22375 #endif
22376
22377 /*
22378 ** The DJGPP compiler environment looks mostly like Unix, but it
22379 ** lacks the fcntl() system call.  So redefine fcntl() to be something
22380 ** that always succeeds.  This means that locking does not occur under
22381 ** DJGPP.  But it is DOS - what did you expect?
22382 */
22383 #ifdef __DJGPP__
22384 # define fcntl(A,B,C) 0
22385 #endif
22386
22387 /*
22388 ** The threadid macro resolves to the thread-id or to 0.  Used for
22389 ** testing and debugging only.
22390 */
22391 #if SQLITE_THREADSAFE
22392 #define threadid pthread_self()
22393 #else
22394 #define threadid 0
22395 #endif
22396
22397
22398 /*
22399 ** Helper functions to obtain and relinquish the global mutex.
22400 */
22401 static void unixEnterMutex(void){
22402   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22403 }
22404 static void unixLeaveMutex(void){
22405   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22406 }
22407
22408
22409 #ifdef SQLITE_DEBUG
22410 /*
22411 ** Helper function for printing out trace information from debugging
22412 ** binaries. This returns the string represetation of the supplied
22413 ** integer lock-type.
22414 */
22415 static const char *locktypeName(int locktype){
22416   switch( locktype ){
22417   case NO_LOCK: return "NONE";
22418   case SHARED_LOCK: return "SHARED";
22419   case RESERVED_LOCK: return "RESERVED";
22420   case PENDING_LOCK: return "PENDING";
22421   case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22422   }
22423   return "ERROR";
22424 }
22425 #endif
22426
22427 #ifdef SQLITE_LOCK_TRACE
22428 /*
22429 ** Print out information about all locking operations.
22430 **
22431 ** This routine is used for troubleshooting locks on multithreaded
22432 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22433 ** command-line option on the compiler.  This code is normally
22434 ** turned off.
22435 */
22436 static int lockTrace(int fd, int op, struct flock *p){
22437   char *zOpName, *zType;
22438   int s;
22439   int savedErrno;
22440   if( op==F_GETLK ){
22441     zOpName = "GETLK";
22442   }else if( op==F_SETLK ){
22443     zOpName = "SETLK";
22444   }else{
22445     s = fcntl(fd, op, p);
22446     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22447     return s;
22448   }
22449   if( p->l_type==F_RDLCK ){
22450     zType = "RDLCK";
22451   }else if( p->l_type==F_WRLCK ){
22452     zType = "WRLCK";
22453   }else if( p->l_type==F_UNLCK ){
22454     zType = "UNLCK";
22455   }else{
22456     assert( 0 );
22457   }
22458   assert( p->l_whence==SEEK_SET );
22459   s = fcntl(fd, op, p);
22460   savedErrno = errno;
22461   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22462      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22463      (int)p->l_pid, s);
22464   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22465     struct flock l2;
22466     l2 = *p;
22467     fcntl(fd, F_GETLK, &l2);
22468     if( l2.l_type==F_RDLCK ){
22469       zType = "RDLCK";
22470     }else if( l2.l_type==F_WRLCK ){
22471       zType = "WRLCK";
22472     }else if( l2.l_type==F_UNLCK ){
22473       zType = "UNLCK";
22474     }else{
22475       assert( 0 );
22476     }
22477     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22478        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22479   }
22480   errno = savedErrno;
22481   return s;
22482 }
22483 #define fcntl lockTrace
22484 #endif /* SQLITE_LOCK_TRACE */
22485
22486
22487
22488 /*
22489 ** This routine translates a standard POSIX errno code into something
22490 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22491 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22492 ** and a variety of "please close the file descriptor NOW" errors into 
22493 ** SQLITE_IOERR
22494 ** 
22495 ** Errors during initialization of locks, or file system support for locks,
22496 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22497 */
22498 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22499   switch (posixError) {
22500   case 0: 
22501     return SQLITE_OK;
22502     
22503   case EAGAIN:
22504   case ETIMEDOUT:
22505   case EBUSY:
22506   case EINTR:
22507   case ENOLCK:  
22508     /* random NFS retry error, unless during file system support 
22509      * introspection, in which it actually means what it says */
22510     return SQLITE_BUSY;
22511     
22512   case EACCES: 
22513     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22514     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22515         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22516         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22517         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22518       return SQLITE_BUSY;
22519     }
22520     /* else fall through */
22521   case EPERM: 
22522     return SQLITE_PERM;
22523     
22524   case EDEADLK:
22525     return SQLITE_IOERR_BLOCKED;
22526     
22527 #if EOPNOTSUPP!=ENOTSUP
22528   case EOPNOTSUPP: 
22529     /* something went terribly awry, unless during file system support 
22530      * introspection, in which it actually means what it says */
22531 #endif
22532 #ifdef ENOTSUP
22533   case ENOTSUP: 
22534     /* invalid fd, unless during file system support introspection, in which 
22535      * it actually means what it says */
22536 #endif
22537   case EIO:
22538   case EBADF:
22539   case EINVAL:
22540   case ENOTCONN:
22541   case ENODEV:
22542   case ENXIO:
22543   case ENOENT:
22544   case ESTALE:
22545   case ENOSYS:
22546     /* these should force the client to close the file and reconnect */
22547     
22548   default: 
22549     return sqliteIOErr;
22550   }
22551 }
22552
22553
22554
22555 /******************************************************************************
22556 ****************** Begin Unique File ID Utility Used By VxWorks ***************
22557 **
22558 ** On most versions of unix, we can get a unique ID for a file by concatenating
22559 ** the device number and the inode number.  But this does not work on VxWorks.
22560 ** On VxWorks, a unique file id must be based on the canonical filename.
22561 **
22562 ** A pointer to an instance of the following structure can be used as a
22563 ** unique file ID in VxWorks.  Each instance of this structure contains
22564 ** a copy of the canonical filename.  There is also a reference count.  
22565 ** The structure is reclaimed when the number of pointers to it drops to
22566 ** zero.
22567 **
22568 ** There are never very many files open at one time and lookups are not
22569 ** a performance-critical path, so it is sufficient to put these
22570 ** structures on a linked list.
22571 */
22572 struct vxworksFileId {
22573   struct vxworksFileId *pNext;  /* Next in a list of them all */
22574   int nRef;                     /* Number of references to this one */
22575   int nName;                    /* Length of the zCanonicalName[] string */
22576   char *zCanonicalName;         /* Canonical filename */
22577 };
22578
22579 #if OS_VXWORKS
22580 /* 
22581 ** All unique filenames are held on a linked list headed by this
22582 ** variable:
22583 */
22584 static struct vxworksFileId *vxworksFileList = 0;
22585
22586 /*
22587 ** Simplify a filename into its canonical form
22588 ** by making the following changes:
22589 **
22590 **  * removing any trailing and duplicate /
22591 **  * convert /./ into just /
22592 **  * convert /A/../ where A is any simple name into just /
22593 **
22594 ** Changes are made in-place.  Return the new name length.
22595 **
22596 ** The original filename is in z[0..n-1].  Return the number of
22597 ** characters in the simplified name.
22598 */
22599 static int vxworksSimplifyName(char *z, int n){
22600   int i, j;
22601   while( n>1 && z[n-1]=='/' ){ n--; }
22602   for(i=j=0; i<n; i++){
22603     if( z[i]=='/' ){
22604       if( z[i+1]=='/' ) continue;
22605       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22606         i += 1;
22607         continue;
22608       }
22609       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22610         while( j>0 && z[j-1]!='/' ){ j--; }
22611         if( j>0 ){ j--; }
22612         i += 2;
22613         continue;
22614       }
22615     }
22616     z[j++] = z[i];
22617   }
22618   z[j] = 0;
22619   return j;
22620 }
22621
22622 /*
22623 ** Find a unique file ID for the given absolute pathname.  Return
22624 ** a pointer to the vxworksFileId object.  This pointer is the unique
22625 ** file ID.
22626 **
22627 ** The nRef field of the vxworksFileId object is incremented before
22628 ** the object is returned.  A new vxworksFileId object is created
22629 ** and added to the global list if necessary.
22630 **
22631 ** If a memory allocation error occurs, return NULL.
22632 */
22633 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22634   struct vxworksFileId *pNew;         /* search key and new file ID */
22635   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22636   int n;                              /* Length of zAbsoluteName string */
22637
22638   assert( zAbsoluteName[0]=='/' );
22639   n = (int)strlen(zAbsoluteName);
22640   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22641   if( pNew==0 ) return 0;
22642   pNew->zCanonicalName = (char*)&pNew[1];
22643   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22644   n = vxworksSimplifyName(pNew->zCanonicalName, n);
22645
22646   /* Search for an existing entry that matching the canonical name.
22647   ** If found, increment the reference count and return a pointer to
22648   ** the existing file ID.
22649   */
22650   unixEnterMutex();
22651   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22652     if( pCandidate->nName==n 
22653      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22654     ){
22655        sqlite3_free(pNew);
22656        pCandidate->nRef++;
22657        unixLeaveMutex();
22658        return pCandidate;
22659     }
22660   }
22661
22662   /* No match was found.  We will make a new file ID */
22663   pNew->nRef = 1;
22664   pNew->nName = n;
22665   pNew->pNext = vxworksFileList;
22666   vxworksFileList = pNew;
22667   unixLeaveMutex();
22668   return pNew;
22669 }
22670
22671 /*
22672 ** Decrement the reference count on a vxworksFileId object.  Free
22673 ** the object when the reference count reaches zero.
22674 */
22675 static void vxworksReleaseFileId(struct vxworksFileId *pId){
22676   unixEnterMutex();
22677   assert( pId->nRef>0 );
22678   pId->nRef--;
22679   if( pId->nRef==0 ){
22680     struct vxworksFileId **pp;
22681     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22682     assert( *pp==pId );
22683     *pp = pId->pNext;
22684     sqlite3_free(pId);
22685   }
22686   unixLeaveMutex();
22687 }
22688 #endif /* OS_VXWORKS */
22689 /*************** End of Unique File ID Utility Used By VxWorks ****************
22690 ******************************************************************************/
22691
22692
22693 /******************************************************************************
22694 *************************** Posix Advisory Locking ****************************
22695 **
22696 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22697 ** section 6.5.2.2 lines 483 through 490 specify that when a process
22698 ** sets or clears a lock, that operation overrides any prior locks set
22699 ** by the same process.  It does not explicitly say so, but this implies
22700 ** that it overrides locks set by the same process using a different
22701 ** file descriptor.  Consider this test case:
22702 **
22703 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22704 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22705 **
22706 ** Suppose ./file1 and ./file2 are really the same file (because
22707 ** one is a hard or symbolic link to the other) then if you set
22708 ** an exclusive lock on fd1, then try to get an exclusive lock
22709 ** on fd2, it works.  I would have expected the second lock to
22710 ** fail since there was already a lock on the file due to fd1.
22711 ** But not so.  Since both locks came from the same process, the
22712 ** second overrides the first, even though they were on different
22713 ** file descriptors opened on different file names.
22714 **
22715 ** This means that we cannot use POSIX locks to synchronize file access
22716 ** among competing threads of the same process.  POSIX locks will work fine
22717 ** to synchronize access for threads in separate processes, but not
22718 ** threads within the same process.
22719 **
22720 ** To work around the problem, SQLite has to manage file locks internally
22721 ** on its own.  Whenever a new database is opened, we have to find the
22722 ** specific inode of the database file (the inode is determined by the
22723 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
22724 ** and check for locks already existing on that inode.  When locks are
22725 ** created or removed, we have to look at our own internal record of the
22726 ** locks to see if another thread has previously set a lock on that same
22727 ** inode.
22728 **
22729 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22730 ** For VxWorks, we have to use the alternative unique ID system based on
22731 ** canonical filename and implemented in the previous division.)
22732 **
22733 ** The sqlite3_file structure for POSIX is no longer just an integer file
22734 ** descriptor.  It is now a structure that holds the integer file
22735 ** descriptor and a pointer to a structure that describes the internal
22736 ** locks on the corresponding inode.  There is one locking structure
22737 ** per inode, so if the same inode is opened twice, both unixFile structures
22738 ** point to the same locking structure.  The locking structure keeps
22739 ** a reference count (so we will know when to delete it) and a "cnt"
22740 ** field that tells us its internal lock status.  cnt==0 means the
22741 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22742 ** cnt>0 means there are cnt shared locks on the file.
22743 **
22744 ** Any attempt to lock or unlock a file first checks the locking
22745 ** structure.  The fcntl() system call is only invoked to set a 
22746 ** POSIX lock if the internal lock structure transitions between
22747 ** a locked and an unlocked state.
22748 **
22749 ** But wait:  there are yet more problems with POSIX advisory locks.
22750 **
22751 ** If you close a file descriptor that points to a file that has locks,
22752 ** all locks on that file that are owned by the current process are
22753 ** released.  To work around this problem, each unixFile structure contains
22754 ** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22755 ** per open inode, which means that multiple unixFile can point to a single
22756 ** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22757 ** other unixFile open on the same inode that are holding locks, the call
22758 ** to close() the file descriptor is deferred until all of the locks clear.
22759 ** The unixOpenCnt structure keeps a list of file descriptors that need to
22760 ** be closed and that list is walked (and cleared) when the last lock
22761 ** clears.
22762 **
22763 ** Yet another problem:  LinuxThreads do not play well with posix locks.
22764 **
22765 ** Many older versions of linux use the LinuxThreads library which is
22766 ** not posix compliant.  Under LinuxThreads, a lock created by thread
22767 ** A cannot be modified or overridden by a different thread B.
22768 ** Only thread A can modify the lock.  Locking behavior is correct
22769 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
22770 ** on linux - with NPTL a lock created by thread A can override locks
22771 ** in thread B.  But there is no way to know at compile-time which
22772 ** threading library is being used.  So there is no way to know at
22773 ** compile-time whether or not thread A can override locks on thread B.
22774 ** We have to do a run-time check to discover the behavior of the
22775 ** current process.
22776 **
22777 ** On systems where thread A is unable to modify locks created by
22778 ** thread B, we have to keep track of which thread created each
22779 ** lock.  Hence there is an extra field in the key to the unixLockInfo
22780 ** structure to record this information.  And on those systems it
22781 ** is illegal to begin a transaction in one thread and finish it
22782 ** in another.  For this latter restriction, there is no work-around.
22783 ** It is a limitation of LinuxThreads.
22784 */
22785
22786 /*
22787 ** Set or check the unixFile.tid field.  This field is set when an unixFile
22788 ** is first opened.  All subsequent uses of the unixFile verify that the
22789 ** same thread is operating on the unixFile.  Some operating systems do
22790 ** not allow locks to be overridden by other threads and that restriction
22791 ** means that sqlite3* database handles cannot be moved from one thread
22792 ** to another while locks are held.
22793 **
22794 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22795 ** another as long as we are running on a system that supports threads
22796 ** overriding each others locks (which is now the most common behavior)
22797 ** or if no locks are held.  But the unixFile.pLock field needs to be
22798 ** recomputed because its key includes the thread-id.  See the 
22799 ** transferOwnership() function below for additional information
22800 */
22801 #if SQLITE_THREADSAFE && defined(__linux__)
22802 # define SET_THREADID(X)   (X)->tid = pthread_self()
22803 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22804                             !pthread_equal((X)->tid, pthread_self()))
22805 #else
22806 # define SET_THREADID(X)
22807 # define CHECK_THREADID(X) 0
22808 #endif
22809
22810 /*
22811 ** An instance of the following structure serves as the key used
22812 ** to locate a particular unixOpenCnt structure given its inode.  This
22813 ** is the same as the unixLockKey except that the thread ID is omitted.
22814 */
22815 struct unixFileId {
22816   dev_t dev;                  /* Device number */
22817 #if OS_VXWORKS
22818   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22819 #else
22820   ino_t ino;                  /* Inode number */
22821 #endif
22822 };
22823
22824 /*
22825 ** An instance of the following structure serves as the key used
22826 ** to locate a particular unixLockInfo structure given its inode.
22827 **
22828 ** If threads cannot override each others locks (LinuxThreads), then we
22829 ** set the unixLockKey.tid field to the thread ID.  If threads can override
22830 ** each others locks (Posix and NPTL) then tid is always set to zero.
22831 ** tid is omitted if we compile without threading support or on an OS
22832 ** other than linux.
22833 */
22834 struct unixLockKey {
22835   struct unixFileId fid;  /* Unique identifier for the file */
22836 #if SQLITE_THREADSAFE && defined(__linux__)
22837   pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22838 #endif
22839 };
22840
22841 /*
22842 ** An instance of the following structure is allocated for each open
22843 ** inode.  Or, on LinuxThreads, there is one of these structures for
22844 ** each inode opened by each thread.
22845 **
22846 ** A single inode can have multiple file descriptors, so each unixFile
22847 ** structure contains a pointer to an instance of this object and this
22848 ** object keeps a count of the number of unixFile pointing to it.
22849 */
22850 struct unixLockInfo {
22851   struct unixLockKey lockKey;     /* The lookup key */
22852   int cnt;                        /* Number of SHARED locks held */
22853   int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22854   int nRef;                       /* Number of pointers to this structure */
22855   struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22856   struct unixLockInfo *pPrev;     /*    .... doubly linked */
22857 };
22858
22859 /*
22860 ** An instance of the following structure is allocated for each open
22861 ** inode.  This structure keeps track of the number of locks on that
22862 ** inode.  If a close is attempted against an inode that is holding
22863 ** locks, the close is deferred until all locks clear by adding the
22864 ** file descriptor to be closed to the pending list.
22865 **
22866 ** TODO:  Consider changing this so that there is only a single file
22867 ** descriptor for each open file, even when it is opened multiple times.
22868 ** The close() system call would only occur when the last database
22869 ** using the file closes.
22870 */
22871 struct unixOpenCnt {
22872   struct unixFileId fileId;   /* The lookup key */
22873   int nRef;                   /* Number of pointers to this structure */
22874   int nLock;                  /* Number of outstanding locks */
22875   int nPending;               /* Number of pending close() operations */
22876   int *aPending;            /* Malloced space holding fd's awaiting a close() */
22877 #if OS_VXWORKS
22878   sem_t *pSem;                     /* Named POSIX semaphore */
22879   char aSemName[MAX_PATHNAME+1];   /* Name of that semaphore */
22880 #endif
22881   struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22882 };
22883
22884 /*
22885 ** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22886 ** tables.  But the number of objects is rarely more than a dozen and
22887 ** never exceeds a few thousand.  And lookup is not on a critical
22888 ** path so a simple linked list will suffice.
22889 */
22890 static struct unixLockInfo *lockList = 0;
22891 static struct unixOpenCnt *openList = 0;
22892
22893 /*
22894 ** This variable remembers whether or not threads can override each others
22895 ** locks.
22896 **
22897 **    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22898 **    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22899 **   -1:  We don't know yet.
22900 **
22901 ** On some systems, we know at compile-time if threads can override each
22902 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22903 ** will be set appropriately.  On other systems, we have to check at
22904 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22905 ** undefined.
22906 **
22907 ** This variable normally has file scope only.  But during testing, we make
22908 ** it a global so that the test code can change its value in order to verify
22909 ** that the right stuff happens in either case.
22910 */
22911 #if SQLITE_THREADSAFE && defined(__linux__)
22912 #  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22913 #    define SQLITE_THREAD_OVERRIDE_LOCK -1
22914 #  endif
22915 #  ifdef SQLITE_TEST
22916 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22917 #  else
22918 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22919 #  endif
22920 #endif
22921
22922 /*
22923 ** This structure holds information passed into individual test
22924 ** threads by the testThreadLockingBehavior() routine.
22925 */
22926 struct threadTestData {
22927   int fd;                /* File to be locked */
22928   struct flock lock;     /* The locking operation */
22929   int result;            /* Result of the locking operation */
22930 };
22931
22932 #if SQLITE_THREADSAFE && defined(__linux__)
22933 /*
22934 ** This function is used as the main routine for a thread launched by
22935 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22936 ** by the main thread in testThreadLockingBehavior() conflicts with a
22937 ** hypothetical write-lock obtained by this thread on the same file.
22938 **
22939 ** The write-lock is not actually acquired, as this is not possible if 
22940 ** the file is open in read-only mode (see ticket #3472).
22941 */ 
22942 static void *threadLockingTest(void *pArg){
22943   struct threadTestData *pData = (struct threadTestData*)pArg;
22944   pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22945   return pArg;
22946 }
22947 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
22948
22949
22950 #if SQLITE_THREADSAFE && defined(__linux__)
22951 /*
22952 ** This procedure attempts to determine whether or not threads
22953 ** can override each others locks then sets the 
22954 ** threadsOverrideEachOthersLocks variable appropriately.
22955 */
22956 static void testThreadLockingBehavior(int fd_orig){
22957   int fd;
22958   int rc;
22959   struct threadTestData d;
22960   struct flock l;
22961   pthread_t t;
22962
22963   fd = dup(fd_orig);
22964   if( fd<0 ) return;
22965   memset(&l, 0, sizeof(l));
22966   l.l_type = F_RDLCK;
22967   l.l_len = 1;
22968   l.l_start = 0;
22969   l.l_whence = SEEK_SET;
22970   rc = fcntl(fd_orig, F_SETLK, &l);
22971   if( rc!=0 ) return;
22972   memset(&d, 0, sizeof(d));
22973   d.fd = fd;
22974   d.lock = l;
22975   d.lock.l_type = F_WRLCK;
22976   pthread_create(&t, 0, threadLockingTest, &d);
22977   pthread_join(t, 0);
22978   close(fd);
22979   if( d.result!=0 ) return;
22980   threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22981 }
22982 #endif /* SQLITE_THERADSAFE && defined(__linux__) */
22983
22984 /*
22985 ** Release a unixLockInfo structure previously allocated by findLockInfo().
22986 */
22987 static void releaseLockInfo(struct unixLockInfo *pLock){
22988   if( pLock ){
22989     pLock->nRef--;
22990     if( pLock->nRef==0 ){
22991       if( pLock->pPrev ){
22992         assert( pLock->pPrev->pNext==pLock );
22993         pLock->pPrev->pNext = pLock->pNext;
22994       }else{
22995         assert( lockList==pLock );
22996         lockList = pLock->pNext;
22997       }
22998       if( pLock->pNext ){
22999         assert( pLock->pNext->pPrev==pLock );
23000         pLock->pNext->pPrev = pLock->pPrev;
23001       }
23002       sqlite3_free(pLock);
23003     }
23004   }
23005 }
23006
23007 /*
23008 ** Release a unixOpenCnt structure previously allocated by findLockInfo().
23009 */
23010 static void releaseOpenCnt(struct unixOpenCnt *pOpen){
23011   if( pOpen ){
23012     pOpen->nRef--;
23013     if( pOpen->nRef==0 ){
23014       if( pOpen->pPrev ){
23015         assert( pOpen->pPrev->pNext==pOpen );
23016         pOpen->pPrev->pNext = pOpen->pNext;
23017       }else{
23018         assert( openList==pOpen );
23019         openList = pOpen->pNext;
23020       }
23021       if( pOpen->pNext ){
23022         assert( pOpen->pNext->pPrev==pOpen );
23023         pOpen->pNext->pPrev = pOpen->pPrev;
23024       }
23025       sqlite3_free(pOpen->aPending);
23026       sqlite3_free(pOpen);
23027     }
23028   }
23029 }
23030
23031 /*
23032 ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
23033 ** describes that file descriptor.  Create new ones if necessary.  The
23034 ** return values might be uninitialized if an error occurs.
23035 **
23036 ** Return an appropriate error code.
23037 */
23038 static int findLockInfo(
23039   unixFile *pFile,               /* Unix file with file desc used in the key */
23040   struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
23041   struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
23042 ){
23043   int rc;                        /* System call return code */
23044   int fd;                        /* The file descriptor for pFile */
23045   struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
23046   struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
23047   struct stat statbuf;           /* Low-level file information */
23048   struct unixLockInfo *pLock;    /* Candidate unixLockInfo object */
23049   struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
23050
23051   /* Get low-level information about the file that we can used to
23052   ** create a unique name for the file.
23053   */
23054   fd = pFile->h;
23055   rc = fstat(fd, &statbuf);
23056   if( rc!=0 ){
23057     pFile->lastErrno = errno;
23058 #ifdef EOVERFLOW
23059     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23060 #endif
23061     return SQLITE_IOERR;
23062   }
23063
23064 #ifdef __APPLE__
23065   /* On OS X on an msdos filesystem, the inode number is reported
23066   ** incorrectly for zero-size files.  See ticket #3260.  To work
23067   ** around this problem (we consider it a bug in OS X, not SQLite)
23068   ** we always increase the file size to 1 by writing a single byte
23069   ** prior to accessing the inode number.  The one byte written is
23070   ** an ASCII 'S' character which also happens to be the first byte
23071   ** in the header of every SQLite database.  In this way, if there
23072   ** is a race condition such that another thread has already populated
23073   ** the first page of the database, no damage is done.
23074   */
23075   if( statbuf.st_size==0 ){
23076     rc = write(fd, "S", 1);
23077     if( rc!=1 ){
23078       return SQLITE_IOERR;
23079     }
23080     rc = fstat(fd, &statbuf);
23081     if( rc!=0 ){
23082       pFile->lastErrno = errno;
23083       return SQLITE_IOERR;
23084     }
23085   }
23086 #endif
23087
23088   memset(&lockKey, 0, sizeof(lockKey));
23089   lockKey.fid.dev = statbuf.st_dev;
23090 #if OS_VXWORKS
23091   lockKey.fid.pId = pFile->pId;
23092 #else
23093   lockKey.fid.ino = statbuf.st_ino;
23094 #endif
23095 #if SQLITE_THREADSAFE && defined(__linux__)
23096   if( threadsOverrideEachOthersLocks<0 ){
23097     testThreadLockingBehavior(fd);
23098   }
23099   lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
23100 #endif
23101   fileId = lockKey.fid;
23102   if( ppLock!=0 ){
23103     pLock = lockList;
23104     while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
23105       pLock = pLock->pNext;
23106     }
23107     if( pLock==0 ){
23108       pLock = sqlite3_malloc( sizeof(*pLock) );
23109       if( pLock==0 ){
23110         rc = SQLITE_NOMEM;
23111         goto exit_findlockinfo;
23112       }
23113       pLock->lockKey = lockKey;
23114       pLock->nRef = 1;
23115       pLock->cnt = 0;
23116       pLock->locktype = 0;
23117       pLock->pNext = lockList;
23118       pLock->pPrev = 0;
23119       if( lockList ) lockList->pPrev = pLock;
23120       lockList = pLock;
23121     }else{
23122       pLock->nRef++;
23123     }
23124     *ppLock = pLock;
23125   }
23126   if( ppOpen!=0 ){
23127     pOpen = openList;
23128     while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
23129       pOpen = pOpen->pNext;
23130     }
23131     if( pOpen==0 ){
23132       pOpen = sqlite3_malloc( sizeof(*pOpen) );
23133       if( pOpen==0 ){
23134         releaseLockInfo(pLock);
23135         rc = SQLITE_NOMEM;
23136         goto exit_findlockinfo;
23137       }
23138       pOpen->fileId = fileId;
23139       pOpen->nRef = 1;
23140       pOpen->nLock = 0;
23141       pOpen->nPending = 0;
23142       pOpen->aPending = 0;
23143       pOpen->pNext = openList;
23144       pOpen->pPrev = 0;
23145       if( openList ) openList->pPrev = pOpen;
23146       openList = pOpen;
23147 #if OS_VXWORKS
23148       pOpen->pSem = NULL;
23149       pOpen->aSemName[0] = '\0';
23150 #endif
23151     }else{
23152       pOpen->nRef++;
23153     }
23154     *ppOpen = pOpen;
23155   }
23156
23157 exit_findlockinfo:
23158   return rc;
23159 }
23160
23161 /*
23162 ** If we are currently in a different thread than the thread that the
23163 ** unixFile argument belongs to, then transfer ownership of the unixFile
23164 ** over to the current thread.
23165 **
23166 ** A unixFile is only owned by a thread on systems that use LinuxThreads.
23167 **
23168 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
23169 ** If the unixFile is locked and an ownership is wrong, then return
23170 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
23171 */
23172 #if SQLITE_THREADSAFE && defined(__linux__)
23173 static int transferOwnership(unixFile *pFile){
23174   int rc;
23175   pthread_t hSelf;
23176   if( threadsOverrideEachOthersLocks ){
23177     /* Ownership transfers not needed on this system */
23178     return SQLITE_OK;
23179   }
23180   hSelf = pthread_self();
23181   if( pthread_equal(pFile->tid, hSelf) ){
23182     /* We are still in the same thread */
23183     OSTRACE1("No-transfer, same thread\n");
23184     return SQLITE_OK;
23185   }
23186   if( pFile->locktype!=NO_LOCK ){
23187     /* We cannot change ownership while we are holding a lock! */
23188     return SQLITE_MISUSE;
23189   }
23190   OSTRACE4("Transfer ownership of %d from %d to %d\n",
23191             pFile->h, pFile->tid, hSelf);
23192   pFile->tid = hSelf;
23193   if (pFile->pLock != NULL) {
23194     releaseLockInfo(pFile->pLock);
23195     rc = findLockInfo(pFile, &pFile->pLock, 0);
23196     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
23197            locktypeName(pFile->locktype),
23198            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
23199     return rc;
23200   } else {
23201     return SQLITE_OK;
23202   }
23203 }
23204 #else  /* if not SQLITE_THREADSAFE */
23205   /* On single-threaded builds, ownership transfer is a no-op */
23206 # define transferOwnership(X) SQLITE_OK
23207 #endif /* SQLITE_THREADSAFE */
23208
23209
23210 /*
23211 ** This routine checks if there is a RESERVED lock held on the specified
23212 ** file by this or any other process. If such a lock is held, set *pResOut
23213 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23214 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23215 */
23216 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23217   int rc = SQLITE_OK;
23218   int reserved = 0;
23219   unixFile *pFile = (unixFile*)id;
23220
23221   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23222
23223   assert( pFile );
23224   unixEnterMutex(); /* Because pFile->pLock is shared across threads */
23225
23226   /* Check if a thread in this process holds such a lock */
23227   if( pFile->pLock->locktype>SHARED_LOCK ){
23228     reserved = 1;
23229   }
23230
23231   /* Otherwise see if some other process holds it.
23232   */
23233 #ifndef __DJGPP__
23234   if( !reserved ){
23235     struct flock lock;
23236     lock.l_whence = SEEK_SET;
23237     lock.l_start = RESERVED_BYTE;
23238     lock.l_len = 1;
23239     lock.l_type = F_WRLCK;
23240     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23241       int tErrno = errno;
23242       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23243       pFile->lastErrno = tErrno;
23244     } else if( lock.l_type!=F_UNLCK ){
23245       reserved = 1;
23246     }
23247   }
23248 #endif
23249   
23250   unixLeaveMutex();
23251   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23252
23253   *pResOut = reserved;
23254   return rc;
23255 }
23256
23257 /*
23258 ** Lock the file with the lock specified by parameter locktype - one
23259 ** of the following:
23260 **
23261 **     (1) SHARED_LOCK
23262 **     (2) RESERVED_LOCK
23263 **     (3) PENDING_LOCK
23264 **     (4) EXCLUSIVE_LOCK
23265 **
23266 ** Sometimes when requesting one lock state, additional lock states
23267 ** are inserted in between.  The locking might fail on one of the later
23268 ** transitions leaving the lock state different from what it started but
23269 ** still short of its goal.  The following chart shows the allowed
23270 ** transitions and the inserted intermediate states:
23271 **
23272 **    UNLOCKED -> SHARED
23273 **    SHARED -> RESERVED
23274 **    SHARED -> (PENDING) -> EXCLUSIVE
23275 **    RESERVED -> (PENDING) -> EXCLUSIVE
23276 **    PENDING -> EXCLUSIVE
23277 **
23278 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23279 ** routine to lower a locking level.
23280 */
23281 static int unixLock(sqlite3_file *id, int locktype){
23282   /* The following describes the implementation of the various locks and
23283   ** lock transitions in terms of the POSIX advisory shared and exclusive
23284   ** lock primitives (called read-locks and write-locks below, to avoid
23285   ** confusion with SQLite lock names). The algorithms are complicated
23286   ** slightly in order to be compatible with windows systems simultaneously
23287   ** accessing the same database file, in case that is ever required.
23288   **
23289   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23290   ** byte', each single bytes at well known offsets, and the 'shared byte
23291   ** range', a range of 510 bytes at a well known offset.
23292   **
23293   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23294   ** byte'.  If this is successful, a random byte from the 'shared byte
23295   ** range' is read-locked and the lock on the 'pending byte' released.
23296   **
23297   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23298   ** A RESERVED lock is implemented by grabbing a write-lock on the
23299   ** 'reserved byte'. 
23300   **
23301   ** A process may only obtain a PENDING lock after it has obtained a
23302   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23303   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23304   ** obtained, but existing SHARED locks are allowed to persist. A process
23305   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23306   ** This property is used by the algorithm for rolling back a journal file
23307   ** after a crash.
23308   **
23309   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23310   ** implemented by obtaining a write-lock on the entire 'shared byte
23311   ** range'. Since all other locks require a read-lock on one of the bytes
23312   ** within this range, this ensures that no other locks are held on the
23313   ** database. 
23314   **
23315   ** The reason a single byte cannot be used instead of the 'shared byte
23316   ** range' is that some versions of windows do not support read-locks. By
23317   ** locking a random byte from a range, concurrent SHARED locks may exist
23318   ** even if the locking primitive used is always a write-lock.
23319   */
23320   int rc = SQLITE_OK;
23321   unixFile *pFile = (unixFile*)id;
23322   struct unixLockInfo *pLock = pFile->pLock;
23323   struct flock lock;
23324   int s;
23325
23326   assert( pFile );
23327   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
23328       locktypeName(locktype), locktypeName(pFile->locktype),
23329       locktypeName(pLock->locktype), pLock->cnt , getpid());
23330
23331   /* If there is already a lock of this type or more restrictive on the
23332   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23333   ** unixEnterMutex() hasn't been called yet.
23334   */
23335   if( pFile->locktype>=locktype ){
23336     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
23337             locktypeName(locktype));
23338     return SQLITE_OK;
23339   }
23340
23341   /* Make sure the locking sequence is correct
23342   */
23343   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23344   assert( locktype!=PENDING_LOCK );
23345   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23346
23347   /* This mutex is needed because pFile->pLock is shared across threads
23348   */
23349   unixEnterMutex();
23350
23351   /* Make sure the current thread owns the pFile.
23352   */
23353   rc = transferOwnership(pFile);
23354   if( rc!=SQLITE_OK ){
23355     unixLeaveMutex();
23356     return rc;
23357   }
23358   pLock = pFile->pLock;
23359
23360   /* If some thread using this PID has a lock via a different unixFile*
23361   ** handle that precludes the requested lock, return BUSY.
23362   */
23363   if( (pFile->locktype!=pLock->locktype && 
23364           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23365   ){
23366     rc = SQLITE_BUSY;
23367     goto end_lock;
23368   }
23369
23370   /* If a SHARED lock is requested, and some thread using this PID already
23371   ** has a SHARED or RESERVED lock, then increment reference counts and
23372   ** return SQLITE_OK.
23373   */
23374   if( locktype==SHARED_LOCK && 
23375       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23376     assert( locktype==SHARED_LOCK );
23377     assert( pFile->locktype==0 );
23378     assert( pLock->cnt>0 );
23379     pFile->locktype = SHARED_LOCK;
23380     pLock->cnt++;
23381     pFile->pOpen->nLock++;
23382     goto end_lock;
23383   }
23384
23385   lock.l_len = 1L;
23386
23387   lock.l_whence = SEEK_SET;
23388
23389   /* A PENDING lock is needed before acquiring a SHARED lock and before
23390   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23391   ** be released.
23392   */
23393   if( locktype==SHARED_LOCK 
23394       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23395   ){
23396     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23397     lock.l_start = PENDING_BYTE;
23398     s = fcntl(pFile->h, F_SETLK, &lock);
23399     if( s==(-1) ){
23400       int tErrno = errno;
23401       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23402       if( IS_LOCK_ERROR(rc) ){
23403         pFile->lastErrno = tErrno;
23404       }
23405       goto end_lock;
23406     }
23407   }
23408
23409
23410   /* If control gets to this point, then actually go ahead and make
23411   ** operating system calls for the specified lock.
23412   */
23413   if( locktype==SHARED_LOCK ){
23414     int tErrno = 0;
23415     assert( pLock->cnt==0 );
23416     assert( pLock->locktype==0 );
23417
23418     /* Now get the read-lock */
23419     lock.l_start = SHARED_FIRST;
23420     lock.l_len = SHARED_SIZE;
23421     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23422       tErrno = errno;
23423     }
23424     /* Drop the temporary PENDING lock */
23425     lock.l_start = PENDING_BYTE;
23426     lock.l_len = 1L;
23427     lock.l_type = F_UNLCK;
23428     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23429       if( s != -1 ){
23430         /* This could happen with a network mount */
23431         tErrno = errno; 
23432         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23433         if( IS_LOCK_ERROR(rc) ){
23434           pFile->lastErrno = tErrno;
23435         }
23436         goto end_lock;
23437       }
23438     }
23439     if( s==(-1) ){
23440       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23441       if( IS_LOCK_ERROR(rc) ){
23442         pFile->lastErrno = tErrno;
23443       }
23444     }else{
23445       pFile->locktype = SHARED_LOCK;
23446       pFile->pOpen->nLock++;
23447       pLock->cnt = 1;
23448     }
23449   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23450     /* We are trying for an exclusive lock but another thread in this
23451     ** same process is still holding a shared lock. */
23452     rc = SQLITE_BUSY;
23453   }else{
23454     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23455     ** assumed that there is a SHARED or greater lock on the file
23456     ** already.
23457     */
23458     assert( 0!=pFile->locktype );
23459     lock.l_type = F_WRLCK;
23460     switch( locktype ){
23461       case RESERVED_LOCK:
23462         lock.l_start = RESERVED_BYTE;
23463         break;
23464       case EXCLUSIVE_LOCK:
23465         lock.l_start = SHARED_FIRST;
23466         lock.l_len = SHARED_SIZE;
23467         break;
23468       default:
23469         assert(0);
23470     }
23471     s = fcntl(pFile->h, F_SETLK, &lock);
23472     if( s==(-1) ){
23473       int tErrno = errno;
23474       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23475       if( IS_LOCK_ERROR(rc) ){
23476         pFile->lastErrno = tErrno;
23477       }
23478     }
23479   }
23480   
23481
23482 #ifndef NDEBUG
23483   /* Set up the transaction-counter change checking flags when
23484   ** transitioning from a SHARED to a RESERVED lock.  The change
23485   ** from SHARED to RESERVED marks the beginning of a normal
23486   ** write operation (not a hot journal rollback).
23487   */
23488   if( rc==SQLITE_OK
23489    && pFile->locktype<=SHARED_LOCK
23490    && locktype==RESERVED_LOCK
23491   ){
23492     pFile->transCntrChng = 0;
23493     pFile->dbUpdate = 0;
23494     pFile->inNormalWrite = 1;
23495   }
23496 #endif
23497
23498
23499   if( rc==SQLITE_OK ){
23500     pFile->locktype = locktype;
23501     pLock->locktype = locktype;
23502   }else if( locktype==EXCLUSIVE_LOCK ){
23503     pFile->locktype = PENDING_LOCK;
23504     pLock->locktype = PENDING_LOCK;
23505   }
23506
23507 end_lock:
23508   unixLeaveMutex();
23509   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
23510       rc==SQLITE_OK ? "ok" : "failed");
23511   return rc;
23512 }
23513
23514 /*
23515 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23516 ** must be either NO_LOCK or SHARED_LOCK.
23517 **
23518 ** If the locking level of the file descriptor is already at or below
23519 ** the requested locking level, this routine is a no-op.
23520 */
23521 static int unixUnlock(sqlite3_file *id, int locktype){
23522   struct unixLockInfo *pLock;
23523   struct flock lock;
23524   int rc = SQLITE_OK;
23525   unixFile *pFile = (unixFile*)id;
23526   int h;
23527
23528   assert( pFile );
23529   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
23530       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23531
23532   assert( locktype<=SHARED_LOCK );
23533   if( pFile->locktype<=locktype ){
23534     return SQLITE_OK;
23535   }
23536   if( CHECK_THREADID(pFile) ){
23537     return SQLITE_MISUSE;
23538   }
23539   unixEnterMutex();
23540   h = pFile->h;
23541   pLock = pFile->pLock;
23542   assert( pLock->cnt!=0 );
23543   if( pFile->locktype>SHARED_LOCK ){
23544     assert( pLock->locktype==pFile->locktype );
23545     SimulateIOErrorBenign(1);
23546     SimulateIOError( h=(-1) )
23547     SimulateIOErrorBenign(0);
23548
23549 #ifndef NDEBUG
23550     /* When reducing a lock such that other processes can start
23551     ** reading the database file again, make sure that the
23552     ** transaction counter was updated if any part of the database
23553     ** file changed.  If the transaction counter is not updated,
23554     ** other connections to the same file might not realize that
23555     ** the file has changed and hence might not know to flush their
23556     ** cache.  The use of a stale cache can lead to database corruption.
23557     */
23558     assert( pFile->inNormalWrite==0
23559          || pFile->dbUpdate==0
23560          || pFile->transCntrChng==1 );
23561     pFile->inNormalWrite = 0;
23562 #endif
23563
23564
23565     if( locktype==SHARED_LOCK ){
23566       lock.l_type = F_RDLCK;
23567       lock.l_whence = SEEK_SET;
23568       lock.l_start = SHARED_FIRST;
23569       lock.l_len = SHARED_SIZE;
23570       if( fcntl(h, F_SETLK, &lock)==(-1) ){
23571         int tErrno = errno;
23572         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23573         if( IS_LOCK_ERROR(rc) ){
23574           pFile->lastErrno = tErrno;
23575         }
23576         goto end_unlock;
23577       }
23578     }
23579     lock.l_type = F_UNLCK;
23580     lock.l_whence = SEEK_SET;
23581     lock.l_start = PENDING_BYTE;
23582     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23583     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23584       pLock->locktype = SHARED_LOCK;
23585     }else{
23586       int tErrno = errno;
23587       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23588       if( IS_LOCK_ERROR(rc) ){
23589         pFile->lastErrno = tErrno;
23590       }
23591                         goto end_unlock;
23592     }
23593   }
23594   if( locktype==NO_LOCK ){
23595     struct unixOpenCnt *pOpen;
23596
23597     /* Decrement the shared lock counter.  Release the lock using an
23598     ** OS call only when all threads in this same process have released
23599     ** the lock.
23600     */
23601     pLock->cnt--;
23602     if( pLock->cnt==0 ){
23603       lock.l_type = F_UNLCK;
23604       lock.l_whence = SEEK_SET;
23605       lock.l_start = lock.l_len = 0L;
23606       SimulateIOErrorBenign(1);
23607       SimulateIOError( h=(-1) )
23608       SimulateIOErrorBenign(0);
23609       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23610         pLock->locktype = NO_LOCK;
23611       }else{
23612         int tErrno = errno;
23613         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23614         if( IS_LOCK_ERROR(rc) ){
23615           pFile->lastErrno = tErrno;
23616         }
23617         pLock->cnt = 1;
23618                                 goto end_unlock;
23619       }
23620     }
23621
23622     /* Decrement the count of locks against this same file.  When the
23623     ** count reaches zero, close any other file descriptors whose close
23624     ** was deferred because of outstanding locks.
23625     */
23626     if( rc==SQLITE_OK ){
23627       pOpen = pFile->pOpen;
23628       pOpen->nLock--;
23629       assert( pOpen->nLock>=0 );
23630       if( pOpen->nLock==0 && pOpen->nPending>0 ){
23631         int i;
23632         for(i=0; i<pOpen->nPending; i++){
23633           /* close pending fds, but if closing fails don't free the array
23634           ** assign -1 to the successfully closed descriptors and record the
23635           ** error.  The next attempt to unlock will try again. */
23636           if( pOpen->aPending[i] < 0 ) continue;
23637           if( close(pOpen->aPending[i]) ){
23638             pFile->lastErrno = errno;
23639             rc = SQLITE_IOERR_CLOSE;
23640           }else{
23641             pOpen->aPending[i] = -1;
23642           }
23643         }
23644         if( rc==SQLITE_OK ){
23645           sqlite3_free(pOpen->aPending);
23646           pOpen->nPending = 0;
23647           pOpen->aPending = 0;
23648         }
23649       }
23650     }
23651   }
23652         
23653 end_unlock:
23654   unixLeaveMutex();
23655   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23656   return rc;
23657 }
23658
23659 /*
23660 ** This function performs the parts of the "close file" operation 
23661 ** common to all locking schemes. It closes the directory and file
23662 ** handles, if they are valid, and sets all fields of the unixFile
23663 ** structure to 0.
23664 **
23665 ** It is *not* necessary to hold the mutex when this routine is called,
23666 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
23667 ** vxworksReleaseFileId() routine.
23668 */
23669 static int closeUnixFile(sqlite3_file *id){
23670   unixFile *pFile = (unixFile*)id;
23671   if( pFile ){
23672     if( pFile->dirfd>=0 ){
23673       int err = close(pFile->dirfd);
23674       if( err ){
23675         pFile->lastErrno = errno;
23676         return SQLITE_IOERR_DIR_CLOSE;
23677       }else{
23678         pFile->dirfd=-1;
23679       }
23680     }
23681     if( pFile->h>=0 ){
23682       int err = close(pFile->h);
23683       if( err ){
23684         pFile->lastErrno = errno;
23685         return SQLITE_IOERR_CLOSE;
23686       }
23687     }
23688 #if OS_VXWORKS
23689     if( pFile->pId ){
23690       if( pFile->isDelete ){
23691         unlink(pFile->pId->zCanonicalName);
23692       }
23693       vxworksReleaseFileId(pFile->pId);
23694       pFile->pId = 0;
23695     }
23696 #endif
23697     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23698     OpenCounter(-1);
23699     memset(pFile, 0, sizeof(unixFile));
23700   }
23701   return SQLITE_OK;
23702 }
23703
23704 /*
23705 ** Close a file.
23706 */
23707 static int unixClose(sqlite3_file *id){
23708   int rc = SQLITE_OK;
23709   if( id ){
23710     unixFile *pFile = (unixFile *)id;
23711     unixUnlock(id, NO_LOCK);
23712     unixEnterMutex();
23713     if( pFile->pOpen && pFile->pOpen->nLock ){
23714       /* If there are outstanding locks, do not actually close the file just
23715       ** yet because that would clear those locks.  Instead, add the file
23716       ** descriptor to pOpen->aPending.  It will be automatically closed when
23717       ** the last lock is cleared.
23718       */
23719       int *aNew;
23720       struct unixOpenCnt *pOpen = pFile->pOpen;
23721       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
23722       if( aNew==0 ){
23723         /* If a malloc fails, just leak the file descriptor */
23724       }else{
23725         pOpen->aPending = aNew;
23726         pOpen->aPending[pOpen->nPending] = pFile->h;
23727         pOpen->nPending++;
23728         pFile->h = -1;
23729       }
23730     }
23731     releaseLockInfo(pFile->pLock);
23732     releaseOpenCnt(pFile->pOpen);
23733     rc = closeUnixFile(id);
23734     unixLeaveMutex();
23735   }
23736   return rc;
23737 }
23738
23739 /************** End of the posix advisory lock implementation *****************
23740 ******************************************************************************/
23741
23742 /******************************************************************************
23743 ****************************** No-op Locking **********************************
23744 **
23745 ** Of the various locking implementations available, this is by far the
23746 ** simplest:  locking is ignored.  No attempt is made to lock the database
23747 ** file for reading or writing.
23748 **
23749 ** This locking mode is appropriate for use on read-only databases
23750 ** (ex: databases that are burned into CD-ROM, for example.)  It can
23751 ** also be used if the application employs some external mechanism to
23752 ** prevent simultaneous access of the same database by two or more
23753 ** database connections.  But there is a serious risk of database
23754 ** corruption if this locking mode is used in situations where multiple
23755 ** database connections are accessing the same database file at the same
23756 ** time and one or more of those connections are writing.
23757 */
23758
23759 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23760   UNUSED_PARAMETER(NotUsed);
23761   *pResOut = 0;
23762   return SQLITE_OK;
23763 }
23764 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23765   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23766   return SQLITE_OK;
23767 }
23768 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23769   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23770   return SQLITE_OK;
23771 }
23772
23773 /*
23774 ** Close the file.
23775 */
23776 static int nolockClose(sqlite3_file *id) {
23777   return closeUnixFile(id);
23778 }
23779
23780 /******************* End of the no-op lock implementation *********************
23781 ******************************************************************************/
23782
23783 /******************************************************************************
23784 ************************* Begin dot-file Locking ******************************
23785 **
23786 ** The dotfile locking implementation uses the existing of separate lock
23787 ** files in order to control access to the database.  This works on just
23788 ** about every filesystem imaginable.  But there are serious downsides:
23789 **
23790 **    (1)  There is zero concurrency.  A single reader blocks all other
23791 **         connections from reading or writing the database.
23792 **
23793 **    (2)  An application crash or power loss can leave stale lock files
23794 **         sitting around that need to be cleared manually.
23795 **
23796 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
23797 ** other locking strategy is available.
23798 **
23799 ** Dotfile locking works by creating a file in the same directory as the
23800 ** database and with the same name but with a ".lock" extension added.
23801 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23802 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23803 */
23804
23805 /*
23806 ** The file suffix added to the data base filename in order to create the
23807 ** lock file.
23808 */
23809 #define DOTLOCK_SUFFIX ".lock"
23810
23811 /*
23812 ** This routine checks if there is a RESERVED lock held on the specified
23813 ** file by this or any other process. If such a lock is held, set *pResOut
23814 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23815 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23816 **
23817 ** In dotfile locking, either a lock exists or it does not.  So in this
23818 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
23819 ** is held on the file and false if the file is unlocked.
23820 */
23821 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23822   int rc = SQLITE_OK;
23823   int reserved = 0;
23824   unixFile *pFile = (unixFile*)id;
23825
23826   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23827   
23828   assert( pFile );
23829
23830   /* Check if a thread in this process holds such a lock */
23831   if( pFile->locktype>SHARED_LOCK ){
23832     /* Either this connection or some other connection in the same process
23833     ** holds a lock on the file.  No need to check further. */
23834     reserved = 1;
23835   }else{
23836     /* The lock is held if and only if the lockfile exists */
23837     const char *zLockFile = (const char*)pFile->lockingContext;
23838     reserved = access(zLockFile, 0)==0;
23839   }
23840   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
23841   *pResOut = reserved;
23842   return rc;
23843 }
23844
23845 /*
23846 ** Lock the file with the lock specified by parameter locktype - one
23847 ** of the following:
23848 **
23849 **     (1) SHARED_LOCK
23850 **     (2) RESERVED_LOCK
23851 **     (3) PENDING_LOCK
23852 **     (4) EXCLUSIVE_LOCK
23853 **
23854 ** Sometimes when requesting one lock state, additional lock states
23855 ** are inserted in between.  The locking might fail on one of the later
23856 ** transitions leaving the lock state different from what it started but
23857 ** still short of its goal.  The following chart shows the allowed
23858 ** transitions and the inserted intermediate states:
23859 **
23860 **    UNLOCKED -> SHARED
23861 **    SHARED -> RESERVED
23862 **    SHARED -> (PENDING) -> EXCLUSIVE
23863 **    RESERVED -> (PENDING) -> EXCLUSIVE
23864 **    PENDING -> EXCLUSIVE
23865 **
23866 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23867 ** routine to lower a locking level.
23868 **
23869 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
23870 ** But we track the other locking levels internally.
23871 */
23872 static int dotlockLock(sqlite3_file *id, int locktype) {
23873   unixFile *pFile = (unixFile*)id;
23874   int fd;
23875   char *zLockFile = (char *)pFile->lockingContext;
23876   int rc = SQLITE_OK;
23877
23878
23879   /* If we have any lock, then the lock file already exists.  All we have
23880   ** to do is adjust our internal record of the lock level.
23881   */
23882   if( pFile->locktype > NO_LOCK ){
23883     pFile->locktype = locktype;
23884 #if !OS_VXWORKS
23885     /* Always update the timestamp on the old file */
23886     utimes(zLockFile, NULL);
23887 #endif
23888     return SQLITE_OK;
23889   }
23890   
23891   /* grab an exclusive lock */
23892   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23893   if( fd<0 ){
23894     /* failed to open/create the file, someone else may have stolen the lock */
23895     int tErrno = errno;
23896     if( EEXIST == tErrno ){
23897       rc = SQLITE_BUSY;
23898     } else {
23899       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23900       if( IS_LOCK_ERROR(rc) ){
23901         pFile->lastErrno = tErrno;
23902       }
23903     }
23904     return rc;
23905   } 
23906   if( close(fd) ){
23907     pFile->lastErrno = errno;
23908     rc = SQLITE_IOERR_CLOSE;
23909   }
23910   
23911   /* got it, set the type and return ok */
23912   pFile->locktype = locktype;
23913   return rc;
23914 }
23915
23916 /*
23917 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23918 ** must be either NO_LOCK or SHARED_LOCK.
23919 **
23920 ** If the locking level of the file descriptor is already at or below
23921 ** the requested locking level, this routine is a no-op.
23922 **
23923 ** When the locking level reaches NO_LOCK, delete the lock file.
23924 */
23925 static int dotlockUnlock(sqlite3_file *id, int locktype) {
23926   unixFile *pFile = (unixFile*)id;
23927   char *zLockFile = (char *)pFile->lockingContext;
23928
23929   assert( pFile );
23930   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
23931            pFile->locktype, getpid());
23932   assert( locktype<=SHARED_LOCK );
23933   
23934   /* no-op if possible */
23935   if( pFile->locktype==locktype ){
23936     return SQLITE_OK;
23937   }
23938
23939   /* To downgrade to shared, simply update our internal notion of the
23940   ** lock state.  No need to mess with the file on disk.
23941   */
23942   if( locktype==SHARED_LOCK ){
23943     pFile->locktype = SHARED_LOCK;
23944     return SQLITE_OK;
23945   }
23946   
23947   /* To fully unlock the database, delete the lock file */
23948   assert( locktype==NO_LOCK );
23949   if( unlink(zLockFile) ){
23950     int rc, tErrno = errno;
23951     if( ENOENT != tErrno ){
23952       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23953     }
23954     if( IS_LOCK_ERROR(rc) ){
23955       pFile->lastErrno = tErrno;
23956     }
23957     return rc; 
23958   }
23959   pFile->locktype = NO_LOCK;
23960   return SQLITE_OK;
23961 }
23962
23963 /*
23964 ** Close a file.  Make sure the lock has been released before closing.
23965 */
23966 static int dotlockClose(sqlite3_file *id) {
23967   int rc;
23968   if( id ){
23969     unixFile *pFile = (unixFile*)id;
23970     dotlockUnlock(id, NO_LOCK);
23971     sqlite3_free(pFile->lockingContext);
23972   }
23973   rc = closeUnixFile(id);
23974   return rc;
23975 }
23976 /****************** End of the dot-file lock implementation *******************
23977 ******************************************************************************/
23978
23979 /******************************************************************************
23980 ************************** Begin flock Locking ********************************
23981 **
23982 ** Use the flock() system call to do file locking.
23983 **
23984 ** flock() locking is like dot-file locking in that the various
23985 ** fine-grain locking levels supported by SQLite are collapsed into
23986 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
23987 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23988 ** still works when you do this, but concurrency is reduced since
23989 ** only a single process can be reading the database at a time.
23990 **
23991 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23992 ** compiling for VXWORKS.
23993 */
23994 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23995
23996 /*
23997 ** This routine checks if there is a RESERVED lock held on the specified
23998 ** file by this or any other process. If such a lock is held, set *pResOut
23999 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24000 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24001 */
24002 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24003   int rc = SQLITE_OK;
24004   int reserved = 0;
24005   unixFile *pFile = (unixFile*)id;
24006   
24007   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24008   
24009   assert( pFile );
24010   
24011   /* Check if a thread in this process holds such a lock */
24012   if( pFile->locktype>SHARED_LOCK ){
24013     reserved = 1;
24014   }
24015   
24016   /* Otherwise see if some other process holds it. */
24017   if( !reserved ){
24018     /* attempt to get the lock */
24019     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24020     if( !lrc ){
24021       /* got the lock, unlock it */
24022       lrc = flock(pFile->h, LOCK_UN);
24023       if ( lrc ) {
24024         int tErrno = errno;
24025         /* unlock failed with an error */
24026         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24027         if( IS_LOCK_ERROR(lrc) ){
24028           pFile->lastErrno = tErrno;
24029           rc = lrc;
24030         }
24031       }
24032     } else {
24033       int tErrno = errno;
24034       reserved = 1;
24035       /* someone else might have it reserved */
24036       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24037       if( IS_LOCK_ERROR(lrc) ){
24038         pFile->lastErrno = tErrno;
24039         rc = lrc;
24040       }
24041     }
24042   }
24043   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
24044
24045 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24046   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24047     rc = SQLITE_OK;
24048     reserved=1;
24049   }
24050 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24051   *pResOut = reserved;
24052   return rc;
24053 }
24054
24055 /*
24056 ** Lock the file with the lock specified by parameter locktype - one
24057 ** of the following:
24058 **
24059 **     (1) SHARED_LOCK
24060 **     (2) RESERVED_LOCK
24061 **     (3) PENDING_LOCK
24062 **     (4) EXCLUSIVE_LOCK
24063 **
24064 ** Sometimes when requesting one lock state, additional lock states
24065 ** are inserted in between.  The locking might fail on one of the later
24066 ** transitions leaving the lock state different from what it started but
24067 ** still short of its goal.  The following chart shows the allowed
24068 ** transitions and the inserted intermediate states:
24069 **
24070 **    UNLOCKED -> SHARED
24071 **    SHARED -> RESERVED
24072 **    SHARED -> (PENDING) -> EXCLUSIVE
24073 **    RESERVED -> (PENDING) -> EXCLUSIVE
24074 **    PENDING -> EXCLUSIVE
24075 **
24076 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24077 ** lock states in the sqlite3_file structure, but all locks SHARED or
24078 ** above are really EXCLUSIVE locks and exclude all other processes from
24079 ** access the file.
24080 **
24081 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24082 ** routine to lower a locking level.
24083 */
24084 static int flockLock(sqlite3_file *id, int locktype) {
24085   int rc = SQLITE_OK;
24086   unixFile *pFile = (unixFile*)id;
24087
24088   assert( pFile );
24089
24090   /* if we already have a lock, it is exclusive.  
24091   ** Just adjust level and punt on outta here. */
24092   if (pFile->locktype > NO_LOCK) {
24093     pFile->locktype = locktype;
24094     return SQLITE_OK;
24095   }
24096   
24097   /* grab an exclusive lock */
24098   
24099   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24100     int tErrno = errno;
24101     /* didn't get, must be busy */
24102     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24103     if( IS_LOCK_ERROR(rc) ){
24104       pFile->lastErrno = tErrno;
24105     }
24106   } else {
24107     /* got it, set the type and return ok */
24108     pFile->locktype = locktype;
24109   }
24110   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
24111            rc==SQLITE_OK ? "ok" : "failed");
24112 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24113   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24114     rc = SQLITE_BUSY;
24115   }
24116 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24117   return rc;
24118 }
24119
24120
24121 /*
24122 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24123 ** must be either NO_LOCK or SHARED_LOCK.
24124 **
24125 ** If the locking level of the file descriptor is already at or below
24126 ** the requested locking level, this routine is a no-op.
24127 */
24128 static int flockUnlock(sqlite3_file *id, int locktype) {
24129   unixFile *pFile = (unixFile*)id;
24130   
24131   assert( pFile );
24132   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24133            pFile->locktype, getpid());
24134   assert( locktype<=SHARED_LOCK );
24135   
24136   /* no-op if possible */
24137   if( pFile->locktype==locktype ){
24138     return SQLITE_OK;
24139   }
24140   
24141   /* shared can just be set because we always have an exclusive */
24142   if (locktype==SHARED_LOCK) {
24143     pFile->locktype = locktype;
24144     return SQLITE_OK;
24145   }
24146   
24147   /* no, really, unlock. */
24148   int rc = flock(pFile->h, LOCK_UN);
24149   if (rc) {
24150     int r, tErrno = errno;
24151     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24152     if( IS_LOCK_ERROR(r) ){
24153       pFile->lastErrno = tErrno;
24154     }
24155 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24156     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24157       r = SQLITE_BUSY;
24158     }
24159 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24160     
24161     return r;
24162   } else {
24163     pFile->locktype = NO_LOCK;
24164     return SQLITE_OK;
24165   }
24166 }
24167
24168 /*
24169 ** Close a file.
24170 */
24171 static int flockClose(sqlite3_file *id) {
24172   if( id ){
24173     flockUnlock(id, NO_LOCK);
24174   }
24175   return closeUnixFile(id);
24176 }
24177
24178 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24179
24180 /******************* End of the flock lock implementation *********************
24181 ******************************************************************************/
24182
24183 /******************************************************************************
24184 ************************ Begin Named Semaphore Locking ************************
24185 **
24186 ** Named semaphore locking is only supported on VxWorks.
24187 **
24188 ** Semaphore locking is like dot-lock and flock in that it really only
24189 ** supports EXCLUSIVE locking.  Only a single process can read or write
24190 ** the database file at a time.  This reduces potential concurrency, but
24191 ** makes the lock implementation much easier.
24192 */
24193 #if OS_VXWORKS
24194
24195 /*
24196 ** This routine checks if there is a RESERVED lock held on the specified
24197 ** file by this or any other process. If such a lock is held, set *pResOut
24198 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24199 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24200 */
24201 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24202   int rc = SQLITE_OK;
24203   int reserved = 0;
24204   unixFile *pFile = (unixFile*)id;
24205
24206   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24207   
24208   assert( pFile );
24209
24210   /* Check if a thread in this process holds such a lock */
24211   if( pFile->locktype>SHARED_LOCK ){
24212     reserved = 1;
24213   }
24214   
24215   /* Otherwise see if some other process holds it. */
24216   if( !reserved ){
24217     sem_t *pSem = pFile->pOpen->pSem;
24218     struct stat statBuf;
24219
24220     if( sem_trywait(pSem)==-1 ){
24221       int tErrno = errno;
24222       if( EAGAIN != tErrno ){
24223         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24224         pFile->lastErrno = tErrno;
24225       } else {
24226         /* someone else has the lock when we are in NO_LOCK */
24227         reserved = (pFile->locktype < SHARED_LOCK);
24228       }
24229     }else{
24230       /* we could have it if we want it */
24231       sem_post(pSem);
24232     }
24233   }
24234   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
24235
24236   *pResOut = reserved;
24237   return rc;
24238 }
24239
24240 /*
24241 ** Lock the file with the lock specified by parameter locktype - one
24242 ** of the following:
24243 **
24244 **     (1) SHARED_LOCK
24245 **     (2) RESERVED_LOCK
24246 **     (3) PENDING_LOCK
24247 **     (4) EXCLUSIVE_LOCK
24248 **
24249 ** Sometimes when requesting one lock state, additional lock states
24250 ** are inserted in between.  The locking might fail on one of the later
24251 ** transitions leaving the lock state different from what it started but
24252 ** still short of its goal.  The following chart shows the allowed
24253 ** transitions and the inserted intermediate states:
24254 **
24255 **    UNLOCKED -> SHARED
24256 **    SHARED -> RESERVED
24257 **    SHARED -> (PENDING) -> EXCLUSIVE
24258 **    RESERVED -> (PENDING) -> EXCLUSIVE
24259 **    PENDING -> EXCLUSIVE
24260 **
24261 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24262 ** lock states in the sqlite3_file structure, but all locks SHARED or
24263 ** above are really EXCLUSIVE locks and exclude all other processes from
24264 ** access the file.
24265 **
24266 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24267 ** routine to lower a locking level.
24268 */
24269 static int semLock(sqlite3_file *id, int locktype) {
24270   unixFile *pFile = (unixFile*)id;
24271   int fd;
24272   sem_t *pSem = pFile->pOpen->pSem;
24273   int rc = SQLITE_OK;
24274
24275   /* if we already have a lock, it is exclusive.  
24276   ** Just adjust level and punt on outta here. */
24277   if (pFile->locktype > NO_LOCK) {
24278     pFile->locktype = locktype;
24279     rc = SQLITE_OK;
24280     goto sem_end_lock;
24281   }
24282   
24283   /* lock semaphore now but bail out when already locked. */
24284   if( sem_trywait(pSem)==-1 ){
24285     rc = SQLITE_BUSY;
24286     goto sem_end_lock;
24287   }
24288
24289   /* got it, set the type and return ok */
24290   pFile->locktype = locktype;
24291
24292  sem_end_lock:
24293   return rc;
24294 }
24295
24296 /*
24297 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24298 ** must be either NO_LOCK or SHARED_LOCK.
24299 **
24300 ** If the locking level of the file descriptor is already at or below
24301 ** the requested locking level, this routine is a no-op.
24302 */
24303 static int semUnlock(sqlite3_file *id, int locktype) {
24304   unixFile *pFile = (unixFile*)id;
24305   sem_t *pSem = pFile->pOpen->pSem;
24306
24307   assert( pFile );
24308   assert( pSem );
24309   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24310            pFile->locktype, getpid());
24311   assert( locktype<=SHARED_LOCK );
24312   
24313   /* no-op if possible */
24314   if( pFile->locktype==locktype ){
24315     return SQLITE_OK;
24316   }
24317   
24318   /* shared can just be set because we always have an exclusive */
24319   if (locktype==SHARED_LOCK) {
24320     pFile->locktype = locktype;
24321     return SQLITE_OK;
24322   }
24323   
24324   /* no, really unlock. */
24325   if ( sem_post(pSem)==-1 ) {
24326     int rc, tErrno = errno;
24327     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24328     if( IS_LOCK_ERROR(rc) ){
24329       pFile->lastErrno = tErrno;
24330     }
24331     return rc; 
24332   }
24333   pFile->locktype = NO_LOCK;
24334   return SQLITE_OK;
24335 }
24336
24337 /*
24338  ** Close a file.
24339  */
24340 static int semClose(sqlite3_file *id) {
24341   if( id ){
24342     unixFile *pFile = (unixFile*)id;
24343     semUnlock(id, NO_LOCK);
24344     assert( pFile );
24345     unixEnterMutex();
24346     releaseLockInfo(pFile->pLock);
24347     releaseOpenCnt(pFile->pOpen);
24348     closeUnixFile(id);
24349     unixLeaveMutex();
24350   }
24351   return SQLITE_OK;
24352 }
24353
24354 #endif /* OS_VXWORKS */
24355 /*
24356 ** Named semaphore locking is only available on VxWorks.
24357 **
24358 *************** End of the named semaphore lock implementation ****************
24359 ******************************************************************************/
24360
24361
24362 /******************************************************************************
24363 *************************** Begin AFP Locking *********************************
24364 **
24365 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24366 ** on Apple Macintosh computers - both OS9 and OSX.
24367 **
24368 ** Third-party implementations of AFP are available.  But this code here
24369 ** only works on OSX.
24370 */
24371
24372 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24373 /*
24374 ** The afpLockingContext structure contains all afp lock specific state
24375 */
24376 typedef struct afpLockingContext afpLockingContext;
24377 struct afpLockingContext {
24378   unsigned long long sharedByte;
24379   const char *dbPath;             /* Name of the open file */
24380 };
24381
24382 struct ByteRangeLockPB2
24383 {
24384   unsigned long long offset;        /* offset to first byte to lock */
24385   unsigned long long length;        /* nbr of bytes to lock */
24386   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24387   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24388   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24389   int fd;                           /* file desc to assoc this lock with */
24390 };
24391
24392 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24393
24394 /*
24395 ** This is a utility for setting or clearing a bit-range lock on an
24396 ** AFP filesystem.
24397 ** 
24398 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24399 */
24400 static int afpSetLock(
24401   const char *path,              /* Name of the file to be locked or unlocked */
24402   unixFile *pFile,               /* Open file descriptor on path */
24403   unsigned long long offset,     /* First byte to be locked */
24404   unsigned long long length,     /* Number of bytes to lock */
24405   int setLockFlag                /* True to set lock.  False to clear lock */
24406 ){
24407   struct ByteRangeLockPB2 pb;
24408   int err;
24409   
24410   pb.unLockFlag = setLockFlag ? 0 : 1;
24411   pb.startEndFlag = 0;
24412   pb.offset = offset;
24413   pb.length = length; 
24414   pb.fd = pFile->h;
24415   
24416   OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24417     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24418     offset, length);
24419   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24420   if ( err==-1 ) {
24421     int rc;
24422     int tErrno = errno;
24423     OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24424              path, tErrno, strerror(tErrno));
24425 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24426     rc = SQLITE_BUSY;
24427 #else
24428     rc = sqliteErrorFromPosixError(tErrno,
24429                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24430 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24431     if( IS_LOCK_ERROR(rc) ){
24432       pFile->lastErrno = tErrno;
24433     }
24434     return rc;
24435   } else {
24436     return SQLITE_OK;
24437   }
24438 }
24439
24440 /*
24441 ** This routine checks if there is a RESERVED lock held on the specified
24442 ** file by this or any other process. If such a lock is held, set *pResOut
24443 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24444 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24445 */
24446 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24447   int rc = SQLITE_OK;
24448   int reserved = 0;
24449   unixFile *pFile = (unixFile*)id;
24450   
24451   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24452   
24453   assert( pFile );
24454   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24455   
24456   /* Check if a thread in this process holds such a lock */
24457   if( pFile->locktype>SHARED_LOCK ){
24458     reserved = 1;
24459   }
24460   
24461   /* Otherwise see if some other process holds it.
24462    */
24463   if( !reserved ){
24464     /* lock the RESERVED byte */
24465     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
24466     if( SQLITE_OK==lrc ){
24467       /* if we succeeded in taking the reserved lock, unlock it to restore
24468       ** the original state */
24469       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24470     } else {
24471       /* if we failed to get the lock then someone else must have it */
24472       reserved = 1;
24473     }
24474     if( IS_LOCK_ERROR(lrc) ){
24475       rc=lrc;
24476     }
24477   }
24478   
24479   OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved);
24480   
24481   *pResOut = reserved;
24482   return rc;
24483 }
24484
24485 /*
24486 ** Lock the file with the lock specified by parameter locktype - one
24487 ** of the following:
24488 **
24489 **     (1) SHARED_LOCK
24490 **     (2) RESERVED_LOCK
24491 **     (3) PENDING_LOCK
24492 **     (4) EXCLUSIVE_LOCK
24493 **
24494 ** Sometimes when requesting one lock state, additional lock states
24495 ** are inserted in between.  The locking might fail on one of the later
24496 ** transitions leaving the lock state different from what it started but
24497 ** still short of its goal.  The following chart shows the allowed
24498 ** transitions and the inserted intermediate states:
24499 **
24500 **    UNLOCKED -> SHARED
24501 **    SHARED -> RESERVED
24502 **    SHARED -> (PENDING) -> EXCLUSIVE
24503 **    RESERVED -> (PENDING) -> EXCLUSIVE
24504 **    PENDING -> EXCLUSIVE
24505 **
24506 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24507 ** routine to lower a locking level.
24508 */
24509 static int afpLock(sqlite3_file *id, int locktype){
24510   int rc = SQLITE_OK;
24511   unixFile *pFile = (unixFile*)id;
24512   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24513   
24514   assert( pFile );
24515   OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
24516          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
24517
24518   /* If there is already a lock of this type or more restrictive on the
24519   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24520   ** unixEnterMutex() hasn't been called yet.
24521   */
24522   if( pFile->locktype>=locktype ){
24523     OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
24524            locktypeName(locktype));
24525     return SQLITE_OK;
24526   }
24527
24528   /* Make sure the locking sequence is correct
24529   */
24530   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24531   assert( locktype!=PENDING_LOCK );
24532   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24533   
24534   /* This mutex is needed because pFile->pLock is shared across threads
24535   */
24536   unixEnterMutex();
24537
24538   /* Make sure the current thread owns the pFile.
24539   */
24540   rc = transferOwnership(pFile);
24541   if( rc!=SQLITE_OK ){
24542     unixLeaveMutex();
24543     return rc;
24544   }
24545     
24546   /* A PENDING lock is needed before acquiring a SHARED lock and before
24547   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24548   ** be released.
24549   */
24550   if( locktype==SHARED_LOCK 
24551       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24552   ){
24553     int failed;
24554     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24555     if (failed) {
24556       rc = failed;
24557       goto afp_end_lock;
24558     }
24559   }
24560   
24561   /* If control gets to this point, then actually go ahead and make
24562   ** operating system calls for the specified lock.
24563   */
24564   if( locktype==SHARED_LOCK ){
24565     int lk, lrc1, lrc2, lrc1Errno;
24566     
24567     /* Now get the read-lock SHARED_LOCK */
24568     /* note that the quality of the randomness doesn't matter that much */
24569     lk = random(); 
24570     context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24571     lrc1 = afpSetLock(context->dbPath, pFile, 
24572           SHARED_FIRST+context->sharedByte, 1, 1);
24573     if( IS_LOCK_ERROR(lrc1) ){
24574       lrc1Errno = pFile->lastErrno;
24575     }
24576     /* Drop the temporary PENDING lock */
24577     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24578     
24579     if( IS_LOCK_ERROR(lrc1) ) {
24580       pFile->lastErrno = lrc1Errno;
24581       rc = lrc1;
24582       goto afp_end_lock;
24583     } else if( IS_LOCK_ERROR(lrc2) ){
24584       rc = lrc2;
24585       goto afp_end_lock;
24586     } else if( lrc1 != SQLITE_OK ) {
24587       rc = lrc1;
24588     } else {
24589       pFile->locktype = SHARED_LOCK;
24590       pFile->pOpen->nLock++;
24591     }
24592   }else{
24593     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24594     ** assumed that there is a SHARED or greater lock on the file
24595     ** already.
24596     */
24597     int failed = 0;
24598     assert( 0!=pFile->locktype );
24599     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24600         /* Acquire a RESERVED lock */
24601         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24602     }
24603     if (!failed && locktype == EXCLUSIVE_LOCK) {
24604       /* Acquire an EXCLUSIVE lock */
24605         
24606       /* Remove the shared lock before trying the range.  we'll need to 
24607       ** reestablish the shared lock if we can't get the  afpUnlock
24608       */
24609       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24610                          context->sharedByte, 1, 0)) ){
24611         int failed2 = SQLITE_OK;
24612         /* now attemmpt to get the exclusive lock range */
24613         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24614                                SHARED_SIZE, 1);
24615         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24616                        SHARED_FIRST + context->sharedByte, 1, 1)) ){
24617           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24618           ** a critical I/O error
24619           */
24620           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
24621                SQLITE_IOERR_LOCK;
24622           goto afp_end_lock;
24623         } 
24624       }else{
24625         rc = failed; 
24626       }
24627     }
24628     if( failed ){
24629       rc = failed;
24630     }
24631   }
24632   
24633   if( rc==SQLITE_OK ){
24634     pFile->locktype = locktype;
24635   }else if( locktype==EXCLUSIVE_LOCK ){
24636     pFile->locktype = PENDING_LOCK;
24637   }
24638   
24639 afp_end_lock:
24640   unixLeaveMutex();
24641   OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
24642          rc==SQLITE_OK ? "ok" : "failed");
24643   return rc;
24644 }
24645
24646 /*
24647 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24648 ** must be either NO_LOCK or SHARED_LOCK.
24649 **
24650 ** If the locking level of the file descriptor is already at or below
24651 ** the requested locking level, this routine is a no-op.
24652 */
24653 static int afpUnlock(sqlite3_file *id, int locktype) {
24654   int rc = SQLITE_OK;
24655   unixFile *pFile = (unixFile*)id;
24656   afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24657
24658   assert( pFile );
24659   OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
24660          pFile->locktype, getpid());
24661
24662   assert( locktype<=SHARED_LOCK );
24663   if( pFile->locktype<=locktype ){
24664     return SQLITE_OK;
24665   }
24666   if( CHECK_THREADID(pFile) ){
24667     return SQLITE_MISUSE;
24668   }
24669   unixEnterMutex();
24670   if( pFile->locktype>SHARED_LOCK ){
24671     
24672     if( pFile->locktype==EXCLUSIVE_LOCK ){
24673       rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24674       if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24675         /* only re-establish the shared lock if necessary */
24676         int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24677         rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24678       }
24679     }
24680     if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24681       rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24682     } 
24683     if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24684       rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24685     }
24686   }else if( locktype==NO_LOCK ){
24687     /* clear the shared lock */
24688     int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24689     rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24690   }
24691
24692   if( rc==SQLITE_OK ){
24693     if( locktype==NO_LOCK ){
24694       struct unixOpenCnt *pOpen = pFile->pOpen;
24695       pOpen->nLock--;
24696       assert( pOpen->nLock>=0 );
24697       if( pOpen->nLock==0 && pOpen->nPending>0 ){
24698         int i;
24699         for(i=0; i<pOpen->nPending; i++){
24700           if( pOpen->aPending[i] < 0 ) continue;
24701           if( close(pOpen->aPending[i]) ){
24702             pFile->lastErrno = errno;
24703             rc = SQLITE_IOERR_CLOSE;
24704           }else{
24705             pOpen->aPending[i] = -1;
24706           }
24707         }
24708         if( rc==SQLITE_OK ){
24709           sqlite3_free(pOpen->aPending);
24710           pOpen->nPending = 0;
24711           pOpen->aPending = 0;
24712         }
24713       }
24714     }
24715   }
24716   unixLeaveMutex();
24717   if( rc==SQLITE_OK ) pFile->locktype = locktype;
24718   return rc;
24719 }
24720
24721 /*
24722 ** Close a file & cleanup AFP specific locking context 
24723 */
24724 static int afpClose(sqlite3_file *id) {
24725   if( id ){
24726     unixFile *pFile = (unixFile*)id;
24727     afpUnlock(id, NO_LOCK);
24728     unixEnterMutex();
24729     if( pFile->pOpen && pFile->pOpen->nLock ){
24730       /* If there are outstanding locks, do not actually close the file just
24731       ** yet because that would clear those locks.  Instead, add the file
24732       ** descriptor to pOpen->aPending.  It will be automatically closed when
24733       ** the last lock is cleared.
24734       */
24735       int *aNew;
24736       struct unixOpenCnt *pOpen = pFile->pOpen;
24737       aNew = sqlite3_realloc(pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
24738       if( aNew==0 ){
24739         /* If a malloc fails, just leak the file descriptor */
24740       }else{
24741         pOpen->aPending = aNew;
24742         pOpen->aPending[pOpen->nPending] = pFile->h;
24743         pOpen->nPending++;
24744         pFile->h = -1;
24745       }
24746     }
24747     releaseOpenCnt(pFile->pOpen);
24748     sqlite3_free(pFile->lockingContext);
24749     closeUnixFile(id);
24750     unixLeaveMutex();
24751   }
24752   return SQLITE_OK;
24753 }
24754
24755 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24756 /*
24757 ** The code above is the AFP lock implementation.  The code is specific
24758 ** to MacOSX and does not work on other unix platforms.  No alternative
24759 ** is available.  If you don't compile for a mac, then the "unix-afp"
24760 ** VFS is not available.
24761 **
24762 ********************* End of the AFP lock implementation **********************
24763 ******************************************************************************/
24764
24765
24766 /******************************************************************************
24767 **************** Non-locking sqlite3_file methods *****************************
24768 **
24769 ** The next division contains implementations for all methods of the 
24770 ** sqlite3_file object other than the locking methods.  The locking
24771 ** methods were defined in divisions above (one locking method per
24772 ** division).  Those methods that are common to all locking modes
24773 ** are gather together into this division.
24774 */
24775
24776 /*
24777 ** Seek to the offset passed as the second argument, then read cnt 
24778 ** bytes into pBuf. Return the number of bytes actually read.
24779 **
24780 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24781 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24782 ** one system to another.  Since SQLite does not define USE_PREAD
24783 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24784 ** See tickets #2741 and #2681.
24785 **
24786 ** To avoid stomping the errno value on a failed read the lastErrno value
24787 ** is set before returning.
24788 */
24789 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24790   int got;
24791   i64 newOffset;
24792   TIMER_START;
24793 #if defined(USE_PREAD)
24794   got = pread(id->h, pBuf, cnt, offset);
24795   SimulateIOError( got = -1 );
24796 #elif defined(USE_PREAD64)
24797   got = pread64(id->h, pBuf, cnt, offset);
24798   SimulateIOError( got = -1 );
24799 #else
24800   newOffset = lseek(id->h, offset, SEEK_SET);
24801   SimulateIOError( newOffset-- );
24802   if( newOffset!=offset ){
24803     if( newOffset == -1 ){
24804       ((unixFile*)id)->lastErrno = errno;
24805     }else{
24806       ((unixFile*)id)->lastErrno = 0;                   
24807     }
24808     return -1;
24809   }
24810   got = read(id->h, pBuf, cnt);
24811 #endif
24812   TIMER_END;
24813   if( got<0 ){
24814     ((unixFile*)id)->lastErrno = errno;
24815   }
24816   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24817   return got;
24818 }
24819
24820 /*
24821 ** Read data from a file into a buffer.  Return SQLITE_OK if all
24822 ** bytes were read successfully and SQLITE_IOERR if anything goes
24823 ** wrong.
24824 */
24825 static int unixRead(
24826   sqlite3_file *id, 
24827   void *pBuf, 
24828   int amt,
24829   sqlite3_int64 offset
24830 ){
24831   int got;
24832   assert( id );
24833
24834   /* Never read or write any of the bytes in the locking range */
24835   assert( ((unixFile*)id)->isLockable==0
24836           || offset>=PENDING_BYTE+512
24837           || offset+amt<=PENDING_BYTE );
24838
24839   got = seekAndRead((unixFile*)id, offset, pBuf, amt);
24840   if( got==amt ){
24841     return SQLITE_OK;
24842   }else if( got<0 ){
24843     /* lastErrno set by seekAndRead */
24844     return SQLITE_IOERR_READ;
24845   }else{
24846     ((unixFile*)id)->lastErrno = 0; /* not a system error */
24847     /* Unread parts of the buffer must be zero-filled */
24848     memset(&((char*)pBuf)[got], 0, amt-got);
24849     return SQLITE_IOERR_SHORT_READ;
24850   }
24851 }
24852
24853 /*
24854 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
24855 ** Return the number of bytes actually read.  Update the offset.
24856 **
24857 ** To avoid stomping the errno value on a failed write the lastErrno value
24858 ** is set before returning.
24859 */
24860 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24861   int got;
24862   i64 newOffset;
24863   TIMER_START;
24864 #if defined(USE_PREAD)
24865   got = pwrite(id->h, pBuf, cnt, offset);
24866 #elif defined(USE_PREAD64)
24867   got = pwrite64(id->h, pBuf, cnt, offset);
24868 #else
24869   newOffset = lseek(id->h, offset, SEEK_SET);
24870   if( newOffset!=offset ){
24871     if( newOffset == -1 ){
24872       ((unixFile*)id)->lastErrno = errno;
24873     }else{
24874       ((unixFile*)id)->lastErrno = 0;                   
24875     }
24876     return -1;
24877   }
24878   got = write(id->h, pBuf, cnt);
24879 #endif
24880   TIMER_END;
24881   if( got<0 ){
24882     ((unixFile*)id)->lastErrno = errno;
24883   }
24884
24885   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24886   return got;
24887 }
24888
24889
24890 /*
24891 ** Write data from a buffer into a file.  Return SQLITE_OK on success
24892 ** or some other error code on failure.
24893 */
24894 static int unixWrite(
24895   sqlite3_file *id, 
24896   const void *pBuf, 
24897   int amt,
24898   sqlite3_int64 offset 
24899 ){
24900   int wrote = 0;
24901   assert( id );
24902   assert( amt>0 );
24903
24904   /* Never read or write any of the bytes in the locking range */
24905   assert( ((unixFile*)id)->isLockable==0
24906           || offset>=PENDING_BYTE+512
24907           || offset+amt<=PENDING_BYTE );
24908
24909 #ifndef NDEBUG
24910   /* If we are doing a normal write to a database file (as opposed to
24911   ** doing a hot-journal rollback or a write to some file other than a
24912   ** normal database file) then record the fact that the database
24913   ** has changed.  If the transaction counter is modified, record that
24914   ** fact too.
24915   */
24916   if( ((unixFile*)id)->inNormalWrite ){
24917     unixFile *pFile = (unixFile*)id;
24918     pFile->dbUpdate = 1;  /* The database has been modified */
24919     if( offset<=24 && offset+amt>=27 ){
24920       int rc;
24921       char oldCntr[4];
24922       SimulateIOErrorBenign(1);
24923       rc = seekAndRead(pFile, 24, oldCntr, 4);
24924       SimulateIOErrorBenign(0);
24925       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24926         pFile->transCntrChng = 1;  /* The transaction counter has changed */
24927       }
24928     }
24929   }
24930 #endif
24931
24932   while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
24933     amt -= wrote;
24934     offset += wrote;
24935     pBuf = &((char*)pBuf)[wrote];
24936   }
24937   SimulateIOError(( wrote=(-1), amt=1 ));
24938   SimulateDiskfullError(( wrote=0, amt=1 ));
24939   if( amt>0 ){
24940     if( wrote<0 ){
24941       /* lastErrno set by seekAndWrite */
24942       return SQLITE_IOERR_WRITE;
24943     }else{
24944       ((unixFile*)id)->lastErrno = 0; /* not a system error */
24945       return SQLITE_FULL;
24946     }
24947   }
24948   return SQLITE_OK;
24949 }
24950
24951 #ifdef SQLITE_TEST
24952 /*
24953 ** Count the number of fullsyncs and normal syncs.  This is used to test
24954 ** that syncs and fullsyncs are occurring at the right times.
24955 */
24956 SQLITE_API int sqlite3_sync_count = 0;
24957 SQLITE_API int sqlite3_fullsync_count = 0;
24958 #endif
24959
24960 /*
24961 ** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
24962 ** Otherwise use fsync() in its place.
24963 */
24964 #ifndef HAVE_FDATASYNC
24965 # define fdatasync fsync
24966 #endif
24967
24968 /*
24969 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24970 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24971 ** only available on Mac OS X.  But that could change.
24972 */
24973 #ifdef F_FULLFSYNC
24974 # define HAVE_FULLFSYNC 1
24975 #else
24976 # define HAVE_FULLFSYNC 0
24977 #endif
24978
24979
24980 /*
24981 ** The fsync() system call does not work as advertised on many
24982 ** unix systems.  The following procedure is an attempt to make
24983 ** it work better.
24984 **
24985 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24986 ** for testing when we want to run through the test suite quickly.
24987 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24988 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24989 ** or power failure will likely corrupt the database file.
24990 */
24991 static int full_fsync(int fd, int fullSync, int dataOnly){
24992   int rc;
24993
24994   /* The following "ifdef/elif/else/" block has the same structure as
24995   ** the one below. It is replicated here solely to avoid cluttering 
24996   ** up the real code with the UNUSED_PARAMETER() macros.
24997   */
24998 #ifdef SQLITE_NO_SYNC
24999   UNUSED_PARAMETER(fd);
25000   UNUSED_PARAMETER(fullSync);
25001   UNUSED_PARAMETER(dataOnly);
25002 #elif HAVE_FULLFSYNC
25003   UNUSED_PARAMETER(dataOnly);
25004 #else
25005   UNUSED_PARAMETER(fullSync);
25006 #endif
25007
25008   /* Record the number of times that we do a normal fsync() and 
25009   ** FULLSYNC.  This is used during testing to verify that this procedure
25010   ** gets called with the correct arguments.
25011   */
25012 #ifdef SQLITE_TEST
25013   if( fullSync ) sqlite3_fullsync_count++;
25014   sqlite3_sync_count++;
25015 #endif
25016
25017   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25018   ** no-op
25019   */
25020 #ifdef SQLITE_NO_SYNC
25021   rc = SQLITE_OK;
25022 #elif HAVE_FULLFSYNC
25023   if( fullSync ){
25024     rc = fcntl(fd, F_FULLFSYNC, 0);
25025   }else{
25026     rc = 1;
25027   }
25028   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25029   ** It shouldn't be possible for fullfsync to fail on the local 
25030   ** file system (on OSX), so failure indicates that FULLFSYNC
25031   ** isn't supported for this file system. So, attempt an fsync 
25032   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25033   ** It'd be better to detect fullfsync support once and avoid 
25034   ** the fcntl call every time sync is called.
25035   */
25036   if( rc ) rc = fsync(fd);
25037
25038 #else 
25039   if( dataOnly ){
25040     rc = fdatasync(fd);
25041 #if OS_VXWORKS
25042     if( rc==-1 && errno==ENOTSUP ){
25043       rc = fsync(fd);
25044     }
25045 #endif
25046   }else{
25047     rc = fsync(fd);
25048   }
25049 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25050
25051   if( OS_VXWORKS && rc!= -1 ){
25052     rc = 0;
25053   }
25054   return rc;
25055 }
25056
25057 /*
25058 ** Make sure all writes to a particular file are committed to disk.
25059 **
25060 ** If dataOnly==0 then both the file itself and its metadata (file
25061 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25062 ** file data is synced.
25063 **
25064 ** Under Unix, also make sure that the directory entry for the file
25065 ** has been created by fsync-ing the directory that contains the file.
25066 ** If we do not do this and we encounter a power failure, the directory
25067 ** entry for the journal might not exist after we reboot.  The next
25068 ** SQLite to access the file will not know that the journal exists (because
25069 ** the directory entry for the journal was never created) and the transaction
25070 ** will not roll back - possibly leading to database corruption.
25071 */
25072 static int unixSync(sqlite3_file *id, int flags){
25073   int rc;
25074   unixFile *pFile = (unixFile*)id;
25075
25076   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25077   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25078
25079   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25080   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25081       || (flags&0x0F)==SQLITE_SYNC_FULL
25082   );
25083
25084   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25085   ** line is to test that doing so does not cause any problems.
25086   */
25087   SimulateDiskfullError( return SQLITE_FULL );
25088
25089   assert( pFile );
25090   OSTRACE2("SYNC    %-3d\n", pFile->h);
25091   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25092   SimulateIOError( rc=1 );
25093   if( rc ){
25094     pFile->lastErrno = errno;
25095     return SQLITE_IOERR_FSYNC;
25096   }
25097   if( pFile->dirfd>=0 ){
25098     int err;
25099     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25100             HAVE_FULLFSYNC, isFullsync);
25101 #ifndef SQLITE_DISABLE_DIRSYNC
25102     /* The directory sync is only attempted if full_fsync is
25103     ** turned off or unavailable.  If a full_fsync occurred above,
25104     ** then the directory sync is superfluous.
25105     */
25106     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25107        /*
25108        ** We have received multiple reports of fsync() returning
25109        ** errors when applied to directories on certain file systems.
25110        ** A failed directory sync is not a big deal.  So it seems
25111        ** better to ignore the error.  Ticket #1657
25112        */
25113        /* pFile->lastErrno = errno; */
25114        /* return SQLITE_IOERR; */
25115     }
25116 #endif
25117     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25118     if( err==0 ){              /* directory when we are done */
25119       pFile->dirfd = -1;
25120     }else{
25121       pFile->lastErrno = errno;
25122       rc = SQLITE_IOERR_DIR_CLOSE;
25123     }
25124   }
25125   return rc;
25126 }
25127
25128 /*
25129 ** Truncate an open file to a specified size
25130 */
25131 static int unixTruncate(sqlite3_file *id, i64 nByte){
25132   int rc;
25133   assert( id );
25134   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25135   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25136   if( rc ){
25137     ((unixFile*)id)->lastErrno = errno;
25138     return SQLITE_IOERR_TRUNCATE;
25139   }else{
25140     return SQLITE_OK;
25141   }
25142 }
25143
25144 /*
25145 ** Determine the current size of a file in bytes
25146 */
25147 static int unixFileSize(sqlite3_file *id, i64 *pSize){
25148   int rc;
25149   struct stat buf;
25150   assert( id );
25151   rc = fstat(((unixFile*)id)->h, &buf);
25152   SimulateIOError( rc=1 );
25153   if( rc!=0 ){
25154     ((unixFile*)id)->lastErrno = errno;
25155     return SQLITE_IOERR_FSTAT;
25156   }
25157   *pSize = buf.st_size;
25158
25159   /* When opening a zero-size database, the findLockInfo() procedure
25160   ** writes a single byte into that file in order to work around a bug
25161   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25162   ** layers, we need to report this file size as zero even though it is
25163   ** really 1.   Ticket #3260.
25164   */
25165   if( *pSize==1 ) *pSize = 0;
25166
25167
25168   return SQLITE_OK;
25169 }
25170
25171 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25172 /*
25173 ** Handler for proxy-locking file-control verbs.  Defined below in the
25174 ** proxying locking division.
25175 */
25176 static int proxyFileControl(sqlite3_file*,int,void*);
25177 #endif
25178
25179
25180 /*
25181 ** Information and control of an open file handle.
25182 */
25183 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25184   switch( op ){
25185     case SQLITE_FCNTL_LOCKSTATE: {
25186       *(int*)pArg = ((unixFile*)id)->locktype;
25187       return SQLITE_OK;
25188     }
25189     case SQLITE_LAST_ERRNO: {
25190       *(int*)pArg = ((unixFile*)id)->lastErrno;
25191       return SQLITE_OK;
25192     }
25193 #ifndef NDEBUG
25194     /* The pager calls this method to signal that it has done
25195     ** a rollback and that the database is therefore unchanged and
25196     ** it hence it is OK for the transaction change counter to be
25197     ** unchanged.
25198     */
25199     case SQLITE_FCNTL_DB_UNCHANGED: {
25200       ((unixFile*)id)->dbUpdate = 0;
25201       return SQLITE_OK;
25202     }
25203 #endif
25204 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25205     case SQLITE_SET_LOCKPROXYFILE:
25206     case SQLITE_GET_LOCKPROXYFILE: {
25207       return proxyFileControl(id,op,pArg);
25208     }
25209 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25210   }
25211   return SQLITE_ERROR;
25212 }
25213
25214 /*
25215 ** Return the sector size in bytes of the underlying block device for
25216 ** the specified file. This is almost always 512 bytes, but may be
25217 ** larger for some devices.
25218 **
25219 ** SQLite code assumes this function cannot fail. It also assumes that
25220 ** if two files are created in the same file-system directory (i.e.
25221 ** a database and its journal file) that the sector size will be the
25222 ** same for both.
25223 */
25224 static int unixSectorSize(sqlite3_file *NotUsed){
25225   UNUSED_PARAMETER(NotUsed);
25226   return SQLITE_DEFAULT_SECTOR_SIZE;
25227 }
25228
25229 /*
25230 ** Return the device characteristics for the file. This is always 0 for unix.
25231 */
25232 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25233   UNUSED_PARAMETER(NotUsed);
25234   return 0;
25235 }
25236
25237 /*
25238 ** Here ends the implementation of all sqlite3_file methods.
25239 **
25240 ********************** End sqlite3_file Methods *******************************
25241 ******************************************************************************/
25242
25243 /*
25244 ** This division contains definitions of sqlite3_io_methods objects that
25245 ** implement various file locking strategies.  It also contains definitions
25246 ** of "finder" functions.  A finder-function is used to locate the appropriate
25247 ** sqlite3_io_methods object for a particular database file.  The pAppData
25248 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
25249 ** the correct finder-function for that VFS.
25250 **
25251 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
25252 ** object.  The only interesting finder-function is autolockIoFinder, which
25253 ** looks at the filesystem type and tries to guess the best locking
25254 ** strategy from that.
25255 **
25256 ** For finder-funtion F, two objects are created:
25257 **
25258 **    (1) The real finder-function named "FImpt()".
25259 **
25260 **    (2) A constant pointer to this functio named just "F".
25261 **
25262 **
25263 ** A pointer to the F pointer is used as the pAppData value for VFS
25264 ** objects.  We have to do this instead of letting pAppData point
25265 ** directly at the finder-function since C90 rules prevent a void*
25266 ** from be cast into a function pointer.
25267 **
25268 **
25269 ** Each instance of this macro generates two objects:
25270 **
25271 **   *  A constant sqlite3_io_methods object call METHOD that has locking
25272 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
25273 **
25274 **   *  An I/O method finder function called FINDER that returns a pointer
25275 **      to the METHOD object in the previous bullet.
25276 */
25277 #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
25278 static const sqlite3_io_methods METHOD = {                                   \
25279    1,                          /* iVersion */                                \
25280    CLOSE,                      /* xClose */                                  \
25281    unixRead,                   /* xRead */                                   \
25282    unixWrite,                  /* xWrite */                                  \
25283    unixTruncate,               /* xTruncate */                               \
25284    unixSync,                   /* xSync */                                   \
25285    unixFileSize,               /* xFileSize */                               \
25286    LOCK,                       /* xLock */                                   \
25287    UNLOCK,                     /* xUnlock */                                 \
25288    CKLOCK,                     /* xCheckReservedLock */                      \
25289    unixFileControl,            /* xFileControl */                            \
25290    unixSectorSize,             /* xSectorSize */                             \
25291    unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
25292 };                                                                           \
25293 static const sqlite3_io_methods *FINDER##Impl(const char *z, int h){         \
25294   UNUSED_PARAMETER(z); UNUSED_PARAMETER(h);                                  \
25295   return &METHOD;                                                            \
25296 }                                                                            \
25297 static const sqlite3_io_methods *(*const FINDER)(const char*,int)            \
25298     = FINDER##Impl;
25299
25300 /*
25301 ** Here are all of the sqlite3_io_methods objects for each of the
25302 ** locking strategies.  Functions that return pointers to these methods
25303 ** are also created.
25304 */
25305 IOMETHODS(
25306   posixIoFinder,            /* Finder function name */
25307   posixIoMethods,           /* sqlite3_io_methods object name */
25308   unixClose,                /* xClose method */
25309   unixLock,                 /* xLock method */
25310   unixUnlock,               /* xUnlock method */
25311   unixCheckReservedLock     /* xCheckReservedLock method */
25312 )
25313 IOMETHODS(
25314   nolockIoFinder,           /* Finder function name */
25315   nolockIoMethods,          /* sqlite3_io_methods object name */
25316   nolockClose,              /* xClose method */
25317   nolockLock,               /* xLock method */
25318   nolockUnlock,             /* xUnlock method */
25319   nolockCheckReservedLock   /* xCheckReservedLock method */
25320 )
25321 IOMETHODS(
25322   dotlockIoFinder,          /* Finder function name */
25323   dotlockIoMethods,         /* sqlite3_io_methods object name */
25324   dotlockClose,             /* xClose method */
25325   dotlockLock,              /* xLock method */
25326   dotlockUnlock,            /* xUnlock method */
25327   dotlockCheckReservedLock  /* xCheckReservedLock method */
25328 )
25329
25330 #if SQLITE_ENABLE_LOCKING_STYLE
25331 IOMETHODS(
25332   flockIoFinder,            /* Finder function name */
25333   flockIoMethods,           /* sqlite3_io_methods object name */
25334   flockClose,               /* xClose method */
25335   flockLock,                /* xLock method */
25336   flockUnlock,              /* xUnlock method */
25337   flockCheckReservedLock    /* xCheckReservedLock method */
25338 )
25339 #endif
25340
25341 #if OS_VXWORKS
25342 IOMETHODS(
25343   semIoFinder,              /* Finder function name */
25344   semIoMethods,             /* sqlite3_io_methods object name */
25345   semClose,                 /* xClose method */
25346   semLock,                  /* xLock method */
25347   semUnlock,                /* xUnlock method */
25348   semCheckReservedLock      /* xCheckReservedLock method */
25349 )
25350 #endif
25351
25352 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25353 IOMETHODS(
25354   afpIoFinder,              /* Finder function name */
25355   afpIoMethods,             /* sqlite3_io_methods object name */
25356   afpClose,                 /* xClose method */
25357   afpLock,                  /* xLock method */
25358   afpUnlock,                /* xUnlock method */
25359   afpCheckReservedLock      /* xCheckReservedLock method */
25360 )
25361 #endif
25362
25363 /*
25364 ** The proxy locking method is a "super-method" in the sense that it
25365 ** opens secondary file descriptors for the conch and lock files and
25366 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
25367 ** secondary files.  For this reason, the division that implements
25368 ** proxy locking is located much further down in the file.  But we need
25369 ** to go ahead and define the sqlite3_io_methods and finder function
25370 ** for proxy locking here.  So we forward declare the I/O methods.
25371 */
25372 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25373 static int proxyClose(sqlite3_file*);
25374 static int proxyLock(sqlite3_file*, int);
25375 static int proxyUnlock(sqlite3_file*, int);
25376 static int proxyCheckReservedLock(sqlite3_file*, int*);
25377 IOMETHODS(
25378   proxyIoFinder,            /* Finder function name */
25379   proxyIoMethods,           /* sqlite3_io_methods object name */
25380   proxyClose,               /* xClose method */
25381   proxyLock,                /* xLock method */
25382   proxyUnlock,              /* xUnlock method */
25383   proxyCheckReservedLock    /* xCheckReservedLock method */
25384 )
25385 #endif
25386
25387
25388 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25389 /* 
25390 ** This "finder" function attempts to determine the best locking strategy 
25391 ** for the database file "filePath".  It then returns the sqlite3_io_methods
25392 ** object that implements that strategy.
25393 **
25394 ** This is for MacOSX only.
25395 */
25396 static const sqlite3_io_methods *autolockIoFinderImpl(
25397   const char *filePath,    /* name of the database file */
25398   int fd                   /* file descriptor open on the database file */
25399 ){
25400   static const struct Mapping {
25401     const char *zFilesystem;              /* Filesystem type name */
25402     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
25403   } aMap[] = {
25404     { "hfs",    &posixIoMethods },
25405     { "ufs",    &posixIoMethods },
25406     { "afpfs",  &afpIoMethods },
25407 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
25408     { "smbfs",  &afpIoMethods },
25409 #else
25410     { "smbfs",  &flockIoMethods },
25411 #endif
25412     { "webdav", &nolockIoMethods },
25413     { 0, 0 }
25414   };
25415   int i;
25416   struct statfs fsInfo;
25417   struct flock lockInfo;
25418
25419   if( !filePath ){
25420     /* If filePath==NULL that means we are dealing with a transient file
25421     ** that does not need to be locked. */
25422     return &nolockIoMethods;
25423   }
25424   if( statfs(filePath, &fsInfo) != -1 ){
25425     if( fsInfo.f_flags & MNT_RDONLY ){
25426       return &nolockIoMethods;
25427     }
25428     for(i=0; aMap[i].zFilesystem; i++){
25429       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
25430         return aMap[i].pMethods;
25431       }
25432     }
25433   }
25434
25435   /* Default case. Handles, amongst others, "nfs".
25436   ** Test byte-range lock using fcntl(). If the call succeeds, 
25437   ** assume that the file-system supports POSIX style locks. 
25438   */
25439   lockInfo.l_len = 1;
25440   lockInfo.l_start = 0;
25441   lockInfo.l_whence = SEEK_SET;
25442   lockInfo.l_type = F_RDLCK;
25443   if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
25444     return &posixIoMethods;
25445   }else{
25446     return &dotlockIoMethods;
25447   }
25448 }
25449 static const sqlite3_io_methods *(*const autolockIoFinder)(const char*,int)
25450         = autolockIoFinderImpl;
25451
25452 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25453
25454 /*
25455 ** An abstract type for a pointer to a IO method finder function:
25456 */
25457 typedef const sqlite3_io_methods *(*finder_type)(const char*,int);
25458
25459
25460 /****************************************************************************
25461 **************************** sqlite3_vfs methods ****************************
25462 **
25463 ** This division contains the implementation of methods on the
25464 ** sqlite3_vfs object.
25465 */
25466
25467 /*
25468 ** Initialize the contents of the unixFile structure pointed to by pId.
25469 */
25470 static int fillInUnixFile(
25471   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
25472   int h,                  /* Open file descriptor of file being opened */
25473   int dirfd,              /* Directory file descriptor */
25474   sqlite3_file *pId,      /* Write to the unixFile structure here */
25475   const char *zFilename,  /* Name of the file being opened */
25476   int noLock,             /* Omit locking if true */
25477   int isDelete            /* Delete on close if true */
25478 ){
25479   const sqlite3_io_methods *pLockingStyle;
25480   unixFile *pNew = (unixFile *)pId;
25481   int rc = SQLITE_OK;
25482
25483   assert( pNew->pLock==NULL );
25484   assert( pNew->pOpen==NULL );
25485
25486   /* Parameter isDelete is only used on vxworks.
25487   ** Express this explicitly here to prevent compiler warnings
25488   ** about unused parameters.
25489   */
25490 #if !OS_VXWORKS
25491   UNUSED_PARAMETER(isDelete);
25492 #endif
25493
25494   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
25495   pNew->h = h;
25496   pNew->dirfd = dirfd;
25497   SET_THREADID(pNew);
25498
25499 #if OS_VXWORKS
25500   pNew->pId = vxworksFindFileId(zFilename);
25501   if( pNew->pId==0 ){
25502     noLock = 1;
25503     rc = SQLITE_NOMEM;
25504   }
25505 #endif
25506
25507   if( noLock ){
25508     pLockingStyle = &nolockIoMethods;
25509   }else{
25510     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, h);
25511 #if SQLITE_ENABLE_LOCKING_STYLE
25512     /* Cache zFilename in the locking context (AFP and dotlock override) for
25513     ** proxyLock activation is possible (remote proxy is based on db name)
25514     ** zFilename remains valid until file is closed, to support */
25515     pNew->lockingContext = (void*)zFilename;
25516 #endif
25517   }
25518
25519   if( pLockingStyle == &posixIoMethods ){
25520     unixEnterMutex();
25521     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25522     unixLeaveMutex();
25523   }
25524
25525 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25526   else if( pLockingStyle == &afpIoMethods ){
25527     /* AFP locking uses the file path so it needs to be included in
25528     ** the afpLockingContext.
25529     */
25530     afpLockingContext *pCtx;
25531     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25532     if( pCtx==0 ){
25533       rc = SQLITE_NOMEM;
25534     }else{
25535       /* NB: zFilename exists and remains valid until the file is closed
25536       ** according to requirement F11141.  So we do not need to make a
25537       ** copy of the filename. */
25538       pCtx->dbPath = zFilename;
25539       srandomdev();
25540       unixEnterMutex();
25541       rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25542       unixLeaveMutex();        
25543     }
25544   }
25545 #endif
25546
25547   else if( pLockingStyle == &dotlockIoMethods ){
25548     /* Dotfile locking uses the file path so it needs to be included in
25549     ** the dotlockLockingContext 
25550     */
25551     char *zLockFile;
25552     int nFilename;
25553     nFilename = (int)strlen(zFilename) + 6;
25554     zLockFile = (char *)sqlite3_malloc(nFilename);
25555     if( zLockFile==0 ){
25556       rc = SQLITE_NOMEM;
25557     }else{
25558       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25559     }
25560     pNew->lockingContext = zLockFile;
25561   }
25562
25563 #if OS_VXWORKS
25564   else if( pLockingStyle == &semIoMethods ){
25565     /* Named semaphore locking uses the file path so it needs to be
25566     ** included in the semLockingContext
25567     */
25568     unixEnterMutex();
25569     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25570     if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25571       char *zSemName = pNew->pOpen->aSemName;
25572       int n;
25573       sqlite3_snprintf(MAX_PATHNAME, zSemName, "%s.sem",
25574                        pNew->pId->zCanonicalName);
25575       for( n=0; zSemName[n]; n++ )
25576         if( zSemName[n]=='/' ) zSemName[n] = '_';
25577       pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25578       if( pNew->pOpen->pSem == SEM_FAILED ){
25579         rc = SQLITE_NOMEM;
25580         pNew->pOpen->aSemName[0] = '\0';
25581       }
25582     }
25583     unixLeaveMutex();
25584   }
25585 #endif
25586   
25587   pNew->lastErrno = 0;
25588 #if OS_VXWORKS
25589   if( rc!=SQLITE_OK ){
25590     unlink(zFilename);
25591     isDelete = 0;
25592   }
25593   pNew->isDelete = isDelete;
25594 #endif
25595   if( rc!=SQLITE_OK ){
25596     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25597     close(h);
25598   }else{
25599     pNew->pMethod = pLockingStyle;
25600     OpenCounter(+1);
25601   }
25602   return rc;
25603 }
25604
25605 /*
25606 ** Open a file descriptor to the directory containing file zFilename.
25607 ** If successful, *pFd is set to the opened file descriptor and
25608 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25609 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25610 ** value.
25611 **
25612 ** If SQLITE_OK is returned, the caller is responsible for closing
25613 ** the file descriptor *pFd using close().
25614 */
25615 static int openDirectory(const char *zFilename, int *pFd){
25616   int ii;
25617   int fd = -1;
25618   char zDirname[MAX_PATHNAME+1];
25619
25620   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25621   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25622   if( ii>0 ){
25623     zDirname[ii] = '\0';
25624     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25625     if( fd>=0 ){
25626 #ifdef FD_CLOEXEC
25627       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25628 #endif
25629       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25630     }
25631   }
25632   *pFd = fd;
25633   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
25634 }
25635
25636 /*
25637 ** Create a temporary file name in zBuf.  zBuf must be allocated
25638 ** by the calling process and must be big enough to hold at least
25639 ** pVfs->mxPathname bytes.
25640 */
25641 static int getTempname(int nBuf, char *zBuf){
25642   static const char *azDirs[] = {
25643      0,
25644      0,
25645      "/var/tmp",
25646      "/usr/tmp",
25647      "/tmp",
25648      ".",
25649   };
25650   static const unsigned char zChars[] =
25651     "abcdefghijklmnopqrstuvwxyz"
25652     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25653     "0123456789";
25654   unsigned int i, j;
25655   struct stat buf;
25656   const char *zDir = ".";
25657
25658   /* It's odd to simulate an io-error here, but really this is just
25659   ** using the io-error infrastructure to test that SQLite handles this
25660   ** function failing. 
25661   */
25662   SimulateIOError( return SQLITE_IOERR );
25663
25664   azDirs[0] = sqlite3_temp_directory;
25665   if (NULL == azDirs[1]) {
25666     azDirs[1] = getenv("TMPDIR");
25667   }
25668   
25669   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25670     if( azDirs[i]==0 ) continue;
25671     if( stat(azDirs[i], &buf) ) continue;
25672     if( !S_ISDIR(buf.st_mode) ) continue;
25673     if( access(azDirs[i], 07) ) continue;
25674     zDir = azDirs[i];
25675     break;
25676   }
25677
25678   /* Check that the output buffer is large enough for the temporary file 
25679   ** name. If it is not, return SQLITE_ERROR.
25680   */
25681   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25682     return SQLITE_ERROR;
25683   }
25684
25685   do{
25686     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25687     j = (int)strlen(zBuf);
25688     sqlite3_randomness(15, &zBuf[j]);
25689     for(i=0; i<15; i++, j++){
25690       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25691     }
25692     zBuf[j] = 0;
25693   }while( access(zBuf,0)==0 );
25694   return SQLITE_OK;
25695 }
25696
25697 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25698 /*
25699 ** Routine to transform a unixFile into a proxy-locking unixFile.
25700 ** Implementation in the proxy-lock division, but used by unixOpen()
25701 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
25702 */
25703 static int proxyTransformUnixFile(unixFile*, const char*);
25704 #endif
25705
25706
25707 /*
25708 ** Open the file zPath.
25709 ** 
25710 ** Previously, the SQLite OS layer used three functions in place of this
25711 ** one:
25712 **
25713 **     sqlite3OsOpenReadWrite();
25714 **     sqlite3OsOpenReadOnly();
25715 **     sqlite3OsOpenExclusive();
25716 **
25717 ** These calls correspond to the following combinations of flags:
25718 **
25719 **     ReadWrite() ->     (READWRITE | CREATE)
25720 **     ReadOnly()  ->     (READONLY) 
25721 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25722 **
25723 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25724 ** true, the file was configured to be automatically deleted when the
25725 ** file handle closed. To achieve the same effect using this new 
25726 ** interface, add the DELETEONCLOSE flag to those specified above for 
25727 ** OpenExclusive().
25728 */
25729 static int unixOpen(
25730   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25731   const char *zPath,           /* Pathname of file to be opened */
25732   sqlite3_file *pFile,         /* The file descriptor to be filled in */
25733   int flags,                   /* Input flags to control the opening */
25734   int *pOutFlags               /* Output flags returned to SQLite core */
25735 ){
25736   int fd = 0;                    /* File descriptor returned by open() */
25737   int dirfd = -1;                /* Directory file descriptor */
25738   int openFlags = 0;             /* Flags to pass to open() */
25739   int eType = flags&0xFFFFFF00;  /* Type of file to open */
25740   int noLock;                    /* True to omit locking primitives */
25741   int rc = SQLITE_OK;
25742
25743   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25744   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25745   int isCreate     = (flags & SQLITE_OPEN_CREATE);
25746   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25747   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25748
25749   /* If creating a master or main-file journal, this function will open
25750   ** a file-descriptor on the directory too. The first time unixSync()
25751   ** is called the directory file descriptor will be fsync()ed and close()d.
25752   */
25753   int isOpenDirectory = (isCreate && 
25754       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25755   );
25756
25757   /* If argument zPath is a NULL pointer, this function is required to open
25758   ** a temporary file. Use this buffer to store the file name in.
25759   */
25760   char zTmpname[MAX_PATHNAME+1];
25761   const char *zName = zPath;
25762
25763   /* Check the following statements are true: 
25764   **
25765   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
25766   **   (b) if CREATE is set, then READWRITE must also be set, and
25767   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25768   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25769   */
25770   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25771   assert(isCreate==0 || isReadWrite);
25772   assert(isExclusive==0 || isCreate);
25773   assert(isDelete==0 || isCreate);
25774
25775   /* The main DB, main journal, and master journal are never automatically
25776   ** deleted
25777   */
25778   assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
25779   assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
25780   assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
25781
25782   /* Assert that the upper layer has set one of the "file-type" flags. */
25783   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
25784        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
25785        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
25786        || eType==SQLITE_OPEN_TRANSIENT_DB
25787   );
25788
25789   memset(pFile, 0, sizeof(unixFile));
25790
25791   if( !zName ){
25792     assert(isDelete && !isOpenDirectory);
25793     rc = getTempname(MAX_PATHNAME+1, zTmpname);
25794     if( rc!=SQLITE_OK ){
25795       return rc;
25796     }
25797     zName = zTmpname;
25798   }
25799
25800   if( isReadonly )  openFlags |= O_RDONLY;
25801   if( isReadWrite ) openFlags |= O_RDWR;
25802   if( isCreate )    openFlags |= O_CREAT;
25803   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25804   openFlags |= (O_LARGEFILE|O_BINARY);
25805
25806   fd = open(zName, openFlags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25807   OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25808   if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25809     /* Failed to open the file for read/write access. Try read-only. */
25810     flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25811     flags |= SQLITE_OPEN_READONLY;
25812     return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
25813   }
25814   if( fd<0 ){
25815     return SQLITE_CANTOPEN;
25816   }
25817   if( isDelete ){
25818 #if OS_VXWORKS
25819     zPath = zName;
25820 #else
25821     unlink(zName);
25822 #endif
25823   }
25824 #if SQLITE_ENABLE_LOCKING_STYLE
25825   else{
25826     ((unixFile*)pFile)->openFlags = openFlags;
25827   }
25828 #endif
25829   if( pOutFlags ){
25830     *pOutFlags = flags;
25831   }
25832
25833 #ifndef NDEBUG
25834   if( (flags & SQLITE_OPEN_MAIN_DB)!=0 ){
25835     ((unixFile*)pFile)->isLockable = 1;
25836   }
25837 #endif
25838
25839   assert(fd!=0);
25840   if( isOpenDirectory ){
25841     rc = openDirectory(zPath, &dirfd);
25842     if( rc!=SQLITE_OK ){
25843       close(fd); /* silently leak if fail, already in error */
25844       return rc;
25845     }
25846   }
25847
25848 #ifdef FD_CLOEXEC
25849   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25850 #endif
25851
25852   noLock = eType!=SQLITE_OPEN_MAIN_DB;
25853
25854 #if SQLITE_PREFER_PROXY_LOCKING
25855   if( zPath!=NULL && !noLock ){
25856     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25857     int useProxy = 0;
25858
25859     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 
25860     ** 0 means never use proxy, NULL means use proxy for non-local files only
25861     */
25862     if( envforce!=NULL ){
25863       useProxy = atoi(envforce)>0;
25864     }else{
25865       struct statfs fsInfo;
25866
25867       if( statfs(zPath, &fsInfo) == -1 ){
25868                                 ((unixFile*)pFile)->lastErrno = errno;
25869         if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
25870         close(fd); /* silently leak if fail, in error */
25871         return SQLITE_IOERR_ACCESS;
25872       }
25873       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25874     }
25875     if( useProxy ){
25876       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25877       if( rc==SQLITE_OK ){
25878         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25879       }
25880       return rc;
25881     }
25882   }
25883 #endif
25884   
25885   return fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25886 }
25887
25888 /*
25889 ** Delete the file at zPath. If the dirSync argument is true, fsync()
25890 ** the directory after deleting the file.
25891 */
25892 static int unixDelete(
25893   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25894   const char *zPath,        /* Name of file to be deleted */
25895   int dirSync               /* If true, fsync() directory after deleting file */
25896 ){
25897   int rc = SQLITE_OK;
25898   UNUSED_PARAMETER(NotUsed);
25899   SimulateIOError(return SQLITE_IOERR_DELETE);
25900   unlink(zPath);
25901 #ifndef SQLITE_DISABLE_DIRSYNC
25902   if( dirSync ){
25903     int fd;
25904     rc = openDirectory(zPath, &fd);
25905     if( rc==SQLITE_OK ){
25906 #if OS_VXWORKS
25907       if( fsync(fd)==-1 )
25908 #else
25909       if( fsync(fd) )
25910 #endif
25911       {
25912         rc = SQLITE_IOERR_DIR_FSYNC;
25913       }
25914       if( close(fd)&&!rc ){
25915         rc = SQLITE_IOERR_DIR_CLOSE;
25916       }
25917     }
25918   }
25919 #endif
25920   return rc;
25921 }
25922
25923 /*
25924 ** Test the existance of or access permissions of file zPath. The
25925 ** test performed depends on the value of flags:
25926 **
25927 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25928 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25929 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25930 **
25931 ** Otherwise return 0.
25932 */
25933 static int unixAccess(
25934   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25935   const char *zPath,      /* Path of the file to examine */
25936   int flags,              /* What do we want to learn about the zPath file? */
25937   int *pResOut            /* Write result boolean here */
25938 ){
25939   int amode = 0;
25940   UNUSED_PARAMETER(NotUsed);
25941   SimulateIOError( return SQLITE_IOERR_ACCESS; );
25942   switch( flags ){
25943     case SQLITE_ACCESS_EXISTS:
25944       amode = F_OK;
25945       break;
25946     case SQLITE_ACCESS_READWRITE:
25947       amode = W_OK|R_OK;
25948       break;
25949     case SQLITE_ACCESS_READ:
25950       amode = R_OK;
25951       break;
25952
25953     default:
25954       assert(!"Invalid flags argument");
25955   }
25956   *pResOut = (access(zPath, amode)==0);
25957   return SQLITE_OK;
25958 }
25959
25960
25961 /*
25962 ** Turn a relative pathname into a full pathname. The relative path
25963 ** is stored as a nul-terminated string in the buffer pointed to by
25964 ** zPath. 
25965 **
25966 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
25967 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
25968 ** this buffer before returning.
25969 */
25970 static int unixFullPathname(
25971   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25972   const char *zPath,            /* Possibly relative input path */
25973   int nOut,                     /* Size of output buffer in bytes */
25974   char *zOut                    /* Output buffer */
25975 ){
25976
25977   /* It's odd to simulate an io-error here, but really this is just
25978   ** using the io-error infrastructure to test that SQLite handles this
25979   ** function failing. This function could fail if, for example, the
25980   ** current working directory has been unlinked.
25981   */
25982   SimulateIOError( return SQLITE_ERROR );
25983
25984   assert( pVfs->mxPathname==MAX_PATHNAME );
25985   UNUSED_PARAMETER(pVfs);
25986
25987   zOut[nOut-1] = '\0';
25988   if( zPath[0]=='/' ){
25989     sqlite3_snprintf(nOut, zOut, "%s", zPath);
25990   }else{
25991     int nCwd;
25992     if( getcwd(zOut, nOut-1)==0 ){
25993       return SQLITE_CANTOPEN;
25994     }
25995     nCwd = (int)strlen(zOut);
25996     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25997   }
25998   return SQLITE_OK;
25999 }
26000
26001
26002 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26003 /*
26004 ** Interfaces for opening a shared library, finding entry points
26005 ** within the shared library, and closing the shared library.
26006 */
26007 #include <dlfcn.h>
26008 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
26009   UNUSED_PARAMETER(NotUsed);
26010   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
26011 }
26012
26013 /*
26014 ** SQLite calls this function immediately after a call to unixDlSym() or
26015 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
26016 ** message is available, it is written to zBufOut. If no error message
26017 ** is available, zBufOut is left unmodified and SQLite uses a default
26018 ** error message.
26019 */
26020 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
26021   char *zErr;
26022   UNUSED_PARAMETER(NotUsed);
26023   unixEnterMutex();
26024   zErr = dlerror();
26025   if( zErr ){
26026     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
26027   }
26028   unixLeaveMutex();
26029 }
26030 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
26031   /* 
26032   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
26033   ** cast into a pointer to a function.  And yet the library dlsym() routine
26034   ** returns a void* which is really a pointer to a function.  So how do we
26035   ** use dlsym() with -pedantic-errors?
26036   **
26037   ** Variable x below is defined to be a pointer to a function taking
26038   ** parameters void* and const char* and returning a pointer to a function.
26039   ** We initialize x by assigning it a pointer to the dlsym() function.
26040   ** (That assignment requires a cast.)  Then we call the function that
26041   ** x points to.  
26042   **
26043   ** This work-around is unlikely to work correctly on any system where
26044   ** you really cannot cast a function pointer into void*.  But then, on the
26045   ** other hand, dlsym() will not work on such a system either, so we have
26046   ** not really lost anything.
26047   */
26048   void (*(*x)(void*,const char*))(void);
26049   UNUSED_PARAMETER(NotUsed);
26050   x = (void(*(*)(void*,const char*))(void))dlsym;
26051   return (*x)(p, zSym);
26052 }
26053 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
26054   UNUSED_PARAMETER(NotUsed);
26055   dlclose(pHandle);
26056 }
26057 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
26058   #define unixDlOpen  0
26059   #define unixDlError 0
26060   #define unixDlSym   0
26061   #define unixDlClose 0
26062 #endif
26063
26064 /*
26065 ** Write nBuf bytes of random data to the supplied buffer zBuf.
26066 */
26067 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
26068   UNUSED_PARAMETER(NotUsed);
26069   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
26070
26071   /* We have to initialize zBuf to prevent valgrind from reporting
26072   ** errors.  The reports issued by valgrind are incorrect - we would
26073   ** prefer that the randomness be increased by making use of the
26074   ** uninitialized space in zBuf - but valgrind errors tend to worry
26075   ** some users.  Rather than argue, it seems easier just to initialize
26076   ** the whole array and silence valgrind, even if that means less randomness
26077   ** in the random seed.
26078   **
26079   ** When testing, initializing zBuf[] to zero is all we do.  That means
26080   ** that we always use the same random number sequence.  This makes the
26081   ** tests repeatable.
26082   */
26083   memset(zBuf, 0, nBuf);
26084 #if !defined(SQLITE_TEST)
26085   {
26086     int pid, fd;
26087     fd = open("/dev/urandom", O_RDONLY);
26088     if( fd<0 ){
26089       time_t t;
26090       time(&t);
26091       memcpy(zBuf, &t, sizeof(t));
26092       pid = getpid();
26093       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
26094       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
26095       nBuf = sizeof(t) + sizeof(pid);
26096     }else{
26097       nBuf = read(fd, zBuf, nBuf);
26098       close(fd);
26099     }
26100   }
26101 #endif
26102   return nBuf;
26103 }
26104
26105
26106 /*
26107 ** Sleep for a little while.  Return the amount of time slept.
26108 ** The argument is the number of microseconds we want to sleep.
26109 ** The return value is the number of microseconds of sleep actually
26110 ** requested from the underlying operating system, a number which
26111 ** might be greater than or equal to the argument, but not less
26112 ** than the argument.
26113 */
26114 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
26115 #if OS_VXWORKS
26116   struct timespec sp;
26117
26118   sp.tv_sec = microseconds / 1000000;
26119   sp.tv_nsec = (microseconds % 1000000) * 1000;
26120   nanosleep(&sp, NULL);
26121   return microseconds;
26122 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
26123   usleep(microseconds);
26124   return microseconds;
26125 #else
26126   int seconds = (microseconds+999999)/1000000;
26127   sleep(seconds);
26128   return seconds*1000000;
26129 #endif
26130   UNUSED_PARAMETER(NotUsed);
26131 }
26132
26133 /*
26134 ** The following variable, if set to a non-zero value, is interpreted as
26135 ** the number of seconds since 1970 and is used to set the result of
26136 ** sqlite3OsCurrentTime() during testing.
26137 */
26138 #ifdef SQLITE_TEST
26139 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
26140 #endif
26141
26142 /*
26143 ** Find the current time (in Universal Coordinated Time).  Write the
26144 ** current time and date as a Julian Day number into *prNow and
26145 ** return 0.  Return 1 if the time and date cannot be found.
26146 */
26147 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
26148 #if defined(NO_GETTOD)
26149   time_t t;
26150   time(&t);
26151   *prNow = t/86400.0 + 2440587.5;
26152 #elif OS_VXWORKS
26153   struct timespec sNow;
26154   clock_gettime(CLOCK_REALTIME, &sNow);
26155   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
26156 #else
26157   struct timeval sNow;
26158   gettimeofday(&sNow, 0);
26159   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
26160 #endif
26161
26162 #ifdef SQLITE_TEST
26163   if( sqlite3_current_time ){
26164     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26165   }
26166 #endif
26167   UNUSED_PARAMETER(NotUsed);
26168   return 0;
26169 }
26170
26171 /*
26172 ** We added the xGetLastError() method with the intention of providing
26173 ** better low-level error messages when operating-system problems come up
26174 ** during SQLite operation.  But so far, none of that has been implemented
26175 ** in the core.  So this routine is never called.  For now, it is merely
26176 ** a place-holder.
26177 */
26178 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
26179   UNUSED_PARAMETER(NotUsed);
26180   UNUSED_PARAMETER(NotUsed2);
26181   UNUSED_PARAMETER(NotUsed3);
26182   return 0;
26183 }
26184
26185 /*
26186 ************************ End of sqlite3_vfs methods ***************************
26187 ******************************************************************************/
26188
26189 /******************************************************************************
26190 ************************** Begin Proxy Locking ********************************
26191 **
26192 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
26193 ** other locking methods on secondary lock files.  Proxy locking is a
26194 ** meta-layer over top of the primitive locking implemented above.  For
26195 ** this reason, the division that implements of proxy locking is deferred
26196 ** until late in the file (here) after all of the other I/O methods have
26197 ** been defined - so that the primitive locking methods are available
26198 ** as services to help with the implementation of proxy locking.
26199 **
26200 ****
26201 **
26202 ** The default locking schemes in SQLite use byte-range locks on the
26203 ** database file to coordinate safe, concurrent access by multiple readers
26204 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
26205 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
26206 ** as POSIX read & write locks over fixed set of locations (via fsctl),
26207 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
26208 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
26209 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
26210 ** address in the shared range is taken for a SHARED lock, the entire
26211 ** shared range is taken for an EXCLUSIVE lock):
26212 **
26213 **      PENDING_BYTE        0x40000000                  
26214 **      RESERVED_BYTE       0x40000001
26215 **      SHARED_RANGE        0x40000002 -> 0x40000200
26216 **
26217 ** This works well on the local file system, but shows a nearly 100x
26218 ** slowdown in read performance on AFP because the AFP client disables
26219 ** the read cache when byte-range locks are present.  Enabling the read
26220 ** cache exposes a cache coherency problem that is present on all OS X
26221 ** supported network file systems.  NFS and AFP both observe the
26222 ** close-to-open semantics for ensuring cache coherency
26223 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
26224 ** address the requirements for concurrent database access by multiple
26225 ** readers and writers
26226 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
26227 **
26228 ** To address the performance and cache coherency issues, proxy file locking
26229 ** changes the way database access is controlled by limiting access to a
26230 ** single host at a time and moving file locks off of the database file
26231 ** and onto a proxy file on the local file system.  
26232 **
26233 **
26234 ** Using proxy locks
26235 ** -----------------
26236 **
26237 ** C APIs
26238 **
26239 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
26240 **                       <proxy_path> | ":auto:");
26241 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
26242 **
26243 **
26244 ** SQL pragmas
26245 **
26246 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
26247 **  PRAGMA [database.]lock_proxy_file
26248 **
26249 ** Specifying ":auto:" means that if there is a conch file with a matching
26250 ** host ID in it, the proxy path in the conch file will be used, otherwise
26251 ** a proxy path based on the user's temp dir
26252 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
26253 ** actual proxy file name is generated from the name and path of the
26254 ** database file.  For example:
26255 **
26256 **       For database path "/Users/me/foo.db" 
26257 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
26258 **
26259 ** Once a lock proxy is configured for a database connection, it can not
26260 ** be removed, however it may be switched to a different proxy path via
26261 ** the above APIs (assuming the conch file is not being held by another
26262 ** connection or process). 
26263 **
26264 **
26265 ** How proxy locking works
26266 ** -----------------------
26267 **
26268 ** Proxy file locking relies primarily on two new supporting files: 
26269 **
26270 **   *  conch file to limit access to the database file to a single host
26271 **      at a time
26272 **
26273 **   *  proxy file to act as a proxy for the advisory locks normally
26274 **      taken on the database
26275 **
26276 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
26277 ** by taking an sqlite-style shared lock on the conch file, reading the
26278 ** contents and comparing the host's unique host ID (see below) and lock
26279 ** proxy path against the values stored in the conch.  The conch file is
26280 ** stored in the same directory as the database file and the file name
26281 ** is patterned after the database file name as ".<databasename>-conch".
26282 ** If the conch file does not exist, or it's contents do not match the
26283 ** host ID and/or proxy path, then the lock is escalated to an exclusive
26284 ** lock and the conch file contents is updated with the host ID and proxy
26285 ** path and the lock is downgraded to a shared lock again.  If the conch
26286 ** is held by another process (with a shared lock), the exclusive lock
26287 ** will fail and SQLITE_BUSY is returned.
26288 **
26289 ** The proxy file - a single-byte file used for all advisory file locks
26290 ** normally taken on the database file.   This allows for safe sharing
26291 ** of the database file for multiple readers and writers on the same
26292 ** host (the conch ensures that they all use the same local lock file).
26293 **
26294 ** There is a third file - the host ID file - used as a persistent record
26295 ** of a unique identifier for the host, a 128-byte unique host id file
26296 ** in the path defined by the HOSTIDPATH macro (default value is
26297 ** /Library/Caches/.com.apple.sqliteConchHostId).
26298 **
26299 ** Requesting the lock proxy does not immediately take the conch, it is
26300 ** only taken when the first request to lock database file is made.  
26301 ** This matches the semantics of the traditional locking behavior, where
26302 ** opening a connection to a database file does not take a lock on it.
26303 ** The shared lock and an open file descriptor are maintained until 
26304 ** the connection to the database is closed. 
26305 **
26306 ** The proxy file and the lock file are never deleted so they only need
26307 ** to be created the first time they are used.
26308 **
26309 ** Configuration options
26310 ** ---------------------
26311 **
26312 **  SQLITE_PREFER_PROXY_LOCKING
26313 **
26314 **       Database files accessed on non-local file systems are
26315 **       automatically configured for proxy locking, lock files are
26316 **       named automatically using the same logic as
26317 **       PRAGMA lock_proxy_file=":auto:"
26318 **    
26319 **  SQLITE_PROXY_DEBUG
26320 **
26321 **       Enables the logging of error messages during host id file
26322 **       retrieval and creation
26323 **
26324 **  HOSTIDPATH
26325 **
26326 **       Overrides the default host ID file path location
26327 **
26328 **  LOCKPROXYDIR
26329 **
26330 **       Overrides the default directory used for lock proxy files that
26331 **       are named automatically via the ":auto:" setting
26332 **
26333 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26334 **
26335 **       Permissions to use when creating a directory for storing the
26336 **       lock proxy files, only used when LOCKPROXYDIR is not set.
26337 **    
26338 **    
26339 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
26340 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
26341 ** force proxy locking to be used for every database file opened, and 0
26342 ** will force automatic proxy locking to be disabled for all database
26343 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
26344 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
26345 */
26346
26347 /*
26348 ** Proxy locking is only available on MacOSX 
26349 */
26350 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26351
26352 #ifdef SQLITE_TEST
26353 /* simulate multiple hosts by creating unique hostid file paths */
26354 SQLITE_API int sqlite3_hostid_num = 0;
26355 #endif
26356
26357 /*
26358 ** The proxyLockingContext has the path and file structures for the remote 
26359 ** and local proxy files in it
26360 */
26361 typedef struct proxyLockingContext proxyLockingContext;
26362 struct proxyLockingContext {
26363   unixFile *conchFile;         /* Open conch file */
26364   char *conchFilePath;         /* Name of the conch file */
26365   unixFile *lockProxy;         /* Open proxy lock file */
26366   char *lockProxyPath;         /* Name of the proxy lock file */
26367   char *dbPath;                /* Name of the open file */
26368   int conchHeld;               /* True if the conch is currently held */
26369   void *oldLockingContext;     /* Original lockingcontext to restore on close */
26370   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26371 };
26372
26373 /* HOSTIDLEN and CONCHLEN both include space for the string 
26374 ** terminating nul 
26375 */
26376 #define HOSTIDLEN         128
26377 #define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26378 #ifndef HOSTIDPATH
26379 # define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26380 #endif
26381
26382 /* basically a copy of unixRandomness with different
26383 ** test behavior built in */
26384 static int proxyGenerateHostID(char *pHostID){
26385   int pid, fd, len;
26386   unsigned char *key = (unsigned char *)pHostID;
26387   
26388   memset(key, 0, HOSTIDLEN);
26389   len = 0;
26390   fd = open("/dev/urandom", O_RDONLY);
26391   if( fd>=0 ){
26392     len = read(fd, key, HOSTIDLEN);
26393     close(fd); /* silently leak the fd if it fails */
26394   }
26395   if( len < HOSTIDLEN ){
26396     time_t t;
26397     time(&t);
26398     memcpy(key, &t, sizeof(t));
26399     pid = getpid();
26400     memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26401   }
26402   
26403 #ifdef MAKE_PRETTY_HOSTID
26404   {
26405     int i;
26406     /* filter the bytes into printable ascii characters and NUL terminate */
26407     key[(HOSTIDLEN-1)] = 0x00;
26408     for( i=0; i<(HOSTIDLEN-1); i++ ){
26409       unsigned char pa = key[i]&0x7F;
26410       if( pa<0x20 ){
26411         key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26412       }else if( pa==0x7F ){
26413         key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26414       }
26415     }
26416   }
26417 #endif
26418   return SQLITE_OK;
26419 }
26420
26421 /* writes the host id path to path, path should be an pre-allocated buffer
26422 ** with enough space for a path 
26423 */
26424 static void proxyGetHostIDPath(char *path, size_t len){
26425   strlcpy(path, HOSTIDPATH, len);
26426 #ifdef SQLITE_TEST
26427   if( sqlite3_hostid_num>0 ){
26428     char suffix[2] = "1";
26429     suffix[0] = suffix[0] + sqlite3_hostid_num;
26430     strlcat(path, suffix, len);
26431   }
26432 #endif
26433   OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26434 }
26435
26436 /* get the host ID from a sqlite hostid file stored in the 
26437 ** user-specific tmp directory, create the ID if it's not there already 
26438 */
26439 static int proxyGetHostID(char *pHostID, int *pError){
26440   int fd;
26441   char path[MAXPATHLEN]; 
26442   size_t len;
26443   int rc=SQLITE_OK;
26444
26445   proxyGetHostIDPath(path, MAXPATHLEN);
26446   /* try to create the host ID file, if it already exists read the contents */
26447   fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26448   if( fd<0 ){
26449     int err=errno;
26450                 
26451     if( err!=EEXIST ){
26452 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26453       fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26454               path, strerror(err));
26455 #endif
26456       return SQLITE_PERM;
26457     }
26458     /* couldn't create the file, read it instead */
26459     fd = open(path, O_RDONLY|O_EXCL);
26460     if( fd<0 ){
26461 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26462       int err = errno;
26463       fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26464               path, strerror(err));
26465 #endif
26466       return SQLITE_PERM;
26467     }
26468     len = pread(fd, pHostID, HOSTIDLEN, 0);
26469     if( len<0 ){
26470       *pError = errno;
26471       rc = SQLITE_IOERR_READ;
26472     }else if( len<HOSTIDLEN ){
26473       *pError = 0;
26474       rc = SQLITE_IOERR_SHORT_READ;
26475     }
26476     close(fd); /* silently leak the fd if it fails */
26477     OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26478     return rc;
26479   }else{
26480     /* we're creating the host ID file (use a random string of bytes) */
26481     proxyGenerateHostID(pHostID);
26482     len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26483     if( len<0 ){
26484       *pError = errno;
26485       rc = SQLITE_IOERR_WRITE;
26486     }else if( len<HOSTIDLEN ){
26487       *pError = 0;
26488       rc = SQLITE_IOERR_WRITE;
26489     }
26490     close(fd); /* silently leak the fd if it fails */
26491     OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26492     return rc;
26493   }
26494 }
26495
26496 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26497   int len;
26498   int dbLen;
26499   int i;
26500
26501 #ifdef LOCKPROXYDIR
26502   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26503 #else
26504 # ifdef _CS_DARWIN_USER_TEMP_DIR
26505   {
26506     confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26507     len = strlcat(lPath, "sqliteplocks", maxLen);
26508     if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26509       /* if mkdir fails, handle as lock file creation failure */
26510       int err = errno;
26511 #  ifdef SQLITE_DEBUG
26512       if( err!=EEXIST ){
26513         fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26514                 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26515       }
26516 #  endif
26517     }else{
26518       OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26519     }
26520     
26521   }
26522 # else
26523   len = strlcpy(lPath, "/tmp/", maxLen);
26524 # endif
26525 #endif
26526
26527   if( lPath[len-1]!='/' ){
26528     len = strlcat(lPath, "/", maxLen);
26529   }
26530   
26531   /* transform the db path to a unique cache name */
26532   dbLen = (int)strlen(dbPath);
26533   for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26534     char c = dbPath[i];
26535     lPath[i+len] = (c=='/')?'_':c;
26536   }
26537   lPath[i+len]='\0';
26538   strlcat(lPath, ":auto:", maxLen);
26539   return SQLITE_OK;
26540 }
26541
26542 /*
26543 ** Create a new VFS file descriptor (stored in memory obtained from
26544 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
26545 **
26546 ** The caller is responsible not only for closing the file descriptor
26547 ** but also for freeing the memory associated with the file descriptor.
26548 */
26549 static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26550   int fd;
26551   int dirfd = -1;
26552   unixFile *pNew;
26553   int rc = SQLITE_OK;
26554   sqlite3_vfs dummyVfs;
26555
26556   fd = open(path, O_RDWR | O_CREAT, SQLITE_DEFAULT_FILE_PERMISSIONS);
26557   if( fd<0 ){
26558     return SQLITE_CANTOPEN;
26559   }
26560   
26561   pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26562   if( pNew==NULL ){
26563     rc = SQLITE_NOMEM;
26564     goto end_create_proxy;
26565   }
26566   memset(pNew, 0, sizeof(unixFile));
26567
26568   dummyVfs.pAppData = (void*)&autolockIoFinder;
26569   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
26570   if( rc==SQLITE_OK ){
26571     *ppFile = pNew;
26572     return SQLITE_OK;
26573   }
26574 end_create_proxy:    
26575   close(fd); /* silently leak fd if error, we're already in error */
26576   sqlite3_free(pNew);
26577   return rc;
26578 }
26579
26580 /* takes the conch by taking a shared lock and read the contents conch, if 
26581 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
26582 ** lockPath means that the lockPath in the conch file will be used if the 
26583 ** host IDs match, or a new lock path will be generated automatically 
26584 ** and written to the conch file.
26585 */
26586 static int proxyTakeConch(unixFile *pFile){
26587   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
26588   
26589   if( pCtx->conchHeld>0 ){
26590     return SQLITE_OK;
26591   }else{
26592     unixFile *conchFile = pCtx->conchFile;
26593     char testValue[CONCHLEN];
26594     char conchValue[CONCHLEN];
26595     char lockPath[MAXPATHLEN];
26596     char *tLockPath = NULL;
26597     int rc = SQLITE_OK;
26598     int readRc = SQLITE_OK;
26599     int syncPerms = 0;
26600
26601     OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26602              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26603
26604     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26605     if( rc==SQLITE_OK ){
26606       int pError = 0;
26607       memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26608       rc = proxyGetHostID(testValue, &pError);
26609       if( (rc&0xff)==SQLITE_IOERR ){
26610         pFile->lastErrno = pError;
26611       }
26612       if( pCtx->lockProxyPath ){
26613         strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26614       }
26615     }
26616     if( rc!=SQLITE_OK ){
26617       goto end_takeconch;
26618     }
26619     
26620     readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26621     if( readRc!=SQLITE_IOERR_SHORT_READ ){
26622       if( readRc!=SQLITE_OK ){
26623         if( (rc&0xff)==SQLITE_IOERR ){
26624           pFile->lastErrno = conchFile->lastErrno;
26625         }
26626         rc = readRc;
26627         goto end_takeconch;
26628       }
26629       /* if the conch has data compare the contents */
26630       if( !pCtx->lockProxyPath ){
26631         /* for auto-named local lock file, just check the host ID and we'll
26632          ** use the local lock file path that's already in there */
26633         if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26634           tLockPath = (char *)&conchValue[HOSTIDLEN];
26635           goto end_takeconch;
26636         }
26637       }else{
26638         /* we've got the conch if conchValue matches our path and host ID */
26639         if( !memcmp(testValue, conchValue, CONCHLEN) ){
26640           goto end_takeconch;
26641         }
26642       }
26643     }else{
26644       /* a short read means we're "creating" the conch (even though it could 
26645       ** have been user-intervention), if we acquire the exclusive lock,
26646       ** we'll try to match the current on-disk permissions of the database
26647       */
26648       syncPerms = 1;
26649     }
26650     
26651     /* either conch was emtpy or didn't match */
26652     if( !pCtx->lockProxyPath ){
26653       proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26654       tLockPath = lockPath;
26655       strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26656     }
26657     
26658     /* update conch with host and path (this will fail if other process
26659      ** has a shared lock already) */
26660     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26661     if( rc==SQLITE_OK ){
26662       rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26663       if( rc==SQLITE_OK && syncPerms ){
26664         struct stat buf;
26665         int err = fstat(pFile->h, &buf);
26666         if( err==0 ){
26667           /* try to match the database file permissions, ignore failure */
26668 #ifndef SQLITE_PROXY_DEBUG
26669           fchmod(conchFile->h, buf.st_mode);
26670 #else
26671           if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26672             int code = errno;
26673             fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26674                              buf.st_mode, code, strerror(code));
26675           } else {
26676             fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26677           }
26678         }else{
26679           int code = errno;
26680           fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
26681                           err, code, strerror(code));
26682 #endif
26683         }
26684       }
26685     }
26686     conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26687   
26688 end_takeconch:
26689     OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26690     if( rc==SQLITE_OK && pFile->openFlags ){
26691       if( pFile->h>=0 ){
26692 #ifdef STRICT_CLOSE_ERROR
26693         if( close(pFile->h) ){
26694           pFile->lastErrno = errno;
26695           return SQLITE_IOERR_CLOSE;
26696         }
26697 #else
26698         close(pFile->h); /* silently leak fd if fail */
26699 #endif
26700       }
26701       pFile->h = -1;
26702       int fd = open(pCtx->dbPath, pFile->openFlags,
26703                     SQLITE_DEFAULT_FILE_PERMISSIONS);
26704       OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26705       if( fd>=0 ){
26706         pFile->h = fd;
26707       }else{
26708         rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26709                                during locking */
26710       }
26711     }
26712     if( rc==SQLITE_OK && !pCtx->lockProxy ){
26713       char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26714       /* ACS: Need to make a copy of path sometimes */
26715       rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26716     }
26717     if( rc==SQLITE_OK ){
26718       pCtx->conchHeld = 1;
26719
26720       if( tLockPath ){
26721         pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26722         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26723           ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26724                      pCtx->lockProxyPath;
26725         }
26726       }
26727     } else {
26728       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26729     }
26730     OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26731     return rc;
26732   }
26733 }
26734
26735 /*
26736 ** If pFile holds a lock on a conch file, then release that lock.
26737 */
26738 static int proxyReleaseConch(unixFile *pFile){
26739   int rc;                     /* Subroutine return code */
26740   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26741   unixFile *conchFile;        /* Name of the conch file */
26742
26743   pCtx = (proxyLockingContext *)pFile->lockingContext;
26744   conchFile = pCtx->conchFile;
26745   OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26746            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
26747            getpid());
26748   pCtx->conchHeld = 0;
26749   rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26750   OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26751            (rc==SQLITE_OK ? "ok" : "failed"));
26752   return rc;
26753 }
26754
26755 /*
26756 ** Given the name of a database file, compute the name of its conch file.
26757 ** Store the conch filename in memory obtained from sqlite3_malloc().
26758 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26759 ** or SQLITE_NOMEM if unable to obtain memory.
26760 **
26761 ** The caller is responsible for ensuring that the allocated memory
26762 ** space is eventually freed.
26763 **
26764 ** *pConchPath is set to NULL if a memory allocation error occurs.
26765 */
26766 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26767   int i;                        /* Loop counter */
26768   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26769   char *conchPath;              /* buffer in which to construct conch name */
26770
26771   /* Allocate space for the conch filename and initialize the name to
26772   ** the name of the original database file. */  
26773   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26774   if( conchPath==0 ){
26775     return SQLITE_NOMEM;
26776   }
26777   memcpy(conchPath, dbPath, len+1);
26778   
26779   /* now insert a "." before the last / character */
26780   for( i=(len-1); i>=0; i-- ){
26781     if( conchPath[i]=='/' ){
26782       i++;
26783       break;
26784     }
26785   }
26786   conchPath[i]='.';
26787   while ( i<len ){
26788     conchPath[i+1]=dbPath[i];
26789     i++;
26790   }
26791
26792   /* append the "-conch" suffix to the file */
26793   memcpy(&conchPath[i+1], "-conch", 7);
26794   assert( (int)strlen(conchPath) == len+7 );
26795
26796   return SQLITE_OK;
26797 }
26798
26799
26800 /* Takes a fully configured proxy locking-style unix file and switches
26801 ** the local lock file path 
26802 */
26803 static int switchLockProxyPath(unixFile *pFile, const char *path) {
26804   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26805   char *oldPath = pCtx->lockProxyPath;
26806   int rc = SQLITE_OK;
26807
26808   if( pFile->locktype!=NO_LOCK ){
26809     return SQLITE_BUSY;
26810   }  
26811
26812   /* nothing to do if the path is NULL, :auto: or matches the existing path */
26813   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26814     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26815     return SQLITE_OK;
26816   }else{
26817     unixFile *lockProxy = pCtx->lockProxy;
26818     pCtx->lockProxy=NULL;
26819     pCtx->conchHeld = 0;
26820     if( lockProxy!=NULL ){
26821       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26822       if( rc ) return rc;
26823       sqlite3_free(lockProxy);
26824     }
26825     sqlite3_free(oldPath);
26826     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26827   }
26828   
26829   return rc;
26830 }
26831
26832 /*
26833 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
26834 ** is a string buffer at least MAXPATHLEN+1 characters in size.
26835 **
26836 ** This routine find the filename associated with pFile and writes it
26837 ** int dbPath.
26838 */
26839 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26840 #if defined(__APPLE__)
26841   if( pFile->pMethod == &afpIoMethods ){
26842     /* afp style keeps a reference to the db path in the filePath field 
26843     ** of the struct */
26844     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26845     strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26846   }else
26847 #endif
26848   if( pFile->pMethod == &dotlockIoMethods ){
26849     /* dot lock style uses the locking context to store the dot lock
26850     ** file path */
26851     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26852     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26853   }else{
26854     /* all other styles use the locking context to store the db file path */
26855     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26856     strcpy(dbPath, (char *)pFile->lockingContext);
26857   }
26858   return SQLITE_OK;
26859 }
26860
26861 /*
26862 ** Takes an already filled in unix file and alters it so all file locking 
26863 ** will be performed on the local proxy lock file.  The following fields
26864 ** are preserved in the locking context so that they can be restored and 
26865 ** the unix structure properly cleaned up at close time:
26866 **  ->lockingContext
26867 **  ->pMethod
26868 */
26869 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26870   proxyLockingContext *pCtx;
26871   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26872   char *lockPath=NULL;
26873   int rc = SQLITE_OK;
26874   
26875   if( pFile->locktype!=NO_LOCK ){
26876     return SQLITE_BUSY;
26877   }
26878   proxyGetDbPathForUnixFile(pFile, dbPath);
26879   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26880     lockPath=NULL;
26881   }else{
26882     lockPath=(char *)path;
26883   }
26884   
26885   OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26886            (lockPath ? lockPath : ":auto:"), getpid());
26887
26888   pCtx = sqlite3_malloc( sizeof(*pCtx) );
26889   if( pCtx==0 ){
26890     return SQLITE_NOMEM;
26891   }
26892   memset(pCtx, 0, sizeof(*pCtx));
26893
26894   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26895   if( rc==SQLITE_OK ){
26896     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26897   }  
26898   if( rc==SQLITE_OK && lockPath ){
26899     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26900   }
26901
26902   if( rc==SQLITE_OK ){
26903     /* all memory is allocated, proxys are created and assigned, 
26904     ** switch the locking context and pMethod then return.
26905     */
26906     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26907     pCtx->oldLockingContext = pFile->lockingContext;
26908     pFile->lockingContext = pCtx;
26909     pCtx->pOldMethod = pFile->pMethod;
26910     pFile->pMethod = &proxyIoMethods;
26911   }else{
26912     if( pCtx->conchFile ){ 
26913       rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26914       if( rc ) return rc;
26915       sqlite3_free(pCtx->conchFile);
26916     }
26917     sqlite3_free(pCtx->conchFilePath); 
26918     sqlite3_free(pCtx);
26919   }
26920   OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26921            (rc==SQLITE_OK ? "ok" : "failed"));
26922   return rc;
26923 }
26924
26925
26926 /*
26927 ** This routine handles sqlite3_file_control() calls that are specific
26928 ** to proxy locking.
26929 */
26930 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26931   switch( op ){
26932     case SQLITE_GET_LOCKPROXYFILE: {
26933       unixFile *pFile = (unixFile*)id;
26934       if( pFile->pMethod == &proxyIoMethods ){
26935         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26936         proxyTakeConch(pFile);
26937         if( pCtx->lockProxyPath ){
26938           *(const char **)pArg = pCtx->lockProxyPath;
26939         }else{
26940           *(const char **)pArg = ":auto: (not held)";
26941         }
26942       } else {
26943         *(const char **)pArg = NULL;
26944       }
26945       return SQLITE_OK;
26946     }
26947     case SQLITE_SET_LOCKPROXYFILE: {
26948       unixFile *pFile = (unixFile*)id;
26949       int rc = SQLITE_OK;
26950       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26951       if( pArg==NULL || (const char *)pArg==0 ){
26952         if( isProxyStyle ){
26953           /* turn off proxy locking - not supported */
26954           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26955         }else{
26956           /* turn off proxy locking - already off - NOOP */
26957           rc = SQLITE_OK;
26958         }
26959       }else{
26960         const char *proxyPath = (const char *)pArg;
26961         if( isProxyStyle ){
26962           proxyLockingContext *pCtx = 
26963             (proxyLockingContext*)pFile->lockingContext;
26964           if( !strcmp(pArg, ":auto:") 
26965            || (pCtx->lockProxyPath &&
26966                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26967           ){
26968             rc = SQLITE_OK;
26969           }else{
26970             rc = switchLockProxyPath(pFile, proxyPath);
26971           }
26972         }else{
26973           /* turn on proxy file locking */
26974           rc = proxyTransformUnixFile(pFile, proxyPath);
26975         }
26976       }
26977       return rc;
26978     }
26979     default: {
26980       assert( 0 );  /* The call assures that only valid opcodes are sent */
26981     }
26982   }
26983   /*NOTREACHED*/
26984   return SQLITE_ERROR;
26985 }
26986
26987 /*
26988 ** Within this division (the proxying locking implementation) the procedures
26989 ** above this point are all utilities.  The lock-related methods of the
26990 ** proxy-locking sqlite3_io_method object follow.
26991 */
26992
26993
26994 /*
26995 ** This routine checks if there is a RESERVED lock held on the specified
26996 ** file by this or any other process. If such a lock is held, set *pResOut
26997 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26998 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26999 */
27000 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
27001   unixFile *pFile = (unixFile*)id;
27002   int rc = proxyTakeConch(pFile);
27003   if( rc==SQLITE_OK ){
27004     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27005     unixFile *proxy = pCtx->lockProxy;
27006     return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
27007   }
27008   return rc;
27009 }
27010
27011 /*
27012 ** Lock the file with the lock specified by parameter locktype - one
27013 ** of the following:
27014 **
27015 **     (1) SHARED_LOCK
27016 **     (2) RESERVED_LOCK
27017 **     (3) PENDING_LOCK
27018 **     (4) EXCLUSIVE_LOCK
27019 **
27020 ** Sometimes when requesting one lock state, additional lock states
27021 ** are inserted in between.  The locking might fail on one of the later
27022 ** transitions leaving the lock state different from what it started but
27023 ** still short of its goal.  The following chart shows the allowed
27024 ** transitions and the inserted intermediate states:
27025 **
27026 **    UNLOCKED -> SHARED
27027 **    SHARED -> RESERVED
27028 **    SHARED -> (PENDING) -> EXCLUSIVE
27029 **    RESERVED -> (PENDING) -> EXCLUSIVE
27030 **    PENDING -> EXCLUSIVE
27031 **
27032 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27033 ** routine to lower a locking level.
27034 */
27035 static int proxyLock(sqlite3_file *id, int locktype) {
27036   unixFile *pFile = (unixFile*)id;
27037   int rc = proxyTakeConch(pFile);
27038   if( rc==SQLITE_OK ){
27039     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27040     unixFile *proxy = pCtx->lockProxy;
27041     rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
27042     pFile->locktype = proxy->locktype;
27043   }
27044   return rc;
27045 }
27046
27047
27048 /*
27049 ** Lower the locking level on file descriptor pFile to locktype.  locktype
27050 ** must be either NO_LOCK or SHARED_LOCK.
27051 **
27052 ** If the locking level of the file descriptor is already at or below
27053 ** the requested locking level, this routine is a no-op.
27054 */
27055 static int proxyUnlock(sqlite3_file *id, int locktype) {
27056   unixFile *pFile = (unixFile*)id;
27057   int rc = proxyTakeConch(pFile);
27058   if( rc==SQLITE_OK ){
27059     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27060     unixFile *proxy = pCtx->lockProxy;
27061     rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
27062     pFile->locktype = proxy->locktype;
27063   }
27064   return rc;
27065 }
27066
27067 /*
27068 ** Close a file that uses proxy locks.
27069 */
27070 static int proxyClose(sqlite3_file *id) {
27071   if( id ){
27072     unixFile *pFile = (unixFile*)id;
27073     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27074     unixFile *lockProxy = pCtx->lockProxy;
27075     unixFile *conchFile = pCtx->conchFile;
27076     int rc = SQLITE_OK;
27077     
27078     if( lockProxy ){
27079       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
27080       if( rc ) return rc;
27081       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
27082       if( rc ) return rc;
27083       sqlite3_free(lockProxy);
27084       pCtx->lockProxy = 0;
27085     }
27086     if( conchFile ){
27087       if( pCtx->conchHeld ){
27088         rc = proxyReleaseConch(pFile);
27089         if( rc ) return rc;
27090       }
27091       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
27092       if( rc ) return rc;
27093       sqlite3_free(conchFile);
27094     }
27095     sqlite3_free(pCtx->lockProxyPath);
27096     sqlite3_free(pCtx->conchFilePath);
27097     sqlite3_free(pCtx->dbPath);
27098     /* restore the original locking context and pMethod then close it */
27099     pFile->lockingContext = pCtx->oldLockingContext;
27100     pFile->pMethod = pCtx->pOldMethod;
27101     sqlite3_free(pCtx);
27102     return pFile->pMethod->xClose(id);
27103   }
27104   return SQLITE_OK;
27105 }
27106
27107
27108
27109 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27110 /*
27111 ** The proxy locking style is intended for use with AFP filesystems.
27112 ** And since AFP is only supported on MacOSX, the proxy locking is also
27113 ** restricted to MacOSX.
27114 ** 
27115 **
27116 ******************* End of the proxy lock implementation **********************
27117 ******************************************************************************/
27118
27119 /*
27120 ** Initialize the operating system interface.
27121 **
27122 ** This routine registers all VFS implementations for unix-like operating
27123 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
27124 ** should be the only routines in this file that are visible from other
27125 ** files.
27126 **
27127 ** This routine is called once during SQLite initialization and by a
27128 ** single thread.  The memory allocation and mutex subsystems have not
27129 ** necessarily been initialized when this routine is called, and so they
27130 ** should not be used.
27131 */
27132 SQLITE_API int sqlite3_os_init(void){ 
27133   /* 
27134   ** The following macro defines an initializer for an sqlite3_vfs object.
27135   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
27136   ** to the "finder" function.  (pAppData is a pointer to a pointer because
27137   ** silly C90 rules prohibit a void* from being cast to a function pointer
27138   ** and so we have to go through the intermediate pointer to avoid problems
27139   ** when compiling with -pedantic-errors on GCC.)
27140   **
27141   ** The FINDER parameter to this macro is the name of the pointer to the
27142   ** finder-function.  The finder-function returns a pointer to the
27143   ** sqlite_io_methods object that implements the desired locking
27144   ** behaviors.  See the division above that contains the IOMETHODS
27145   ** macro for addition information on finder-functions.
27146   **
27147   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
27148   ** object.  But the "autolockIoFinder" available on MacOSX does a little
27149   ** more than that; it looks at the filesystem type that hosts the 
27150   ** database file and tries to choose an locking method appropriate for
27151   ** that filesystem time.
27152   */
27153   #define UNIXVFS(VFSNAME, FINDER) {                        \
27154     1,                    /* iVersion */                    \
27155     sizeof(unixFile),     /* szOsFile */                    \
27156     MAX_PATHNAME,         /* mxPathname */                  \
27157     0,                    /* pNext */                       \
27158     VFSNAME,              /* zName */                       \
27159     (void*)&FINDER,       /* pAppData */                    \
27160     unixOpen,             /* xOpen */                       \
27161     unixDelete,           /* xDelete */                     \
27162     unixAccess,           /* xAccess */                     \
27163     unixFullPathname,     /* xFullPathname */               \
27164     unixDlOpen,           /* xDlOpen */                     \
27165     unixDlError,          /* xDlError */                    \
27166     unixDlSym,            /* xDlSym */                      \
27167     unixDlClose,          /* xDlClose */                    \
27168     unixRandomness,       /* xRandomness */                 \
27169     unixSleep,            /* xSleep */                      \
27170     unixCurrentTime,      /* xCurrentTime */                \
27171     unixGetLastError      /* xGetLastError */               \
27172   }
27173
27174   /*
27175   ** All default VFSes for unix are contained in the following array.
27176   **
27177   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
27178   ** by the SQLite core when the VFS is registered.  So the following
27179   ** array cannot be const.
27180   */
27181   static sqlite3_vfs aVfs[] = {
27182 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27183     UNIXVFS("unix",          autolockIoFinder ),
27184 #else
27185     UNIXVFS("unix",          posixIoFinder ),
27186 #endif
27187     UNIXVFS("unix-none",     nolockIoFinder ),
27188     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
27189 #if OS_VXWORKS
27190     UNIXVFS("unix-namedsem", semIoFinder ),
27191 #endif
27192 #if SQLITE_ENABLE_LOCKING_STYLE
27193     UNIXVFS("unix-posix",    posixIoFinder ),
27194     UNIXVFS("unix-flock",    flockIoFinder ),
27195 #endif
27196 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27197     UNIXVFS("unix-afp",      afpIoFinder ),
27198     UNIXVFS("unix-proxy",    proxyIoFinder ),
27199 #endif
27200   };
27201   unsigned int i;          /* Loop counter */
27202
27203   /* Register all VFSes defined in the aVfs[] array */
27204   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
27205     sqlite3_vfs_register(&aVfs[i], i==0);
27206   }
27207   return SQLITE_OK; 
27208 }
27209
27210 /*
27211 ** Shutdown the operating system interface.
27212 **
27213 ** Some operating systems might need to do some cleanup in this routine,
27214 ** to release dynamically allocated objects.  But not on unix.
27215 ** This routine is a no-op for unix.
27216 */
27217 SQLITE_API int sqlite3_os_end(void){ 
27218   return SQLITE_OK; 
27219 }
27220  
27221 #endif /* SQLITE_OS_UNIX */
27222
27223 /************** End of os_unix.c *********************************************/
27224 /************** Begin file os_win.c ******************************************/
27225 /*
27226 ** 2004 May 22
27227 **
27228 ** The author disclaims copyright to this source code.  In place of
27229 ** a legal notice, here is a blessing:
27230 **
27231 **    May you do good and not evil.
27232 **    May you find forgiveness for yourself and forgive others.
27233 **    May you share freely, never taking more than you give.
27234 **
27235 ******************************************************************************
27236 **
27237 ** This file contains code that is specific to windows.
27238 **
27239 ** $Id: os_win.c,v 1.148 2009/02/05 03:16:21 shane Exp $
27240 */
27241 #if SQLITE_OS_WIN               /* This file is used for windows only */
27242
27243
27244 /*
27245 ** A Note About Memory Allocation:
27246 **
27247 ** This driver uses malloc()/free() directly rather than going through
27248 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
27249 ** are designed for use on embedded systems where memory is scarce and
27250 ** malloc failures happen frequently.  Win32 does not typically run on
27251 ** embedded systems, and when it does the developers normally have bigger
27252 ** problems to worry about than running out of memory.  So there is not
27253 ** a compelling need to use the wrappers.
27254 **
27255 ** But there is a good reason to not use the wrappers.  If we use the
27256 ** wrappers then we will get simulated malloc() failures within this
27257 ** driver.  And that causes all kinds of problems for our tests.  We
27258 ** could enhance SQLite to deal with simulated malloc failures within
27259 ** the OS driver, but the code to deal with those failure would not
27260 ** be exercised on Linux (which does not need to malloc() in the driver)
27261 ** and so we would have difficulty writing coverage tests for that
27262 ** code.  Better to leave the code out, we think.
27263 **
27264 ** The point of this discussion is as follows:  When creating a new
27265 ** OS layer for an embedded system, if you use this file as an example,
27266 ** avoid the use of malloc()/free().  Those routines work ok on windows
27267 ** desktops but not so well in embedded systems.
27268 */
27269
27270 #include <winbase.h>
27271
27272 #ifdef __CYGWIN__
27273 # include <sys/cygwin.h>
27274 #endif
27275
27276 /*
27277 ** Macros used to determine whether or not to use threads.
27278 */
27279 #if defined(THREADSAFE) && THREADSAFE
27280 # define SQLITE_W32_THREADS 1
27281 #endif
27282
27283 /*
27284 ** Include code that is common to all os_*.c files
27285 */
27286 /************** Include os_common.h in the middle of os_win.c ****************/
27287 /************** Begin file os_common.h ***************************************/
27288 /*
27289 ** 2004 May 22
27290 **
27291 ** The author disclaims copyright to this source code.  In place of
27292 ** a legal notice, here is a blessing:
27293 **
27294 **    May you do good and not evil.
27295 **    May you find forgiveness for yourself and forgive others.
27296 **    May you share freely, never taking more than you give.
27297 **
27298 ******************************************************************************
27299 **
27300 ** This file contains macros and a little bit of code that is common to
27301 ** all of the platform-specific files (os_*.c) and is #included into those
27302 ** files.
27303 **
27304 ** This file should be #included by the os_*.c files only.  It is not a
27305 ** general purpose header file.
27306 **
27307 ** $Id: os_common.h,v 1.37 2008/05/29 20:22:37 shane Exp $
27308 */
27309 #ifndef _OS_COMMON_H_
27310 #define _OS_COMMON_H_
27311
27312 /*
27313 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
27314 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
27315 ** switch.  The following code should catch this problem at compile-time.
27316 */
27317 #ifdef MEMORY_DEBUG
27318 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
27319 #endif
27320
27321
27322 /*
27323  * When testing, this global variable stores the location of the
27324  * pending-byte in the database file.
27325  */
27326 #ifdef SQLITE_TEST
27327 SQLITE_API unsigned int sqlite3_pending_byte = 0x40000000;
27328 #endif
27329
27330 #ifdef SQLITE_DEBUG
27331 SQLITE_PRIVATE int sqlite3OSTrace = 0;
27332 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
27333 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
27334 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
27335 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27336 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27337 #define OSTRACE6(X,Y,Z,A,B,C) \
27338     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27339 #define OSTRACE7(X,Y,Z,A,B,C,D) \
27340     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27341 #else
27342 #define OSTRACE1(X)
27343 #define OSTRACE2(X,Y)
27344 #define OSTRACE3(X,Y,Z)
27345 #define OSTRACE4(X,Y,Z,A)
27346 #define OSTRACE5(X,Y,Z,A,B)
27347 #define OSTRACE6(X,Y,Z,A,B,C)
27348 #define OSTRACE7(X,Y,Z,A,B,C,D)
27349 #endif
27350
27351 /*
27352 ** Macros for performance tracing.  Normally turned off.  Only works
27353 ** on i486 hardware.
27354 */
27355 #ifdef SQLITE_PERFORMANCE_TRACE
27356
27357 /* 
27358 ** hwtime.h contains inline assembler code for implementing 
27359 ** high-performance timing routines.
27360 */
27361 /************** Include hwtime.h in the middle of os_common.h ****************/
27362 /************** Begin file hwtime.h ******************************************/
27363 /*
27364 ** 2008 May 27
27365 **
27366 ** The author disclaims copyright to this source code.  In place of
27367 ** a legal notice, here is a blessing:
27368 **
27369 **    May you do good and not evil.
27370 **    May you find forgiveness for yourself and forgive others.
27371 **    May you share freely, never taking more than you give.
27372 **
27373 ******************************************************************************
27374 **
27375 ** This file contains inline asm code for retrieving "high-performance"
27376 ** counters for x86 class CPUs.
27377 **
27378 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
27379 */
27380 #ifndef _HWTIME_H_
27381 #define _HWTIME_H_
27382
27383 /*
27384 ** The following routine only works on pentium-class (or newer) processors.
27385 ** It uses the RDTSC opcode to read the cycle count value out of the
27386 ** processor and returns that value.  This can be used for high-res
27387 ** profiling.
27388 */
27389 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
27390       (defined(i386) || defined(__i386__) || defined(_M_IX86))
27391
27392   #if defined(__GNUC__)
27393
27394   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27395      unsigned int lo, hi;
27396      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27397      return (sqlite_uint64)hi << 32 | lo;
27398   }
27399
27400   #elif defined(_MSC_VER)
27401
27402   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27403      __asm {
27404         rdtsc
27405         ret       ; return value at EDX:EAX
27406      }
27407   }
27408
27409   #endif
27410
27411 #elif (defined(__GNUC__) && defined(__x86_64__))
27412
27413   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27414       unsigned long val;
27415       __asm__ __volatile__ ("rdtsc" : "=A" (val));
27416       return val;
27417   }
27418  
27419 #elif (defined(__GNUC__) && defined(__ppc__))
27420
27421   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27422       unsigned long long retval;
27423       unsigned long junk;
27424       __asm__ __volatile__ ("\n\
27425           1:      mftbu   %1\n\
27426                   mftb    %L0\n\
27427                   mftbu   %0\n\
27428                   cmpw    %0,%1\n\
27429                   bne     1b"
27430                   : "=r" (retval), "=r" (junk));
27431       return retval;
27432   }
27433
27434 #else
27435
27436   #error Need implementation of sqlite3Hwtime() for your platform.
27437
27438   /*
27439   ** To compile without implementing sqlite3Hwtime() for your platform,
27440   ** you can remove the above #error and use the following
27441   ** stub function.  You will lose timing support for many
27442   ** of the debugging and testing utilities, but it should at
27443   ** least compile and run.
27444   */
27445 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27446
27447 #endif
27448
27449 #endif /* !defined(_HWTIME_H_) */
27450
27451 /************** End of hwtime.h **********************************************/
27452 /************** Continuing where we left off in os_common.h ******************/
27453
27454 static sqlite_uint64 g_start;
27455 static sqlite_uint64 g_elapsed;
27456 #define TIMER_START       g_start=sqlite3Hwtime()
27457 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27458 #define TIMER_ELAPSED     g_elapsed
27459 #else
27460 #define TIMER_START
27461 #define TIMER_END
27462 #define TIMER_ELAPSED     ((sqlite_uint64)0)
27463 #endif
27464
27465 /*
27466 ** If we compile with the SQLITE_TEST macro set, then the following block
27467 ** of code will give us the ability to simulate a disk I/O error.  This
27468 ** is used for testing the I/O recovery logic.
27469 */
27470 #ifdef SQLITE_TEST
27471 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27472 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27473 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27474 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27475 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27476 SQLITE_API int sqlite3_diskfull_pending = 0;
27477 SQLITE_API int sqlite3_diskfull = 0;
27478 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27479 #define SimulateIOError(CODE)  \
27480   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27481        || sqlite3_io_error_pending-- == 1 )  \
27482               { local_ioerr(); CODE; }
27483 static void local_ioerr(){
27484   IOTRACE(("IOERR\n"));
27485   sqlite3_io_error_hit++;
27486   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27487 }
27488 #define SimulateDiskfullError(CODE) \
27489    if( sqlite3_diskfull_pending ){ \
27490      if( sqlite3_diskfull_pending == 1 ){ \
27491        local_ioerr(); \
27492        sqlite3_diskfull = 1; \
27493        sqlite3_io_error_hit = 1; \
27494        CODE; \
27495      }else{ \
27496        sqlite3_diskfull_pending--; \
27497      } \
27498    }
27499 #else
27500 #define SimulateIOErrorBenign(X)
27501 #define SimulateIOError(A)
27502 #define SimulateDiskfullError(A)
27503 #endif
27504
27505 /*
27506 ** When testing, keep a count of the number of open files.
27507 */
27508 #ifdef SQLITE_TEST
27509 SQLITE_API int sqlite3_open_file_count = 0;
27510 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
27511 #else
27512 #define OpenCounter(X)
27513 #endif
27514
27515 #endif /* !defined(_OS_COMMON_H_) */
27516
27517 /************** End of os_common.h *******************************************/
27518 /************** Continuing where we left off in os_win.c *********************/
27519
27520 /*
27521 ** Some microsoft compilers lack this definition.
27522 */
27523 #ifndef INVALID_FILE_ATTRIBUTES
27524 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
27525 #endif
27526
27527 /*
27528 ** Determine if we are dealing with WindowsCE - which has a much
27529 ** reduced API.
27530 */
27531 #if SQLITE_OS_WINCE
27532 # define AreFileApisANSI() 1
27533 #endif
27534
27535 /*
27536 ** WinCE lacks native support for file locking so we have to fake it
27537 ** with some code of our own.
27538 */
27539 #if SQLITE_OS_WINCE
27540 typedef struct winceLock {
27541   int nReaders;       /* Number of reader locks obtained */
27542   BOOL bPending;      /* Indicates a pending lock has been obtained */
27543   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27544   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27545 } winceLock;
27546 #endif
27547
27548 /*
27549 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
27550 ** portability layer.
27551 */
27552 typedef struct winFile winFile;
27553 struct winFile {
27554   const sqlite3_io_methods *pMethod;/* Must be first */
27555   HANDLE h;               /* Handle for accessing the file */
27556   unsigned char locktype; /* Type of lock currently held on this file */
27557   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27558   DWORD lastErrno;        /* The Windows errno from the last I/O error */
27559 #if SQLITE_OS_WINCE
27560   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27561   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
27562   HANDLE hShared;         /* Shared memory segment used for locking */
27563   winceLock local;        /* Locks obtained by this instance of winFile */
27564   winceLock *shared;      /* Global shared lock memory for the file  */
27565 #endif
27566 };
27567
27568
27569 /*
27570 ** The following variable is (normally) set once and never changes
27571 ** thereafter.  It records whether the operating system is Win95
27572 ** or WinNT.
27573 **
27574 ** 0:   Operating system unknown.
27575 ** 1:   Operating system is Win95.
27576 ** 2:   Operating system is WinNT.
27577 **
27578 ** In order to facilitate testing on a WinNT system, the test fixture
27579 ** can manually set this value to 1 to emulate Win98 behavior.
27580 */
27581 #ifdef SQLITE_TEST
27582 SQLITE_API int sqlite3_os_type = 0;
27583 #else
27584 static int sqlite3_os_type = 0;
27585 #endif
27586
27587 /*
27588 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27589 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27590 **
27591 ** Here is an interesting observation:  Win95, Win98, and WinME lack
27592 ** the LockFileEx() API.  But we can still statically link against that
27593 ** API as long as we don't call it win running Win95/98/ME.  A call to
27594 ** this routine is used to determine if the host is Win95/98/ME or
27595 ** WinNT/2K/XP so that we will know whether or not we can safely call
27596 ** the LockFileEx() API.
27597 */
27598 #if SQLITE_OS_WINCE
27599 # define isNT()  (1)
27600 #else
27601   static int isNT(void){
27602     if( sqlite3_os_type==0 ){
27603       OSVERSIONINFO sInfo;
27604       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27605       GetVersionEx(&sInfo);
27606       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27607     }
27608     return sqlite3_os_type==2;
27609   }
27610 #endif /* SQLITE_OS_WINCE */
27611
27612 /*
27613 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
27614 **
27615 ** Space to hold the returned string is obtained from malloc.
27616 */
27617 static WCHAR *utf8ToUnicode(const char *zFilename){
27618   int nChar;
27619   WCHAR *zWideFilename;
27620
27621   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27622   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27623   if( zWideFilename==0 ){
27624     return 0;
27625   }
27626   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27627   if( nChar==0 ){
27628     free(zWideFilename);
27629     zWideFilename = 0;
27630   }
27631   return zWideFilename;
27632 }
27633
27634 /*
27635 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27636 ** obtained from malloc().
27637 */
27638 static char *unicodeToUtf8(const WCHAR *zWideFilename){
27639   int nByte;
27640   char *zFilename;
27641
27642   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27643   zFilename = malloc( nByte );
27644   if( zFilename==0 ){
27645     return 0;
27646   }
27647   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27648                               0, 0);
27649   if( nByte == 0 ){
27650     free(zFilename);
27651     zFilename = 0;
27652   }
27653   return zFilename;
27654 }
27655
27656 /*
27657 ** Convert an ansi string to microsoft unicode, based on the
27658 ** current codepage settings for file apis.
27659 ** 
27660 ** Space to hold the returned string is obtained
27661 ** from malloc.
27662 */
27663 static WCHAR *mbcsToUnicode(const char *zFilename){
27664   int nByte;
27665   WCHAR *zMbcsFilename;
27666   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27667
27668   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27669   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27670   if( zMbcsFilename==0 ){
27671     return 0;
27672   }
27673   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27674   if( nByte==0 ){
27675     free(zMbcsFilename);
27676     zMbcsFilename = 0;
27677   }
27678   return zMbcsFilename;
27679 }
27680
27681 /*
27682 ** Convert microsoft unicode to multibyte character string, based on the
27683 ** user's Ansi codepage.
27684 **
27685 ** Space to hold the returned string is obtained from
27686 ** malloc().
27687 */
27688 static char *unicodeToMbcs(const WCHAR *zWideFilename){
27689   int nByte;
27690   char *zFilename;
27691   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27692
27693   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27694   zFilename = malloc( nByte );
27695   if( zFilename==0 ){
27696     return 0;
27697   }
27698   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27699                               0, 0);
27700   if( nByte == 0 ){
27701     free(zFilename);
27702     zFilename = 0;
27703   }
27704   return zFilename;
27705 }
27706
27707 /*
27708 ** Convert multibyte character string to UTF-8.  Space to hold the
27709 ** returned string is obtained from malloc().
27710 */
27711 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27712   char *zFilenameUtf8;
27713   WCHAR *zTmpWide;
27714
27715   zTmpWide = mbcsToUnicode(zFilename);
27716   if( zTmpWide==0 ){
27717     return 0;
27718   }
27719   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27720   free(zTmpWide);
27721   return zFilenameUtf8;
27722 }
27723
27724 /*
27725 ** Convert UTF-8 to multibyte character string.  Space to hold the 
27726 ** returned string is obtained from malloc().
27727 */
27728 static char *utf8ToMbcs(const char *zFilename){
27729   char *zFilenameMbcs;
27730   WCHAR *zTmpWide;
27731
27732   zTmpWide = utf8ToUnicode(zFilename);
27733   if( zTmpWide==0 ){
27734     return 0;
27735   }
27736   zFilenameMbcs = unicodeToMbcs(zTmpWide);
27737   free(zTmpWide);
27738   return zFilenameMbcs;
27739 }
27740
27741 #if SQLITE_OS_WINCE
27742 /*************************************************************************
27743 ** This section contains code for WinCE only.
27744 */
27745 /*
27746 ** WindowsCE does not have a localtime() function.  So create a
27747 ** substitute.
27748 */
27749 struct tm *__cdecl localtime(const time_t *t)
27750 {
27751   static struct tm y;
27752   FILETIME uTm, lTm;
27753   SYSTEMTIME pTm;
27754   sqlite3_int64 t64;
27755   t64 = *t;
27756   t64 = (t64 + 11644473600)*10000000;
27757   uTm.dwLowDateTime = t64 & 0xFFFFFFFF;
27758   uTm.dwHighDateTime= t64 >> 32;
27759   FileTimeToLocalFileTime(&uTm,&lTm);
27760   FileTimeToSystemTime(&lTm,&pTm);
27761   y.tm_year = pTm.wYear - 1900;
27762   y.tm_mon = pTm.wMonth - 1;
27763   y.tm_wday = pTm.wDayOfWeek;
27764   y.tm_mday = pTm.wDay;
27765   y.tm_hour = pTm.wHour;
27766   y.tm_min = pTm.wMinute;
27767   y.tm_sec = pTm.wSecond;
27768   return &y;
27769 }
27770
27771 /* This will never be called, but defined to make the code compile */
27772 #define GetTempPathA(a,b)
27773
27774 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27775 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27776 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27777
27778 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-offsetof(winFile,h)]
27779
27780 /*
27781 ** Acquire a lock on the handle h
27782 */
27783 static void winceMutexAcquire(HANDLE h){
27784    DWORD dwErr;
27785    do {
27786      dwErr = WaitForSingleObject(h, INFINITE);
27787    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27788 }
27789 /*
27790 ** Release a lock acquired by winceMutexAcquire()
27791 */
27792 #define winceMutexRelease(h) ReleaseMutex(h)
27793
27794 /*
27795 ** Create the mutex and shared memory used for locking in the file
27796 ** descriptor pFile
27797 */
27798 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27799   WCHAR *zTok;
27800   WCHAR *zName = utf8ToUnicode(zFilename);
27801   BOOL bInit = TRUE;
27802
27803   /* Initialize the local lockdata */
27804   ZeroMemory(&pFile->local, sizeof(pFile->local));
27805
27806   /* Replace the backslashes from the filename and lowercase it
27807   ** to derive a mutex name. */
27808   zTok = CharLowerW(zName);
27809   for (;*zTok;zTok++){
27810     if (*zTok == '\\') *zTok = '_';
27811   }
27812
27813   /* Create/open the named mutex */
27814   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27815   if (!pFile->hMutex){
27816     pFile->lastErrno = GetLastError();
27817     free(zName);
27818     return FALSE;
27819   }
27820
27821   /* Acquire the mutex before continuing */
27822   winceMutexAcquire(pFile->hMutex);
27823   
27824   /* Since the names of named mutexes, semaphores, file mappings etc are 
27825   ** case-sensitive, take advantage of that by uppercasing the mutex name
27826   ** and using that as the shared filemapping name.
27827   */
27828   CharUpperW(zName);
27829   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27830                                        PAGE_READWRITE, 0, sizeof(winceLock),
27831                                        zName);  
27832
27833   /* Set a flag that indicates we're the first to create the memory so it 
27834   ** must be zero-initialized */
27835   if (GetLastError() == ERROR_ALREADY_EXISTS){
27836     bInit = FALSE;
27837   }
27838
27839   free(zName);
27840
27841   /* If we succeeded in making the shared memory handle, map it. */
27842   if (pFile->hShared){
27843     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
27844              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27845     /* If mapping failed, close the shared memory handle and erase it */
27846     if (!pFile->shared){
27847       pFile->lastErrno = GetLastError();
27848       CloseHandle(pFile->hShared);
27849       pFile->hShared = NULL;
27850     }
27851   }
27852
27853   /* If shared memory could not be created, then close the mutex and fail */
27854   if (pFile->hShared == NULL){
27855     winceMutexRelease(pFile->hMutex);
27856     CloseHandle(pFile->hMutex);
27857     pFile->hMutex = NULL;
27858     return FALSE;
27859   }
27860   
27861   /* Initialize the shared memory if we're supposed to */
27862   if (bInit) {
27863     ZeroMemory(pFile->shared, sizeof(winceLock));
27864   }
27865
27866   winceMutexRelease(pFile->hMutex);
27867   return TRUE;
27868 }
27869
27870 /*
27871 ** Destroy the part of winFile that deals with wince locks
27872 */
27873 static void winceDestroyLock(winFile *pFile){
27874   if (pFile->hMutex){
27875     /* Acquire the mutex */
27876     winceMutexAcquire(pFile->hMutex);
27877
27878     /* The following blocks should probably assert in debug mode, but they
27879        are to cleanup in case any locks remained open */
27880     if (pFile->local.nReaders){
27881       pFile->shared->nReaders --;
27882     }
27883     if (pFile->local.bReserved){
27884       pFile->shared->bReserved = FALSE;
27885     }
27886     if (pFile->local.bPending){
27887       pFile->shared->bPending = FALSE;
27888     }
27889     if (pFile->local.bExclusive){
27890       pFile->shared->bExclusive = FALSE;
27891     }
27892
27893     /* De-reference and close our copy of the shared memory handle */
27894     UnmapViewOfFile(pFile->shared);
27895     CloseHandle(pFile->hShared);
27896
27897     /* Done with the mutex */
27898     winceMutexRelease(pFile->hMutex);    
27899     CloseHandle(pFile->hMutex);
27900     pFile->hMutex = NULL;
27901   }
27902 }
27903
27904 /* 
27905 ** An implementation of the LockFile() API of windows for wince
27906 */
27907 static BOOL winceLockFile(
27908   HANDLE *phFile,
27909   DWORD dwFileOffsetLow,
27910   DWORD dwFileOffsetHigh,
27911   DWORD nNumberOfBytesToLockLow,
27912   DWORD nNumberOfBytesToLockHigh
27913 ){
27914   winFile *pFile = HANDLE_TO_WINFILE(phFile);
27915   BOOL bReturn = FALSE;
27916
27917   if (!pFile->hMutex) return TRUE;
27918   winceMutexAcquire(pFile->hMutex);
27919
27920   /* Wanting an exclusive lock? */
27921   if (dwFileOffsetLow == SHARED_FIRST
27922        && nNumberOfBytesToLockLow == SHARED_SIZE){
27923     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27924        pFile->shared->bExclusive = TRUE;
27925        pFile->local.bExclusive = TRUE;
27926        bReturn = TRUE;
27927     }
27928   }
27929
27930   /* Want a read-only lock? */
27931   else if ((dwFileOffsetLow >= SHARED_FIRST &&
27932             dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE) &&
27933             nNumberOfBytesToLockLow == 1){
27934     if (pFile->shared->bExclusive == 0){
27935       pFile->local.nReaders ++;
27936       if (pFile->local.nReaders == 1){
27937         pFile->shared->nReaders ++;
27938       }
27939       bReturn = TRUE;
27940     }
27941   }
27942
27943   /* Want a pending lock? */
27944   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27945     /* If no pending lock has been acquired, then acquire it */
27946     if (pFile->shared->bPending == 0) {
27947       pFile->shared->bPending = TRUE;
27948       pFile->local.bPending = TRUE;
27949       bReturn = TRUE;
27950     }
27951   }
27952   /* Want a reserved lock? */
27953   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27954     if (pFile->shared->bReserved == 0) {
27955       pFile->shared->bReserved = TRUE;
27956       pFile->local.bReserved = TRUE;
27957       bReturn = TRUE;
27958     }
27959   }
27960
27961   winceMutexRelease(pFile->hMutex);
27962   return bReturn;
27963 }
27964
27965 /*
27966 ** An implementation of the UnlockFile API of windows for wince
27967 */
27968 static BOOL winceUnlockFile(
27969   HANDLE *phFile,
27970   DWORD dwFileOffsetLow,
27971   DWORD dwFileOffsetHigh,
27972   DWORD nNumberOfBytesToUnlockLow,
27973   DWORD nNumberOfBytesToUnlockHigh
27974 ){
27975   winFile *pFile = HANDLE_TO_WINFILE(phFile);
27976   BOOL bReturn = FALSE;
27977
27978   if (!pFile->hMutex) return TRUE;
27979   winceMutexAcquire(pFile->hMutex);
27980
27981   /* Releasing a reader lock or an exclusive lock */
27982   if (dwFileOffsetLow >= SHARED_FIRST &&
27983        dwFileOffsetLow < SHARED_FIRST + SHARED_SIZE){
27984     /* Did we have an exclusive lock? */
27985     if (pFile->local.bExclusive){
27986       pFile->local.bExclusive = FALSE;
27987       pFile->shared->bExclusive = FALSE;
27988       bReturn = TRUE;
27989     }
27990
27991     /* Did we just have a reader lock? */
27992     else if (pFile->local.nReaders){
27993       pFile->local.nReaders --;
27994       if (pFile->local.nReaders == 0)
27995       {
27996         pFile->shared->nReaders --;
27997       }
27998       bReturn = TRUE;
27999     }
28000   }
28001
28002   /* Releasing a pending lock */
28003   else if (dwFileOffsetLow == PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
28004     if (pFile->local.bPending){
28005       pFile->local.bPending = FALSE;
28006       pFile->shared->bPending = FALSE;
28007       bReturn = TRUE;
28008     }
28009   }
28010   /* Releasing a reserved lock */
28011   else if (dwFileOffsetLow == RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
28012     if (pFile->local.bReserved) {
28013       pFile->local.bReserved = FALSE;
28014       pFile->shared->bReserved = FALSE;
28015       bReturn = TRUE;
28016     }
28017   }
28018
28019   winceMutexRelease(pFile->hMutex);
28020   return bReturn;
28021 }
28022
28023 /*
28024 ** An implementation of the LockFileEx() API of windows for wince
28025 */
28026 static BOOL winceLockFileEx(
28027   HANDLE *phFile,
28028   DWORD dwFlags,
28029   DWORD dwReserved,
28030   DWORD nNumberOfBytesToLockLow,
28031   DWORD nNumberOfBytesToLockHigh,
28032   LPOVERLAPPED lpOverlapped
28033 ){
28034   /* If the caller wants a shared read lock, forward this call
28035   ** to winceLockFile */
28036   if (lpOverlapped->Offset == SHARED_FIRST &&
28037       dwFlags == 1 &&
28038       nNumberOfBytesToLockLow == SHARED_SIZE){
28039     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
28040   }
28041   return FALSE;
28042 }
28043 /*
28044 ** End of the special code for wince
28045 *****************************************************************************/
28046 #endif /* SQLITE_OS_WINCE */
28047
28048 /*****************************************************************************
28049 ** The next group of routines implement the I/O methods specified
28050 ** by the sqlite3_io_methods object.
28051 ******************************************************************************/
28052
28053 /*
28054 ** Close a file.
28055 **
28056 ** It is reported that an attempt to close a handle might sometimes
28057 ** fail.  This is a very unreasonable result, but windows is notorious
28058 ** for being unreasonable so I do not doubt that it might happen.  If
28059 ** the close fails, we pause for 100 milliseconds and try again.  As
28060 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
28061 ** giving up and returning an error.
28062 */
28063 #define MX_CLOSE_ATTEMPT 3
28064 static int winClose(sqlite3_file *id){
28065   int rc, cnt = 0;
28066   winFile *pFile = (winFile*)id;
28067   OSTRACE2("CLOSE %d\n", pFile->h);
28068   do{
28069     rc = CloseHandle(pFile->h);
28070   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
28071 #if SQLITE_OS_WINCE
28072 #define WINCE_DELETION_ATTEMPTS 3
28073   winceDestroyLock(pFile);
28074   if( pFile->zDeleteOnClose ){
28075     int cnt = 0;
28076     while(
28077            DeleteFileW(pFile->zDeleteOnClose)==0
28078         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
28079         && cnt++ < WINCE_DELETION_ATTEMPTS
28080     ){
28081        Sleep(100);  /* Wait a little before trying again */
28082     }
28083     free(pFile->zDeleteOnClose);
28084   }
28085 #endif
28086   OpenCounter(-1);
28087   return rc ? SQLITE_OK : SQLITE_IOERR;
28088 }
28089
28090 /*
28091 ** Some microsoft compilers lack this definition.
28092 */
28093 #ifndef INVALID_SET_FILE_POINTER
28094 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
28095 #endif
28096
28097 /*
28098 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28099 ** bytes were read successfully and SQLITE_IOERR if anything goes
28100 ** wrong.
28101 */
28102 static int winRead(
28103   sqlite3_file *id,          /* File to read from */
28104   void *pBuf,                /* Write content into this buffer */
28105   int amt,                   /* Number of bytes to read */
28106   sqlite3_int64 offset       /* Begin reading at this offset */
28107 ){
28108   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28109   LONG lowerBits = (LONG)(offset & 0xffffffff);
28110   DWORD rc;
28111   DWORD got;
28112   winFile *pFile = (winFile*)id;
28113   DWORD error;
28114   assert( id!=0 );
28115   SimulateIOError(return SQLITE_IOERR_READ);
28116   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
28117   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28118   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28119     pFile->lastErrno = error;
28120     return SQLITE_FULL;
28121   }
28122   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
28123     pFile->lastErrno = GetLastError();
28124     return SQLITE_IOERR_READ;
28125   }
28126   if( got==(DWORD)amt ){
28127     return SQLITE_OK;
28128   }else{
28129     /* Unread parts of the buffer must be zero-filled */
28130     memset(&((char*)pBuf)[got], 0, amt-got);
28131     return SQLITE_IOERR_SHORT_READ;
28132   }
28133 }
28134
28135 /*
28136 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28137 ** or some other error code on failure.
28138 */
28139 static int winWrite(
28140   sqlite3_file *id,         /* File to write into */
28141   const void *pBuf,         /* The bytes to be written */
28142   int amt,                  /* Number of bytes to write */
28143   sqlite3_int64 offset      /* Offset into the file to begin writing at */
28144 ){
28145   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28146   LONG lowerBits = (LONG)(offset & 0xffffffff);
28147   DWORD rc;
28148   DWORD wrote = 0;
28149   winFile *pFile = (winFile*)id;
28150   DWORD error;
28151   assert( id!=0 );
28152   SimulateIOError(return SQLITE_IOERR_WRITE);
28153   SimulateDiskfullError(return SQLITE_FULL);
28154   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
28155   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28156   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28157     pFile->lastErrno = error;
28158     return SQLITE_FULL;
28159   }
28160   assert( amt>0 );
28161   while(
28162      amt>0
28163      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
28164      && wrote>0
28165   ){
28166     amt -= wrote;
28167     pBuf = &((char*)pBuf)[wrote];
28168   }
28169   if( !rc || amt>(int)wrote ){
28170     pFile->lastErrno = GetLastError();
28171     return SQLITE_FULL;
28172   }
28173   return SQLITE_OK;
28174 }
28175
28176 /*
28177 ** Truncate an open file to a specified size
28178 */
28179 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
28180   DWORD rc;
28181   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
28182   LONG lowerBits = (LONG)(nByte & 0xffffffff);
28183   winFile *pFile = (winFile*)id;
28184   DWORD error = NO_ERROR;
28185   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
28186   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
28187   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28188   if( INVALID_SET_FILE_POINTER == rc ){
28189     error = GetLastError();
28190   }
28191   if( error == NO_ERROR ){
28192     /* SetEndOfFile will fail if nByte is negative */
28193     if( SetEndOfFile(pFile->h) ){
28194       return SQLITE_OK;
28195     }
28196     error = GetLastError();
28197   }
28198   pFile->lastErrno = error;
28199   return SQLITE_IOERR_TRUNCATE;
28200 }
28201
28202 #ifdef SQLITE_TEST
28203 /*
28204 ** Count the number of fullsyncs and normal syncs.  This is used to test
28205 ** that syncs and fullsyncs are occuring at the right times.
28206 */
28207 SQLITE_API int sqlite3_sync_count = 0;
28208 SQLITE_API int sqlite3_fullsync_count = 0;
28209 #endif
28210
28211 /*
28212 ** Make sure all writes to a particular file are committed to disk.
28213 */
28214 static int winSync(sqlite3_file *id, int flags){
28215 #ifndef SQLITE_NO_SYNC
28216   winFile *pFile = (winFile*)id;
28217   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
28218 #else
28219   UNUSED_PARAMETER(id);
28220 #endif
28221 #ifndef SQLITE_TEST
28222   UNUSED_PARAMETER(flags);
28223 #else
28224   if( flags & SQLITE_SYNC_FULL ){
28225     sqlite3_fullsync_count++;
28226   }
28227   sqlite3_sync_count++;
28228 #endif
28229   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28230   ** no-op
28231   */
28232 #ifdef SQLITE_NO_SYNC
28233     return SQLITE_OK;
28234 #else
28235   if( FlushFileBuffers(pFile->h) ){
28236     return SQLITE_OK;
28237   }else{
28238     pFile->lastErrno = GetLastError();
28239     return SQLITE_IOERR;
28240   }
28241 #endif
28242 }
28243
28244 /*
28245 ** Determine the current size of a file in bytes
28246 */
28247 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
28248   winFile *pFile = (winFile*)id;
28249   DWORD upperBits, lowerBits;
28250   DWORD error;
28251   SimulateIOError(return SQLITE_IOERR_FSTAT);
28252   lowerBits = GetFileSize(pFile->h, &upperBits);
28253   if(   (lowerBits == INVALID_FILE_SIZE)
28254      && ((error = GetLastError()) != NO_ERROR) )
28255   {
28256     pFile->lastErrno = error;
28257     return SQLITE_IOERR_FSTAT;
28258   }
28259   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
28260   return SQLITE_OK;
28261 }
28262
28263 /*
28264 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
28265 */
28266 #ifndef LOCKFILE_FAIL_IMMEDIATELY
28267 # define LOCKFILE_FAIL_IMMEDIATELY 1
28268 #endif
28269
28270 /*
28271 ** Acquire a reader lock.
28272 ** Different API routines are called depending on whether or not this
28273 ** is Win95 or WinNT.
28274 */
28275 static int getReadLock(winFile *pFile){
28276   int res;
28277   if( isNT() ){
28278     OVERLAPPED ovlp;
28279     ovlp.Offset = SHARED_FIRST;
28280     ovlp.OffsetHigh = 0;
28281     ovlp.hEvent = 0;
28282     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
28283                      0, SHARED_SIZE, 0, &ovlp);
28284 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28285 */
28286 #if SQLITE_OS_WINCE==0
28287   }else{
28288     int lk;
28289     sqlite3_randomness(sizeof(lk), &lk);
28290     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
28291     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
28292 #endif
28293   }
28294   if( res == 0 ){
28295     pFile->lastErrno = GetLastError();
28296   }
28297   return res;
28298 }
28299
28300 /*
28301 ** Undo a readlock
28302 */
28303 static int unlockReadLock(winFile *pFile){
28304   int res;
28305   if( isNT() ){
28306     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28307 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28308 */
28309 #if SQLITE_OS_WINCE==0
28310   }else{
28311     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
28312 #endif
28313   }
28314   if( res == 0 ){
28315     pFile->lastErrno = GetLastError();
28316   }
28317   return res;
28318 }
28319
28320 /*
28321 ** Lock the file with the lock specified by parameter locktype - one
28322 ** of the following:
28323 **
28324 **     (1) SHARED_LOCK
28325 **     (2) RESERVED_LOCK
28326 **     (3) PENDING_LOCK
28327 **     (4) EXCLUSIVE_LOCK
28328 **
28329 ** Sometimes when requesting one lock state, additional lock states
28330 ** are inserted in between.  The locking might fail on one of the later
28331 ** transitions leaving the lock state different from what it started but
28332 ** still short of its goal.  The following chart shows the allowed
28333 ** transitions and the inserted intermediate states:
28334 **
28335 **    UNLOCKED -> SHARED
28336 **    SHARED -> RESERVED
28337 **    SHARED -> (PENDING) -> EXCLUSIVE
28338 **    RESERVED -> (PENDING) -> EXCLUSIVE
28339 **    PENDING -> EXCLUSIVE
28340 **
28341 ** This routine will only increase a lock.  The winUnlock() routine
28342 ** erases all locks at once and returns us immediately to locking level 0.
28343 ** It is not possible to lower the locking level one step at a time.  You
28344 ** must go straight to locking level 0.
28345 */
28346 static int winLock(sqlite3_file *id, int locktype){
28347   int rc = SQLITE_OK;    /* Return code from subroutines */
28348   int res = 1;           /* Result of a windows lock call */
28349   int newLocktype;       /* Set pFile->locktype to this value before exiting */
28350   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28351   winFile *pFile = (winFile*)id;
28352   DWORD error = NO_ERROR;
28353
28354   assert( pFile!=0 );
28355   OSTRACE5("LOCK %d %d was %d(%d)\n",
28356           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28357
28358   /* If there is already a lock of this type or more restrictive on the
28359   ** OsFile, do nothing. Don't use the end_lock: exit path, as
28360   ** sqlite3OsEnterMutex() hasn't been called yet.
28361   */
28362   if( pFile->locktype>=locktype ){
28363     return SQLITE_OK;
28364   }
28365
28366   /* Make sure the locking sequence is correct
28367   */
28368   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28369   assert( locktype!=PENDING_LOCK );
28370   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28371
28372   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28373   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28374   ** the PENDING_LOCK byte is temporary.
28375   */
28376   newLocktype = pFile->locktype;
28377   if(   (pFile->locktype==NO_LOCK)
28378      || (   (locktype==EXCLUSIVE_LOCK)
28379          && (pFile->locktype==RESERVED_LOCK))
28380   ){
28381     int cnt = 3;
28382     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28383       /* Try 3 times to get the pending lock.  The pending lock might be
28384       ** held by another reader process who will release it momentarily.
28385       */
28386       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28387       Sleep(1);
28388     }
28389     gotPendingLock = res;
28390     if( !res ){
28391       error = GetLastError();
28392     }
28393   }
28394
28395   /* Acquire a shared lock
28396   */
28397   if( locktype==SHARED_LOCK && res ){
28398     assert( pFile->locktype==NO_LOCK );
28399     res = getReadLock(pFile);
28400     if( res ){
28401       newLocktype = SHARED_LOCK;
28402     }else{
28403       error = GetLastError();
28404     }
28405   }
28406
28407   /* Acquire a RESERVED lock
28408   */
28409   if( locktype==RESERVED_LOCK && res ){
28410     assert( pFile->locktype==SHARED_LOCK );
28411     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28412     if( res ){
28413       newLocktype = RESERVED_LOCK;
28414     }else{
28415       error = GetLastError();
28416     }
28417   }
28418
28419   /* Acquire a PENDING lock
28420   */
28421   if( locktype==EXCLUSIVE_LOCK && res ){
28422     newLocktype = PENDING_LOCK;
28423     gotPendingLock = 0;
28424   }
28425
28426   /* Acquire an EXCLUSIVE lock
28427   */
28428   if( locktype==EXCLUSIVE_LOCK && res ){
28429     assert( pFile->locktype>=SHARED_LOCK );
28430     res = unlockReadLock(pFile);
28431     OSTRACE2("unreadlock = %d\n", res);
28432     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28433     if( res ){
28434       newLocktype = EXCLUSIVE_LOCK;
28435     }else{
28436       error = GetLastError();
28437       OSTRACE2("error-code = %d\n", error);
28438       getReadLock(pFile);
28439     }
28440   }
28441
28442   /* If we are holding a PENDING lock that ought to be released, then
28443   ** release it now.
28444   */
28445   if( gotPendingLock && locktype==SHARED_LOCK ){
28446     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28447   }
28448
28449   /* Update the state of the lock has held in the file descriptor then
28450   ** return the appropriate result code.
28451   */
28452   if( res ){
28453     rc = SQLITE_OK;
28454   }else{
28455     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28456            locktype, newLocktype);
28457     pFile->lastErrno = error;
28458     rc = SQLITE_BUSY;
28459   }
28460   pFile->locktype = (u8)newLocktype;
28461   return rc;
28462 }
28463
28464 /*
28465 ** This routine checks if there is a RESERVED lock held on the specified
28466 ** file by this or any other process. If such a lock is held, return
28467 ** non-zero, otherwise zero.
28468 */
28469 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28470   int rc;
28471   winFile *pFile = (winFile*)id;
28472   assert( pFile!=0 );
28473   if( pFile->locktype>=RESERVED_LOCK ){
28474     rc = 1;
28475     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28476   }else{
28477     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28478     if( rc ){
28479       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28480     }
28481     rc = !rc;
28482     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28483   }
28484   *pResOut = rc;
28485   return SQLITE_OK;
28486 }
28487
28488 /*
28489 ** Lower the locking level on file descriptor id to locktype.  locktype
28490 ** must be either NO_LOCK or SHARED_LOCK.
28491 **
28492 ** If the locking level of the file descriptor is already at or below
28493 ** the requested locking level, this routine is a no-op.
28494 **
28495 ** It is not possible for this routine to fail if the second argument
28496 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28497 ** might return SQLITE_IOERR;
28498 */
28499 static int winUnlock(sqlite3_file *id, int locktype){
28500   int type;
28501   winFile *pFile = (winFile*)id;
28502   int rc = SQLITE_OK;
28503   assert( pFile!=0 );
28504   assert( locktype<=SHARED_LOCK );
28505   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28506           pFile->locktype, pFile->sharedLockByte);
28507   type = pFile->locktype;
28508   if( type>=EXCLUSIVE_LOCK ){
28509     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28510     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28511       /* This should never happen.  We should always be able to
28512       ** reacquire the read lock */
28513       rc = SQLITE_IOERR_UNLOCK;
28514     }
28515   }
28516   if( type>=RESERVED_LOCK ){
28517     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28518   }
28519   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28520     unlockReadLock(pFile);
28521   }
28522   if( type>=PENDING_LOCK ){
28523     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28524   }
28525   pFile->locktype = (u8)locktype;
28526   return rc;
28527 }
28528
28529 /*
28530 ** Control and query of the open file handle.
28531 */
28532 static int winFileControl(sqlite3_file *id, int op, void *pArg){
28533   switch( op ){
28534     case SQLITE_FCNTL_LOCKSTATE: {
28535       *(int*)pArg = ((winFile*)id)->locktype;
28536       return SQLITE_OK;
28537     }
28538     case SQLITE_LAST_ERRNO: {
28539       *(int*)pArg = (int)((winFile*)id)->lastErrno;
28540       return SQLITE_OK;
28541     }
28542   }
28543   return SQLITE_ERROR;
28544 }
28545
28546 /*
28547 ** Return the sector size in bytes of the underlying block device for
28548 ** the specified file. This is almost always 512 bytes, but may be
28549 ** larger for some devices.
28550 **
28551 ** SQLite code assumes this function cannot fail. It also assumes that
28552 ** if two files are created in the same file-system directory (i.e.
28553 ** a database and its journal file) that the sector size will be the
28554 ** same for both.
28555 */
28556 static int winSectorSize(sqlite3_file *id){
28557   UNUSED_PARAMETER(id);
28558   return SQLITE_DEFAULT_SECTOR_SIZE;
28559 }
28560
28561 /*
28562 ** Return a vector of device characteristics.
28563 */
28564 static int winDeviceCharacteristics(sqlite3_file *id){
28565   UNUSED_PARAMETER(id);
28566   return 0;
28567 }
28568
28569 /*
28570 ** This vector defines all the methods that can operate on an
28571 ** sqlite3_file for win32.
28572 */
28573 static const sqlite3_io_methods winIoMethod = {
28574   1,                        /* iVersion */
28575   winClose,
28576   winRead,
28577   winWrite,
28578   winTruncate,
28579   winSync,
28580   winFileSize,
28581   winLock,
28582   winUnlock,
28583   winCheckReservedLock,
28584   winFileControl,
28585   winSectorSize,
28586   winDeviceCharacteristics
28587 };
28588
28589 /***************************************************************************
28590 ** Here ends the I/O methods that form the sqlite3_io_methods object.
28591 **
28592 ** The next block of code implements the VFS methods.
28593 ****************************************************************************/
28594
28595 /*
28596 ** Convert a UTF-8 filename into whatever form the underlying
28597 ** operating system wants filenames in.  Space to hold the result
28598 ** is obtained from malloc and must be freed by the calling
28599 ** function.
28600 */
28601 static void *convertUtf8Filename(const char *zFilename){
28602   void *zConverted = 0;
28603   if( isNT() ){
28604     zConverted = utf8ToUnicode(zFilename);
28605 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28606 */
28607 #if SQLITE_OS_WINCE==0
28608   }else{
28609     zConverted = utf8ToMbcs(zFilename);
28610 #endif
28611   }
28612   /* caller will handle out of memory */
28613   return zConverted;
28614 }
28615
28616 /*
28617 ** Create a temporary file name in zBuf.  zBuf must be big enough to
28618 ** hold at pVfs->mxPathname characters.
28619 */
28620 static int getTempname(int nBuf, char *zBuf){
28621   static char zChars[] =
28622     "abcdefghijklmnopqrstuvwxyz"
28623     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28624     "0123456789";
28625   size_t i, j;
28626   char zTempPath[MAX_PATH+1];
28627   if( sqlite3_temp_directory ){
28628     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28629   }else if( isNT() ){
28630     char *zMulti;
28631     WCHAR zWidePath[MAX_PATH];
28632     GetTempPathW(MAX_PATH-30, zWidePath);
28633     zMulti = unicodeToUtf8(zWidePath);
28634     if( zMulti ){
28635       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28636       free(zMulti);
28637     }else{
28638       return SQLITE_NOMEM;
28639     }
28640 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28641 ** Since the ASCII version of these Windows API do not exist for WINCE,
28642 ** it's important to not reference them for WINCE builds.
28643 */
28644 #if SQLITE_OS_WINCE==0
28645   }else{
28646     char *zUtf8;
28647     char zMbcsPath[MAX_PATH];
28648     GetTempPathA(MAX_PATH-30, zMbcsPath);
28649     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28650     if( zUtf8 ){
28651       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28652       free(zUtf8);
28653     }else{
28654       return SQLITE_NOMEM;
28655     }
28656 #endif
28657   }
28658   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28659   zTempPath[i] = 0;
28660   sqlite3_snprintf(nBuf-30, zBuf,
28661                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28662   j = sqlite3Strlen30(zBuf);
28663   sqlite3_randomness(20, &zBuf[j]);
28664   for(i=0; i<20; i++, j++){
28665     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28666   }
28667   zBuf[j] = 0;
28668   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28669   return SQLITE_OK; 
28670 }
28671
28672 /*
28673 ** The return value of getLastErrorMsg
28674 ** is zero if the error message fits in the buffer, or non-zero
28675 ** otherwise (if the message was truncated).
28676 */
28677 static int getLastErrorMsg(int nBuf, char *zBuf){
28678   DWORD error = GetLastError();
28679
28680 #if SQLITE_OS_WINCE
28681   sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28682 #else
28683   /* FormatMessage returns 0 on failure.  Otherwise it
28684   ** returns the number of TCHARs written to the output
28685   ** buffer, excluding the terminating null char.
28686   */
28687   if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
28688                       NULL,
28689                       error,
28690                       0,
28691                       zBuf,
28692                       nBuf-1,
28693                       0))
28694   {
28695     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28696   }
28697 #endif
28698
28699   return 0;
28700 }
28701
28702
28703 /*
28704 ** Open a file.
28705 */
28706 static int winOpen(
28707   sqlite3_vfs *pVfs,        /* Not used */
28708   const char *zName,        /* Name of the file (UTF-8) */
28709   sqlite3_file *id,         /* Write the SQLite file handle here */
28710   int flags,                /* Open mode flags */
28711   int *pOutFlags            /* Status return flags */
28712 ){
28713   HANDLE h;
28714   DWORD dwDesiredAccess;
28715   DWORD dwShareMode;
28716   DWORD dwCreationDisposition;
28717   DWORD dwFlagsAndAttributes = 0;
28718 #if SQLITE_OS_WINCE
28719   int isTemp = 0;
28720 #endif
28721   winFile *pFile = (winFile*)id;
28722   void *zConverted;                 /* Filename in OS encoding */
28723   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28724   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28725
28726   UNUSED_PARAMETER(pVfs);
28727
28728   /* If the second argument to this function is NULL, generate a 
28729   ** temporary file name to use 
28730   */
28731   if( !zUtf8Name ){
28732     int rc = getTempname(MAX_PATH+1, zTmpname);
28733     if( rc!=SQLITE_OK ){
28734       return rc;
28735     }
28736     zUtf8Name = zTmpname;
28737   }
28738
28739   /* Convert the filename to the system encoding. */
28740   zConverted = convertUtf8Filename(zUtf8Name);
28741   if( zConverted==0 ){
28742     return SQLITE_NOMEM;
28743   }
28744
28745   if( flags & SQLITE_OPEN_READWRITE ){
28746     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28747   }else{
28748     dwDesiredAccess = GENERIC_READ;
28749   }
28750   if( flags & SQLITE_OPEN_CREATE ){
28751     dwCreationDisposition = OPEN_ALWAYS;
28752   }else{
28753     dwCreationDisposition = OPEN_EXISTING;
28754   }
28755   if( flags & SQLITE_OPEN_MAIN_DB ){
28756     dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28757   }else{
28758     dwShareMode = 0;
28759   }
28760   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28761 #if SQLITE_OS_WINCE
28762     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28763     isTemp = 1;
28764 #else
28765     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28766                                | FILE_ATTRIBUTE_HIDDEN
28767                                | FILE_FLAG_DELETE_ON_CLOSE;
28768 #endif
28769   }else{
28770     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28771   }
28772   /* Reports from the internet are that performance is always
28773   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28774 #if SQLITE_OS_WINCE
28775   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28776 #endif
28777   if( isNT() ){
28778     h = CreateFileW((WCHAR*)zConverted,
28779        dwDesiredAccess,
28780        dwShareMode,
28781        NULL,
28782        dwCreationDisposition,
28783        dwFlagsAndAttributes,
28784        NULL
28785     );
28786 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28787 ** Since the ASCII version of these Windows API do not exist for WINCE,
28788 ** it's important to not reference them for WINCE builds.
28789 */
28790 #if SQLITE_OS_WINCE==0
28791   }else{
28792     h = CreateFileA((char*)zConverted,
28793        dwDesiredAccess,
28794        dwShareMode,
28795        NULL,
28796        dwCreationDisposition,
28797        dwFlagsAndAttributes,
28798        NULL
28799     );
28800 #endif
28801   }
28802   if( h==INVALID_HANDLE_VALUE ){
28803     free(zConverted);
28804     if( flags & SQLITE_OPEN_READWRITE ){
28805       return winOpen(0, zName, id, 
28806              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28807     }else{
28808       return SQLITE_CANTOPEN;
28809     }
28810   }
28811   if( pOutFlags ){
28812     if( flags & SQLITE_OPEN_READWRITE ){
28813       *pOutFlags = SQLITE_OPEN_READWRITE;
28814     }else{
28815       *pOutFlags = SQLITE_OPEN_READONLY;
28816     }
28817   }
28818   memset(pFile, 0, sizeof(*pFile));
28819   pFile->pMethod = &winIoMethod;
28820   pFile->h = h;
28821   pFile->lastErrno = NO_ERROR;
28822 #if SQLITE_OS_WINCE
28823   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28824                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28825        && !winceCreateLock(zName, pFile)
28826   ){
28827     CloseHandle(h);
28828     free(zConverted);
28829     return SQLITE_CANTOPEN;
28830   }
28831   if( isTemp ){
28832     pFile->zDeleteOnClose = zConverted;
28833   }else
28834 #endif
28835   {
28836     free(zConverted);
28837   }
28838   OpenCounter(+1);
28839   return SQLITE_OK;
28840 }
28841
28842 /*
28843 ** Delete the named file.
28844 **
28845 ** Note that windows does not allow a file to be deleted if some other
28846 ** process has it open.  Sometimes a virus scanner or indexing program
28847 ** will open a journal file shortly after it is created in order to do
28848 ** whatever it does.  While this other process is holding the
28849 ** file open, we will be unable to delete it.  To work around this
28850 ** problem, we delay 100 milliseconds and try to delete again.  Up
28851 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28852 ** up and returning an error.
28853 */
28854 #define MX_DELETION_ATTEMPTS 5
28855 static int winDelete(
28856   sqlite3_vfs *pVfs,          /* Not used on win32 */
28857   const char *zFilename,      /* Name of file to delete */
28858   int syncDir                 /* Not used on win32 */
28859 ){
28860   int cnt = 0;
28861   DWORD rc;
28862   DWORD error = 0;
28863   void *zConverted = convertUtf8Filename(zFilename);
28864   UNUSED_PARAMETER(pVfs);
28865   UNUSED_PARAMETER(syncDir);
28866   if( zConverted==0 ){
28867     return SQLITE_NOMEM;
28868   }
28869   SimulateIOError(return SQLITE_IOERR_DELETE);
28870   if( isNT() ){
28871     do{
28872       DeleteFileW(zConverted);
28873     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28874                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28875            && (++cnt < MX_DELETION_ATTEMPTS)
28876            && (Sleep(100), 1) );
28877 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28878 ** Since the ASCII version of these Windows API do not exist for WINCE,
28879 ** it's important to not reference them for WINCE builds.
28880 */
28881 #if SQLITE_OS_WINCE==0
28882   }else{
28883     do{
28884       DeleteFileA(zConverted);
28885     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28886                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28887            && (++cnt < MX_DELETION_ATTEMPTS)
28888            && (Sleep(100), 1) );
28889 #endif
28890   }
28891   free(zConverted);
28892   OSTRACE2("DELETE \"%s\"\n", zFilename);
28893   return (   (rc == INVALID_FILE_ATTRIBUTES) 
28894           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28895 }
28896
28897 /*
28898 ** Check the existance and status of a file.
28899 */
28900 static int winAccess(
28901   sqlite3_vfs *pVfs,         /* Not used on win32 */
28902   const char *zFilename,     /* Name of file to check */
28903   int flags,                 /* Type of test to make on this file */
28904   int *pResOut               /* OUT: Result */
28905 ){
28906   DWORD attr;
28907   int rc = 0;
28908   void *zConverted = convertUtf8Filename(zFilename);
28909   UNUSED_PARAMETER(pVfs);
28910   if( zConverted==0 ){
28911     return SQLITE_NOMEM;
28912   }
28913   if( isNT() ){
28914     attr = GetFileAttributesW((WCHAR*)zConverted);
28915 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28916 ** Since the ASCII version of these Windows API do not exist for WINCE,
28917 ** it's important to not reference them for WINCE builds.
28918 */
28919 #if SQLITE_OS_WINCE==0
28920   }else{
28921     attr = GetFileAttributesA((char*)zConverted);
28922 #endif
28923   }
28924   free(zConverted);
28925   switch( flags ){
28926     case SQLITE_ACCESS_READ:
28927     case SQLITE_ACCESS_EXISTS:
28928       rc = attr!=INVALID_FILE_ATTRIBUTES;
28929       break;
28930     case SQLITE_ACCESS_READWRITE:
28931       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28932       break;
28933     default:
28934       assert(!"Invalid flags argument");
28935   }
28936   *pResOut = rc;
28937   return SQLITE_OK;
28938 }
28939
28940
28941 /*
28942 ** Turn a relative pathname into a full pathname.  Write the full
28943 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28944 ** bytes in size.
28945 */
28946 static int winFullPathname(
28947   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28948   const char *zRelative,        /* Possibly relative input path */
28949   int nFull,                    /* Size of output buffer in bytes */
28950   char *zFull                   /* Output buffer */
28951 ){
28952   
28953 #if defined(__CYGWIN__)
28954   UNUSED_PARAMETER(nFull);
28955   cygwin_conv_to_full_win32_path(zRelative, zFull);
28956   return SQLITE_OK;
28957 #endif
28958
28959 #if SQLITE_OS_WINCE
28960   UNUSED_PARAMETER(nFull);
28961   /* WinCE has no concept of a relative pathname, or so I am told. */
28962   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28963   return SQLITE_OK;
28964 #endif
28965
28966 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28967   int nByte;
28968   void *zConverted;
28969   char *zOut;
28970   UNUSED_PARAMETER(nFull);
28971   zConverted = convertUtf8Filename(zRelative);
28972   if( isNT() ){
28973     WCHAR *zTemp;
28974     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28975     zTemp = malloc( nByte*sizeof(zTemp[0]) );
28976     if( zTemp==0 ){
28977       free(zConverted);
28978       return SQLITE_NOMEM;
28979     }
28980     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28981     free(zConverted);
28982     zOut = unicodeToUtf8(zTemp);
28983     free(zTemp);
28984 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28985 ** Since the ASCII version of these Windows API do not exist for WINCE,
28986 ** it's important to not reference them for WINCE builds.
28987 */
28988 #if SQLITE_OS_WINCE==0
28989   }else{
28990     char *zTemp;
28991     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28992     zTemp = malloc( nByte*sizeof(zTemp[0]) );
28993     if( zTemp==0 ){
28994       free(zConverted);
28995       return SQLITE_NOMEM;
28996     }
28997     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28998     free(zConverted);
28999     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
29000     free(zTemp);
29001 #endif
29002   }
29003   if( zOut ){
29004     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
29005     free(zOut);
29006     return SQLITE_OK;
29007   }else{
29008     return SQLITE_NOMEM;
29009   }
29010 #endif
29011 }
29012
29013 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29014 /*
29015 ** Interfaces for opening a shared library, finding entry points
29016 ** within the shared library, and closing the shared library.
29017 */
29018 /*
29019 ** Interfaces for opening a shared library, finding entry points
29020 ** within the shared library, and closing the shared library.
29021 */
29022 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
29023   HANDLE h;
29024   void *zConverted = convertUtf8Filename(zFilename);
29025   UNUSED_PARAMETER(pVfs);
29026   if( zConverted==0 ){
29027     return 0;
29028   }
29029   if( isNT() ){
29030     h = LoadLibraryW((WCHAR*)zConverted);
29031 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29032 ** Since the ASCII version of these Windows API do not exist for WINCE,
29033 ** it's important to not reference them for WINCE builds.
29034 */
29035 #if SQLITE_OS_WINCE==0
29036   }else{
29037     h = LoadLibraryA((char*)zConverted);
29038 #endif
29039   }
29040   free(zConverted);
29041   return (void*)h;
29042 }
29043 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
29044   UNUSED_PARAMETER(pVfs);
29045   getLastErrorMsg(nBuf, zBufOut);
29046 }
29047 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
29048   UNUSED_PARAMETER(pVfs);
29049 #if SQLITE_OS_WINCE
29050   /* The GetProcAddressA() routine is only available on wince. */
29051   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
29052 #else
29053   /* All other windows platforms expect GetProcAddress() to take
29054   ** an Ansi string regardless of the _UNICODE setting */
29055   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
29056 #endif
29057 }
29058 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
29059   UNUSED_PARAMETER(pVfs);
29060   FreeLibrary((HANDLE)pHandle);
29061 }
29062 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29063   #define winDlOpen  0
29064   #define winDlError 0
29065   #define winDlSym   0
29066   #define winDlClose 0
29067 #endif
29068
29069
29070 /*
29071 ** Write up to nBuf bytes of randomness into zBuf.
29072 */
29073 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29074   int n = 0;
29075   UNUSED_PARAMETER(pVfs);
29076 #if defined(SQLITE_TEST)
29077   n = nBuf;
29078   memset(zBuf, 0, nBuf);
29079 #else
29080   if( sizeof(SYSTEMTIME)<=nBuf-n ){
29081     SYSTEMTIME x;
29082     GetSystemTime(&x);
29083     memcpy(&zBuf[n], &x, sizeof(x));
29084     n += sizeof(x);
29085   }
29086   if( sizeof(DWORD)<=nBuf-n ){
29087     DWORD pid = GetCurrentProcessId();
29088     memcpy(&zBuf[n], &pid, sizeof(pid));
29089     n += sizeof(pid);
29090   }
29091   if( sizeof(DWORD)<=nBuf-n ){
29092     DWORD cnt = GetTickCount();
29093     memcpy(&zBuf[n], &cnt, sizeof(cnt));
29094     n += sizeof(cnt);
29095   }
29096   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
29097     LARGE_INTEGER i;
29098     QueryPerformanceCounter(&i);
29099     memcpy(&zBuf[n], &i, sizeof(i));
29100     n += sizeof(i);
29101   }
29102 #endif
29103   return n;
29104 }
29105
29106
29107 /*
29108 ** Sleep for a little while.  Return the amount of time slept.
29109 */
29110 static int winSleep(sqlite3_vfs *pVfs, int microsec){
29111   Sleep((microsec+999)/1000);
29112   UNUSED_PARAMETER(pVfs);
29113   return ((microsec+999)/1000)*1000;
29114 }
29115
29116 /*
29117 ** The following variable, if set to a non-zero value, becomes the result
29118 ** returned from sqlite3OsCurrentTime().  This is used for testing.
29119 */
29120 #ifdef SQLITE_TEST
29121 SQLITE_API int sqlite3_current_time = 0;
29122 #endif
29123
29124 /*
29125 ** Find the current time (in Universal Coordinated Time).  Write the
29126 ** current time and date as a Julian Day number into *prNow and
29127 ** return 0.  Return 1 if the time and date cannot be found.
29128 */
29129 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
29130   FILETIME ft;
29131   /* FILETIME structure is a 64-bit value representing the number of 
29132      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
29133   */
29134   sqlite3_int64 timeW, timeF;
29135 #if SQLITE_OS_WINCE
29136   SYSTEMTIME time;
29137   GetSystemTime(&time);
29138   /* if SystemTimeToFileTime() fails, it returns zero. */
29139   if (!SystemTimeToFileTime(&time,&ft)){
29140     return 1;
29141   }
29142 #else
29143   GetSystemTimeAsFileTime( &ft );
29144 #endif
29145   UNUSED_PARAMETER(pVfs);
29146 #if defined(_MSC_VER)
29147   timeW = (((sqlite3_int64)ft.dwHighDateTime)*4294967296) + ft.dwLowDateTime;
29148   timeF = timeW % 864000000000;           /* fractional days (100-nanoseconds) */
29149   timeW = timeW / 864000000000;           /* whole days */
29150   timeW = timeW + 2305813;                /* add whole days (from 2305813.5) */
29151   timeF = timeF + 432000000000;           /* add half a day (from 2305813.5) */
29152   timeW = timeW + (timeF / 864000000000); /* add whole day if half day made one */
29153   timeF = timeF % 864000000000;           /* compute new fractional days */
29154   *prNow = (double)timeW + ((double)timeF / (double)864000000000);
29155 #else
29156   timeW = (((sqlite3_int64)ft.dwHighDateTime)*4294967296LL) + ft.dwLowDateTime;
29157   timeF = timeW % 864000000000LL;           /* fractional days (100-nanoseconds) */
29158   timeW = timeW / 864000000000LL;           /* whole days */
29159   timeW = timeW + 2305813;                  /* add whole days (from 2305813.5) */
29160   timeF = timeF + 432000000000LL;           /* add half a day (from 2305813.5) */
29161   timeW = timeW + (timeF / 864000000000LL); /* add whole day if half day made one */
29162   timeF = timeF % 864000000000LL;           /* compute new fractional days */
29163   *prNow = (double)timeW + ((double)timeF / (double)864000000000LL);
29164 #endif
29165 #ifdef SQLITE_TEST
29166   if( sqlite3_current_time ){
29167     *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
29168   }
29169 #endif
29170   return 0;
29171 }
29172
29173 /*
29174 ** The idea is that this function works like a combination of
29175 ** GetLastError() and FormatMessage() on windows (or errno and
29176 ** strerror_r() on unix). After an error is returned by an OS
29177 ** function, SQLite calls this function with zBuf pointing to
29178 ** a buffer of nBuf bytes. The OS layer should populate the
29179 ** buffer with a nul-terminated UTF-8 encoded error message
29180 ** describing the last IO error to have occured within the calling
29181 ** thread.
29182 **
29183 ** If the error message is too large for the supplied buffer,
29184 ** it should be truncated. The return value of xGetLastError
29185 ** is zero if the error message fits in the buffer, or non-zero
29186 ** otherwise (if the message was truncated). If non-zero is returned,
29187 ** then it is not necessary to include the nul-terminator character
29188 ** in the output buffer.
29189 **
29190 ** Not supplying an error message will have no adverse effect
29191 ** on SQLite. It is fine to have an implementation that never
29192 ** returns an error message:
29193 **
29194 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29195 **     assert(zBuf[0]=='\0');
29196 **     return 0;
29197 **   }
29198 **
29199 ** However if an error message is supplied, it will be incorporated
29200 ** by sqlite into the error message available to the user using
29201 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
29202 */
29203 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29204   UNUSED_PARAMETER(pVfs);
29205   return getLastErrorMsg(nBuf, zBuf);
29206 }
29207
29208 /*
29209 ** Initialize and deinitialize the operating system interface.
29210 */
29211 SQLITE_API int sqlite3_os_init(void){
29212   static sqlite3_vfs winVfs = {
29213     1,                 /* iVersion */
29214     sizeof(winFile),   /* szOsFile */
29215     MAX_PATH,          /* mxPathname */
29216     0,                 /* pNext */
29217     "win32",           /* zName */
29218     0,                 /* pAppData */
29219  
29220     winOpen,           /* xOpen */
29221     winDelete,         /* xDelete */
29222     winAccess,         /* xAccess */
29223     winFullPathname,   /* xFullPathname */
29224     winDlOpen,         /* xDlOpen */
29225     winDlError,        /* xDlError */
29226     winDlSym,          /* xDlSym */
29227     winDlClose,        /* xDlClose */
29228     winRandomness,     /* xRandomness */
29229     winSleep,          /* xSleep */
29230     winCurrentTime,    /* xCurrentTime */
29231     winGetLastError    /* xGetLastError */
29232   };
29233   sqlite3_vfs_register(&winVfs, 1);
29234   return SQLITE_OK; 
29235 }
29236 SQLITE_API int sqlite3_os_end(void){ 
29237   return SQLITE_OK;
29238 }
29239
29240 #endif /* SQLITE_OS_WIN */
29241
29242 /************** End of os_win.c **********************************************/
29243 /************** Begin file bitvec.c ******************************************/
29244 /*
29245 ** 2008 February 16
29246 **
29247 ** The author disclaims copyright to this source code.  In place of
29248 ** a legal notice, here is a blessing:
29249 **
29250 **    May you do good and not evil.
29251 **    May you find forgiveness for yourself and forgive others.
29252 **    May you share freely, never taking more than you give.
29253 **
29254 *************************************************************************
29255 ** This file implements an object that represents a fixed-length
29256 ** bitmap.  Bits are numbered starting with 1.
29257 **
29258 ** A bitmap is used to record which pages of a database file have been
29259 ** journalled during a transaction, or which pages have the "dont-write"
29260 ** property.  Usually only a few pages are meet either condition.
29261 ** So the bitmap is usually sparse and has low cardinality.
29262 ** But sometimes (for example when during a DROP of a large table) most
29263 ** or all of the pages in a database can get journalled.  In those cases, 
29264 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
29265 ** to handle both cases well.
29266 **
29267 ** The size of the bitmap is fixed when the object is created.
29268 **
29269 ** All bits are clear when the bitmap is created.  Individual bits
29270 ** may be set or cleared one at a time.
29271 **
29272 ** Test operations are about 100 times more common that set operations.
29273 ** Clear operations are exceedingly rare.  There are usually between
29274 ** 5 and 500 set operations per Bitvec object, though the number of sets can
29275 ** sometimes grow into tens of thousands or larger.  The size of the
29276 ** Bitvec object is the number of pages in the database file at the
29277 ** start of a transaction, and is thus usually less than a few thousand,
29278 ** but can be as large as 2 billion for a really big database.
29279 **
29280 ** @(#) $Id: bitvec.c,v 1.13 2009/01/20 17:06:27 danielk1977 Exp $
29281 */
29282
29283 /* Size of the Bitvec structure in bytes. */
29284 #define BITVEC_SZ        512
29285
29286 /* Round the union size down to the nearest pointer boundary, since that's how 
29287 ** it will be aligned within the Bitvec struct. */
29288 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29289
29290 /* Type of the array "element" for the bitmap representation. 
29291 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
29292 ** Setting this to the "natural word" size of your CPU may improve
29293 ** performance. */
29294 #define BITVEC_TELEM     u8
29295 /* Size, in bits, of the bitmap element. */
29296 #define BITVEC_SZELEM    8
29297 /* Number of elements in a bitmap array. */
29298 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29299 /* Number of bits in the bitmap array. */
29300 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29301
29302 /* Number of u32 values in hash table. */
29303 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29304 /* Maximum number of entries in hash table before 
29305 ** sub-dividing and re-hashing. */
29306 #define BITVEC_MXHASH    (BITVEC_NINT/2)
29307 /* Hashing function for the aHash representation.
29308 ** Empirical testing showed that the *37 multiplier 
29309 ** (an arbitrary prime)in the hash function provided 
29310 ** no fewer collisions than the no-op *1. */
29311 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29312
29313 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29314
29315
29316 /*
29317 ** A bitmap is an instance of the following structure.
29318 **
29319 ** This bitmap records the existance of zero or more bits
29320 ** with values between 1 and iSize, inclusive.
29321 **
29322 ** There are three possible representations of the bitmap.
29323 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29324 ** bitmap.  The least significant bit is bit 1.
29325 **
29326 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29327 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
29328 **
29329 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
29330 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29331 ** handles up to iDivisor separate values of i.  apSub[0] holds
29332 ** values between 1 and iDivisor.  apSub[1] holds values between
29333 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29334 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29335 ** to hold deal with values between 1 and iDivisor.
29336 */
29337 struct Bitvec {
29338   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29339   u32 nSet;       /* Number of bits that are set - only valid for aHash element */
29340                   /* Max nSet is BITVEC_NINT.  For BITVEC_SZ of 512, this would be 125. */
29341   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29342                   /* Should >=0 for apSub element. */
29343                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29344                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29345   union {
29346     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29347     u32 aHash[BITVEC_NINT];      /* Hash table representation */
29348     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29349   } u;
29350 };
29351
29352 /*
29353 ** Create a new bitmap object able to handle bits between 0 and iSize,
29354 ** inclusive.  Return a pointer to the new object.  Return NULL if 
29355 ** malloc fails.
29356 */
29357 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29358   Bitvec *p;
29359   assert( sizeof(*p)==BITVEC_SZ );
29360   p = sqlite3MallocZero( sizeof(*p) );
29361   if( p ){
29362     p->iSize = iSize;
29363   }
29364   return p;
29365 }
29366
29367 /*
29368 ** Check to see if the i-th bit is set.  Return true or false.
29369 ** If p is NULL (if the bitmap has not been created) or if
29370 ** i is out of range, then return false.
29371 */
29372 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29373   if( p==0 ) return 0;
29374   if( i>p->iSize || i==0 ) return 0;
29375   i--;
29376   while( p->iDivisor ){
29377     u32 bin = i/p->iDivisor;
29378     i = i%p->iDivisor;
29379     p = p->u.apSub[bin];
29380     if (!p) {
29381       return 0;
29382     }
29383   }
29384   if( p->iSize<=BITVEC_NBIT ){
29385     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29386   } else{
29387     u32 h = BITVEC_HASH(i++);
29388     while( p->u.aHash[h] ){
29389       if( p->u.aHash[h]==i ) return 1;
29390       h++;
29391       if( h>=BITVEC_NINT ) h = 0;
29392     }
29393     return 0;
29394   }
29395 }
29396
29397 /*
29398 ** Set the i-th bit.  Return 0 on success and an error code if
29399 ** anything goes wrong.
29400 **
29401 ** This routine might cause sub-bitmaps to be allocated.  Failing
29402 ** to get the memory needed to hold the sub-bitmap is the only
29403 ** that can go wrong with an insert, assuming p and i are valid.
29404 **
29405 ** The calling function must ensure that p is a valid Bitvec object
29406 ** and that the value for "i" is within range of the Bitvec object.
29407 ** Otherwise the behavior is undefined.
29408 */
29409 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29410   u32 h;
29411   assert( p!=0 );
29412   assert( i>0 );
29413   assert( i<=p->iSize );
29414   i--;
29415   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29416     u32 bin = i/p->iDivisor;
29417     i = i%p->iDivisor;
29418     if( p->u.apSub[bin]==0 ){
29419       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29420       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29421     }
29422     p = p->u.apSub[bin];
29423   }
29424   if( p->iSize<=BITVEC_NBIT ){
29425     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29426     return SQLITE_OK;
29427   }
29428   h = BITVEC_HASH(i++);
29429   /* if there wasn't a hash collision, and this doesn't */
29430   /* completely fill the hash, then just add it without */
29431   /* worring about sub-dividing and re-hashing. */
29432   if( !p->u.aHash[h] ){
29433     if (p->nSet<(BITVEC_NINT-1)) {
29434       goto bitvec_set_end;
29435     } else {
29436       goto bitvec_set_rehash;
29437     }
29438   }
29439   /* there was a collision, check to see if it's already */
29440   /* in hash, if not, try to find a spot for it */
29441   do {
29442     if( p->u.aHash[h]==i ) return SQLITE_OK;
29443     h++;
29444     if( h>=BITVEC_NINT ) h = 0;
29445   } while( p->u.aHash[h] );
29446   /* we didn't find it in the hash.  h points to the first */
29447   /* available free spot. check to see if this is going to */
29448   /* make our hash too "full".  */
29449 bitvec_set_rehash:
29450   if( p->nSet>=BITVEC_MXHASH ){
29451     unsigned int j;
29452     int rc;
29453     u32 aiValues[BITVEC_NINT];
29454     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
29455     memset(p->u.apSub, 0, sizeof(aiValues));
29456     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29457     rc = sqlite3BitvecSet(p, i);
29458     for(j=0; j<BITVEC_NINT; j++){
29459       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29460     }
29461     return rc;
29462   }
29463 bitvec_set_end:
29464   p->nSet++;
29465   p->u.aHash[h] = i;
29466   return SQLITE_OK;
29467 }
29468
29469 /*
29470 ** Clear the i-th bit.
29471 */
29472 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i){
29473   assert( p!=0 );
29474   assert( i>0 );
29475   i--;
29476   while( p->iDivisor ){
29477     u32 bin = i/p->iDivisor;
29478     i = i%p->iDivisor;
29479     p = p->u.apSub[bin];
29480     if (!p) {
29481       return;
29482     }
29483   }
29484   if( p->iSize<=BITVEC_NBIT ){
29485     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29486   }else{
29487     unsigned int j;
29488     u32 aiValues[BITVEC_NINT];
29489     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
29490     memset(p->u.aHash, 0, sizeof(aiValues));
29491     p->nSet = 0;
29492     for(j=0; j<BITVEC_NINT; j++){
29493       if( aiValues[j] && aiValues[j]!=(i+1) ){
29494         u32 h = BITVEC_HASH(aiValues[j]-1);
29495         p->nSet++;
29496         while( p->u.aHash[h] ){
29497           h++;
29498           if( h>=BITVEC_NINT ) h = 0;
29499         }
29500         p->u.aHash[h] = aiValues[j];
29501       }
29502     }
29503   }
29504 }
29505
29506 /*
29507 ** Destroy a bitmap object.  Reclaim all memory used.
29508 */
29509 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29510   if( p==0 ) return;
29511   if( p->iDivisor ){
29512     unsigned int i;
29513     for(i=0; i<BITVEC_NPTR; i++){
29514       sqlite3BitvecDestroy(p->u.apSub[i]);
29515     }
29516   }
29517   sqlite3_free(p);
29518 }
29519
29520 /*
29521 ** Return the value of the iSize parameter specified when Bitvec *p
29522 ** was created.
29523 */
29524 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29525   return p->iSize;
29526 }
29527
29528 #ifndef SQLITE_OMIT_BUILTIN_TEST
29529 /*
29530 ** Let V[] be an array of unsigned characters sufficient to hold
29531 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29532 ** Then the following macros can be used to set, clear, or test
29533 ** individual bits within V.
29534 */
29535 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29536 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29537 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29538
29539 /*
29540 ** This routine runs an extensive test of the Bitvec code.
29541 **
29542 ** The input is an array of integers that acts as a program
29543 ** to test the Bitvec.  The integers are opcodes followed
29544 ** by 0, 1, or 3 operands, depending on the opcode.  Another
29545 ** opcode follows immediately after the last operand.
29546 **
29547 ** There are 6 opcodes numbered from 0 through 5.  0 is the
29548 ** "halt" opcode and causes the test to end.
29549 **
29550 **    0          Halt and return the number of errors
29551 **    1 N S X    Set N bits beginning with S and incrementing by X
29552 **    2 N S X    Clear N bits beginning with S and incrementing by X
29553 **    3 N        Set N randomly chosen bits
29554 **    4 N        Clear N randomly chosen bits
29555 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
29556 **
29557 ** The opcodes 1 through 4 perform set and clear operations are performed
29558 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
29559 ** Opcode 5 works on the linear array only, not on the Bitvec.
29560 ** Opcode 5 is used to deliberately induce a fault in order to
29561 ** confirm that error detection works.
29562 **
29563 ** At the conclusion of the test the linear array is compared
29564 ** against the Bitvec object.  If there are any differences,
29565 ** an error is returned.  If they are the same, zero is returned.
29566 **
29567 ** If a memory allocation error occurs, return -1.
29568 */
29569 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29570   Bitvec *pBitvec = 0;
29571   unsigned char *pV = 0;
29572   int rc = -1;
29573   int i, nx, pc, op;
29574
29575   /* Allocate the Bitvec to be tested and a linear array of
29576   ** bits to act as the reference */
29577   pBitvec = sqlite3BitvecCreate( sz );
29578   pV = sqlite3_malloc( (sz+7)/8 + 1 );
29579   if( pBitvec==0 || pV==0 ) goto bitvec_end;
29580   memset(pV, 0, (sz+7)/8 + 1);
29581
29582   /* Run the program */
29583   pc = 0;
29584   while( (op = aOp[pc])!=0 ){
29585     switch( op ){
29586       case 1:
29587       case 2:
29588       case 5: {
29589         nx = 4;
29590         i = aOp[pc+2] - 1;
29591         aOp[pc+2] += aOp[pc+3];
29592         break;
29593       }
29594       case 3:
29595       case 4: 
29596       default: {
29597         nx = 2;
29598         sqlite3_randomness(sizeof(i), &i);
29599         break;
29600       }
29601     }
29602     if( (--aOp[pc+1]) > 0 ) nx = 0;
29603     pc += nx;
29604     i = (i & 0x7fffffff)%sz;
29605     if( (op & 1)!=0 ){
29606       SETBIT(pV, (i+1));
29607       if( op!=5 ){
29608         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29609       }
29610     }else{
29611       CLEARBIT(pV, (i+1));
29612       sqlite3BitvecClear(pBitvec, i+1);
29613     }
29614   }
29615
29616   /* Test to make sure the linear array exactly matches the
29617   ** Bitvec object.  Start with the assumption that they do
29618   ** match (rc==0).  Change rc to non-zero if a discrepancy
29619   ** is found.
29620   */
29621   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29622           + sqlite3BitvecTest(pBitvec, 0);
29623   for(i=1; i<=sz; i++){
29624     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29625       rc = i;
29626       break;
29627     }
29628   }
29629
29630   /* Free allocated structure */
29631 bitvec_end:
29632   sqlite3_free(pV);
29633   sqlite3BitvecDestroy(pBitvec);
29634   return rc;
29635 }
29636 #endif /* SQLITE_OMIT_BUILTIN_TEST */
29637
29638 /************** End of bitvec.c **********************************************/
29639 /************** Begin file pcache.c ******************************************/
29640 /*
29641 ** 2008 August 05
29642 **
29643 ** The author disclaims copyright to this source code.  In place of
29644 ** a legal notice, here is a blessing:
29645 **
29646 **    May you do good and not evil.
29647 **    May you find forgiveness for yourself and forgive others.
29648 **    May you share freely, never taking more than you give.
29649 **
29650 *************************************************************************
29651 ** This file implements that page cache.
29652 **
29653 ** @(#) $Id: pcache.c,v 1.43 2009/01/23 16:45:01 danielk1977 Exp $
29654 */
29655
29656 /*
29657 ** A complete page cache is an instance of this structure.
29658 */
29659 struct PCache {
29660   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29661   PgHdr *pSynced;                     /* Last synced page in dirty page list */
29662   int nRef;                           /* Number of referenced pages */
29663   int nMax;                           /* Configured cache size */
29664   int szPage;                         /* Size of every page in this cache */
29665   int szExtra;                        /* Size of extra space for each page */
29666   int bPurgeable;                     /* True if pages are on backing store */
29667   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29668   void *pStress;                      /* Argument to xStress */
29669   sqlite3_pcache *pCache;             /* Pluggable cache module */
29670   PgHdr *pPage1;                      /* Reference to page 1 */
29671 };
29672
29673 /*
29674 ** Some of the assert() macros in this code are too expensive to run
29675 ** even during normal debugging.  Use them only rarely on long-running
29676 ** tests.  Enable the expensive asserts using the
29677 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29678 */
29679 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29680 # define expensive_assert(X)  assert(X)
29681 #else
29682 # define expensive_assert(X)
29683 #endif
29684
29685 /********************************** Linked List Management ********************/
29686
29687 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29688 /*
29689 ** Check that the pCache->pSynced variable is set correctly. If it
29690 ** is not, either fail an assert or return zero. Otherwise, return
29691 ** non-zero. This is only used in debugging builds, as follows:
29692 **
29693 **   expensive_assert( pcacheCheckSynced(pCache) );
29694 */
29695 static int pcacheCheckSynced(PCache *pCache){
29696   PgHdr *p;
29697   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29698     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29699   }
29700   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29701 }
29702 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29703
29704 /*
29705 ** Remove page pPage from the list of dirty pages.
29706 */
29707 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29708   PCache *p = pPage->pCache;
29709
29710   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29711   assert( pPage->pDirtyPrev || pPage==p->pDirty );
29712
29713   /* Update the PCache1.pSynced variable if necessary. */
29714   if( p->pSynced==pPage ){
29715     PgHdr *pSynced = pPage->pDirtyPrev;
29716     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29717       pSynced = pSynced->pDirtyPrev;
29718     }
29719     p->pSynced = pSynced;
29720   }
29721
29722   if( pPage->pDirtyNext ){
29723     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29724   }else{
29725     assert( pPage==p->pDirtyTail );
29726     p->pDirtyTail = pPage->pDirtyPrev;
29727   }
29728   if( pPage->pDirtyPrev ){
29729     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29730   }else{
29731     assert( pPage==p->pDirty );
29732     p->pDirty = pPage->pDirtyNext;
29733   }
29734   pPage->pDirtyNext = 0;
29735   pPage->pDirtyPrev = 0;
29736
29737   expensive_assert( pcacheCheckSynced(p) );
29738 }
29739
29740 /*
29741 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29742 ** pPage).
29743 */
29744 static void pcacheAddToDirtyList(PgHdr *pPage){
29745   PCache *p = pPage->pCache;
29746
29747   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29748
29749   pPage->pDirtyNext = p->pDirty;
29750   if( pPage->pDirtyNext ){
29751     assert( pPage->pDirtyNext->pDirtyPrev==0 );
29752     pPage->pDirtyNext->pDirtyPrev = pPage;
29753   }
29754   p->pDirty = pPage;
29755   if( !p->pDirtyTail ){
29756     p->pDirtyTail = pPage;
29757   }
29758   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29759     p->pSynced = pPage;
29760   }
29761   expensive_assert( pcacheCheckSynced(p) );
29762 }
29763
29764 /*
29765 ** Wrapper around the pluggable caches xUnpin method. If the cache is
29766 ** being used for an in-memory database, this function is a no-op.
29767 */
29768 static void pcacheUnpin(PgHdr *p){
29769   PCache *pCache = p->pCache;
29770   if( pCache->bPurgeable ){
29771     if( p->pgno==1 ){
29772       pCache->pPage1 = 0;
29773     }
29774     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29775   }
29776 }
29777
29778 /*************************************************** General Interfaces ******
29779 **
29780 ** Initialize and shutdown the page cache subsystem. Neither of these 
29781 ** functions are threadsafe.
29782 */
29783 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29784   if( sqlite3GlobalConfig.pcache.xInit==0 ){
29785     sqlite3PCacheSetDefault();
29786   }
29787   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29788 }
29789 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29790   if( sqlite3GlobalConfig.pcache.xShutdown ){
29791     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29792   }
29793 }
29794
29795 /*
29796 ** Return the size in bytes of a PCache object.
29797 */
29798 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29799
29800 /*
29801 ** Create a new PCache object. Storage space to hold the object
29802 ** has already been allocated and is passed in as the p pointer. 
29803 ** The caller discovers how much space needs to be allocated by 
29804 ** calling sqlite3PcacheSize().
29805 */
29806 SQLITE_PRIVATE void sqlite3PcacheOpen(
29807   int szPage,                  /* Size of every page */
29808   int szExtra,                 /* Extra space associated with each page */
29809   int bPurgeable,              /* True if pages are on backing store */
29810   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29811   void *pStress,               /* Argument to xStress */
29812   PCache *p                    /* Preallocated space for the PCache */
29813 ){
29814   memset(p, 0, sizeof(PCache));
29815   p->szPage = szPage;
29816   p->szExtra = szExtra;
29817   p->bPurgeable = bPurgeable;
29818   p->xStress = xStress;
29819   p->pStress = pStress;
29820   p->nMax = 100;
29821 }
29822
29823 /*
29824 ** Change the page size for PCache object. The caller must ensure that there
29825 ** are no outstanding page references when this function is called.
29826 */
29827 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29828   assert( pCache->nRef==0 && pCache->pDirty==0 );
29829   if( pCache->pCache ){
29830     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29831     pCache->pCache = 0;
29832   }
29833   pCache->szPage = szPage;
29834 }
29835
29836 /*
29837 ** Try to obtain a page from the cache.
29838 */
29839 SQLITE_PRIVATE int sqlite3PcacheFetch(
29840   PCache *pCache,       /* Obtain the page from this cache */
29841   Pgno pgno,            /* Page number to obtain */
29842   int createFlag,       /* If true, create page if it does not exist already */
29843   PgHdr **ppPage        /* Write the page here */
29844 ){
29845   PgHdr *pPage = 0;
29846   int eCreate;
29847
29848   assert( pCache!=0 );
29849   assert( pgno>0 );
29850
29851   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29852   ** allocate it now.
29853   */
29854   if( !pCache->pCache && createFlag ){
29855     sqlite3_pcache *p;
29856     int nByte;
29857     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29858     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29859     if( !p ){
29860       return SQLITE_NOMEM;
29861     }
29862     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29863     pCache->pCache = p;
29864   }
29865
29866   eCreate = createFlag ? 1 : 0;
29867   if( eCreate && (!pCache->bPurgeable || !pCache->pDirty) ){
29868     eCreate = 2;
29869   }
29870   if( pCache->pCache ){
29871     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29872   }
29873
29874   if( !pPage && eCreate==1 ){
29875     PgHdr *pPg;
29876
29877     /* Find a dirty page to write-out and recycle. First try to find a 
29878     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29879     ** cleared), but if that is not possible settle for any other 
29880     ** unreferenced dirty page.
29881     */
29882     expensive_assert( pcacheCheckSynced(pCache) );
29883     for(pPg=pCache->pSynced; 
29884         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
29885         pPg=pPg->pDirtyPrev
29886     );
29887     if( !pPg ){
29888       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29889     }
29890     if( pPg ){
29891       int rc;
29892       rc = pCache->xStress(pCache->pStress, pPg);
29893       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29894         return rc;
29895       }
29896     }
29897
29898     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29899   }
29900
29901   if( pPage ){
29902     if( !pPage->pData ){
29903       memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29904       pPage->pExtra = (void*)&pPage[1];
29905       pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29906       pPage->pCache = pCache;
29907       pPage->pgno = pgno;
29908     }
29909     assert( pPage->pCache==pCache );
29910     assert( pPage->pgno==pgno );
29911     assert( pPage->pExtra==(void *)&pPage[1] );
29912
29913     if( 0==pPage->nRef ){
29914       pCache->nRef++;
29915     }
29916     pPage->nRef++;
29917     if( pgno==1 ){
29918       pCache->pPage1 = pPage;
29919     }
29920   }
29921   *ppPage = pPage;
29922   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29923 }
29924
29925 /*
29926 ** Decrement the reference count on a page. If the page is clean and the
29927 ** reference count drops to 0, then it is made elible for recycling.
29928 */
29929 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29930   assert( p->nRef>0 );
29931   p->nRef--;
29932   if( p->nRef==0 ){
29933     PCache *pCache = p->pCache;
29934     pCache->nRef--;
29935     if( (p->flags&PGHDR_DIRTY)==0 ){
29936       pcacheUnpin(p);
29937     }else{
29938       /* Move the page to the head of the dirty list. */
29939       pcacheRemoveFromDirtyList(p);
29940       pcacheAddToDirtyList(p);
29941     }
29942   }
29943 }
29944
29945 /*
29946 ** Increase the reference count of a supplied page by 1.
29947 */
29948 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29949   assert(p->nRef>0);
29950   p->nRef++;
29951 }
29952
29953 /*
29954 ** Drop a page from the cache. There must be exactly one reference to the
29955 ** page. This function deletes that reference, so after it returns the
29956 ** page pointed to by p is invalid.
29957 */
29958 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29959   PCache *pCache;
29960   assert( p->nRef==1 );
29961   if( p->flags&PGHDR_DIRTY ){
29962     pcacheRemoveFromDirtyList(p);
29963   }
29964   pCache = p->pCache;
29965   pCache->nRef--;
29966   if( p->pgno==1 ){
29967     pCache->pPage1 = 0;
29968   }
29969   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29970 }
29971
29972 /*
29973 ** Make sure the page is marked as dirty. If it isn't dirty already,
29974 ** make it so.
29975 */
29976 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29977   PCache *pCache;
29978   p->flags &= ~PGHDR_DONT_WRITE;
29979   assert( p->nRef>0 );
29980   if( 0==(p->flags & PGHDR_DIRTY) ){
29981     pCache = p->pCache;
29982     p->flags |= PGHDR_DIRTY;
29983     pcacheAddToDirtyList( p);
29984   }
29985 }
29986
29987 /*
29988 ** Make sure the page is marked as clean. If it isn't clean already,
29989 ** make it so.
29990 */
29991 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
29992   if( (p->flags & PGHDR_DIRTY) ){
29993     pcacheRemoveFromDirtyList(p);
29994     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
29995     if( p->nRef==0 ){
29996       pcacheUnpin(p);
29997     }
29998   }
29999 }
30000
30001 /*
30002 ** Make every page in the cache clean.
30003 */
30004 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
30005   PgHdr *p;
30006   while( (p = pCache->pDirty)!=0 ){
30007     sqlite3PcacheMakeClean(p);
30008   }
30009 }
30010
30011 /*
30012 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
30013 */
30014 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
30015   PgHdr *p;
30016   for(p=pCache->pDirty; p; p=p->pDirtyNext){
30017     p->flags &= ~PGHDR_NEED_SYNC;
30018   }
30019   pCache->pSynced = pCache->pDirtyTail;
30020 }
30021
30022 /*
30023 ** Change the page number of page p to newPgno. 
30024 */
30025 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
30026   PCache *pCache = p->pCache;
30027   assert( p->nRef>0 );
30028   assert( newPgno>0 );
30029   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
30030   p->pgno = newPgno;
30031   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
30032     pcacheRemoveFromDirtyList(p);
30033     pcacheAddToDirtyList(p);
30034   }
30035 }
30036
30037 /*
30038 ** Drop every cache entry whose page number is greater than "pgno". The
30039 ** caller must ensure that there are no outstanding references to any pages
30040 ** other than page 1 with a page number greater than pgno.
30041 **
30042 ** If there is a reference to page 1 and the pgno parameter passed to this
30043 ** function is 0, then the data area associated with page 1 is zeroed, but
30044 ** the page object is not dropped.
30045 */
30046 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
30047   if( pCache->pCache ){
30048     PgHdr *p;
30049     PgHdr *pNext;
30050     for(p=pCache->pDirty; p; p=pNext){
30051       pNext = p->pDirtyNext;
30052       if( p->pgno>pgno ){
30053         assert( p->flags&PGHDR_DIRTY );
30054         sqlite3PcacheMakeClean(p);
30055       }
30056     }
30057     if( pgno==0 && pCache->pPage1 ){
30058       memset(pCache->pPage1->pData, 0, pCache->szPage);
30059       pgno = 1;
30060     }
30061     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
30062   }
30063 }
30064
30065 /*
30066 ** Close a cache.
30067 */
30068 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
30069   if( pCache->pCache ){
30070     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
30071   }
30072 }
30073
30074 /* 
30075 ** Discard the contents of the cache.
30076 */
30077 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
30078   sqlite3PcacheTruncate(pCache, 0);
30079 }
30080
30081 /*
30082 ** Merge two lists of pages connected by pDirty and in pgno order.
30083 ** Do not both fixing the pDirtyPrev pointers.
30084 */
30085 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
30086   PgHdr result, *pTail;
30087   pTail = &result;
30088   while( pA && pB ){
30089     if( pA->pgno<pB->pgno ){
30090       pTail->pDirty = pA;
30091       pTail = pA;
30092       pA = pA->pDirty;
30093     }else{
30094       pTail->pDirty = pB;
30095       pTail = pB;
30096       pB = pB->pDirty;
30097     }
30098   }
30099   if( pA ){
30100     pTail->pDirty = pA;
30101   }else if( pB ){
30102     pTail->pDirty = pB;
30103   }else{
30104     pTail->pDirty = 0;
30105   }
30106   return result.pDirty;
30107 }
30108
30109 /*
30110 ** Sort the list of pages in accending order by pgno.  Pages are
30111 ** connected by pDirty pointers.  The pDirtyPrev pointers are
30112 ** corrupted by this sort.
30113 */
30114 #define N_SORT_BUCKET_ALLOC 25
30115 #define N_SORT_BUCKET       25
30116 #ifdef SQLITE_TEST
30117   int sqlite3_pager_n_sort_bucket = 0;
30118   #undef N_SORT_BUCKET
30119   #define N_SORT_BUCKET \
30120    (sqlite3_pager_n_sort_bucket?sqlite3_pager_n_sort_bucket:N_SORT_BUCKET_ALLOC)
30121 #endif
30122 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
30123   PgHdr *a[N_SORT_BUCKET_ALLOC], *p;
30124   int i;
30125   memset(a, 0, sizeof(a));
30126   while( pIn ){
30127     p = pIn;
30128     pIn = p->pDirty;
30129     p->pDirty = 0;
30130     for(i=0; i<N_SORT_BUCKET-1; i++){
30131       if( a[i]==0 ){
30132         a[i] = p;
30133         break;
30134       }else{
30135         p = pcacheMergeDirtyList(a[i], p);
30136         a[i] = 0;
30137       }
30138     }
30139     if( i==N_SORT_BUCKET-1 ){
30140       /* Coverage: To get here, there need to be 2^(N_SORT_BUCKET) 
30141       ** elements in the input list. This is possible, but impractical.
30142       ** Testing this line is the point of global variable
30143       ** sqlite3_pager_n_sort_bucket.
30144       */
30145       a[i] = pcacheMergeDirtyList(a[i], p);
30146     }
30147   }
30148   p = a[0];
30149   for(i=1; i<N_SORT_BUCKET; i++){
30150     p = pcacheMergeDirtyList(p, a[i]);
30151   }
30152   return p;
30153 }
30154
30155 /*
30156 ** Return a list of all dirty pages in the cache, sorted by page number.
30157 */
30158 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
30159   PgHdr *p;
30160   for(p=pCache->pDirty; p; p=p->pDirtyNext){
30161     p->pDirty = p->pDirtyNext;
30162   }
30163   return pcacheSortDirtyList(pCache->pDirty);
30164 }
30165
30166 /* 
30167 ** Return the total number of referenced pages held by the cache.
30168 */
30169 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
30170   return pCache->nRef;
30171 }
30172
30173 /*
30174 ** Return the number of references to the page supplied as an argument.
30175 */
30176 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
30177   return p->nRef;
30178 }
30179
30180 /* 
30181 ** Return the total number of pages in the cache.
30182 */
30183 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
30184   int nPage = 0;
30185   if( pCache->pCache ){
30186     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
30187   }
30188   return nPage;
30189 }
30190
30191 #ifdef SQLITE_TEST
30192 /*
30193 ** Get the suggested cache-size value.
30194 */
30195 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
30196   return pCache->nMax;
30197 }
30198 #endif
30199
30200 /*
30201 ** Set the suggested cache-size value.
30202 */
30203 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30204   pCache->nMax = mxPage;
30205   if( pCache->pCache ){
30206     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30207   }
30208 }
30209
30210 #ifdef SQLITE_CHECK_PAGES
30211 /*
30212 ** For all dirty pages currently in the cache, invoke the specified
30213 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30214 ** defined.
30215 */
30216 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30217   PgHdr *pDirty;
30218   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30219     xIter(pDirty);
30220   }
30221 }
30222 #endif
30223
30224 /************** End of pcache.c **********************************************/
30225 /************** Begin file pcache1.c *****************************************/
30226 /*
30227 ** 2008 November 05
30228 **
30229 ** The author disclaims copyright to this source code.  In place of
30230 ** a legal notice, here is a blessing:
30231 **
30232 **    May you do good and not evil.
30233 **    May you find forgiveness for yourself and forgive others.
30234 **    May you share freely, never taking more than you give.
30235 **
30236 *************************************************************************
30237 **
30238 ** This file implements the default page cache implementation (the
30239 ** sqlite3_pcache interface). It also contains part of the implementation
30240 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30241 ** If the default page cache implementation is overriden, then neither of
30242 ** these two features are available.
30243 **
30244 ** @(#) $Id: pcache1.c,v 1.8 2009/01/23 16:45:01 danielk1977 Exp $
30245 */
30246
30247
30248 typedef struct PCache1 PCache1;
30249 typedef struct PgHdr1 PgHdr1;
30250 typedef struct PgFreeslot PgFreeslot;
30251
30252 /* Pointers to structures of this type are cast and returned as 
30253 ** opaque sqlite3_pcache* handles
30254 */
30255 struct PCache1 {
30256   /* Cache configuration parameters. Page size (szPage) and the purgeable
30257   ** flag (bPurgeable) are set when the cache is created. nMax may be 
30258   ** modified at any time by a call to the pcache1CacheSize() method.
30259   ** The global mutex must be held when accessing nMax.
30260   */
30261   int szPage;                         /* Size of allocated pages in bytes */
30262   int bPurgeable;                     /* True if cache is purgeable */
30263   unsigned int nMin;                  /* Minimum number of pages reserved */
30264   unsigned int nMax;                  /* Configured "cache_size" value */
30265
30266   /* Hash table of all pages. The following variables may only be accessed
30267   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
30268   ** and pcache1LeaveMutex()).
30269   */
30270   unsigned int nRecyclable;           /* Number of pages in the LRU list */
30271   unsigned int nPage;                 /* Total number of pages in apHash */
30272   unsigned int nHash;                 /* Number of slots in apHash[] */
30273   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30274
30275   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30276 };
30277
30278 /*
30279 ** Each cache entry is represented by an instance of the following 
30280 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
30281 ** directly after the structure in memory (see the PGHDR1_TO_PAGE() 
30282 ** macro below).
30283 */
30284 struct PgHdr1 {
30285   unsigned int iKey;             /* Key value (page number) */
30286   PgHdr1 *pNext;                 /* Next in hash table chain */
30287   PCache1 *pCache;               /* Cache that currently owns this page */
30288   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30289   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30290 };
30291
30292 /*
30293 ** Free slots in the allocator used to divide up the buffer provided using
30294 ** the SQLITE_CONFIG_PAGECACHE mechanism.
30295 */
30296 struct PgFreeslot {
30297   PgFreeslot *pNext;  /* Next free slot */
30298 };
30299
30300 /*
30301 ** Global data used by this cache.
30302 */
30303 static SQLITE_WSD struct PCacheGlobal {
30304   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30305
30306   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30307   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30308   int nCurrentPage;                   /* Number of purgeable pages allocated */
30309   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30310
30311   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30312   int szSlot;                         /* Size of each free slot */
30313   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30314   PgFreeslot *pFree;                  /* Free page blocks */
30315 } pcache1_g;
30316
30317 /*
30318 ** All code in this file should access the global structure above via the
30319 ** alias "pcache1". This ensures that the WSD emulation is used when
30320 ** compiling for systems that do not support real WSD.
30321 */
30322 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30323
30324 /*
30325 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30326 ** bytes of data are located directly after it in memory (i.e. the total
30327 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30328 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30329 ** an argument and returns a pointer to the associated block of szPage
30330 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30331 ** a pointer to a block of szPage bytes of data and the return value is
30332 ** a pointer to the associated PgHdr1 structure.
30333 **
30334 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(X))==X );
30335 */
30336 #define PGHDR1_TO_PAGE(p) (void *)(&((unsigned char *)p)[sizeof(PgHdr1)])
30337 #define PAGE_TO_PGHDR1(p) (PgHdr1 *)(&((unsigned char *)p)[-1*(int)sizeof(PgHdr1)])
30338
30339 /*
30340 ** Macros to enter and leave the global LRU mutex.
30341 */
30342 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30343 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30344
30345 /******************************************************************************/
30346 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30347
30348 /*
30349 ** This function is called during initialization if a static buffer is 
30350 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30351 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30352 ** enough to contain 'n' buffers of 'sz' bytes each.
30353 */
30354 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30355   PgFreeslot *p;
30356   sz &= ~7;
30357   pcache1.szSlot = sz;
30358   pcache1.pStart = pBuf;
30359   pcache1.pFree = 0;
30360   while( n-- ){
30361     p = (PgFreeslot*)pBuf;
30362     p->pNext = pcache1.pFree;
30363     pcache1.pFree = p;
30364     pBuf = (void*)&((char*)pBuf)[sz];
30365   }
30366   pcache1.pEnd = pBuf;
30367 }
30368
30369 /*
30370 ** Malloc function used within this file to allocate space from the buffer
30371 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
30372 ** such buffer exists or there is no space left in it, this function falls 
30373 ** back to sqlite3Malloc().
30374 */
30375 static void *pcache1Alloc(int nByte){
30376   void *p;
30377   assert( sqlite3_mutex_held(pcache1.mutex) );
30378   if( nByte<=pcache1.szSlot && pcache1.pFree ){
30379     p = (PgHdr1 *)pcache1.pFree;
30380     pcache1.pFree = pcache1.pFree->pNext;
30381     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30382     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30383   }else{
30384
30385     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30386     ** global pcache mutex and unlock the pager-cache object pCache. This is 
30387     ** so that if the attempt to allocate a new buffer causes the the 
30388     ** configured soft-heap-limit to be breached, it will be possible to
30389     ** reclaim memory from this pager-cache.
30390     */
30391     pcache1LeaveMutex();
30392     p = sqlite3Malloc(nByte);
30393     pcache1EnterMutex();
30394     if( p ){
30395       int sz = sqlite3MallocSize(p);
30396       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30397     }
30398   }
30399   return p;
30400 }
30401
30402 /*
30403 ** Free an allocated buffer obtained from pcache1Alloc().
30404 */
30405 static void pcache1Free(void *p){
30406   assert( sqlite3_mutex_held(pcache1.mutex) );
30407   if( p==0 ) return;
30408   if( p>=pcache1.pStart && p<pcache1.pEnd ){
30409     PgFreeslot *pSlot;
30410     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30411     pSlot = (PgFreeslot*)p;
30412     pSlot->pNext = pcache1.pFree;
30413     pcache1.pFree = pSlot;
30414   }else{
30415     int iSize = sqlite3MallocSize(p);
30416     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30417     sqlite3_free(p);
30418   }
30419 }
30420
30421 /*
30422 ** Allocate a new page object initially associated with cache pCache.
30423 */
30424 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30425   int nByte = sizeof(PgHdr1) + pCache->szPage;
30426   PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
30427   if( p ){
30428     if( pCache->bPurgeable ){
30429       pcache1.nCurrentPage++;
30430     }
30431   }
30432   return p;
30433 }
30434
30435 /*
30436 ** Free a page object allocated by pcache1AllocPage().
30437 */
30438 static void pcache1FreePage(PgHdr1 *p){
30439   if( p ){
30440     if( p->pCache->bPurgeable ){
30441       pcache1.nCurrentPage--;
30442     }
30443     pcache1Free(p);
30444   }
30445 }
30446
30447 /*
30448 ** Malloc function used by SQLite to obtain space from the buffer configured
30449 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30450 ** exists, this function falls back to sqlite3Malloc().
30451 */
30452 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30453   void *p;
30454   pcache1EnterMutex();
30455   p = pcache1Alloc(sz);
30456   pcache1LeaveMutex();
30457   return p;
30458 }
30459
30460 /*
30461 ** Free an allocated buffer obtained from sqlite3PageMalloc().
30462 */
30463 SQLITE_PRIVATE void sqlite3PageFree(void *p){
30464   pcache1EnterMutex();
30465   pcache1Free(p);
30466   pcache1LeaveMutex();
30467 }
30468
30469 /******************************************************************************/
30470 /******** General Implementation Functions ************************************/
30471
30472 /*
30473 ** This function is used to resize the hash table used by the cache passed
30474 ** as the first argument.
30475 **
30476 ** The global mutex must be held when this function is called.
30477 */
30478 static int pcache1ResizeHash(PCache1 *p){
30479   PgHdr1 **apNew;
30480   unsigned int nNew;
30481   unsigned int i;
30482
30483   assert( sqlite3_mutex_held(pcache1.mutex) );
30484
30485   nNew = p->nHash*2;
30486   if( nNew<256 ){
30487     nNew = 256;
30488   }
30489
30490   pcache1LeaveMutex();
30491   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30492   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30493   if( p->nHash ){ sqlite3EndBenignMalloc(); }
30494   pcache1EnterMutex();
30495   if( apNew ){
30496     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30497     for(i=0; i<p->nHash; i++){
30498       PgHdr1 *pPage;
30499       PgHdr1 *pNext = p->apHash[i];
30500       while( (pPage = pNext)!=0 ){
30501         unsigned int h = pPage->iKey % nNew;
30502         pNext = pPage->pNext;
30503         pPage->pNext = apNew[h];
30504         apNew[h] = pPage;
30505       }
30506     }
30507     sqlite3_free(p->apHash);
30508     p->apHash = apNew;
30509     p->nHash = nNew;
30510   }
30511
30512   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30513 }
30514
30515 /*
30516 ** This function is used internally to remove the page pPage from the 
30517 ** global LRU list, if is part of it. If pPage is not part of the global
30518 ** LRU list, then this function is a no-op.
30519 **
30520 ** The global mutex must be held when this function is called.
30521 */
30522 static void pcache1PinPage(PgHdr1 *pPage){
30523   assert( sqlite3_mutex_held(pcache1.mutex) );
30524   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30525     if( pPage->pLruPrev ){
30526       pPage->pLruPrev->pLruNext = pPage->pLruNext;
30527     }
30528     if( pPage->pLruNext ){
30529       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30530     }
30531     if( pcache1.pLruHead==pPage ){
30532       pcache1.pLruHead = pPage->pLruNext;
30533     }
30534     if( pcache1.pLruTail==pPage ){
30535       pcache1.pLruTail = pPage->pLruPrev;
30536     }
30537     pPage->pLruNext = 0;
30538     pPage->pLruPrev = 0;
30539     pPage->pCache->nRecyclable--;
30540   }
30541 }
30542
30543
30544 /*
30545 ** Remove the page supplied as an argument from the hash table 
30546 ** (PCache1.apHash structure) that it is currently stored in.
30547 **
30548 ** The global mutex must be held when this function is called.
30549 */
30550 static void pcache1RemoveFromHash(PgHdr1 *pPage){
30551   unsigned int h;
30552   PCache1 *pCache = pPage->pCache;
30553   PgHdr1 **pp;
30554
30555   h = pPage->iKey % pCache->nHash;
30556   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30557   *pp = (*pp)->pNext;
30558
30559   pCache->nPage--;
30560 }
30561
30562 /*
30563 ** If there are currently more than pcache.nMaxPage pages allocated, try
30564 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30565 */
30566 static void pcache1EnforceMaxPage(void){
30567   assert( sqlite3_mutex_held(pcache1.mutex) );
30568   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30569     PgHdr1 *p = pcache1.pLruTail;
30570     pcache1PinPage(p);
30571     pcache1RemoveFromHash(p);
30572     pcache1FreePage(p);
30573   }
30574 }
30575
30576 /*
30577 ** Discard all pages from cache pCache with a page number (key value) 
30578 ** greater than or equal to iLimit. Any pinned pages that meet this 
30579 ** criteria are unpinned before they are discarded.
30580 **
30581 ** The global mutex must be held when this function is called.
30582 */
30583 static void pcache1TruncateUnsafe(
30584   PCache1 *pCache, 
30585   unsigned int iLimit 
30586 ){
30587   unsigned int h;
30588   assert( sqlite3_mutex_held(pcache1.mutex) );
30589   for(h=0; h<pCache->nHash; h++){
30590     PgHdr1 **pp = &pCache->apHash[h]; 
30591     PgHdr1 *pPage;
30592     while( (pPage = *pp)!=0 ){
30593       if( pPage->iKey>=iLimit ){
30594         pcache1PinPage(pPage);
30595         *pp = pPage->pNext;
30596         pcache1FreePage(pPage);
30597       }else{
30598         pp = &pPage->pNext;
30599       }
30600     }
30601   }
30602 }
30603
30604 /******************************************************************************/
30605 /******** sqlite3_pcache Methods **********************************************/
30606
30607 /*
30608 ** Implementation of the sqlite3_pcache.xInit method.
30609 */
30610 static int pcache1Init(void *NotUsed){
30611   UNUSED_PARAMETER(NotUsed);
30612   memset(&pcache1, 0, sizeof(pcache1));
30613   if( sqlite3GlobalConfig.bCoreMutex ){
30614     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30615   }
30616   return SQLITE_OK;
30617 }
30618
30619 /*
30620 ** Implementation of the sqlite3_pcache.xShutdown method.
30621 */
30622 static void pcache1Shutdown(void *NotUsed){
30623   UNUSED_PARAMETER(NotUsed);
30624   /* no-op */
30625 }
30626
30627 /*
30628 ** Implementation of the sqlite3_pcache.xCreate method.
30629 **
30630 ** Allocate a new cache.
30631 */
30632 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30633   PCache1 *pCache;
30634
30635   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30636   if( pCache ){
30637     memset(pCache, 0, sizeof(PCache1));
30638     pCache->szPage = szPage;
30639     pCache->bPurgeable = (bPurgeable ? 1 : 0);
30640     if( bPurgeable ){
30641       pCache->nMin = 10;
30642       pcache1EnterMutex();
30643       pcache1.nMinPage += pCache->nMin;
30644       pcache1LeaveMutex();
30645     }
30646   }
30647   return (sqlite3_pcache *)pCache;
30648 }
30649
30650 /*
30651 ** Implementation of the sqlite3_pcache.xCachesize method. 
30652 **
30653 ** Configure the cache_size limit for a cache.
30654 */
30655 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30656   PCache1 *pCache = (PCache1 *)p;
30657   if( pCache->bPurgeable ){
30658     pcache1EnterMutex();
30659     pcache1.nMaxPage += (nMax - pCache->nMax);
30660     pCache->nMax = nMax;
30661     pcache1EnforceMaxPage();
30662     pcache1LeaveMutex();
30663   }
30664 }
30665
30666 /*
30667 ** Implementation of the sqlite3_pcache.xPagecount method. 
30668 */
30669 static int pcache1Pagecount(sqlite3_pcache *p){
30670   int n;
30671   pcache1EnterMutex();
30672   n = ((PCache1 *)p)->nPage;
30673   pcache1LeaveMutex();
30674   return n;
30675 }
30676
30677 /*
30678 ** Implementation of the sqlite3_pcache.xFetch method. 
30679 **
30680 ** Fetch a page by key value.
30681 **
30682 ** Whether or not a new page may be allocated by this function depends on
30683 ** the value of the createFlag argument.
30684 **
30685 ** There are three different approaches to obtaining space for a page,
30686 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30687 **
30688 **   1. Regardless of the value of createFlag, the cache is searched for a 
30689 **      copy of the requested page. If one is found, it is returned.
30690 **
30691 **   2. If createFlag==0 and the page is not already in the cache, NULL is
30692 **      returned.
30693 **
30694 **   3. If createFlag is 1, the cache is marked as purgeable and the page is 
30695 **      not already in the cache, and if either of the following are true, 
30696 **      return NULL:
30697 **
30698 **       (a) the number of pages pinned by the cache is greater than
30699 **           PCache1.nMax, or
30700 **       (b) the number of pages pinned by the cache is greater than
30701 **           the sum of nMax for all purgeable caches, less the sum of 
30702 **           nMin for all other purgeable caches. 
30703 **
30704 **   4. If none of the first three conditions apply and the cache is marked
30705 **      as purgeable, and if one of the following is true:
30706 **
30707 **       (a) The number of pages allocated for the cache is already 
30708 **           PCache1.nMax, or
30709 **
30710 **       (b) The number of pages allocated for all purgeable caches is
30711 **           already equal to or greater than the sum of nMax for all
30712 **           purgeable caches,
30713 **
30714 **      then attempt to recycle a page from the LRU list. If it is the right
30715 **      size, return the recycled buffer. Otherwise, free the buffer and
30716 **      proceed to step 5. 
30717 **
30718 **   5. Otherwise, allocate and return a new page buffer.
30719 */
30720 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30721   unsigned int nPinned;
30722   PCache1 *pCache = (PCache1 *)p;
30723   PgHdr1 *pPage = 0;
30724
30725   pcache1EnterMutex();
30726   if( createFlag==1 ) sqlite3BeginBenignMalloc();
30727
30728   /* Search the hash table for an existing entry. */
30729   if( pCache->nHash>0 ){
30730     unsigned int h = iKey % pCache->nHash;
30731     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30732   }
30733
30734   if( pPage || createFlag==0 ){
30735     pcache1PinPage(pPage);
30736     goto fetch_out;
30737   }
30738
30739   /* Step 3 of header comment. */
30740   nPinned = pCache->nPage - pCache->nRecyclable;
30741   if( createFlag==1 && pCache->bPurgeable && (
30742         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30743      || nPinned>=(pCache->nMax)
30744   )){
30745     goto fetch_out;
30746   }
30747
30748   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30749     goto fetch_out;
30750   }
30751
30752   /* Step 4. Try to recycle a page buffer if appropriate. */
30753   if( pCache->bPurgeable && pcache1.pLruTail && (
30754       pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
30755   )){
30756     pPage = pcache1.pLruTail;
30757     pcache1RemoveFromHash(pPage);
30758     pcache1PinPage(pPage);
30759     if( pPage->pCache->szPage!=pCache->szPage ){
30760       pcache1FreePage(pPage);
30761       pPage = 0;
30762     }else{
30763       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30764     }
30765   }
30766
30767   /* Step 5. If a usable page buffer has still not been found, 
30768   ** attempt to allocate a new one. 
30769   */
30770   if( !pPage ){
30771     pPage = pcache1AllocPage(pCache);
30772   }
30773
30774   if( pPage ){
30775     unsigned int h = iKey % pCache->nHash;
30776     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30777     pCache->nPage++;
30778     pPage->iKey = iKey;
30779     pPage->pNext = pCache->apHash[h];
30780     pPage->pCache = pCache;
30781     pPage->pLruPrev = 0;
30782     pPage->pLruNext = 0;
30783     pCache->apHash[h] = pPage;
30784   }
30785
30786 fetch_out:
30787   if( pPage && iKey>pCache->iMaxKey ){
30788     pCache->iMaxKey = iKey;
30789   }
30790   if( createFlag==1 ) sqlite3EndBenignMalloc();
30791   pcache1LeaveMutex();
30792   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30793 }
30794
30795
30796 /*
30797 ** Implementation of the sqlite3_pcache.xUnpin method.
30798 **
30799 ** Mark a page as unpinned (eligible for asynchronous recycling).
30800 */
30801 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30802   PCache1 *pCache = (PCache1 *)p;
30803   PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
30804
30805   pcache1EnterMutex();
30806
30807   /* It is an error to call this function if the page is already 
30808   ** part of the global LRU list.
30809   */
30810   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30811   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30812
30813   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30814     pcache1RemoveFromHash(pPage);
30815     pcache1FreePage(pPage);
30816   }else{
30817     /* Add the page to the global LRU list. Normally, the page is added to
30818     ** the head of the list (last page to be recycled). However, if the 
30819     ** reuseUnlikely flag passed to this function is true, the page is added
30820     ** to the tail of the list (first page to be recycled).
30821     */
30822     if( pcache1.pLruHead ){
30823       pcache1.pLruHead->pLruPrev = pPage;
30824       pPage->pLruNext = pcache1.pLruHead;
30825       pcache1.pLruHead = pPage;
30826     }else{
30827       pcache1.pLruTail = pPage;
30828       pcache1.pLruHead = pPage;
30829     }
30830     pCache->nRecyclable++;
30831   }
30832
30833   pcache1LeaveMutex();
30834 }
30835
30836 /*
30837 ** Implementation of the sqlite3_pcache.xRekey method. 
30838 */
30839 static void pcache1Rekey(
30840   sqlite3_pcache *p,
30841   void *pPg,
30842   unsigned int iOld,
30843   unsigned int iNew
30844 ){
30845   PCache1 *pCache = (PCache1 *)p;
30846   PgHdr1 *pPage = PAGE_TO_PGHDR1(pPg);
30847   PgHdr1 **pp;
30848   unsigned int h; 
30849   assert( pPage->iKey==iOld );
30850
30851   pcache1EnterMutex();
30852
30853   h = iOld%pCache->nHash;
30854   pp = &pCache->apHash[h];
30855   while( (*pp)!=pPage ){
30856     pp = &(*pp)->pNext;
30857   }
30858   *pp = pPage->pNext;
30859
30860   h = iNew%pCache->nHash;
30861   pPage->iKey = iNew;
30862   pPage->pNext = pCache->apHash[h];
30863   pCache->apHash[h] = pPage;
30864
30865   if( iNew>pCache->iMaxKey ){
30866     pCache->iMaxKey = iNew;
30867   }
30868
30869   pcache1LeaveMutex();
30870 }
30871
30872 /*
30873 ** Implementation of the sqlite3_pcache.xTruncate method. 
30874 **
30875 ** Discard all unpinned pages in the cache with a page number equal to
30876 ** or greater than parameter iLimit. Any pinned pages with a page number
30877 ** equal to or greater than iLimit are implicitly unpinned.
30878 */
30879 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30880   PCache1 *pCache = (PCache1 *)p;
30881   pcache1EnterMutex();
30882   if( iLimit<=pCache->iMaxKey ){
30883     pcache1TruncateUnsafe(pCache, iLimit);
30884     pCache->iMaxKey = iLimit-1;
30885   }
30886   pcache1LeaveMutex();
30887 }
30888
30889 /*
30890 ** Implementation of the sqlite3_pcache.xDestroy method. 
30891 **
30892 ** Destroy a cache allocated using pcache1Create().
30893 */
30894 static void pcache1Destroy(sqlite3_pcache *p){
30895   PCache1 *pCache = (PCache1 *)p;
30896   pcache1EnterMutex();
30897   pcache1TruncateUnsafe(pCache, 0);
30898   pcache1.nMaxPage -= pCache->nMax;
30899   pcache1.nMinPage -= pCache->nMin;
30900   pcache1EnforceMaxPage();
30901   pcache1LeaveMutex();
30902   sqlite3_free(pCache->apHash);
30903   sqlite3_free(pCache);
30904 }
30905
30906 /*
30907 ** This function is called during initialization (sqlite3_initialize()) to
30908 ** install the default pluggable cache module, assuming the user has not
30909 ** already provided an alternative.
30910 */
30911 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30912   static sqlite3_pcache_methods defaultMethods = {
30913     0,                       /* pArg */
30914     pcache1Init,             /* xInit */
30915     pcache1Shutdown,         /* xShutdown */
30916     pcache1Create,           /* xCreate */
30917     pcache1Cachesize,        /* xCachesize */
30918     pcache1Pagecount,        /* xPagecount */
30919     pcache1Fetch,            /* xFetch */
30920     pcache1Unpin,            /* xUnpin */
30921     pcache1Rekey,            /* xRekey */
30922     pcache1Truncate,         /* xTruncate */
30923     pcache1Destroy           /* xDestroy */
30924   };
30925   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30926 }
30927
30928 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30929 /*
30930 ** This function is called to free superfluous dynamically allocated memory
30931 ** held by the pager system. Memory in use by any SQLite pager allocated
30932 ** by the current thread may be sqlite3_free()ed.
30933 **
30934 ** nReq is the number of bytes of memory required. Once this much has
30935 ** been released, the function returns. The return value is the total number 
30936 ** of bytes of memory released.
30937 */
30938 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30939   int nFree = 0;
30940   if( pcache1.pStart==0 ){
30941     PgHdr1 *p;
30942     pcache1EnterMutex();
30943     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30944       nFree += sqlite3MallocSize(p);
30945       pcache1PinPage(p);
30946       pcache1RemoveFromHash(p);
30947       pcache1FreePage(p);
30948     }
30949     pcache1LeaveMutex();
30950   }
30951   return nFree;
30952 }
30953 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30954
30955 #ifdef SQLITE_TEST
30956 /*
30957 ** This function is used by test procedures to inspect the internal state
30958 ** of the global cache.
30959 */
30960 SQLITE_PRIVATE void sqlite3PcacheStats(
30961   int *pnCurrent,      /* OUT: Total number of pages cached */
30962   int *pnMax,          /* OUT: Global maximum cache size */
30963   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30964   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30965 ){
30966   PgHdr1 *p;
30967   int nRecyclable = 0;
30968   for(p=pcache1.pLruHead; p; p=p->pLruNext){
30969     nRecyclable++;
30970   }
30971   *pnCurrent = pcache1.nCurrentPage;
30972   *pnMax = pcache1.nMaxPage;
30973   *pnMin = pcache1.nMinPage;
30974   *pnRecyclable = nRecyclable;
30975 }
30976 #endif
30977
30978 /************** End of pcache1.c *********************************************/
30979 /************** Begin file rowset.c ******************************************/
30980 /*
30981 ** 2008 December 3
30982 **
30983 ** The author disclaims copyright to this source code.  In place of
30984 ** a legal notice, here is a blessing:
30985 **
30986 **    May you do good and not evil.
30987 **    May you find forgiveness for yourself and forgive others.
30988 **    May you share freely, never taking more than you give.
30989 **
30990 *************************************************************************
30991 **
30992 ** This module implements an object we call a "Row Set".
30993 **
30994 ** The RowSet object is a bag of rowids.  Rowids
30995 ** are inserted into the bag in an arbitrary order.  Then they are
30996 ** pulled from the bag in sorted order.  Rowids only appear in the
30997 ** bag once.  If the same rowid is inserted multiple times, the
30998 ** second and subsequent inserts make no difference on the output.
30999 **
31000 ** This implementation accumulates rowids in a linked list.  For
31001 ** output, it first sorts the linked list (removing duplicates during
31002 ** the sort) then returns elements one by one by walking the list.
31003 **
31004 ** Big chunks of rowid/next-ptr pairs are allocated at a time, to
31005 ** reduce the malloc overhead.
31006 **
31007 ** $Id: rowset.c,v 1.3 2009/01/13 20:14:16 drh Exp $
31008 */
31009
31010 /*
31011 ** The number of rowset entries per allocation chunk.
31012 */
31013 #define ROWSET_ENTRY_PER_CHUNK  63
31014
31015 /*
31016 ** Each entry in a RowSet is an instance of the following
31017 ** structure:
31018 */
31019 struct RowSetEntry {            
31020   i64 v;                        /* ROWID value for this entry */
31021   struct RowSetEntry *pNext;    /* Next entry on a list of all entries */
31022 };
31023
31024 /*
31025 ** Index entries are allocated in large chunks (instances of the
31026 ** following structure) to reduce memory allocation overhead.  The
31027 ** chunks are kept on a linked list so that they can be deallocated
31028 ** when the RowSet is destroyed.
31029 */
31030 struct RowSetChunk {
31031   struct RowSetChunk *pNext;             /* Next chunk on list of them all */
31032   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
31033 };
31034
31035 /*
31036 ** A RowSet in an instance of the following structure.
31037 **
31038 ** A typedef of this structure if found in sqliteInt.h.
31039 */
31040 struct RowSet {
31041   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
31042   sqlite3 *db;                   /* The database connection */
31043   struct RowSetEntry *pEntry;    /* List of entries in the rowset */
31044   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
31045   struct RowSetEntry *pFresh;    /* Source of new entry objects */
31046   u16 nFresh;                    /* Number of objects on pFresh */
31047   u8 isSorted;                   /* True if content is sorted */
31048 };
31049
31050 /*
31051 ** Turn bulk memory into a RowSet object.  N bytes of memory
31052 ** are available at pSpace.  The db pointer is used as a memory context
31053 ** for any subsequent allocations that need to occur.
31054 ** Return a pointer to the new RowSet object.
31055 **
31056 ** It must be the case that N is sufficient to make a Rowset.  If not
31057 ** an assertion fault occurs.
31058 ** 
31059 ** If N is larger than the minimum, use the surplus as an initial
31060 ** allocation of entries available to be filled.
31061 */
31062 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
31063   RowSet *p;
31064   assert( N >= sizeof(*p) );
31065   p = pSpace;
31066   p->pChunk = 0;
31067   p->db = db;
31068   p->pEntry = 0;
31069   p->pLast = 0;
31070   p->pFresh = (struct RowSetEntry*)&p[1];
31071   p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
31072   p->isSorted = 1;
31073   return p;
31074 }
31075
31076 /*
31077 ** Deallocate all chunks from a RowSet.
31078 */
31079 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
31080   struct RowSetChunk *pChunk, *pNextChunk;
31081   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
31082     pNextChunk = pChunk->pNext;
31083     sqlite3DbFree(p->db, pChunk);
31084   }
31085   p->pChunk = 0;
31086   p->nFresh = 0;
31087   p->pEntry = 0;
31088   p->pLast = 0;
31089   p->isSorted = 1;
31090 }
31091
31092 /*
31093 ** Insert a new value into a RowSet.
31094 **
31095 ** The mallocFailed flag of the database connection is set if a
31096 ** memory allocation fails.
31097 */
31098 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
31099   struct RowSetEntry *pEntry;
31100   struct RowSetEntry *pLast;
31101   if( p==0 ) return;  /* Must have been a malloc failure */
31102   if( p->nFresh==0 ){
31103     struct RowSetChunk *pNew;
31104     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
31105     if( pNew==0 ){
31106       return;
31107     }
31108     pNew->pNext = p->pChunk;
31109     p->pChunk = pNew;
31110     p->pFresh = pNew->aEntry;
31111     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
31112   }
31113   pEntry = p->pFresh++;
31114   p->nFresh--;
31115   pEntry->v = rowid;
31116   pEntry->pNext = 0;
31117   pLast = p->pLast;
31118   if( pLast ){
31119     if( p->isSorted && rowid<=pLast->v ){
31120       p->isSorted = 0;
31121     }
31122     pLast->pNext = pEntry;
31123   }else{
31124     assert( p->pEntry==0 );
31125     p->pEntry = pEntry;
31126   }
31127   p->pLast = pEntry;
31128 }
31129
31130 /*
31131 ** Merge two lists of RowSet entries.  Remove duplicates.
31132 **
31133 ** The input lists are assumed to be in sorted order.
31134 */
31135 static struct RowSetEntry *boolidxMerge(
31136   struct RowSetEntry *pA,    /* First sorted list to be merged */
31137   struct RowSetEntry *pB     /* Second sorted list to be merged */
31138 ){
31139   struct RowSetEntry head;
31140   struct RowSetEntry *pTail;
31141
31142   pTail = &head;
31143   while( pA && pB ){
31144     assert( pA->pNext==0 || pA->v<=pA->pNext->v );
31145     assert( pB->pNext==0 || pB->v<=pB->pNext->v );
31146     if( pA->v<pB->v ){
31147       pTail->pNext = pA;
31148       pA = pA->pNext;
31149       pTail = pTail->pNext;
31150     }else if( pB->v<pA->v ){
31151       pTail->pNext = pB;
31152       pB = pB->pNext;
31153       pTail = pTail->pNext;
31154     }else{
31155       pA = pA->pNext;
31156     }
31157   }
31158   if( pA ){
31159     assert( pA->pNext==0 || pA->v<=pA->pNext->v );
31160     pTail->pNext = pA;
31161   }else{
31162     assert( pB==0 || pB->pNext==0 || pB->v<=pB->pNext->v );
31163     pTail->pNext = pB;
31164   }
31165   return head.pNext;
31166 }
31167
31168 /*
31169 ** Sort all elements of the RowSet into ascending order.
31170 */ 
31171 static void sqlite3RowSetSort(RowSet *p){
31172   unsigned int i;
31173   struct RowSetEntry *pEntry;
31174   struct RowSetEntry *aBucket[40];
31175
31176   assert( p->isSorted==0 );
31177   memset(aBucket, 0, sizeof(aBucket));
31178   while( p->pEntry ){
31179     pEntry = p->pEntry;
31180     p->pEntry = pEntry->pNext;
31181     pEntry->pNext = 0;
31182     for(i=0; aBucket[i]; i++){
31183       pEntry = boolidxMerge(aBucket[i],pEntry);
31184       aBucket[i] = 0;
31185     }
31186     aBucket[i] = pEntry;
31187   }
31188   pEntry = 0;
31189   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31190     pEntry = boolidxMerge(pEntry,aBucket[i]);
31191   }
31192   p->pEntry = pEntry;
31193   p->pLast = 0;
31194   p->isSorted = 1;
31195 }
31196
31197 /*
31198 ** Extract the next (smallest) element from the RowSet.
31199 ** Write the element into *pRowid.  Return 1 on success.  Return
31200 ** 0 if the RowSet is already empty.
31201 */
31202 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31203   if( !p->isSorted ){
31204     sqlite3RowSetSort(p);
31205   }
31206   if( p->pEntry ){
31207     *pRowid = p->pEntry->v;
31208     p->pEntry = p->pEntry->pNext;
31209     if( p->pEntry==0 ){
31210       sqlite3RowSetClear(p);
31211     }
31212     return 1;
31213   }else{
31214     return 0;
31215   }
31216 }
31217
31218 /************** End of rowset.c **********************************************/
31219 /************** Begin file pager.c *******************************************/
31220 /*
31221 ** 2001 September 15
31222 **
31223 ** The author disclaims copyright to this source code.  In place of
31224 ** a legal notice, here is a blessing:
31225 **
31226 **    May you do good and not evil.
31227 **    May you find forgiveness for yourself and forgive others.
31228 **    May you share freely, never taking more than you give.
31229 **
31230 *************************************************************************
31231 ** This is the implementation of the page cache subsystem or "pager".
31232 ** 
31233 ** The pager is used to access a database disk file.  It implements
31234 ** atomic commit and rollback through the use of a journal file that
31235 ** is separate from the database file.  The pager also implements file
31236 ** locking to prevent two processes from writing the same database
31237 ** file simultaneously, or one process from reading the database while
31238 ** another is writing.
31239 **
31240 ** @(#) $Id: pager.c,v 1.570 2009/02/17 17:56:30 danielk1977 Exp $
31241 */
31242 #ifndef SQLITE_OMIT_DISKIO
31243
31244 /*
31245 ** Macros for troubleshooting.  Normally turned off
31246 */
31247 #if 0
31248 int sqlite3PagerTrace=1;  /* True to enable tracing */
31249 #define sqlite3DebugPrintf printf
31250 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31251 #else
31252 #define PAGERTRACE(X)
31253 #endif
31254
31255 /*
31256 ** The following two macros are used within the PAGERTRACE() macros above
31257 ** to print out file-descriptors. 
31258 **
31259 ** PAGERID() takes a pointer to a Pager struct as its argument. The
31260 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31261 ** struct as its argument.
31262 */
31263 #define PAGERID(p) ((int)(p->fd))
31264 #define FILEHANDLEID(fd) ((int)fd)
31265
31266 /*
31267 ** The page cache as a whole is always in one of the following
31268 ** states:
31269 **
31270 **   PAGER_UNLOCK        The page cache is not currently reading or 
31271 **                       writing the database file.  There is no
31272 **                       data held in memory.  This is the initial
31273 **                       state.
31274 **
31275 **   PAGER_SHARED        The page cache is reading the database.
31276 **                       Writing is not permitted.  There can be
31277 **                       multiple readers accessing the same database
31278 **                       file at the same time.
31279 **
31280 **   PAGER_RESERVED      This process has reserved the database for writing
31281 **                       but has not yet made any changes.  Only one process
31282 **                       at a time can reserve the database.  The original
31283 **                       database file has not been modified so other
31284 **                       processes may still be reading the on-disk
31285 **                       database file.
31286 **
31287 **   PAGER_EXCLUSIVE     The page cache is writing the database.
31288 **                       Access is exclusive.  No other processes or
31289 **                       threads can be reading or writing while one
31290 **                       process is writing.
31291 **
31292 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31293 **                       after all dirty pages have been written to the
31294 **                       database file and the file has been synced to
31295 **                       disk. All that remains to do is to remove or
31296 **                       truncate the journal file and the transaction 
31297 **                       will be committed.
31298 **
31299 ** The page cache comes up in PAGER_UNLOCK.  The first time a
31300 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31301 ** After all pages have been released using sqlite_page_unref(),
31302 ** the state transitions back to PAGER_UNLOCK.  The first time
31303 ** that sqlite3PagerWrite() is called, the state transitions to
31304 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31305 ** called on an outstanding page which means that the pager must
31306 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31307 ** PAGER_RESERVED means that there is an open rollback journal.
31308 ** The transition to PAGER_EXCLUSIVE occurs before any changes
31309 ** are made to the database file, though writes to the rollback
31310 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31311 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31312 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31313 */
31314 #define PAGER_UNLOCK      0
31315 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
31316 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31317 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31318 #define PAGER_SYNCED      5
31319
31320 /*
31321 ** This macro rounds values up so that if the value is an address it
31322 ** is guaranteed to be an address that is aligned to an 8-byte boundary.
31323 */
31324 #define FORCE_ALIGNMENT(X)   (((X)+7)&~7)
31325
31326 /*
31327 ** A macro used for invoking the codec if there is one
31328 */
31329 #ifdef SQLITE_HAS_CODEC
31330 # define CODEC1(P,D,N,X) if( P->xCodec!=0 ){ P->xCodec(P->pCodecArg,D,N,X); }
31331 # define CODEC2(P,D,N,X) ((char*)(P->xCodec!=0?P->xCodec(P->pCodecArg,D,N,X):D))
31332 #else
31333 # define CODEC1(P,D,N,X) /* NO-OP */
31334 # define CODEC2(P,D,N,X) ((char*)D)
31335 #endif
31336
31337 /*
31338 ** The maximum allowed sector size. 16MB. If the xSectorsize() method 
31339 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31340 ** This could conceivably cause corruption following a power failure on
31341 ** such a system. This is currently an undocumented limit.
31342 */
31343 #define MAX_SECTOR_SIZE 0x0100000
31344
31345 /*
31346 ** An instance of the following structure is allocated for each active
31347 ** savepoint and statement transaction in the system. All such structures
31348 ** are stored in the Pager.aSavepoint[] array, which is allocated and
31349 ** resized using sqlite3Realloc().
31350 **
31351 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31352 ** set to 0. If a journal-header is written into the main journal while
31353 ** the savepoint is active, then iHdrOffset is set to the byte offset 
31354 ** immediately following the last journal record written into the main
31355 ** journal before the journal-header. This is required during savepoint
31356 ** rollback (see pagerPlaybackSavepoint()).
31357 */
31358 typedef struct PagerSavepoint PagerSavepoint;
31359 struct PagerSavepoint {
31360   i64 iOffset;                 /* Starting offset in main journal */
31361   i64 iHdrOffset;              /* See above */
31362   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31363   Pgno nOrig;                  /* Original number of pages in file */
31364   Pgno iSubRec;                /* Index of first record in sub-journal */
31365 };
31366
31367 /*
31368 ** A open page cache is an instance of the following structure.
31369 **
31370 ** errCode
31371 **
31372 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31373 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31374 **   and is returned as the result of every major pager API call.  The
31375 **   SQLITE_FULL return code is slightly different. It persists only until the
31376 **   next successful rollback is performed on the pager cache. Also,
31377 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31378 **   APIs, they may still be used successfully.
31379 **
31380 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31381 **
31382 **   Managing the size of the database file in pages is a little complicated.
31383 **   The variable Pager.dbSize contains the number of pages that the database
31384 **   image currently contains. As the database image grows or shrinks this
31385 **   variable is updated. The variable Pager.dbFileSize contains the number
31386 **   of pages in the database file. This may be different from Pager.dbSize
31387 **   if some pages have been appended to the database image but not yet written
31388 **   out from the cache to the actual file on disk. Or if the image has been
31389 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31390 **   contains the number of pages in the database image when the current
31391 **   transaction was opened. The contents of all three of these variables is
31392 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31393 **
31394 **   TODO: Under what conditions is dbSizeValid set? Cleared?
31395 **
31396 ** changeCountDone
31397 **
31398 **   This boolean variable is used to make sure that the change-counter 
31399 **   (the 4-byte header field at byte offset 24 of the database file) is 
31400 **   not updated more often than necessary. 
31401 **
31402 **   It is set to true when the change-counter field is updated, which 
31403 **   can only happen if an exclusive lock is held on the database file.
31404 **   It is cleared (set to false) whenever an exclusive lock is 
31405 **   relinquished on the database file. Each time a transaction is committed,
31406 **   The changeCountDone flag is inspected. If it is true, the work of
31407 **   updating the change-counter is omitted for the current transaction.
31408 **
31409 **   This mechanism means that when running in exclusive mode, a connection 
31410 **   need only update the change-counter once, for the first transaction
31411 **   committed.
31412 **
31413 ** dbModified
31414 **
31415 **   The dbModified flag is set whenever a database page is dirtied.
31416 **   It is cleared at the end of each transaction.
31417 **
31418 **   It is used when committing or otherwise ending a transaction. If
31419 **   the dbModified flag is clear then less work has to be done.
31420 **
31421 ** journalStarted
31422 **
31423 **   This flag is set whenever the the main journal is synced. 
31424 **
31425 **   The point of this flag is that it must be set after the 
31426 **   first journal header in a journal file has been synced to disk.
31427 **   After this has happened, new pages appended to the database 
31428 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31429 **   to wait for a journal sync before they can be written out to
31430 **   the database file (see function pager_write()).
31431 **   
31432 ** setMaster
31433 **
31434 **   This variable is used to ensure that the master journal file name
31435 **   (if any) is only written into the journal file once.
31436 **
31437 **   When committing a transaction, the master journal file name (if any)
31438 **   may be written into the journal file while the pager is still in
31439 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31440 **   then attempts to upgrade to an exclusive lock. If this attempt
31441 **   fails, then SQLITE_BUSY may be returned to the user and the user
31442 **   may attempt to commit the transaction again later (calling
31443 **   CommitPhaseOne() again). This flag is used to ensure that the 
31444 **   master journal name is only written to the journal file the first
31445 **   time CommitPhaseOne() is called.
31446 **
31447 ** doNotSync
31448 **
31449 **   This variable is set and cleared by sqlite3PagerWrite().
31450 **
31451 ** needSync
31452 **
31453 **   TODO: It might be easier to set this variable in writeJournalHdr()
31454 **   and writeMasterJournal() only. Change its meaning to "unsynced data
31455 **   has been written to the journal".
31456 */
31457 struct Pager {
31458   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31459   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31460   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31461   u8 useJournal;              /* Use a rollback journal on this file */
31462   u8 noReadlock;              /* Do not bother to obtain readlocks */
31463   u8 noSync;                  /* Do not sync the journal if true */
31464   u8 fullSync;                /* Do extra syncs of the journal for robustness */
31465   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31466   u8 tempFile;                /* zFilename is a temporary file */
31467   u8 readOnly;                /* True for a read-only database */
31468   u8 memDb;                   /* True to inhibit all file I/O */
31469
31470   /* The following block contains those class members that are dynamically
31471   ** modified during normal operations. The other variables in this structure
31472   ** are either constant throughout the lifetime of the pager, or else
31473   ** used to store configuration parameters that affect the way the pager 
31474   ** operates.
31475   **
31476   ** The 'state' variable is described in more detail along with the
31477   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31478   ** other variables in this block are described in the comment directly 
31479   ** above this class definition.
31480   */
31481   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31482   u8 dbModified;              /* True if there are any changes to the Db */
31483   u8 needSync;                /* True if an fsync() is needed on the journal */
31484   u8 journalStarted;          /* True if header of journal is synced */
31485   u8 changeCountDone;         /* Set after incrementing the change-counter */
31486   u8 setMaster;               /* True if a m-j name has been written to jrnl */
31487   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31488   u8 dbSizeValid;             /* Set when dbSize is correct */
31489   Pgno dbSize;                /* Number of pages in the database */
31490   Pgno dbOrigSize;            /* dbSize before the current transaction */
31491   Pgno dbFileSize;            /* Number of pages in the database file */
31492   int errCode;                /* One of several kinds of errors */
31493   int nRec;                   /* Pages journalled since last j-header written */
31494   u32 cksumInit;              /* Quasi-random value added to every checksum */
31495   u32 nSubRec;                /* Number of records written to sub-journal */
31496   Bitvec *pInJournal;         /* One bit for each page in the database file */
31497   sqlite3_file *fd;           /* File descriptor for database */
31498   sqlite3_file *jfd;          /* File descriptor for main journal */
31499   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31500   i64 journalOff;             /* Current write offset in the journal file */
31501   i64 journalHdr;             /* Byte offset to previous journal header */
31502   PagerSavepoint *aSavepoint; /* Array of active savepoints */
31503   int nSavepoint;             /* Number of elements in aSavepoint[] */
31504   char dbFileVers[16];        /* Changes whenever database file changes */
31505   u32 sectorSize;             /* Assumed sector size during rollback */
31506
31507   int nExtra;                 /* Add this many bytes to each in-memory page */
31508   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31509   int pageSize;               /* Number of bytes in a page */
31510   Pgno mxPgno;                /* Maximum allowed size of the database */
31511   char *zFilename;            /* Name of the database file */
31512   char *zJournal;             /* Name of the journal file */
31513   int (*xBusyHandler)(void*); /* Function to call when busy */
31514   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31515 #ifdef SQLITE_TEST
31516   int nHit, nMiss;            /* Cache hits and missing */
31517   int nRead, nWrite;          /* Database pages read/written */
31518 #endif
31519   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31520 #ifdef SQLITE_HAS_CODEC
31521   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31522   void *pCodecArg;            /* First argument to xCodec() */
31523 #endif
31524   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31525   i64 journalSizeLimit;       /* Size limit for persistent journal files */
31526   PCache *pPCache;            /* Pointer to page cache object */
31527   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31528 };
31529
31530 /*
31531 ** The following global variables hold counters used for
31532 ** testing purposes only.  These variables do not exist in
31533 ** a non-testing build.  These variables are not thread-safe.
31534 */
31535 #ifdef SQLITE_TEST
31536 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31537 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31538 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31539 # define PAGER_INCR(v)  v++
31540 #else
31541 # define PAGER_INCR(v)
31542 #endif
31543
31544
31545
31546 /*
31547 ** Journal files begin with the following magic string.  The data
31548 ** was obtained from /dev/random.  It is used only as a sanity check.
31549 **
31550 ** Since version 2.8.0, the journal format contains additional sanity
31551 ** checking information.  If the power fails while the journal is being
31552 ** written, semi-random garbage data might appear in the journal
31553 ** file after power is restored.  If an attempt is then made
31554 ** to roll the journal back, the database could be corrupted.  The additional
31555 ** sanity checking data is an attempt to discover the garbage in the
31556 ** journal and ignore it.
31557 **
31558 ** The sanity checking information for the new journal format consists
31559 ** of a 32-bit checksum on each page of data.  The checksum covers both
31560 ** the page number and the pPager->pageSize bytes of data for the page.
31561 ** This cksum is initialized to a 32-bit random value that appears in the
31562 ** journal file right after the header.  The random initializer is important,
31563 ** because garbage data that appears at the end of a journal is likely
31564 ** data that was once in other files that have now been deleted.  If the
31565 ** garbage data came from an obsolete journal file, the checksums might
31566 ** be correct.  But by initializing the checksum to random value which
31567 ** is different for every journal, we minimize that risk.
31568 */
31569 static const unsigned char aJournalMagic[] = {
31570   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31571 };
31572
31573 /*
31574 ** The size of the of each page record in the journal is given by
31575 ** the following macro.
31576 */
31577 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31578
31579 /*
31580 ** The journal header size for this pager. This is usually the same 
31581 ** size as a single disk sector. See also setSectorSize().
31582 */
31583 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31584
31585 /*
31586 ** The macro MEMDB is true if we are dealing with an in-memory database.
31587 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31588 ** the value of MEMDB will be a constant and the compiler will optimize
31589 ** out code that would never execute.
31590 */
31591 #ifdef SQLITE_OMIT_MEMORYDB
31592 # define MEMDB 0
31593 #else
31594 # define MEMDB pPager->memDb
31595 #endif
31596
31597 /*
31598 ** The maximum legal page number is (2^31 - 1).
31599 */
31600 #define PAGER_MAX_PGNO 2147483647
31601
31602 #ifndef NDEBUG 
31603 /*
31604 ** Usage:
31605 **
31606 **   assert( assert_pager_state(pPager) );
31607 */
31608 static int assert_pager_state(Pager *pPager){
31609
31610   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31611   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31612
31613   /* The changeCountDone flag is always set for temp-files */
31614   assert( pPager->tempFile==0 || pPager->changeCountDone );
31615
31616   return 1;
31617 }
31618 #endif
31619
31620 /*
31621 ** Return true if it is necessary to write page *pPg into the sub-journal.
31622 ** A page needs to be written into the sub-journal if there exists one
31623 ** or more open savepoints for which:
31624 **
31625 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31626 **   * The bit corresponding to the page-number is not set in
31627 **     PagerSavepoint.pInSavepoint.
31628 */
31629 static int subjRequiresPage(PgHdr *pPg){
31630   Pgno pgno = pPg->pgno;
31631   Pager *pPager = pPg->pPager;
31632   int i;
31633   for(i=0; i<pPager->nSavepoint; i++){
31634     PagerSavepoint *p = &pPager->aSavepoint[i];
31635     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31636       return 1;
31637     }
31638   }
31639   return 0;
31640 }
31641
31642 /*
31643 ** Return true if the page is already in the journal file.
31644 */
31645 static int pageInJournal(PgHdr *pPg){
31646   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31647 }
31648
31649 /*
31650 ** Read a 32-bit integer from the given file descriptor.  Store the integer
31651 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31652 ** error code is something goes wrong.
31653 **
31654 ** All values are stored on disk as big-endian.
31655 */
31656 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31657   unsigned char ac[4];
31658   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31659   if( rc==SQLITE_OK ){
31660     *pRes = sqlite3Get4byte(ac);
31661   }
31662   return rc;
31663 }
31664
31665 /*
31666 ** Write a 32-bit integer into a string buffer in big-endian byte order.
31667 */
31668 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31669
31670 /*
31671 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31672 ** on success or an error code is something goes wrong.
31673 */
31674 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31675   char ac[4];
31676   put32bits(ac, val);
31677   return sqlite3OsWrite(fd, ac, 4, offset);
31678 }
31679
31680 /*
31681 ** The argument to this macro is a file descriptor (type sqlite3_file*).
31682 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
31683 **
31684 ** This is so that expressions can be written as:
31685 **
31686 **   if( isOpen(pPager->jfd) ){ ...
31687 **
31688 ** instead of
31689 **
31690 **   if( pPager->jfd->pMethods ){ ...
31691 */
31692 #define isOpen(pFd) ((pFd)->pMethods)
31693
31694 /*
31695 ** If file pFd is open, call sqlite3OsUnlock() on it.
31696 */
31697 static int osUnlock(sqlite3_file *pFd, int eLock){
31698   if( !isOpen(pFd) ){
31699     return SQLITE_OK;
31700   }
31701   return sqlite3OsUnlock(pFd, eLock);
31702 }
31703
31704 /*
31705 ** This function determines whether or not the atomic-write optimization
31706 ** can be used with this pager. The optimization can be used if:
31707 **
31708 **  (a) the value returned by OsDeviceCharacteristics() indicates that
31709 **      a database page may be written atomically, and
31710 **  (b) the value returned by OsSectorSize() is less than or equal
31711 **      to the page size.
31712 **
31713 ** The optimization is also always enabled for temporary files. It is
31714 ** an error to call this function if pPager is opened on an in-memory
31715 ** database.
31716 **
31717 ** If the optimization cannot be used, 0 is returned. If it can be used,
31718 ** then the value returned is the size of the journal file when it
31719 ** contains rollback data for exactly one page.
31720 */
31721 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31722 static int jrnlBufferSize(Pager *pPager){
31723   assert( !MEMDB );
31724   if( !pPager->tempFile ){
31725     int dc;                           /* Device characteristics */
31726     int nSector;                      /* Sector size */
31727     int szPage;                       /* Page size */
31728
31729     assert( isOpen(pPager->fd) );
31730     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31731     nSector = pPager->sectorSize;
31732     szPage = pPager->pageSize;
31733
31734     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31735     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31736     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31737       return 0;
31738     }
31739   }
31740
31741   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31742 }
31743 #endif
31744
31745 /*
31746 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31747 ** on the cache using a hash function.  This is used for testing
31748 ** and debugging only.
31749 */
31750 #ifdef SQLITE_CHECK_PAGES
31751 /*
31752 ** Return a 32-bit hash of the page data for pPage.
31753 */
31754 static u32 pager_datahash(int nByte, unsigned char *pData){
31755   u32 hash = 0;
31756   int i;
31757   for(i=0; i<nByte; i++){
31758     hash = (hash*1039) + pData[i];
31759   }
31760   return hash;
31761 }
31762 static u32 pager_pagehash(PgHdr *pPage){
31763   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31764 }
31765 static void pager_set_pagehash(PgHdr *pPage){
31766   pPage->pageHash = pager_pagehash(pPage);
31767 }
31768
31769 /*
31770 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31771 ** is defined, and NDEBUG is not defined, an assert() statement checks
31772 ** that the page is either dirty or still matches the calculated page-hash.
31773 */
31774 #define CHECK_PAGE(x) checkPage(x)
31775 static void checkPage(PgHdr *pPg){
31776   Pager *pPager = pPg->pPager;
31777   assert( !pPg->pageHash || pPager->errCode
31778       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
31779 }
31780
31781 #else
31782 #define pager_datahash(X,Y)  0
31783 #define pager_pagehash(X)  0
31784 #define CHECK_PAGE(x)
31785 #endif  /* SQLITE_CHECK_PAGES */
31786
31787 /*
31788 ** When this is called the journal file for pager pPager must be open.
31789 ** This function attempts to read a master journal file name from the 
31790 ** end of the file and, if successful, copies it into memory supplied 
31791 ** by the caller. See comments above writeMasterJournal() for the format
31792 ** used to store a master journal file name at the end of a journal file.
31793 **
31794 ** zMaster must point to a buffer of at least nMaster bytes allocated by
31795 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
31796 ** enough space to write the master journal name). If the master journal
31797 ** name in the journal is longer than nMaster bytes (including a
31798 ** nul-terminator), then this is handled as if no master journal name
31799 ** were present in the journal.
31800 **
31801 ** If a master journal file name is present at the end of the journal
31802 ** file, then it is copied into the buffer pointed to by zMaster. A
31803 ** nul-terminator byte is appended to the buffer following the master
31804 ** journal file name.
31805 **
31806 ** If it is determined that no master journal file name is present 
31807 ** zMaster[0] is set to 0 and SQLITE_OK returned.
31808 **
31809 ** If an error occurs while reading from the journal file, an SQLite
31810 ** error code is returned.
31811 */
31812 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
31813   int rc;                    /* Return code */
31814   u32 len;                   /* Length in bytes of master journal name */
31815   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
31816   u32 cksum;                 /* MJ checksum value read from journal */
31817   u32 u;                     /* Unsigned loop counter */
31818   unsigned char aMagic[8];   /* A buffer to hold the magic header */
31819   zMaster[0] = '\0';
31820
31821   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
31822    || szJ<16
31823    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
31824    || len>=nMaster 
31825    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
31826    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
31827    || memcmp(aMagic, aJournalMagic, 8)
31828    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
31829   ){
31830     return rc;
31831   }
31832
31833   /* See if the checksum matches the master journal name */
31834   for(u=0; u<len; u++){
31835     cksum -= zMaster[u];
31836   }
31837   if( cksum ){
31838     /* If the checksum doesn't add up, then one or more of the disk sectors
31839     ** containing the master journal filename is corrupted. This means
31840     ** definitely roll back, so just return SQLITE_OK and report a (nul)
31841     ** master-journal filename.
31842     */
31843     len = 0;
31844   }
31845   zMaster[len] = '\0';
31846    
31847   return SQLITE_OK;
31848 }
31849
31850 /*
31851 ** Return the offset of the sector boundary at or immediately 
31852 ** following the value in pPager->journalOff, assuming a sector 
31853 ** size of pPager->sectorSize bytes.
31854 **
31855 ** i.e for a sector size of 512:
31856 **
31857 **   Pager.journalOff          Return value
31858 **   ---------------------------------------
31859 **   0                         0
31860 **   512                       512
31861 **   100                       512
31862 **   2000                      2048
31863 ** 
31864 */
31865 static i64 journalHdrOffset(Pager *pPager){
31866   i64 offset = 0;
31867   i64 c = pPager->journalOff;
31868   if( c ){
31869     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
31870   }
31871   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
31872   assert( offset>=c );
31873   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
31874   return offset;
31875 }
31876
31877 /*
31878 ** The journal file must be open when this function is called.
31879 **
31880 ** This function is a no-op if the journal file has not been written to
31881 ** within the current transaction (i.e. if Pager.journalOff==0).
31882 **
31883 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
31884 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
31885 ** zero the 28-byte header at the start of the journal file. In either case, 
31886 ** if the pager is not in no-sync mode, sync the journal file immediately 
31887 ** after writing or truncating it.
31888 **
31889 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
31890 ** following the truncation or zeroing described above the size of the 
31891 ** journal file in bytes is larger than this value, then truncate the
31892 ** journal file to Pager.journalSizeLimit bytes. The journal file does
31893 ** not need to be synced following this operation.
31894 **
31895 ** If an IO error occurs, abandon processing and return the IO error code.
31896 ** Otherwise, return SQLITE_OK.
31897 */
31898 static int zeroJournalHdr(Pager *pPager, int doTruncate){
31899   int rc = SQLITE_OK;                               /* Return code */
31900   assert( isOpen(pPager->jfd) );
31901   if( pPager->journalOff ){
31902     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
31903
31904     IOTRACE(("JZEROHDR %p\n", pPager))
31905     if( doTruncate || iLimit==0 ){
31906       rc = sqlite3OsTruncate(pPager->jfd, 0);
31907     }else{
31908       static const char zeroHdr[28] = {0};
31909       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
31910     }
31911     if( rc==SQLITE_OK && !pPager->noSync ){
31912       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
31913     }
31914
31915     /* At this point the transaction is committed but the write lock 
31916     ** is still held on the file. If there is a size limit configured for 
31917     ** the persistent journal and the journal file currently consumes more
31918     ** space than that limit allows for, truncate it now. There is no need
31919     ** to sync the file following this operation.
31920     */
31921     if( rc==SQLITE_OK && iLimit>0 ){
31922       i64 sz;
31923       rc = sqlite3OsFileSize(pPager->jfd, &sz);
31924       if( rc==SQLITE_OK && sz>iLimit ){
31925         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
31926       }
31927     }
31928   }
31929   return rc;
31930 }
31931
31932 /*
31933 ** The journal file must be open when this routine is called. A journal
31934 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
31935 ** current location.
31936 **
31937 ** The format for the journal header is as follows:
31938 ** - 8 bytes: Magic identifying journal format.
31939 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
31940 ** - 4 bytes: Random number used for page hash.
31941 ** - 4 bytes: Initial database page count.
31942 ** - 4 bytes: Sector size used by the process that wrote this journal.
31943 ** - 4 bytes: Database page size.
31944 ** 
31945 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
31946 */
31947 static int writeJournalHdr(Pager *pPager){
31948   int rc = SQLITE_OK;                 /* Return code */
31949   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
31950   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
31951   u32 nWrite;                         /* Bytes of header sector written */
31952   int ii;                             /* Loop counter */
31953
31954   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
31955
31956   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
31957     nHeader = JOURNAL_HDR_SZ(pPager);
31958   }
31959
31960   /* If there are active savepoints and any of them were created 
31961   ** since the most recent journal header was written, update the 
31962   ** PagerSavepoint.iHdrOffset fields now.
31963   */
31964   for(ii=0; ii<pPager->nSavepoint; ii++){
31965     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
31966       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
31967     }
31968   }
31969
31970   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
31971   memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
31972
31973   /* 
31974   ** Write the nRec Field - the number of page records that follow this
31975   ** journal header. Normally, zero is written to this value at this time.
31976   ** After the records are added to the journal (and the journal synced, 
31977   ** if in full-sync mode), the zero is overwritten with the true number
31978   ** of records (see syncJournal()).
31979   **
31980   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
31981   ** reading the journal this value tells SQLite to assume that the
31982   ** rest of the journal file contains valid page records. This assumption
31983   ** is dangerous, as if a failure occured whilst writing to the journal
31984   ** file it may contain some garbage data. There are two scenarios
31985   ** where this risk can be ignored:
31986   **
31987   **   * When the pager is in no-sync mode. Corruption can follow a
31988   **     power failure in this case anyway.
31989   **
31990   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
31991   **     that garbage data is never appended to the journal file.
31992   */
31993   assert( isOpen(pPager->fd) || pPager->noSync );
31994   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
31995    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
31996   ){
31997     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
31998   }else{
31999     put32bits(&zHeader[sizeof(aJournalMagic)], 0);
32000   }
32001
32002   /* The random check-hash initialiser */ 
32003   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32004   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32005   /* The initial database size */
32006   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32007   /* The assumed sector size for this process */
32008   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32009
32010   /* The page size */
32011   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32012
32013   /* Initializing the tail of the buffer is not necessary.  Everything
32014   ** works find if the following memset() is omitted.  But initializing
32015   ** the memory prevents valgrind from complaining, so we are willing to
32016   ** take the performance hit.
32017   */
32018   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32019          nHeader-(sizeof(aJournalMagic)+20));
32020
32021   /* In theory, it is only necessary to write the 28 bytes that the 
32022   ** journal header consumes to the journal file here. Then increment the 
32023   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
32024   ** record is written to the following sector (leaving a gap in the file
32025   ** that will be implicitly filled in by the OS).
32026   **
32027   ** However it has been discovered that on some systems this pattern can 
32028   ** be significantly slower than contiguously writing data to the file,
32029   ** even if that means explicitly writing data to the block of 
32030   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32031   ** is done. 
32032   **
32033   ** The loop is required here in case the sector-size is larger than the 
32034   ** database page size. Since the zHeader buffer is only Pager.pageSize
32035   ** bytes in size, more than one call to sqlite3OsWrite() may be required
32036   ** to populate the entire journal header sector.
32037   */ 
32038   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32039     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32040     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32041     pPager->journalOff += nHeader;
32042   }
32043
32044   return rc;
32045 }
32046
32047 /*
32048 ** The journal file must be open when this is called. A journal header file
32049 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32050 ** file. The current location in the journal file is given by
32051 ** pPager->journalOff. See comments above function writeJournalHdr() for
32052 ** a description of the journal header format.
32053 **
32054 ** If the header is read successfully, *pNRec is set to the number of
32055 ** page records following this header and *pDbSize is set to the size of the
32056 ** database before the transaction began, in pages. Also, pPager->cksumInit
32057 ** is set to the value read from the journal header. SQLITE_OK is returned
32058 ** in this case.
32059 **
32060 ** If the journal header file appears to be corrupted, SQLITE_DONE is
32061 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32062 ** cannot be read from the journal file an error code is returned.
32063 */
32064 static int readJournalHdr(
32065   Pager *pPager,               /* Pager object */
32066   i64 journalSize,             /* Size of the open journal file in bytes */
32067   u32 *pNRec,                  /* OUT: Value read from the nRec field */
32068   u32 *pDbSize                 /* OUT: Value of original database size field */
32069 ){
32070   int rc;                      /* Return code */
32071   unsigned char aMagic[8];     /* A buffer to hold the magic header */
32072   i64 iHdrOff;                 /* Offset of journal header being read */
32073
32074   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32075
32076   /* Advance Pager.journalOff to the start of the next sector. If the
32077   ** journal file is too small for there to be a header stored at this
32078   ** point, return SQLITE_DONE.
32079   */
32080   pPager->journalOff = journalHdrOffset(pPager);
32081   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32082     return SQLITE_DONE;
32083   }
32084   iHdrOff = pPager->journalOff;
32085
32086   /* Read in the first 8 bytes of the journal header. If they do not match
32087   ** the  magic string found at the start of each journal header, return
32088   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32089   ** proceed.
32090   */
32091   rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32092   if( rc ){
32093     return rc;
32094   }
32095   if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32096     return SQLITE_DONE;
32097   }
32098
32099   /* Read the first three 32-bit fields of the journal header: The nRec
32100   ** field, the checksum-initializer and the database size at the start
32101   ** of the transaction. Return an error code if anything goes wrong.
32102   */
32103   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32104    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32105    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32106   ){
32107     return rc;
32108   }
32109
32110   if( pPager->journalOff==0 ){
32111     u32 iPageSize;               /* Page-size field of journal header */
32112     u32 iSectorSize;             /* Sector-size field of journal header */
32113     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32114
32115     /* Read the page-size and sector-size journal header fields. */
32116     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32117      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32118     ){
32119       return rc;
32120     }
32121
32122     /* Check that the values read from the page-size and sector-size fields
32123     ** are within range. To be 'in range', both values need to be a power
32124     ** of two greater than or equal to 512, and not greater than their 
32125     ** respective compile time maximum limits.
32126     */
32127     if( iPageSize<512                  || iSectorSize<512
32128      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32129      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
32130     ){
32131       /* If the either the page-size or sector-size in the journal-header is 
32132       ** invalid, then the process that wrote the journal-header must have 
32133       ** crashed before the header was synced. In this case stop reading 
32134       ** the journal file here.
32135       */
32136       return SQLITE_DONE;
32137     }
32138
32139     /* Update the page-size to match the value read from the journal. 
32140     ** Use a testcase() macro to make sure that malloc failure within 
32141     ** PagerSetPagesize() is tested.
32142     */
32143     iPageSize16 = (u16)iPageSize;
32144     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16);
32145     testcase( rc!=SQLITE_OK );
32146     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32147
32148     /* Update the assumed sector-size to match the value used by 
32149     ** the process that created this journal. If this journal was
32150     ** created by a process other than this one, then this routine
32151     ** is being called from within pager_playback(). The local value
32152     ** of Pager.sectorSize is restored at the end of that routine.
32153     */
32154     pPager->sectorSize = iSectorSize;
32155   }
32156
32157   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32158   return rc;
32159 }
32160
32161
32162 /*
32163 ** Write the supplied master journal name into the journal file for pager
32164 ** pPager at the current location. The master journal name must be the last
32165 ** thing written to a journal file. If the pager is in full-sync mode, the
32166 ** journal file descriptor is advanced to the next sector boundary before
32167 ** anything is written. The format is:
32168 **
32169 **   + 4 bytes: PAGER_MJ_PGNO.
32170 **   + N bytes: Master journal filename in utf-8.
32171 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32172 **   + 4 bytes: Master journal name checksum.
32173 **   + 8 bytes: aJournalMagic[].
32174 **
32175 ** The master journal page checksum is the sum of the bytes in the master
32176 ** journal name, where each byte is interpreted as a signed 8-bit integer.
32177 **
32178 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
32179 ** this call is a no-op.
32180 */
32181 static int writeMasterJournal(Pager *pPager, const char *zMaster){
32182   int rc;                          /* Return code */
32183   int nMaster;                     /* Length of string zMaster */
32184   i64 iHdrOff;                     /* Offset of header in journal file */
32185   i64 jrnlSize;                    /* Size of journal file on disk */
32186   u32 cksum = 0;                   /* Checksum of string zMaster */
32187
32188   if( !zMaster || pPager->setMaster
32189    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
32190    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
32191   ){
32192     return SQLITE_OK;
32193   }
32194   pPager->setMaster = 1;
32195   assert( isOpen(pPager->jfd) );
32196
32197   /* Calculate the length in bytes and the checksum of zMaster */
32198   for(nMaster=0; zMaster[nMaster]; nMaster++){
32199     cksum += zMaster[nMaster];
32200   }
32201
32202   /* If in full-sync mode, advance to the next disk sector before writing
32203   ** the master journal name. This is in case the previous page written to
32204   ** the journal has already been synced.
32205   */
32206   if( pPager->fullSync ){
32207     pPager->journalOff = journalHdrOffset(pPager);
32208   }
32209   iHdrOff = pPager->journalOff;
32210
32211   /* Write the master journal data to the end of the journal file. If
32212   ** an error occurs, return the error code to the caller.
32213   */
32214   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32215    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32216    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32217    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32218    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32219   ){
32220     return rc;
32221   }
32222   pPager->journalOff += (nMaster+20);
32223   pPager->needSync = !pPager->noSync;
32224
32225   /* If the pager is in peristent-journal mode, then the physical 
32226   ** journal-file may extend past the end of the master-journal name
32227   ** and 8 bytes of magic data just written to the file. This is 
32228   ** dangerous because the code to rollback a hot-journal file
32229   ** will not be able to find the master-journal name to determine 
32230   ** whether or not the journal is hot. 
32231   **
32232   ** Easiest thing to do in this scenario is to truncate the journal 
32233   ** file to the required size.
32234   */ 
32235   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32236    && jrnlSize>pPager->journalOff
32237   ){
32238     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32239   }
32240   return rc;
32241 }
32242
32243 /*
32244 ** Find a page in the hash table given its page number. Return
32245 ** a pointer to the page or NULL if the requested page is not 
32246 ** already in memory.
32247 */
32248 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32249   PgHdr *p;                         /* Return value */
32250
32251   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32252   ** fail, since no attempt to allocate dynamic memory will be made.
32253   */
32254   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32255   return p;
32256 }
32257
32258 /*
32259 ** Unless the pager is in error-state, discard all in-memory pages. If
32260 ** the pager is in error-state, then this call is a no-op.
32261 **
32262 ** TODO: Why can we not reset the pager while in error state?
32263 */
32264 static void pager_reset(Pager *pPager){
32265   if( SQLITE_OK==pPager->errCode ){
32266     sqlite3BackupRestart(pPager->pBackup);
32267     sqlite3PcacheClear(pPager->pPCache);
32268   }
32269 }
32270
32271 /*
32272 ** Free all structures in the Pager.aSavepoint[] array and set both
32273 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32274 ** if it is open and the pager is not in exclusive mode.
32275 */
32276 static void releaseAllSavepoints(Pager *pPager){
32277   int ii;               /* Iterator for looping through Pager.aSavepoint */
32278   for(ii=0; ii<pPager->nSavepoint; ii++){
32279     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32280   }
32281   if( !pPager->exclusiveMode ){
32282     sqlite3OsClose(pPager->sjfd);
32283   }
32284   sqlite3_free(pPager->aSavepoint);
32285   pPager->aSavepoint = 0;
32286   pPager->nSavepoint = 0;
32287   pPager->nSubRec = 0;
32288 }
32289
32290 /*
32291 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
32292 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
32293 ** or SQLITE_NOMEM if a malloc failure occurs.
32294 */
32295 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32296   int ii;                   /* Loop counter */
32297   int rc = SQLITE_OK;       /* Result code */
32298
32299   for(ii=0; ii<pPager->nSavepoint; ii++){
32300     PagerSavepoint *p = &pPager->aSavepoint[ii];
32301     if( pgno<=p->nOrig ){
32302       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32303       testcase( rc==SQLITE_NOMEM );
32304       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32305     }
32306   }
32307   return rc;
32308 }
32309
32310 /*
32311 ** Unlock the database file. This function is a no-op if the pager
32312 ** is in exclusive mode.
32313 **
32314 ** If the pager is currently in error state, discard the contents of 
32315 ** the cache and reset the Pager structure internal state. If there is
32316 ** an open journal-file, then the next time a shared-lock is obtained
32317 ** on the pager file (by this or any other process), it will be
32318 ** treated as a hot-journal and rolled back.
32319 */
32320 static void pager_unlock(Pager *pPager){
32321   if( !pPager->exclusiveMode ){
32322     int rc;                      /* Return code */
32323
32324     /* Always close the journal file when dropping the database lock.
32325     ** Otherwise, another connection with journal_mode=delete might
32326     ** delete the file out from under us.
32327     */
32328     sqlite3OsClose(pPager->jfd);
32329     sqlite3BitvecDestroy(pPager->pInJournal);
32330     pPager->pInJournal = 0;
32331     releaseAllSavepoints(pPager);
32332
32333     /* If the file is unlocked, somebody else might change it. The
32334     ** values stored in Pager.dbSize etc. might become invalid if
32335     ** this happens. TODO: Really, this doesn't need to be cleared
32336     ** until the change-counter check fails in pagerSharedLock().
32337     */
32338     pPager->dbSizeValid = 0;
32339
32340     rc = osUnlock(pPager->fd, NO_LOCK);
32341     if( rc ){
32342       pPager->errCode = rc;
32343     }
32344     IOTRACE(("UNLOCK %p\n", pPager))
32345
32346     /* If Pager.errCode is set, the contents of the pager cache cannot be
32347     ** trusted. Now that the pager file is unlocked, the contents of the
32348     ** cache can be discarded and the error code safely cleared.
32349     */
32350     if( pPager->errCode ){
32351       if( rc==SQLITE_OK ){
32352         pPager->errCode = SQLITE_OK;
32353       }
32354       pager_reset(pPager);
32355     }
32356
32357     pPager->changeCountDone = 0;
32358     pPager->state = PAGER_UNLOCK;
32359   }
32360 }
32361
32362 /*
32363 ** This function should be called when an IOERR, CORRUPT or FULL error
32364 ** may have occured. The first argument is a pointer to the pager 
32365 ** structure, the second the error-code about to be returned by a pager 
32366 ** API function. The value returned is a copy of the second argument 
32367 ** to this function. 
32368 **
32369 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32370 ** the error becomes persistent. Until the persisten error is cleared,
32371 ** subsequent API calls on this Pager will immediately return the same 
32372 ** error code.
32373 **
32374 ** A persistent error indicates that the contents of the pager-cache 
32375 ** cannot be trusted. This state can be cleared by completely discarding 
32376 ** the contents of the pager-cache. If a transaction was active when
32377 ** the persistent error occured, then the rollback journal may need
32378 ** to be replayed to restore the contents of the database file (as if
32379 ** it were a hot-journal).
32380 */
32381 static int pager_error(Pager *pPager, int rc){
32382   int rc2 = rc & 0xff;
32383   assert(
32384        pPager->errCode==SQLITE_FULL ||
32385        pPager->errCode==SQLITE_OK ||
32386        (pPager->errCode & 0xff)==SQLITE_IOERR
32387   );
32388   if(
32389     rc2==SQLITE_FULL ||
32390     rc2==SQLITE_IOERR ||
32391     rc2==SQLITE_CORRUPT
32392   ){
32393     pPager->errCode = rc;
32394     if( pPager->state==PAGER_UNLOCK 
32395      && sqlite3PcacheRefCount(pPager->pPCache)==0 
32396     ){
32397       /* If the pager is already unlocked, call pager_unlock() now to
32398       ** clear the error state and ensure that the pager-cache is 
32399       ** completely empty.
32400       */
32401       pager_unlock(pPager);
32402     }
32403   }
32404   return rc;
32405 }
32406
32407 /*
32408 ** Execute a rollback if a transaction is active and unlock the 
32409 ** database file. 
32410 **
32411 ** If the pager has already entered the error state, do not attempt 
32412 ** the rollback at this time. Instead, pager_unlock() is called. The
32413 ** call to pager_unlock() will discard all in-memory pages, unlock
32414 ** the database file and clear the error state. If this means that
32415 ** there is a hot-journal left in the file-system, the next connection
32416 ** to obtain a shared lock on the pager (which may be this one) will
32417 ** roll it back.
32418 **
32419 ** If the pager has not already entered the error state, but an IO or
32420 ** malloc error occurs during a rollback, then this will itself cause 
32421 ** the pager to enter the error state. Which will be cleared by the
32422 ** call to pager_unlock(), as described above.
32423 */
32424 static void pagerUnlockAndRollback(Pager *pPager){
32425   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32426     sqlite3BeginBenignMalloc();
32427     sqlite3PagerRollback(pPager);
32428     sqlite3EndBenignMalloc();
32429   }
32430   pager_unlock(pPager);
32431 }
32432
32433 /*
32434 ** This routine ends a transaction. A transaction is usually ended by 
32435 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
32436 ** after rollback of a hot-journal, or if an error occurs while opening
32437 ** the journal file or writing the very first journal-header of a
32438 ** database transaction.
32439 ** 
32440 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32441 ** routine is called, it is a no-op (returns SQLITE_OK).
32442 **
32443 ** Otherwise, any active savepoints are released.
32444 **
32445 ** If the journal file is open, then it is "finalized". Once a journal 
32446 ** file has been finalized it is not possible to use it to roll back a 
32447 ** transaction. Nor will it be considered to be a hot-journal by this
32448 ** or any other database connection. Exactly how a journal is finalized
32449 ** depends on whether or not the pager is running in exclusive mode and
32450 ** the current journal-mode (Pager.journalMode value), as follows:
32451 **
32452 **   journalMode==MEMORY
32453 **     Journal file descriptor is simply closed. This destroys an 
32454 **     in-memory journal.
32455 **
32456 **   journalMode==TRUNCATE
32457 **     Journal file is truncated to zero bytes in size.
32458 **
32459 **   journalMode==PERSIST
32460 **     The first 28 bytes of the journal file are zeroed. This invalidates
32461 **     the first journal header in the file, and hence the entire journal
32462 **     file. An invalid journal file cannot be rolled back.
32463 **
32464 **   journalMode==DELETE
32465 **     The journal file is closed and deleted using sqlite3OsDelete().
32466 **
32467 **     If the pager is running in exclusive mode, this method of finalizing
32468 **     the journal file is never used. Instead, if the journalMode is
32469 **     DELETE and the pager is in exclusive mode, the method described under
32470 **     journalMode==PERSIST is used instead.
32471 **
32472 ** After the journal is finalized, if running in non-exclusive mode, the
32473 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
32474 ** database file accordingly).
32475 **
32476 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32477 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32478 ** exclusive mode.
32479 **
32480 ** SQLITE_OK is returned if no error occurs. If an error occurs during
32481 ** any of the IO operations to finalize the journal file or unlock the
32482 ** database then the IO error code is returned to the user. If the 
32483 ** operation to finalize the journal file fails, then the code still
32484 ** tries to unlock the database file if not in exclusive mode. If the
32485 ** unlock operation fails as well, then the first error code related
32486 ** to the first error encountered (the journal finalization one) is
32487 ** returned.
32488 */
32489 static int pager_end_transaction(Pager *pPager, int hasMaster){
32490   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32491   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32492
32493   if( pPager->state<PAGER_RESERVED ){
32494     return SQLITE_OK;
32495   }
32496   releaseAllSavepoints(pPager);
32497
32498   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32499   if( isOpen(pPager->jfd) ){
32500
32501     /* TODO: There's a problem here if a journal-file was opened in MEMORY
32502     ** mode and then the journal-mode is changed to TRUNCATE or PERSIST
32503     ** during the transaction. This code should be changed to assume
32504     ** that the journal mode has not changed since the transaction was
32505     ** started. And the sqlite3PagerJournalMode() function should be
32506     ** changed to make sure that this is the case too.
32507     */
32508
32509     /* Finalize the journal file. */
32510     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
32511       int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
32512       sqlite3OsClose(pPager->jfd);
32513       if( !isMemoryJournal ){
32514         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32515       }
32516     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32517       rc = sqlite3OsTruncate(pPager->jfd, 0);
32518       pPager->journalOff = 0;
32519       pPager->journalStarted = 0;
32520     }else if( pPager->exclusiveMode 
32521      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32522     ){
32523       rc = zeroJournalHdr(pPager, hasMaster);
32524       pager_error(pPager, rc);
32525       pPager->journalOff = 0;
32526       pPager->journalStarted = 0;
32527     }else{
32528       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
32529       sqlite3OsClose(pPager->jfd);
32530       if( rc==SQLITE_OK && !pPager->tempFile ){
32531         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32532       }
32533     }
32534
32535 #ifdef SQLITE_CHECK_PAGES
32536     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32537 #endif
32538
32539     sqlite3PcacheCleanAll(pPager->pPCache);
32540     sqlite3BitvecDestroy(pPager->pInJournal);
32541     pPager->pInJournal = 0;
32542     pPager->nRec = 0;
32543   }
32544
32545   if( !pPager->exclusiveMode ){
32546     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32547     pPager->state = PAGER_SHARED;
32548     pPager->changeCountDone = 0;
32549   }else if( pPager->state==PAGER_SYNCED ){
32550     pPager->state = PAGER_EXCLUSIVE;
32551   }
32552   pPager->setMaster = 0;
32553   pPager->needSync = 0;
32554   pPager->dbModified = 0;
32555
32556   /* TODO: Is this optimal? Why is the db size invalidated here 
32557   ** when the database file is not unlocked? */
32558   pPager->dbOrigSize = 0;
32559   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32560   if( !MEMDB ){
32561     pPager->dbSizeValid = 0;
32562   }
32563
32564   return (rc==SQLITE_OK?rc2:rc);
32565 }
32566
32567 /*
32568 ** Parameter aData must point to a buffer of pPager->pageSize bytes
32569 ** of data. Compute and return a checksum based ont the contents of the 
32570 ** page of data and the current value of pPager->cksumInit.
32571 **
32572 ** This is not a real checksum. It is really just the sum of the 
32573 ** random initial value (pPager->cksumInit) and every 200th byte
32574 ** of the page data, starting with byte offset (pPager->pageSize%200).
32575 ** Each byte is interpreted as an 8-bit unsigned integer.
32576 **
32577 ** Changing the formula used to compute this checksum results in an
32578 ** incompatible journal file format.
32579 **
32580 ** If journal corruption occurs due to a power failure, the most likely 
32581 ** scenario is that one end or the other of the record will be changed. 
32582 ** It is much less likely that the two ends of the journal record will be
32583 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32584 ** though fast and simple, catches the mostly likely kind of corruption.
32585 */
32586 static u32 pager_cksum(Pager *pPager, const u8 *aData){
32587   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32588   int i = pPager->pageSize-200;          /* Loop counter */
32589   while( i>0 ){
32590     cksum += aData[i];
32591     i -= 200;
32592   }
32593   return cksum;
32594 }
32595
32596 /*
32597 ** Read a single page from either the journal file (if isMainJrnl==1) or
32598 ** from the sub-journal (if isMainJrnl==0) and playback that page.
32599 ** The page begins at offset *pOffset into the file. The *pOffset
32600 ** value is increased to the start of the next page in the journal.
32601 **
32602 ** The isMainJrnl flag is true if this is the main rollback journal and
32603 ** false for the statement journal.  The main rollback journal uses
32604 ** checksums - the statement journal does not.
32605 **
32606 ** If the page number of the page record read from the (sub-)journal file
32607 ** is greater than the current value of Pager.dbSize, then playback is
32608 ** skipped and SQLITE_OK is returned.
32609 **
32610 ** If pDone is not NULL, then it is a record of pages that have already
32611 ** been played back.  If the page at *pOffset has already been played back
32612 ** (if the corresponding pDone bit is set) then skip the playback.
32613 ** Make sure the pDone bit corresponding to the *pOffset page is set
32614 ** prior to returning.
32615 **
32616 ** If the page record is successfully read from the (sub-)journal file
32617 ** and played back, then SQLITE_OK is returned. If an IO error occurs
32618 ** while reading the record from the (sub-)journal file or while writing
32619 ** to the database file, then the IO error code is returned. If data
32620 ** is successfully read from the (sub-)journal file but appears to be
32621 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32622 ** two circumstances:
32623 ** 
32624 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32625 **   * If the record is being rolled back from the main journal file
32626 **     and the checksum field does not match the record content.
32627 **
32628 ** Neither of these two scenarios are possible during a savepoint rollback.
32629 **
32630 ** If this is a savepoint rollback, then memory may have to be dynamically
32631 ** allocated by this function. If this is the case and an allocation fails,
32632 ** SQLITE_NOMEM is returned.
32633 */
32634 static int pager_playback_one_page(
32635   Pager *pPager,                /* The pager being played back */
32636   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32637   int isUnsync,                 /* True if reading from unsynced main journal */
32638   i64 *pOffset,                 /* Offset of record to playback */
32639   int isSavepnt,                /* True for a savepoint rollback */
32640   Bitvec *pDone                 /* Bitvec of pages already played back */
32641 ){
32642   int rc;
32643   PgHdr *pPg;                   /* An existing page in the cache */
32644   Pgno pgno;                    /* The page number of a page in journal */
32645   u32 cksum;                    /* Checksum used for sanity checking */
32646   u8 *aData;                    /* Temporary storage for the page */
32647   sqlite3_file *jfd;            /* The file descriptor for the journal file */
32648
32649   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32650   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32651   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32652   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32653
32654   aData = (u8*)pPager->pTmpSpace;
32655   assert( aData );         /* Temp storage must have already been allocated */
32656
32657   /* Read the page number and page data from the journal or sub-journal
32658   ** file. Return an error code to the caller if an IO error occurs.
32659   */
32660   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32661   rc = read32bits(jfd, *pOffset, &pgno);
32662   if( rc!=SQLITE_OK ) return rc;
32663   rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
32664   if( rc!=SQLITE_OK ) return rc;
32665   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32666
32667   /* Sanity checking on the page.  This is more important that I originally
32668   ** thought.  If a power failure occurs while the journal is being written,
32669   ** it could cause invalid data to be written into the journal.  We need to
32670   ** detect this invalid data (with high probability) and ignore it.
32671   */
32672   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32673     assert( !isSavepnt );
32674     return SQLITE_DONE;
32675   }
32676   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32677     return SQLITE_OK;
32678   }
32679   if( isMainJrnl ){
32680     rc = read32bits(jfd, (*pOffset)-4, &cksum);
32681     if( rc ) return rc;
32682     if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
32683       return SQLITE_DONE;
32684     }
32685   }
32686
32687   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32688     return rc;
32689   }
32690
32691   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32692
32693   /* If the pager is in RESERVED state, then there must be a copy of this
32694   ** page in the pager cache. In this case just update the pager cache,
32695   ** not the database file. The page is left marked dirty in this case.
32696   **
32697   ** An exception to the above rule: If the database is in no-sync mode
32698   ** and a page is moved during an incremental vacuum then the page may
32699   ** not be in the pager cache. Later: if a malloc() or IO error occurs
32700   ** during a Movepage() call, then the page may not be in the cache
32701   ** either. So the condition described in the above paragraph is not
32702   ** assert()able.
32703   **
32704   ** If in EXCLUSIVE state, then we update the pager cache if it exists
32705   ** and the main file. The page is then marked not dirty.
32706   **
32707   ** Ticket #1171:  The statement journal might contain page content that is
32708   ** different from the page content at the start of the transaction.
32709   ** This occurs when a page is changed prior to the start of a statement
32710   ** then changed again within the statement.  When rolling back such a
32711   ** statement we must not write to the original database unless we know
32712   ** for certain that original page contents are synced into the main rollback
32713   ** journal.  Otherwise, a power loss might leave modified data in the
32714   ** database file without an entry in the rollback journal that can
32715   ** restore the database to its original form.  Two conditions must be
32716   ** met before writing to the database files. (1) the database must be
32717   ** locked.  (2) we know that the original page content is fully synced
32718   ** in the main journal either because the page is not in cache or else
32719   ** the page is marked as needSync==0.
32720   **
32721   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32722   ** is possible to fail a statement on a database that does not yet exist.
32723   ** Do not attempt to write if database file has never been opened.
32724   */
32725   pPg = pager_lookup(pPager, pgno);
32726   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32727                PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
32728                (isMainJrnl?"main-journal":"sub-journal")
32729   ));
32730   if( (pPager->state>=PAGER_EXCLUSIVE)
32731    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32732    && isOpen(pPager->fd)
32733    && !isUnsync
32734   ){
32735     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32736     rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
32737     if( pgno>pPager->dbFileSize ){
32738       pPager->dbFileSize = pgno;
32739     }
32740     sqlite3BackupUpdate(pPager->pBackup, pgno, aData);
32741   }else if( !isMainJrnl && pPg==0 ){
32742     /* If this is a rollback of a savepoint and data was not written to
32743     ** the database and the page is not in-memory, there is a potential
32744     ** problem. When the page is next fetched by the b-tree layer, it 
32745     ** will be read from the database file, which may or may not be 
32746     ** current. 
32747     **
32748     ** There are a couple of different ways this can happen. All are quite
32749     ** obscure. When running in synchronous mode, this can only happen 
32750     ** if the page is on the free-list at the start of the transaction, then
32751     ** populated, then moved using sqlite3PagerMovepage().
32752     **
32753     ** The solution is to add an in-memory page to the cache containing
32754     ** the data just read from the sub-journal. Mark the page as dirty 
32755     ** and if the pager requires a journal-sync, then mark the page as 
32756     ** requiring a journal-sync before it is written.
32757     */
32758     assert( isSavepnt );
32759     if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32760       return rc;
32761     }
32762     pPg->flags &= ~PGHDR_NEED_READ;
32763     sqlite3PcacheMakeDirty(pPg);
32764   }
32765   if( pPg ){
32766     /* No page should ever be explicitly rolled back that is in use, except
32767     ** for page 1 which is held in use in order to keep the lock on the
32768     ** database active. However such a page may be rolled back as a result
32769     ** of an internal error resulting in an automatic call to
32770     ** sqlite3PagerRollback().
32771     */
32772     void *pData;
32773     pData = pPg->pData;
32774     memcpy(pData, aData, pPager->pageSize);
32775     if( pPager->xReiniter ){
32776       pPager->xReiniter(pPg);
32777     }
32778     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32779       /* If the contents of this page were just restored from the main 
32780       ** journal file, then its content must be as they were when the 
32781       ** transaction was first opened. In this case we can mark the page
32782       ** as clean, since there will be no need to write it out to the.
32783       **
32784       ** There is one exception to this rule. If the page is being rolled
32785       ** back as part of a savepoint (or statement) rollback from an 
32786       ** unsynced portion of the main journal file, then it is not safe
32787       ** to mark the page as clean. This is because marking the page as
32788       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
32789       ** already in the journal file (recorded in Pager.pInJournal) and
32790       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
32791       ** again within this transaction, it will be marked as dirty but
32792       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
32793       ** be written out into the database file before its journal file
32794       ** segment is synced. If a crash occurs during or following this,
32795       ** database corruption may ensue.
32796       */
32797       sqlite3PcacheMakeClean(pPg);
32798     }
32799 #ifdef SQLITE_CHECK_PAGES
32800     pPg->pageHash = pager_pagehash(pPg);
32801 #endif
32802     /* If this was page 1, then restore the value of Pager.dbFileVers.
32803     ** Do this before any decoding. */
32804     if( pgno==1 ){
32805       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
32806     }
32807
32808     /* Decode the page just read from disk */
32809     CODEC1(pPager, pData, pPg->pgno, 3);
32810     sqlite3PcacheRelease(pPg);
32811   }
32812   return rc;
32813 }
32814
32815 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
32816 /*
32817 ** This routine looks ahead into the main journal file and determines
32818 ** whether or not the next record (the record that begins at file
32819 ** offset pPager->journalOff) is a well-formed page record consisting
32820 ** of a valid page number, pPage->pageSize bytes of content, followed
32821 ** by a valid checksum.
32822 **
32823 ** The pager never needs to know this in order to do its job.   This
32824 ** routine is only used from with assert() and testcase() macros.
32825 */
32826 static int pagerNextJournalPageIsValid(Pager *pPager){
32827   Pgno pgno;           /* The page number of the page */
32828   u32 cksum;           /* The page checksum */
32829   int rc;              /* Return code from read operations */
32830   sqlite3_file *fd;    /* The file descriptor from which we are reading */
32831   u8 *aData;           /* Content of the page */
32832
32833   /* Read the page number header */
32834   fd = pPager->jfd;
32835   rc = read32bits(fd, pPager->journalOff, &pgno);
32836   if( rc!=SQLITE_OK ){ return 0; }                                  /*NO_TEST*/
32837   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){ return 0; }         /*NO_TEST*/
32838   if( pgno>(Pgno)pPager->dbSize ){ return 0; }                      /*NO_TEST*/
32839
32840   /* Read the checksum */
32841   rc = read32bits(fd, pPager->journalOff+pPager->pageSize+4, &cksum);
32842   if( rc!=SQLITE_OK ){ return 0; }                                  /*NO_TEST*/
32843
32844   /* Read the data and verify the checksum */
32845   aData = (u8*)pPager->pTmpSpace;
32846   rc = sqlite3OsRead(fd, aData, pPager->pageSize, pPager->journalOff+4);
32847   if( rc!=SQLITE_OK ){ return 0; }                                  /*NO_TEST*/
32848   if( pager_cksum(pPager, aData)!=cksum ){ return 0; }              /*NO_TEST*/
32849
32850   /* Reach this point only if the page is valid */
32851   return 1;
32852 }
32853 #endif /* !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) */
32854
32855 /*
32856 ** Parameter zMaster is the name of a master journal file. A single journal
32857 ** file that referred to the master journal file has just been rolled back.
32858 ** This routine checks if it is possible to delete the master journal file,
32859 ** and does so if it is.
32860 **
32861 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
32862 ** available for use within this function.
32863 **
32864 ** When a master journal file is created, it is populated with the names 
32865 ** of all of its child journals, one after another, formatted as utf-8 
32866 ** encoded text. The end of each child journal file is marked with a 
32867 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
32868 ** file for a transaction involving two databases might be:
32869 **
32870 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
32871 **
32872 ** A master journal file may only be deleted once all of its child 
32873 ** journals have been rolled back.
32874 **
32875 ** This function reads the contents of the master-journal file into 
32876 ** memory and loops through each of the child journal names. For
32877 ** each child journal, it checks if:
32878 **
32879 **   * if the child journal exists, and if so
32880 **   * if the child journal contains a reference to master journal 
32881 **     file zMaster
32882 **
32883 ** If a child journal can be found that matches both of the criteria
32884 ** above, this function returns without doing anything. Otherwise, if
32885 ** no such child journal can be found, file zMaster is deleted from
32886 ** the file-system using sqlite3OsDelete().
32887 **
32888 ** If an IO error within this function, an error code is returned. This
32889 ** function allocates memory by calling sqlite3Malloc(). If an allocation
32890 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
32891 ** occur, SQLITE_OK is returned.
32892 **
32893 ** TODO: This function allocates a single block of memory to load
32894 ** the entire contents of the master journal file. This could be
32895 ** a couple of kilobytes or so - potentially larger than the page 
32896 ** size.
32897 */
32898 static int pager_delmaster(Pager *pPager, const char *zMaster){
32899   sqlite3_vfs *pVfs = pPager->pVfs;
32900   int rc;                   /* Return code */
32901   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
32902   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
32903   char *zMasterJournal = 0; /* Contents of master journal file */
32904   i64 nMasterJournal;       /* Size of master journal file */
32905
32906   /* Allocate space for both the pJournal and pMaster file descriptors.
32907   ** If successful, open the master journal file for reading.
32908   */
32909   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
32910   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
32911   if( !pMaster ){
32912     rc = SQLITE_NOMEM;
32913   }else{
32914     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
32915     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
32916   }
32917   if( rc!=SQLITE_OK ) goto delmaster_out;
32918
32919   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
32920   if( rc!=SQLITE_OK ) goto delmaster_out;
32921
32922   if( nMasterJournal>0 ){
32923     char *zJournal;
32924     char *zMasterPtr = 0;
32925     int nMasterPtr = pVfs->mxPathname+1;
32926
32927     /* Load the entire master journal file into space obtained from
32928     ** sqlite3_malloc() and pointed to by zMasterJournal. 
32929     */
32930     zMasterJournal = (char *)sqlite3Malloc((int)nMasterJournal + nMasterPtr);
32931     if( !zMasterJournal ){
32932       rc = SQLITE_NOMEM;
32933       goto delmaster_out;
32934     }
32935     zMasterPtr = &zMasterJournal[nMasterJournal];
32936     rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
32937     if( rc!=SQLITE_OK ) goto delmaster_out;
32938
32939     zJournal = zMasterJournal;
32940     while( (zJournal-zMasterJournal)<nMasterJournal ){
32941       int exists;
32942       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
32943       if( rc!=SQLITE_OK ){
32944         goto delmaster_out;
32945       }
32946       if( exists ){
32947         /* One of the journals pointed to by the master journal exists.
32948         ** Open it and check if it points at the master journal. If
32949         ** so, return without deleting the master journal file.
32950         */
32951         int c;
32952         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
32953         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
32954         if( rc!=SQLITE_OK ){
32955           goto delmaster_out;
32956         }
32957
32958         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
32959         sqlite3OsClose(pJournal);
32960         if( rc!=SQLITE_OK ){
32961           goto delmaster_out;
32962         }
32963
32964         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
32965         if( c ){
32966           /* We have a match. Do not delete the master journal file. */
32967           goto delmaster_out;
32968         }
32969       }
32970       zJournal += (sqlite3Strlen30(zJournal)+1);
32971     }
32972   }
32973   
32974   rc = sqlite3OsDelete(pVfs, zMaster, 0);
32975
32976 delmaster_out:
32977   if( zMasterJournal ){
32978     sqlite3_free(zMasterJournal);
32979   }  
32980   if( pMaster ){
32981     sqlite3OsClose(pMaster);
32982     assert( !isOpen(pJournal) );
32983   }
32984   sqlite3_free(pMaster);
32985   return rc;
32986 }
32987
32988
32989 /*
32990 ** This function is used to change the actual size of the database 
32991 ** file in the file-system. This only happens when committing a transaction,
32992 ** or rolling back a transaction (including rolling back a hot-journal).
32993 **
32994 ** If the main database file is not open, or an exclusive lock is not
32995 ** held, this function is a no-op. Otherwise, the size of the file is
32996 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
32997 ** on disk is currently larger than nPage pages, then use the VFS
32998 ** xTruncate() method to truncate it.
32999 **
33000 ** Or, it might might be the case that the file on disk is smaller than 
33001 ** nPage pages. Some operating system implementations can get confused if 
33002 ** you try to truncate a file to some size that is larger than it 
33003 ** currently is, so detect this case and write a single zero byte to 
33004 ** the end of the new file instead.
33005 **
33006 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
33007 ** the database file, return the error code to the caller.
33008 */
33009 static int pager_truncate(Pager *pPager, Pgno nPage){
33010   int rc = SQLITE_OK;
33011   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
33012     i64 currentSize, newSize;
33013     /* TODO: Is it safe to use Pager.dbFileSize here? */
33014     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33015     newSize = pPager->pageSize*(i64)nPage;
33016     if( rc==SQLITE_OK && currentSize!=newSize ){
33017       if( currentSize>newSize ){
33018         rc = sqlite3OsTruncate(pPager->fd, newSize);
33019       }else{
33020         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
33021       }
33022       if( rc==SQLITE_OK ){
33023         pPager->dbFileSize = nPage;
33024       }
33025     }
33026   }
33027   return rc;
33028 }
33029
33030 /*
33031 ** Set the value of the Pager.sectorSize variable for the given
33032 ** pager based on the value returned by the xSectorSize method
33033 ** of the open database file. The sector size will be used used 
33034 ** to determine the size and alignment of journal header and 
33035 ** master journal pointers within created journal files.
33036 **
33037 ** For temporary files the effective sector size is always 512 bytes.
33038 **
33039 ** Otherwise, for non-temporary files, the effective sector size is
33040 ** the value returned by the xSectorSize() method rounded up to 512 if
33041 ** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it
33042 ** is greater than MAX_SECTOR_SIZE.
33043 */
33044 static void setSectorSize(Pager *pPager){
33045   assert( isOpen(pPager->fd) || pPager->tempFile );
33046
33047   if( !pPager->tempFile ){
33048     /* Sector size doesn't matter for temporary files. Also, the file
33049     ** may not have been opened yet, in which case the OsSectorSize()
33050     ** call will segfault.
33051     */
33052     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33053   }
33054   if( pPager->sectorSize<512 ){
33055     pPager->sectorSize = 512;
33056   }
33057   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33058     assert( MAX_SECTOR_SIZE>=512 );
33059     pPager->sectorSize = MAX_SECTOR_SIZE;
33060   }
33061 }
33062
33063 /*
33064 ** Playback the journal and thus restore the database file to
33065 ** the state it was in before we started making changes.  
33066 **
33067 ** The journal file format is as follows: 
33068 **
33069 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
33070 **  (2)  4 byte big-endian integer which is the number of valid page records
33071 **       in the journal.  If this value is 0xffffffff, then compute the
33072 **       number of page records from the journal size.
33073 **  (3)  4 byte big-endian integer which is the initial value for the 
33074 **       sanity checksum.
33075 **  (4)  4 byte integer which is the number of pages to truncate the
33076 **       database to during a rollback.
33077 **  (5)  4 byte big-endian integer which is the sector size.  The header
33078 **       is this many bytes in size.
33079 **  (6)  4 byte big-endian integer which is the page case.
33080 **  (7)  4 byte integer which is the number of bytes in the master journal
33081 **       name.  The value may be zero (indicate that there is no master
33082 **       journal.)
33083 **  (8)  N bytes of the master journal name.  The name will be nul-terminated
33084 **       and might be shorter than the value read from (5).  If the first byte
33085 **       of the name is \000 then there is no master journal.  The master
33086 **       journal name is stored in UTF-8.
33087 **  (9)  Zero or more pages instances, each as follows:
33088 **        +  4 byte page number.
33089 **        +  pPager->pageSize bytes of data.
33090 **        +  4 byte checksum
33091 **
33092 ** When we speak of the journal header, we mean the first 8 items above.
33093 ** Each entry in the journal is an instance of the 9th item.
33094 **
33095 ** Call the value from the second bullet "nRec".  nRec is the number of
33096 ** valid page entries in the journal.  In most cases, you can compute the
33097 ** value of nRec from the size of the journal file.  But if a power
33098 ** failure occurred while the journal was being written, it could be the
33099 ** case that the size of the journal file had already been increased but
33100 ** the extra entries had not yet made it safely to disk.  In such a case,
33101 ** the value of nRec computed from the file size would be too large.  For
33102 ** that reason, we always use the nRec value in the header.
33103 **
33104 ** If the nRec value is 0xffffffff it means that nRec should be computed
33105 ** from the file size.  This value is used when the user selects the
33106 ** no-sync option for the journal.  A power failure could lead to corruption
33107 ** in this case.  But for things like temporary table (which will be
33108 ** deleted when the power is restored) we don't care.  
33109 **
33110 ** If the file opened as the journal file is not a well-formed
33111 ** journal file then all pages up to the first corrupted page are rolled
33112 ** back (or no pages if the journal header is corrupted). The journal file
33113 ** is then deleted and SQLITE_OK returned, just as if no corruption had
33114 ** been encountered.
33115 **
33116 ** If an I/O or malloc() error occurs, the journal-file is not deleted
33117 ** and an error code is returned.
33118 **
33119 ** The isHot parameter indicates that we are trying to rollback a journal
33120 ** that might be a hot journal.  Or, it could be that the journal is 
33121 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33122 ** If the journal really is hot, reset the pager cache prior rolling
33123 ** back any content.  If the journal is merely persistent, no reset is
33124 ** needed.
33125 */
33126 static int pager_playback(Pager *pPager, int isHot){
33127   sqlite3_vfs *pVfs = pPager->pVfs;
33128   i64 szJ;                 /* Size of the journal file in bytes */
33129   u32 nRec;                /* Number of Records in the journal */
33130   u32 u;                   /* Unsigned loop counter */
33131   Pgno mxPg = 0;           /* Size of the original file in pages */
33132   int rc;                  /* Result code of a subroutine */
33133   int res = 1;             /* Value returned by sqlite3OsAccess() */
33134   char *zMaster = 0;       /* Name of master journal file if any */
33135   int needPagerReset;      /* True to reset page prior to first page rollback */
33136
33137   /* Figure out how many records are in the journal.  Abort early if
33138   ** the journal is empty.
33139   */
33140   assert( isOpen(pPager->jfd) );
33141   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33142   if( rc!=SQLITE_OK || szJ==0 ){
33143     goto end_playback;
33144   }
33145
33146   /* Read the master journal name from the journal, if it is present.
33147   ** If a master journal file name is specified, but the file is not
33148   ** present on disk, then the journal is not hot and does not need to be
33149   ** played back.
33150   **
33151   ** TODO: Technically the following is an error because it assumes that
33152   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33153   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33154   **  mxPathname is 512, which is the same as the minimum allowable value
33155   ** for pageSize.
33156   */
33157   zMaster = pPager->pTmpSpace;
33158   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33159   if( rc==SQLITE_OK && zMaster[0] ){
33160     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33161   }
33162   zMaster = 0;
33163   if( rc!=SQLITE_OK || !res ){
33164     goto end_playback;
33165   }
33166   pPager->journalOff = 0;
33167   needPagerReset = isHot;
33168
33169   /* This loop terminates either when a readJournalHdr() or 
33170   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
33171   ** occurs. 
33172   */
33173   while( 1 ){
33174     int isUnsync = 0;
33175
33176     /* Read the next journal header from the journal file.  If there are
33177     ** not enough bytes left in the journal file for a complete header, or
33178     ** it is corrupted, then a process must of failed while writing it.
33179     ** This indicates nothing more needs to be rolled back.
33180     */
33181     rc = readJournalHdr(pPager, szJ, &nRec, &mxPg);
33182     if( rc!=SQLITE_OK ){ 
33183       if( rc==SQLITE_DONE ){
33184         rc = SQLITE_OK;
33185       }
33186       goto end_playback;
33187     }
33188
33189     /* If nRec is 0xffffffff, then this journal was created by a process
33190     ** working in no-sync mode. This means that the rest of the journal
33191     ** file consists of pages, there are no more journal headers. Compute
33192     ** the value of nRec based on this assumption.
33193     */
33194     if( nRec==0xffffffff ){
33195       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33196       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33197     }
33198
33199     /* If nRec is 0 and this rollback is of a transaction created by this
33200     ** process and if this is the final header in the journal, then it means
33201     ** that this part of the journal was being filled but has not yet been
33202     ** synced to disk.  Compute the number of pages based on the remaining
33203     ** size of the file.
33204     **
33205     ** The third term of the test was added to fix ticket #2565.
33206     ** When rolling back a hot journal, nRec==0 always means that the next
33207     ** chunk of the journal contains zero pages to be rolled back.  But
33208     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33209     ** the journal, it means that the journal might contain additional
33210     ** pages that need to be rolled back and that the number of pages 
33211     ** should be computed based on the journal file size.
33212     */
33213     testcase( nRec==0 && !isHot
33214          && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
33215          && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
33216          && pagerNextJournalPageIsValid(pPager)
33217     );
33218     if( nRec==0 && !isHot &&
33219         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33220       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33221       isUnsync = 1;
33222     }
33223
33224     /* If this is the first header read from the journal, truncate the
33225     ** database file back to its original size.
33226     */
33227     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33228       rc = pager_truncate(pPager, mxPg);
33229       if( rc!=SQLITE_OK ){
33230         goto end_playback;
33231       }
33232       pPager->dbSize = mxPg;
33233     }
33234
33235     /* Copy original pages out of the journal and back into the 
33236     ** database file and/or page cache.
33237     */
33238     for(u=0; u<nRec; u++){
33239       if( needPagerReset ){
33240         pager_reset(pPager);
33241         needPagerReset = 0;
33242       }
33243       rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33244       if( rc!=SQLITE_OK ){
33245         if( rc==SQLITE_DONE ){
33246           rc = SQLITE_OK;
33247           pPager->journalOff = szJ;
33248           break;
33249         }else{
33250           /* If we are unable to rollback, then the database is probably
33251           ** going to end up being corrupt.  It is corrupt to us, anyhow.
33252           ** Perhaps the next process to come along can fix it....
33253           */
33254           rc = SQLITE_CORRUPT_BKPT;
33255           goto end_playback;
33256         }
33257       }
33258     }
33259   }
33260   /*NOTREACHED*/
33261   assert( 0 );
33262
33263 end_playback:
33264   /* Following a rollback, the database file should be back in its original
33265   ** state prior to the start of the transaction, so invoke the
33266   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33267   ** assertion that the transaction counter was modified.
33268   */
33269   assert(
33270     pPager->fd->pMethods==0 ||
33271     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33272   );
33273
33274   /* If this playback is happening automatically as a result of an IO or 
33275   ** malloc error that occured after the change-counter was updated but 
33276   ** before the transaction was committed, then the change-counter 
33277   ** modification may just have been reverted. If this happens in exclusive 
33278   ** mode, then subsequent transactions performed by the connection will not
33279   ** update the change-counter at all. This may lead to cache inconsistency
33280   ** problems for other processes at some point in the future. So, just
33281   ** in case this has happened, clear the changeCountDone flag now.
33282   */
33283   pPager->changeCountDone = pPager->tempFile;
33284
33285   if( rc==SQLITE_OK ){
33286     zMaster = pPager->pTmpSpace;
33287     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33288     testcase( rc!=SQLITE_OK );
33289   }
33290   if( rc==SQLITE_OK ){
33291     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33292     testcase( rc!=SQLITE_OK );
33293   }
33294   if( rc==SQLITE_OK && zMaster[0] && res ){
33295     /* If there was a master journal and this routine will return success,
33296     ** see if it is possible to delete the master journal.
33297     */
33298     rc = pager_delmaster(pPager, zMaster);
33299     testcase( rc!=SQLITE_OK );
33300   }
33301
33302   /* The Pager.sectorSize variable may have been updated while rolling
33303   ** back a journal created by a process with a different sector size
33304   ** value. Reset it to the correct value for this process.
33305   */
33306   setSectorSize(pPager);
33307   return rc;
33308 }
33309
33310 /*
33311 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33312 ** the entire master journal file. The case pSavepoint==NULL occurs when 
33313 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
33314 ** savepoint.
33315 **
33316 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
33317 ** being rolled back), then the rollback consists of up to three stages,
33318 ** performed in the order specified:
33319 **
33320 **   * Pages are played back from the main journal starting at byte
33321 **     offset PagerSavepoint.iOffset and continuing to 
33322 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
33323 **     file if PagerSavepoint.iHdrOffset is zero.
33324 **
33325 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33326 **     back starting from the journal header immediately following 
33327 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
33328 **
33329 **   * Pages are then played back from the sub-journal file, starting
33330 **     with the PagerSavepoint.iSubRec and continuing to the end of
33331 **     the journal file.
33332 **
33333 ** Throughout the rollback process, each time a page is rolled back, the
33334 ** corresponding bit is set in a bitvec structure (variable pDone in the
33335 ** implementation below). This is used to ensure that a page is only
33336 ** rolled back the first time it is encountered in either journal.
33337 **
33338 ** If pSavepoint is NULL, then pages are only played back from the main
33339 ** journal file. There is no need for a bitvec in this case.
33340 **
33341 ** In either case, before playback commences the Pager.dbSize variable
33342 ** is reset to the value that it held at the start of the savepoint 
33343 ** (or transaction). No page with a page-number greater than this value
33344 ** is played back. If one is encountered it is simply skipped.
33345 */
33346 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33347   i64 szJ;                 /* Effective size of the main journal */
33348   i64 iHdrOff;             /* End of first segment of main-journal records */
33349   int rc = SQLITE_OK;      /* Return code */
33350   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33351
33352   assert( pPager->state>=PAGER_SHARED );
33353
33354   /* Allocate a bitvec to use to store the set of pages rolled back */
33355   if( pSavepoint ){
33356     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33357     if( !pDone ){
33358       return SQLITE_NOMEM;
33359     }
33360   }
33361
33362   /* Set the database size back to the value it was before the savepoint 
33363   ** being reverted was opened.
33364   */
33365   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33366
33367   /* Use pPager->journalOff as the effective size of the main rollback
33368   ** journal.  The actual file might be larger than this in
33369   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33370   ** past pPager->journalOff is off-limits to us.
33371   */
33372   szJ = pPager->journalOff;
33373
33374   /* Begin by rolling back records from the main journal starting at
33375   ** PagerSavepoint.iOffset and continuing to the next journal header.
33376   ** There might be records in the main journal that have a page number
33377   ** greater than the current database size (pPager->dbSize) but those
33378   ** will be skipped automatically.  Pages are added to pDone as they
33379   ** are played back.
33380   */
33381   if( pSavepoint ){
33382     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33383     pPager->journalOff = pSavepoint->iOffset;
33384     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33385       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33386     }
33387     assert( rc!=SQLITE_DONE );
33388   }else{
33389     pPager->journalOff = 0;
33390   }
33391
33392   /* Continue rolling back records out of the main journal starting at
33393   ** the first journal header seen and continuing until the effective end
33394   ** of the main journal file.  Continue to skip out-of-range pages and
33395   ** continue adding pages rolled back to pDone.
33396   */
33397   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33398     u32 ii;            /* Loop counter */
33399     u32 nJRec = 0;     /* Number of Journal Records */
33400     u32 dummy;
33401     rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
33402     assert( rc!=SQLITE_DONE );
33403
33404     /*
33405     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33406     ** test is related to ticket #2565.  See the discussion in the
33407     ** pager_playback() function for additional information.
33408     */
33409     assert( !(nJRec==0
33410          && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
33411          && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
33412          && pagerNextJournalPageIsValid(pPager))
33413     );
33414     if( nJRec==0 
33415      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33416     ){
33417       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33418     }
33419     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33420       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33421     }
33422     assert( rc!=SQLITE_DONE );
33423   }
33424   assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33425
33426   /* Finally,  rollback pages from the sub-journal.  Page that were
33427   ** previously rolled back out of the main journal (and are hence in pDone)
33428   ** will be skipped.  Out-of-range pages are also skipped.
33429   */
33430   if( pSavepoint ){
33431     u32 ii;            /* Loop counter */
33432     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33433     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33434       assert( offset==ii*(4+pPager->pageSize) );
33435       rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33436     }
33437     assert( rc!=SQLITE_DONE );
33438   }
33439
33440   sqlite3BitvecDestroy(pDone);
33441   if( rc==SQLITE_OK ){
33442     pPager->journalOff = szJ;
33443   }
33444   return rc;
33445 }
33446
33447 /*
33448 ** Change the maximum number of in-memory pages that are allowed.
33449 */
33450 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33451   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33452 }
33453
33454 /*
33455 ** Adjust the robustness of the database to damage due to OS crashes
33456 ** or power failures by changing the number of syncs()s when writing
33457 ** the rollback journal.  There are three levels:
33458 **
33459 **    OFF       sqlite3OsSync() is never called.  This is the default
33460 **              for temporary and transient files.
33461 **
33462 **    NORMAL    The journal is synced once before writes begin on the
33463 **              database.  This is normally adequate protection, but
33464 **              it is theoretically possible, though very unlikely,
33465 **              that an inopertune power failure could leave the journal
33466 **              in a state which would cause damage to the database
33467 **              when it is rolled back.
33468 **
33469 **    FULL      The journal is synced twice before writes begin on the
33470 **              database (with some additional information - the nRec field
33471 **              of the journal header - being written in between the two
33472 **              syncs).  If we assume that writing a
33473 **              single disk sector is atomic, then this mode provides
33474 **              assurance that the journal will not be corrupted to the
33475 **              point of causing damage to the database during rollback.
33476 **
33477 ** Numeric values associated with these states are OFF==1, NORMAL=2,
33478 ** and FULL=3.
33479 */
33480 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
33481 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33482   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33483   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33484   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33485   if( pPager->noSync ) pPager->needSync = 0;
33486 }
33487 #endif
33488
33489 /*
33490 ** The following global variable is incremented whenever the library
33491 ** attempts to open a temporary file.  This information is used for
33492 ** testing and analysis only.  
33493 */
33494 #ifdef SQLITE_TEST
33495 SQLITE_API int sqlite3_opentemp_count = 0;
33496 #endif
33497
33498 /*
33499 ** Open a temporary file.
33500 **
33501 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
33502 ** or some other error code if we fail. The OS will automatically 
33503 ** delete the temporary file when it is closed.
33504 **
33505 ** The flags passed to the VFS layer xOpen() call are those specified
33506 ** by parameter vfsFlags ORed with the following:
33507 **
33508 **     SQLITE_OPEN_READWRITE
33509 **     SQLITE_OPEN_CREATE
33510 **     SQLITE_OPEN_EXCLUSIVE
33511 **     SQLITE_OPEN_DELETEONCLOSE
33512 */
33513 static int pagerOpentemp(
33514   Pager *pPager,        /* The pager object */
33515   sqlite3_file *pFile,  /* Write the file descriptor here */
33516   int vfsFlags          /* Flags passed through to the VFS */
33517 ){
33518   int rc;               /* Return code */
33519
33520 #ifdef SQLITE_TEST
33521   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33522 #endif
33523
33524   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33525             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33526   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33527   assert( rc!=SQLITE_OK || isOpen(pFile) );
33528   return rc;
33529 }
33530
33531 /*
33532 ** Set the busy handler function.
33533 **
33534 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
33535 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33536 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
33537 ** lock. It does *not* invoke the busy handler when upgrading from
33538 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33539 ** (which occurs during hot-journal rollback). Summary:
33540 **
33541 **   Transition                        | Invokes xBusyHandler
33542 **   --------------------------------------------------------
33543 **   NO_LOCK       -> SHARED_LOCK      | Yes
33544 **   SHARED_LOCK   -> RESERVED_LOCK    | No
33545 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33546 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33547 **
33548 ** If the busy-handler callback returns non-zero, the lock is 
33549 ** retried. If it returns zero, then the SQLITE_BUSY error is
33550 ** returned to the caller of the pager API function.
33551 */
33552 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33553   Pager *pPager,                       /* Pager object */
33554   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33555   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33556 ){  
33557   pPager->xBusyHandler = xBusyHandler;
33558   pPager->pBusyHandlerArg = pBusyHandlerArg;
33559 }
33560
33561 /*
33562 ** Set the reinitializer for this pager. If not NULL, the reinitializer
33563 ** is called when the content of a page in cache is modified (restored)
33564 ** as part of a transaction or savepoint rollback. The callback gives 
33565 ** higher-level code an opportunity to restore the EXTRA section to 
33566 ** agree with the restored page data.
33567 */
33568 SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
33569   pPager->xReiniter = xReinit;
33570 }
33571
33572 /*
33573 ** Change the page size used by the Pager object. The new page size 
33574 ** is passed in *pPageSize.
33575 **
33576 ** If the pager is in the error state when this function is called, it
33577 ** is a no-op. The value returned is the error state error code (i.e. 
33578 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33579 **
33580 ** Otherwise, if all of the following are true:
33581 **
33582 **   * the new page size (value of *pPageSize) is valid (a power 
33583 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33584 **
33585 **   * there are no outstanding page references, and
33586 **
33587 **   * the database is either not an in-memory database or it is
33588 **     an in-memory database that currently consists of zero pages.
33589 **
33590 ** then the pager object page size is set to *pPageSize.
33591 **
33592 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
33593 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
33594 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
33595 ** In all other cases, SQLITE_OK is returned.
33596 **
33597 ** If the page size is not changed, either because one of the enumerated
33598 ** conditions above is not true, the pager was in error state when this
33599 ** function was called, or because the memory allocation attempt failed, 
33600 ** then *pPageSize is set to the old, retained page size before returning.
33601 */
33602 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
33603   int rc = pPager->errCode;
33604   if( rc==SQLITE_OK ){
33605     u16 pageSize = *pPageSize;
33606     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33607     if( pageSize && pageSize!=pPager->pageSize 
33608      && (pPager->memDb==0 || pPager->dbSize==0)
33609      && sqlite3PcacheRefCount(pPager->pPCache)==0 
33610     ){
33611       char *pNew = (char *)sqlite3PageMalloc(pageSize);
33612       if( !pNew ){
33613         rc = SQLITE_NOMEM;
33614       }else{
33615         pager_reset(pPager);
33616         pPager->pageSize = pageSize;
33617         sqlite3PageFree(pPager->pTmpSpace);
33618         pPager->pTmpSpace = pNew;
33619         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33620       }
33621     }
33622     *pPageSize = (u16)pPager->pageSize;
33623   }
33624   return rc;
33625 }
33626
33627 /*
33628 ** Return a pointer to the "temporary page" buffer held internally
33629 ** by the pager.  This is a buffer that is big enough to hold the
33630 ** entire content of a database page.  This buffer is used internally
33631 ** during rollback and will be overwritten whenever a rollback
33632 ** occurs.  But other modules are free to use it too, as long as
33633 ** no rollbacks are happening.
33634 */
33635 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33636   return pPager->pTmpSpace;
33637 }
33638
33639 /*
33640 ** Attempt to set the maximum database page count if mxPage is positive. 
33641 ** Make no changes if mxPage is zero or negative.  And never reduce the
33642 ** maximum page count below the current size of the database.
33643 **
33644 ** Regardless of mxPage, return the current maximum page count.
33645 */
33646 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33647   if( mxPage>0 ){
33648     pPager->mxPgno = mxPage;
33649   }
33650   sqlite3PagerPagecount(pPager, 0);
33651   return pPager->mxPgno;
33652 }
33653
33654 /*
33655 ** The following set of routines are used to disable the simulated
33656 ** I/O error mechanism.  These routines are used to avoid simulated
33657 ** errors in places where we do not care about errors.
33658 **
33659 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33660 ** and generate no code.
33661 */
33662 #ifdef SQLITE_TEST
33663 SQLITE_API extern int sqlite3_io_error_pending;
33664 SQLITE_API extern int sqlite3_io_error_hit;
33665 static int saved_cnt;
33666 void disable_simulated_io_errors(void){
33667   saved_cnt = sqlite3_io_error_pending;
33668   sqlite3_io_error_pending = -1;
33669 }
33670 void enable_simulated_io_errors(void){
33671   sqlite3_io_error_pending = saved_cnt;
33672 }
33673 #else
33674 # define disable_simulated_io_errors()
33675 # define enable_simulated_io_errors()
33676 #endif
33677
33678 /*
33679 ** Read the first N bytes from the beginning of the file into memory
33680 ** that pDest points to. 
33681 **
33682 ** If the pager was opened on a transient file (zFilename==""), or
33683 ** opened on a file less than N bytes in size, the output buffer is
33684 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
33685 ** function is used to read database headers, and a new transient or
33686 ** zero sized database has a header than consists entirely of zeroes.
33687 **
33688 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33689 ** the error code is returned to the caller and the contents of the
33690 ** output buffer undefined.
33691 */
33692 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33693   int rc = SQLITE_OK;
33694   memset(pDest, 0, N);
33695   assert( isOpen(pPager->fd) || pPager->tempFile );
33696   if( isOpen(pPager->fd) ){
33697     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33698     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33699     if( rc==SQLITE_IOERR_SHORT_READ ){
33700       rc = SQLITE_OK;
33701     }
33702   }
33703   return rc;
33704 }
33705
33706 /*
33707 ** Return the total number of pages in the database file associated 
33708 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33709 ** However, if the file is between 1 and <page-size> bytes in size, then 
33710 ** this is considered a 1 page file.
33711 **
33712 ** If the pager is in error state when this function is called, then the
33713 ** error state error code is returned and *pnPage left unchanged. Or,
33714 ** if the file system has to be queried for the size of the file and
33715 ** the query attempt returns an IO error, the IO error code is returned
33716 ** and *pnPage is left unchanged.
33717 **
33718 ** Otherwise, if everything is successful, then SQLITE_OK is returned
33719 ** and *pnPage is set to the number of pages in the database.
33720 */
33721 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33722   Pgno nPage;               /* Value to return via *pnPage */
33723
33724   /* If the pager is already in the error state, return the error code. */
33725   if( pPager->errCode ){
33726     return pPager->errCode;
33727   }
33728
33729   /* Determine the number of pages in the file. Store this in nPage. */
33730   if( pPager->dbSizeValid ){
33731     nPage = pPager->dbSize;
33732   }else{
33733     int rc;                 /* Error returned by OsFileSize() */
33734     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33735
33736     assert( isOpen(pPager->fd) || pPager->tempFile );
33737     if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33738       pager_error(pPager, rc);
33739       return rc;
33740     }
33741     if( n>0 && n<pPager->pageSize ){
33742       nPage = 1;
33743     }else{
33744       nPage = (Pgno)(n / pPager->pageSize);
33745     }
33746     if( pPager->state!=PAGER_UNLOCK ){
33747       pPager->dbSize = nPage;
33748       pPager->dbFileSize = nPage;
33749       pPager->dbSizeValid = 1;
33750     }
33751   }
33752
33753   /* If the current number of pages in the file is greater than the 
33754   ** configured maximum pager number, increase the allowed limit so
33755   ** that the file can be read.
33756   */
33757   if( nPage>pPager->mxPgno ){
33758     pPager->mxPgno = (Pgno)nPage;
33759   }
33760
33761   /* Set the output variable and return SQLITE_OK */
33762   if( pnPage ){
33763     *pnPage = nPage;
33764   }
33765   return SQLITE_OK;
33766 }
33767
33768
33769 /*
33770 ** Try to obtain a lock of type locktype on the database file. If
33771 ** a similar or greater lock is already held, this function is a no-op
33772 ** (returning SQLITE_OK immediately).
33773 **
33774 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
33775 ** the busy callback if the lock is currently not available. Repeat 
33776 ** until the busy callback returns false or until the attempt to 
33777 ** obtain the lock succeeds.
33778 **
33779 ** Return SQLITE_OK on success and an error code if we cannot obtain
33780 ** the lock. If the lock is obtained successfully, set the Pager.state 
33781 ** variable to locktype before returning.
33782 */
33783 static int pager_wait_on_lock(Pager *pPager, int locktype){
33784   int rc;                              /* Return code */
33785
33786   /* The OS lock values must be the same as the Pager lock values */
33787   assert( PAGER_SHARED==SHARED_LOCK );
33788   assert( PAGER_RESERVED==RESERVED_LOCK );
33789   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33790
33791   /* If the file is currently unlocked then the size must be unknown */
33792   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33793
33794   /* Check that this is either a no-op (because the requested lock is 
33795   ** already held, or one of the transistions that the busy-handler
33796   ** may be invoked during, according to the comment above
33797   ** sqlite3PagerSetBusyhandler().
33798   */
33799   assert( (pPager->state>=locktype)
33800        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33801        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33802   );
33803
33804   if( pPager->state>=locktype ){
33805     rc = SQLITE_OK;
33806   }else{
33807     do {
33808       rc = sqlite3OsLock(pPager->fd, locktype);
33809     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33810     if( rc==SQLITE_OK ){
33811       pPager->state = (u8)locktype;
33812       IOTRACE(("LOCK %p %d\n", pPager, locktype))
33813     }
33814   }
33815   return rc;
33816 }
33817
33818 /*
33819 ** Truncate the in-memory database file image to nPage pages. This 
33820 ** function does not actually modify the database file on disk. It 
33821 ** just sets the internal state of the pager object so that the 
33822 ** truncation will be done when the current transaction is committed.
33823 */
33824 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
33825   assert( pPager->dbSizeValid );
33826   assert( pPager->dbSize>=nPage );
33827   assert( pPager->state>=PAGER_RESERVED );
33828   pPager->dbSize = nPage;
33829 }
33830
33831 /*
33832 ** Shutdown the page cache.  Free all memory and close all files.
33833 **
33834 ** If a transaction was in progress when this routine is called, that
33835 ** transaction is rolled back.  All outstanding pages are invalidated
33836 ** and their memory is freed.  Any attempt to use a page associated
33837 ** with this page cache after this function returns will likely
33838 ** result in a coredump.
33839 **
33840 ** This function always succeeds. If a transaction is active an attempt
33841 ** is made to roll it back. If an error occurs during the rollback 
33842 ** a hot journal may be left in the filesystem but no error is returned
33843 ** to the caller.
33844 */
33845 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
33846   disable_simulated_io_errors();
33847   sqlite3BeginBenignMalloc();
33848   pPager->errCode = 0;
33849   pPager->exclusiveMode = 0;
33850   pager_reset(pPager);
33851   if( MEMDB ){
33852     pager_unlock(pPager);
33853   }else{
33854     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
33855     ** call which may be made from within pagerUnlockAndRollback(). If it
33856     ** is not -1, then the unsynced portion of an open journal file may
33857     ** be played back into the database. If a power failure occurs while
33858     ** this is happening, the database may become corrupt.
33859     */
33860     pPager->journalHdr = -1;
33861     pagerUnlockAndRollback(pPager);
33862   }
33863   sqlite3EndBenignMalloc();
33864   enable_simulated_io_errors();
33865   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
33866   IOTRACE(("CLOSE %p\n", pPager))
33867   sqlite3OsClose(pPager->fd);
33868   sqlite3PageFree(pPager->pTmpSpace);
33869   sqlite3PcacheClose(pPager->pPCache);
33870
33871   assert( !pPager->aSavepoint && !pPager->pInJournal );
33872   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
33873
33874   sqlite3_free(pPager);
33875   return SQLITE_OK;
33876 }
33877
33878 #if !defined(NDEBUG) || defined(SQLITE_TEST)
33879 /*
33880 ** Return the page number for page pPg.
33881 */
33882 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
33883   return pPg->pgno;
33884 }
33885 #endif
33886
33887 /*
33888 ** Increment the reference count for page pPg.
33889 */
33890 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
33891   sqlite3PcacheRef(pPg);
33892 }
33893
33894 /*
33895 ** Sync the journal. In other words, make sure all the pages that have
33896 ** been written to the journal have actually reached the surface of the
33897 ** disk and can be restored in the event of a hot-journal rollback.
33898 **
33899 ** If the Pager.needSync flag is not set, then this function is a
33900 ** no-op. Otherwise, the actions required depend on the journal-mode
33901 ** and the device characteristics of the the file-system, as follows:
33902 **
33903 **   * If the journal file is an in-memory journal file, no action need
33904 **     be taken.
33905 **
33906 **   * Otherwise, if the device does not support the SAFE_APPEND property,
33907 **     then the nRec field of the most recently written journal header
33908 **     is updated to contain the number of journal records that have
33909 **     been written following it. If the pager is operating in full-sync
33910 **     mode, then the journal file is synced before this field is updated.
33911 **
33912 **   * If the device does not support the SEQUENTIAL property, then 
33913 **     journal file is synced.
33914 **
33915 ** Or, in pseudo-code:
33916 **
33917 **   if( NOT <in-memory journal> ){
33918 **     if( NOT SAFE_APPEND ){
33919 **       if( <full-sync mode> ) xSync(<journal file>);
33920 **       <update nRec field>
33921 **     } 
33922 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
33923 **   }
33924 **
33925 ** The Pager.needSync flag is never be set for temporary files, or any
33926 ** file operating in no-sync mode (Pager.noSync set to non-zero).
33927 **
33928 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
33929 ** page currently held in memory before returning SQLITE_OK. If an IO
33930 ** error is encountered, then the IO error code is returned to the caller.
33931 */
33932 static int syncJournal(Pager *pPager){
33933   if( pPager->needSync ){
33934     assert( !pPager->tempFile );
33935     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
33936       int rc;                              /* Return code */
33937       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
33938       assert( isOpen(pPager->jfd) );
33939
33940       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
33941         /* Variable iNRecOffset is set to the offset in the journal file
33942         ** of the nRec field of the most recently written journal header.
33943         ** This field will be updated following the xSync() operation
33944         ** on the journal file. */
33945         i64 iNRecOffset = pPager->journalHdr + sizeof(aJournalMagic);
33946
33947         /* This block deals with an obscure problem. If the last connection
33948         ** that wrote to this database was operating in persistent-journal
33949         ** mode, then the journal file may at this point actually be larger
33950         ** than Pager.journalOff bytes. If the next thing in the journal
33951         ** file happens to be a journal-header (written as part of the
33952         ** previous connections transaction), and a crash or power-failure 
33953         ** occurs after nRec is updated but before this connection writes 
33954         ** anything else to the journal file (or commits/rolls back its 
33955         ** transaction), then SQLite may become confused when doing the 
33956         ** hot-journal rollback following recovery. It may roll back all
33957         ** of this connections data, then proceed to rolling back the old,
33958         ** out-of-date data that follows it. Database corruption.
33959         **
33960         ** To work around this, if the journal file does appear to contain
33961         ** a valid header following Pager.journalOff, then write a 0x00
33962         ** byte to the start of it to prevent it from being recognized.
33963         **
33964         ** Variable iNextHdrOffset is set to the offset at which this
33965         ** problematic header will occur, if it exists. aMagic is used 
33966         ** as a temporary buffer to inspect the first couple of bytes of
33967         ** the potential journal header.
33968         */
33969         i64 iNextHdrOffset = journalHdrOffset(pPager);
33970         u8 aMagic[8];
33971         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
33972         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
33973           static const u8 zerobyte = 0;
33974           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
33975         }
33976         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
33977           return rc;
33978         }
33979
33980         /* Write the nRec value into the journal file header. If in
33981         ** full-synchronous mode, sync the journal first. This ensures that
33982         ** all data has really hit the disk before nRec is updated to mark
33983         ** it as a candidate for rollback.
33984         **
33985         ** This is not required if the persistent media supports the
33986         ** SAFE_APPEND property. Because in this case it is not possible 
33987         ** for garbage data to be appended to the file, the nRec field
33988         ** is populated with 0xFFFFFFFF when the journal header is written
33989         ** and never needs to be updated.
33990         */
33991         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
33992           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
33993           IOTRACE(("JSYNC %p\n", pPager))
33994           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
33995           if( rc!=SQLITE_OK ) return rc;
33996         }
33997         IOTRACE(("JHDR %p %lld %d\n", pPager, iNRecOffset, 4));
33998         rc = write32bits(pPager->jfd, iNRecOffset, pPager->nRec);
33999         if( rc!=SQLITE_OK ) return rc;
34000       }
34001       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34002         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34003         IOTRACE(("JSYNC %p\n", pPager))
34004         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
34005           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34006         );
34007         if( rc!=SQLITE_OK ) return rc;
34008       }
34009     }
34010
34011     /* The journal file was just successfully synced. Set Pager.needSync 
34012     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34013     */
34014     pPager->needSync = 0;
34015     pPager->journalStarted = 1;
34016     sqlite3PcacheClearSyncFlags(pPager->pPCache);
34017   }
34018
34019   return SQLITE_OK;
34020 }
34021
34022 /*
34023 ** The argument is the first in a linked list of dirty pages connected
34024 ** by the PgHdr.pDirty pointer. This function writes each one of the
34025 ** in-memory pages in the list to the database file. The argument may
34026 ** be NULL, representing an empty list. In this case this function is
34027 ** a no-op.
34028 **
34029 ** The pager must hold at least a RESERVED lock when this function
34030 ** is called. Before writing anything to the database file, this lock
34031 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34032 ** SQLITE_BUSY is returned and no data is written to the database file.
34033 ** 
34034 ** If the pager is a temp-file pager and the actual file-system file
34035 ** is not yet open, it is created and opened before any data is 
34036 ** written out.
34037 **
34038 ** Once the lock has been upgraded and, if necessary, the file opened,
34039 ** the pages are written out to the database file in list order. Writing
34040 ** a page is skipped if it meets either of the following criteria:
34041 **
34042 **   * The page number is greater than Pager.dbSize, or
34043 **   * The PGHDR_DONT_WRITE flag is set on the page.
34044 **
34045 ** If writing out a page causes the database file to grow, Pager.dbFileSize
34046 ** is updated accordingly. If page 1 is written out, then the value cached
34047 ** in Pager.dbFileVers[] is updated to match the new value stored in
34048 ** the database file.
34049 **
34050 ** If everything is successful, SQLITE_OK is returned. If an IO error 
34051 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34052 ** be obtained, SQLITE_BUSY is returned.
34053 */
34054 static int pager_write_pagelist(PgHdr *pList){
34055   Pager *pPager;                       /* Pager object */
34056   int rc;                              /* Return code */
34057
34058   if( pList==0 ) return SQLITE_OK;
34059   pPager = pList->pPager;
34060
34061   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34062   ** database file. If there is already an EXCLUSIVE lock, the following
34063   ** call is a no-op.
34064   **
34065   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34066   ** through an intermediate state PENDING.   A PENDING lock prevents new
34067   ** readers from attaching to the database but is unsufficient for us to
34068   ** write.  The idea of a PENDING lock is to prevent new readers from
34069   ** coming in while we wait for existing readers to clear.
34070   **
34071   ** While the pager is in the RESERVED state, the original database file
34072   ** is unchanged and we can rollback without having to playback the
34073   ** journal into the original database file.  Once we transition to
34074   ** EXCLUSIVE, it means the database file has been changed and any rollback
34075   ** will require a journal playback.
34076   */
34077   assert( pPager->state>=PAGER_RESERVED );
34078   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34079
34080   /* If the file is a temp-file has not yet been opened, open it now. It
34081   ** is not possible for rc to be other than SQLITE_OK if this branch
34082   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34083   */
34084   if( !isOpen(pPager->fd) ){
34085     assert( pPager->tempFile && rc==SQLITE_OK );
34086     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34087   }
34088
34089   while( rc==SQLITE_OK && pList ){
34090     Pgno pgno = pList->pgno;
34091
34092     /* If there are dirty pages in the page cache with page numbers greater
34093     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34094     ** make the file smaller (presumably by auto-vacuum code). Do not write
34095     ** any such pages to the file.
34096     **
34097     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34098     ** set (set by sqlite3PagerDontWrite()).
34099     */
34100     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34101       i64 offset = (pgno-1)*(i64)pPager->pageSize;         /* Offset to write */
34102       char *pData = CODEC2(pPager, pList->pData, pgno, 6); /* Data to write */
34103
34104       /* Write out the page data. */
34105       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34106
34107       /* If page 1 was just written, update Pager.dbFileVers to match
34108       ** the value now stored in the database file. If writing this 
34109       ** page caused the database file to grow, update dbFileSize. 
34110       */
34111       if( pgno==1 ){
34112         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34113       }
34114       if( pgno>pPager->dbFileSize ){
34115         pPager->dbFileSize = pgno;
34116       }
34117
34118       /* Update any backup objects copying the contents of this pager. */
34119       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8 *)pData);
34120
34121       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34122                    PAGERID(pPager), pgno, pager_pagehash(pList)));
34123       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34124       PAGER_INCR(sqlite3_pager_writedb_count);
34125       PAGER_INCR(pPager->nWrite);
34126     }else{
34127       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34128     }
34129 #ifdef SQLITE_CHECK_PAGES
34130     pList->pageHash = pager_pagehash(pList);
34131 #endif
34132     pList = pList->pDirty;
34133   }
34134
34135   return rc;
34136 }
34137
34138 /*
34139 ** Append a record of the current state of page pPg to the sub-journal. 
34140 ** It is the callers responsibility to use subjRequiresPage() to check 
34141 ** that it is really required before calling this function.
34142 **
34143 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34144 ** for all open savepoints before returning.
34145 **
34146 ** This function returns SQLITE_OK if everything is successful, an IO
34147 ** error code if the attempt to write to the sub-journal fails, or 
34148 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34149 ** bitvec.
34150 */
34151 static int subjournalPage(PgHdr *pPg){
34152   int rc = SQLITE_OK;
34153   Pager *pPager = pPg->pPager;
34154   if( isOpen(pPager->sjfd) ){
34155     void *pData = pPg->pData;
34156     i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34157     char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
34158   
34159     PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34160   
34161     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34162     rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34163     if( rc==SQLITE_OK ){
34164       rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34165     }
34166   }
34167   if( rc==SQLITE_OK ){
34168     pPager->nSubRec++;
34169     assert( pPager->nSavepoint>0 );
34170     rc = addToSavepointBitvecs(pPager, pPg->pgno);
34171     testcase( rc!=SQLITE_OK );
34172   }
34173   return rc;
34174 }
34175
34176
34177 /*
34178 ** This function is called by the pcache layer when it has reached some
34179 ** soft memory limit. The first argument is a pointer to a Pager object
34180 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34181 ** database). The second argument is a reference to a page that is 
34182 ** currently dirty but has no outstanding references. The page
34183 ** is always associated with the Pager object passed as the first 
34184 ** argument.
34185 **
34186 ** The job of this function is to make pPg clean by writing its contents
34187 ** out to the database file, if possible. This may involve syncing the
34188 ** journal file. 
34189 **
34190 ** If successful, sqlite3PcacheMakeClean() is called on the page and
34191 ** SQLITE_OK returned. If an IO error occurs while trying to make the
34192 ** page clean, the IO error code is returned. If the page cannot be
34193 ** made clean for some other reason, but no error occurs, then SQLITE_OK
34194 ** is returned by sqlite3PcacheMakeClean() is not called.
34195 */
34196 static int pagerStress(void *p, PgHdr *pPg){
34197   Pager *pPager = (Pager *)p;
34198   int rc = SQLITE_OK;
34199
34200   assert( pPg->pPager==pPager );
34201   assert( pPg->flags&PGHDR_DIRTY );
34202
34203   /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34204   ** is journalling a set of two or more database pages that are stored
34205   ** on the same disk sector. Syncing the journal is not allowed while
34206   ** this is happening as it is important that all members of such a
34207   ** set of pages are synced to disk together. So, if the page this function
34208   ** is trying to make clean will require a journal sync and the doNotSync
34209   ** flag is set, return without doing anything. The pcache layer will
34210   ** just have to go ahead and allocate a new page buffer instead of
34211   ** reusing pPg.
34212   **
34213   ** Similarly, if the pager has already entered the error state, do not
34214   ** try to write the contents of pPg to disk.
34215   */
34216   if( pPager->errCode || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC) ){
34217     return SQLITE_OK;
34218   }
34219
34220   /* Sync the journal file if required. */
34221   if( pPg->flags&PGHDR_NEED_SYNC ){
34222     rc = syncJournal(pPager);
34223     if( rc==SQLITE_OK && pPager->fullSync && 
34224       !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34225       !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34226     ){
34227       pPager->nRec = 0;
34228       rc = writeJournalHdr(pPager);
34229     }
34230   }
34231
34232   /* If the page number of this page is larger than the current size of
34233   ** the database image, it may need to be written to the sub-journal.
34234   ** This is because the call to pager_write_pagelist() below will not
34235   ** actually write data to the file in this case.
34236   **
34237   ** Consider the following sequence of events:
34238   **
34239   **   BEGIN;
34240   **     <journal page X>
34241   **     <modify page X>
34242   **     SAVEPOINT sp;
34243   **       <shrink database file to Y pages>
34244   **       pagerStress(page X)
34245   **     ROLLBACK TO sp;
34246   **
34247   ** If (X>Y), then when pagerStress is called page X will not be written
34248   ** out to the database file, but will be dropped from the cache. Then,
34249   ** following the "ROLLBACK TO sp" statement, reading page X will read
34250   ** data from the database file. This will be the copy of page X as it
34251   ** was when the transaction started, not as it was when "SAVEPOINT sp"
34252   ** was executed.
34253   **
34254   ** The solution is to write the current data for page X into the 
34255   ** sub-journal file now (if it is not already there), so that it will
34256   ** be restored to its current value when the "ROLLBACK TO sp" is 
34257   ** executed.
34258   */
34259   if( rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) ){
34260     rc = subjournalPage(pPg);
34261   }
34262
34263   /* Write the contents of the page out to the database file. */
34264   if( rc==SQLITE_OK ){
34265     pPg->pDirty = 0;
34266     rc = pager_write_pagelist(pPg);
34267   }
34268
34269   /* Mark the page as clean. */
34270   if( rc==SQLITE_OK ){
34271     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34272     sqlite3PcacheMakeClean(pPg);
34273   }
34274
34275   return pager_error(pPager, rc);
34276 }
34277
34278
34279 /*
34280 ** Allocate and initialize a new Pager object and put a pointer to it
34281 ** in *ppPager. The pager should eventually be freed by passing it
34282 ** to sqlite3PagerClose().
34283 **
34284 ** The zFilename argument is the path to the database file to open.
34285 ** If zFilename is NULL then a randomly-named temporary file is created
34286 ** and used as the file to be cached. Temporary files are be deleted
34287 ** automatically when they are closed. If zFilename is ":memory:" then 
34288 ** all information is held in cache. It is never written to disk. 
34289 ** This can be used to implement an in-memory database.
34290 **
34291 ** The nExtra parameter specifies the number of bytes of space allocated
34292 ** along with each page reference. This space is available to the user
34293 ** via the sqlite3PagerGetExtra() API.
34294 **
34295 ** The flags argument is used to specify properties that affect the
34296 ** operation of the pager. It should be passed some bitwise combination
34297 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34298 **
34299 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
34300 ** of the xOpen() method of the supplied VFS when opening files. 
34301 **
34302 ** If the pager object is allocated and the specified file opened 
34303 ** successfully, SQLITE_OK is returned and *ppPager set to point to
34304 ** the new pager object. If an error occurs, *ppPager is set to NULL
34305 ** and error code returned. This function may return SQLITE_NOMEM
34306 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
34307 ** various SQLITE_IO_XXX errors.
34308 */
34309 SQLITE_PRIVATE int sqlite3PagerOpen(
34310   sqlite3_vfs *pVfs,       /* The virtual file system to use */
34311   Pager **ppPager,         /* OUT: Return the Pager structure here */
34312   const char *zFilename,   /* Name of the database file to open */
34313   int nExtra,              /* Extra bytes append to each in-memory page */
34314   int flags,               /* flags controlling this file */
34315   int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
34316 ){
34317   u8 *pPtr;
34318   Pager *pPager = 0;       /* Pager object to allocate and return */
34319   int rc = SQLITE_OK;      /* Return code */
34320   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34321   int memDb = 0;           /* True if this is an in-memory file */
34322   int readOnly = 0;        /* True if this is a read-only file */
34323   int journalFileSize;     /* Bytes to allocate for each journal fd */
34324   char *zPathname = 0;     /* Full path to database file */
34325   int nPathname = 0;       /* Number of bytes in zPathname */
34326   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34327   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34328   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34329   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34330
34331   /* Figure out how much space is required for each journal file-handle
34332   ** (there are two of them, the main journal and the sub-journal). This
34333   ** is the maximum space required for an in-memory journal file handle 
34334   ** and a regular journal file-handle. Note that a "regular journal-handle"
34335   ** may be a wrapper capable of caching the first portion of the journal
34336   ** file in memory to implement the atomic-write optimization (see 
34337   ** source file journal.c).
34338   */
34339   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34340     journalFileSize = sqlite3JournalSize(pVfs);
34341   }else{
34342     journalFileSize = sqlite3MemJournalSize();
34343   }
34344
34345   /* Set the output variable to NULL in case an error occurs. */
34346   *ppPager = 0;
34347
34348   /* Compute and store the full pathname in an allocated buffer pointed
34349   ** to by zPathname, length nPathname. Or, if this is a temporary file,
34350   ** leave both nPathname and zPathname set to 0.
34351   */
34352   if( zFilename && zFilename[0] ){
34353     nPathname = pVfs->mxPathname+1;
34354     zPathname = sqlite3Malloc(nPathname*2);
34355     if( zPathname==0 ){
34356       return SQLITE_NOMEM;
34357     }
34358 #ifndef SQLITE_OMIT_MEMORYDB
34359     if( strcmp(zFilename,":memory:")==0 ){
34360       memDb = 1;
34361       zPathname[0] = 0;
34362     }else
34363 #endif
34364     {
34365       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34366       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34367     }
34368
34369     nPathname = sqlite3Strlen30(zPathname);
34370     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34371       /* This branch is taken when the journal path required by
34372       ** the database being opened will be more than pVfs->mxPathname
34373       ** bytes in length. This means the database cannot be opened,
34374       ** as it will not be possible to open the journal file or even
34375       ** check for a hot-journal before reading.
34376       */
34377       rc = SQLITE_CANTOPEN;
34378     }
34379     if( rc!=SQLITE_OK ){
34380       sqlite3_free(zPathname);
34381       return rc;
34382     }
34383   }
34384
34385   /* Allocate memory for the Pager structure, PCache object, the
34386   ** three file descriptors, the database file name and the journal 
34387   ** file name. The layout in memory is as follows:
34388   **
34389   **     Pager object                    (sizeof(Pager) bytes)
34390   **     PCache object                   (sqlite3PcacheSize() bytes)
34391   **     Database file handle            (pVfs->szOsFile bytes)
34392   **     Sub-journal file handle         (journalFileSize bytes)
34393   **     Main journal file handle        (journalFileSize bytes)
34394   **     Database file name              (nPathname+1 bytes)
34395   **     Journal file name               (nPathname+8+1 bytes)
34396   */
34397   pPtr = (u8 *)sqlite3MallocZero(
34398     sizeof(*pPager) +           /* Pager structure */
34399     pcacheSize      +           /* PCache object */
34400     pVfs->szOsFile  +           /* The main db file */
34401     journalFileSize * 2 +       /* The two journal files */ 
34402     nPathname + 1 +             /* zFilename */
34403     nPathname + 8 + 1           /* zJournal */
34404   );
34405   if( !pPtr ){
34406     sqlite3_free(zPathname);
34407     return SQLITE_NOMEM;
34408   }
34409   pPager =              (Pager*)(pPtr);
34410   pPager->pPCache =    (PCache*)(pPtr += sizeof(*pPager));
34411   pPager->fd =   (sqlite3_file*)(pPtr += pcacheSize);
34412   pPager->sjfd = (sqlite3_file*)(pPtr += pVfs->szOsFile);
34413   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34414   pPager->zFilename =    (char*)(pPtr += journalFileSize);
34415
34416   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34417   if( zPathname ){
34418     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34419     memcpy(pPager->zFilename, zPathname, nPathname);
34420     memcpy(pPager->zJournal, zPathname, nPathname);
34421     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34422     sqlite3_free(zPathname);
34423   }
34424   pPager->pVfs = pVfs;
34425   pPager->vfsFlags = vfsFlags;
34426
34427   /* Open the pager file.
34428   */
34429   if( zFilename && zFilename[0] && !memDb ){
34430     int fout = 0;                    /* VFS flags returned by xOpen() */
34431     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34432     readOnly = (fout&SQLITE_OPEN_READONLY);
34433
34434     /* If the file was successfully opened for read/write access,
34435     ** choose a default page size in case we have to create the
34436     ** database file. The default page size is the maximum of:
34437     **
34438     **    + SQLITE_DEFAULT_PAGE_SIZE,
34439     **    + The value returned by sqlite3OsSectorSize()
34440     **    + The largest page size that can be written atomically.
34441     */
34442     if( rc==SQLITE_OK && !readOnly ){
34443       setSectorSize(pPager);
34444       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34445       if( szPageDflt<pPager->sectorSize ){
34446         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34447           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34448         }else{
34449           szPageDflt = (u16)pPager->sectorSize;
34450         }
34451       }
34452 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
34453       {
34454         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34455         int ii;
34456         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34457         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34458         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34459         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34460           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34461             szPageDflt = ii;
34462           }
34463         }
34464       }
34465 #endif
34466     }
34467   }else{
34468     /* If a temporary file is requested, it is not opened immediately.
34469     ** In this case we accept the default page size and delay actually
34470     ** opening the file until the first call to OsWrite().
34471     **
34472     ** This branch is also run for an in-memory database. An in-memory
34473     ** database is the same as a temp-file that is never written out to
34474     ** disk and uses an in-memory rollback journal.
34475     */ 
34476     tempFile = 1;
34477     pPager->state = PAGER_EXCLUSIVE;
34478   }
34479
34480   /* The following call to PagerSetPagesize() serves to set the value of 
34481   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34482   */
34483   if( rc==SQLITE_OK ){
34484     assert( pPager->memDb==0 );
34485     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt);
34486     testcase( rc!=SQLITE_OK );
34487   }
34488
34489   /* If an error occured in either of the blocks above, free the 
34490   ** Pager structure and close the file.
34491   */
34492   if( rc!=SQLITE_OK ){
34493     assert( !pPager->pTmpSpace );
34494     sqlite3OsClose(pPager->fd);
34495     sqlite3_free(pPager);
34496     return rc;
34497   }
34498
34499   /* Initialize the PCache object. */
34500   nExtra = FORCE_ALIGNMENT(nExtra);
34501   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34502                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34503
34504   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34505   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34506
34507   pPager->useJournal = (u8)useJournal;
34508   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34509   /* pPager->stmtOpen = 0; */
34510   /* pPager->stmtInUse = 0; */
34511   /* pPager->nRef = 0; */
34512   pPager->dbSizeValid = (u8)memDb;
34513   /* pPager->stmtSize = 0; */
34514   /* pPager->stmtJSize = 0; */
34515   /* pPager->nPage = 0; */
34516   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34517   /* pPager->state = PAGER_UNLOCK; */
34518   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34519   /* pPager->errMask = 0; */
34520   pPager->tempFile = (u8)tempFile;
34521   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
34522           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34523   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34524   pPager->exclusiveMode = (u8)tempFile; 
34525   pPager->changeCountDone = pPager->tempFile;
34526   pPager->memDb = (u8)memDb;
34527   pPager->readOnly = (u8)readOnly;
34528   /* pPager->needSync = 0; */
34529   pPager->noSync = (pPager->tempFile || !useJournal) ?1:0;
34530   pPager->fullSync = pPager->noSync ?0:1;
34531   pPager->sync_flags = SQLITE_SYNC_NORMAL;
34532   /* pPager->pFirst = 0; */
34533   /* pPager->pFirstSynced = 0; */
34534   /* pPager->pLast = 0; */
34535   pPager->nExtra = nExtra;
34536   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34537   assert( isOpen(pPager->fd) || tempFile );
34538   setSectorSize(pPager);
34539   if( memDb ){
34540     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34541   }
34542   /* pPager->xBusyHandler = 0; */
34543   /* pPager->pBusyHandlerArg = 0; */
34544   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34545   *ppPager = pPager;
34546   return SQLITE_OK;
34547 }
34548
34549
34550
34551 /*
34552 ** This function is called after transitioning from PAGER_UNLOCK to
34553 ** PAGER_SHARED state. It tests if there is a hot journal present in
34554 ** the file-system for the given pager. A hot journal is one that 
34555 ** needs to be played back. According to this function, a hot-journal
34556 ** file exists if the following three criteria are met:
34557 **
34558 **   * The journal file exists in the file system, and
34559 **   * No process holds a RESERVED or greater lock on the database file, and
34560 **   * The database file itself is greater than 0 bytes in size.
34561 **
34562 ** If the current size of the database file is 0 but a journal file
34563 ** exists, that is probably an old journal left over from a prior
34564 ** database with the same name. In this case the journal file is
34565 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34566 ** is returned.
34567 **
34568 ** This routine does not open the journal file to examine its
34569 ** content.  Hence, the journal might contain the name of a master
34570 ** journal file that has been deleted, and hence not be hot.  Or
34571 ** the header of the journal might be zeroed out.  This routine
34572 ** does not discover these cases of a non-hot journal - if the
34573 ** journal file exists and is not empty this routine assumes it
34574 ** is hot.  The pager_playback() routine will discover that the
34575 ** journal file is not really hot and will no-op.
34576 **
34577 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
34578 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34579 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34580 ** to determine whether or not a hot-journal file exists, the IO error
34581 ** code is returned and the value of *pExists is undefined.
34582 */
34583 static int hasHotJournal(Pager *pPager, int *pExists){
34584   sqlite3_vfs * const pVfs = pPager->pVfs;
34585   int rc;                       /* Return code */
34586   int exists = 0;               /* True if a journal file is present */
34587   int locked = 0;               /* True if some process holds a RESERVED lock */
34588
34589   assert( pPager!=0 );
34590   assert( pPager->useJournal );
34591   assert( isOpen(pPager->fd) );
34592
34593   *pExists = 0;
34594   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34595   if( rc==SQLITE_OK && exists ){
34596     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34597     if( rc==SQLITE_OK && !locked ){
34598       int nPage;
34599       rc = sqlite3PagerPagecount(pPager, &nPage);
34600       if( rc==SQLITE_OK ){
34601        if( nPage==0 ){
34602           sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34603         }else{
34604           *pExists = 1;
34605         }
34606       }
34607     }
34608   }
34609   return rc;
34610 }
34611
34612 /*
34613 ** Read the content for page pPg out of the database file and into 
34614 ** pPg->pData. A shared lock or greater must be held on the database
34615 ** file before this function is called.
34616 **
34617 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34618 ** the value read from the database file.
34619 **
34620 ** If an IO error occurs, then the IO error is returned to the caller.
34621 ** Otherwise, SQLITE_OK is returned.
34622 */
34623 static int readDbPage(PgHdr *pPg){
34624   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34625   Pgno pgno = pPg->pgno;       /* Page number to read */
34626   int rc;                      /* Return code */
34627   i64 iOffset;                 /* Byte offset of file to read from */
34628
34629   assert( pPager->state>=PAGER_SHARED && !MEMDB );
34630
34631   if( !isOpen(pPager->fd) ){
34632     assert( pPager->tempFile );
34633     memset(pPg->pData, 0, pPager->pageSize);
34634     return SQLITE_IOERR_SHORT_READ;
34635   }
34636   iOffset = (pgno-1)*(i64)pPager->pageSize;
34637   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34638   if( pgno==1 ){
34639     u8 *dbFileVers = &((u8*)pPg->pData)[24];
34640     memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34641   }
34642   CODEC1(pPager, pPg->pData, pgno, 3);
34643
34644   PAGER_INCR(sqlite3_pager_readdb_count);
34645   PAGER_INCR(pPager->nRead);
34646   IOTRACE(("PGIN %p %d\n", pPager, pgno));
34647   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34648                PAGERID(pPager), pgno, pager_pagehash(pPg)));
34649
34650   return rc;
34651 }
34652
34653 /*
34654 ** This function is called whenever the upper layer requests a database
34655 ** page is requested, before the cache is checked for a suitable page
34656 ** or any data is read from the database. It performs the following
34657 ** two functions:
34658 **
34659 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34660 **      on the database file), then an attempt is made to obtain a
34661 **      SHARED lock on the database file. Immediately after obtaining
34662 **      the SHARED lock, the file-system is checked for a hot-journal,
34663 **      which is played back if present. Following any hot-journal 
34664 **      rollback, the contents of the cache are validated by checking
34665 **      the 'change-counter' field of the database file header and
34666 **      discarded if they are found to be invalid.
34667 **
34668 **   2) If the pager is running in exclusive-mode, and there are currently
34669 **      no outstanding references to any pages, and is in the error state,
34670 **      then an attempt is made to clear the error state by discarding
34671 **      the contents of the page cache and rolling back any open journal
34672 **      file.
34673 **
34674 ** If the operation described by (2) above is not attempted, and if the
34675 ** pager is in an error state other than SQLITE_FULL when this is called,
34676 ** the error state error code is returned. It is permitted to read the
34677 ** database when in SQLITE_FULL error state.
34678 **
34679 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34680 ** IO error occurs while locking the database, checking for a hot-journal
34681 ** file or rolling back a journal file, the IO error code is returned.
34682 */
34683 static int pagerSharedLock(Pager *pPager){
34684   int rc = SQLITE_OK;                /* Return code */
34685   int isErrorReset = 0;              /* True if recovering from error state */
34686
34687   /* If this database is opened for exclusive access, has no outstanding 
34688   ** page references and is in an error-state, this is a chance to clear
34689   ** the error. Discard the contents of the pager-cache and treat any
34690   ** open journal file as a hot-journal.
34691   */
34692   if( !MEMDB && pPager->exclusiveMode 
34693    && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
34694   ){
34695     if( isOpen(pPager->jfd) ){
34696       isErrorReset = 1;
34697     }
34698     pPager->errCode = SQLITE_OK;
34699     pager_reset(pPager);
34700   }
34701
34702   /* If the pager is still in an error state, do not proceed. The error 
34703   ** state will be cleared at some point in the future when all page 
34704   ** references are dropped and the cache can be discarded.
34705   */
34706   if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
34707     return pPager->errCode;
34708   }
34709
34710   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
34711     sqlite3_vfs * const pVfs = pPager->pVfs;
34712     int isHotJournal = 0;
34713     assert( !MEMDB );
34714     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34715     if( !pPager->noReadlock ){
34716       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
34717       if( rc!=SQLITE_OK ){
34718         assert( pPager->state==PAGER_UNLOCK );
34719         return pager_error(pPager, rc);
34720       }
34721     }else if( pPager->state==PAGER_UNLOCK ){
34722       pPager->state = PAGER_SHARED;
34723     }
34724     assert( pPager->state>=SHARED_LOCK );
34725
34726     /* If a journal file exists, and there is no RESERVED lock on the
34727     ** database file, then it either needs to be played back or deleted.
34728     */
34729     if( !isErrorReset ){
34730       rc = hasHotJournal(pPager, &isHotJournal);
34731       if( rc!=SQLITE_OK ){
34732         goto failed;
34733       }
34734     }
34735     if( isErrorReset || isHotJournal ){
34736       /* Get an EXCLUSIVE lock on the database file. At this point it is
34737       ** important that a RESERVED lock is not obtained on the way to the
34738       ** EXCLUSIVE lock. If it were, another process might open the
34739       ** database file, detect the RESERVED lock, and conclude that the
34740       ** database is safe to read while this process is still rolling the 
34741       ** hot-journal back.
34742       ** 
34743       ** Because the intermediate RESERVED lock is not requested, any
34744       ** other process attempting to access the database file will get to 
34745       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
34746       ** on the database file.
34747       */
34748       if( pPager->state<EXCLUSIVE_LOCK ){
34749         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
34750         if( rc!=SQLITE_OK ){
34751           rc = pager_error(pPager, rc);
34752           goto failed;
34753         }
34754         pPager->state = PAGER_EXCLUSIVE;
34755       }
34756  
34757       /* Open the journal for read/write access. This is because in 
34758       ** exclusive-access mode the file descriptor will be kept open and
34759       ** possibly used for a transaction later on. On some systems, the
34760       ** OsTruncate() call used in exclusive-access mode also requires
34761       ** a read/write file handle.
34762       */
34763       if( !isOpen(pPager->jfd) ){
34764         int res;
34765         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
34766         if( rc==SQLITE_OK ){
34767           if( res ){
34768             int fout = 0;
34769             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
34770             assert( !pPager->tempFile );
34771             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
34772             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
34773             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
34774               rc = SQLITE_CANTOPEN;
34775               sqlite3OsClose(pPager->jfd);
34776             }
34777           }else{
34778             /* If the journal does not exist, that means some other process
34779             ** has already rolled it back */
34780             rc = SQLITE_BUSY;
34781           }
34782         }
34783       }
34784       if( rc!=SQLITE_OK ){
34785         goto failed;
34786       }
34787
34788       /* TODO: Why are these cleared here? Is it necessary? */
34789       pPager->journalStarted = 0;
34790       pPager->journalOff = 0;
34791       pPager->setMaster = 0;
34792       pPager->journalHdr = 0;
34793  
34794       /* Playback and delete the journal.  Drop the database write
34795       ** lock and reacquire the read lock. Purge the cache before
34796       ** playing back the hot-journal so that we don't end up with
34797       ** an inconsistent cache.
34798       */
34799       rc = pager_playback(pPager, 1);
34800       if( rc!=SQLITE_OK ){
34801         rc = pager_error(pPager, rc);
34802         goto failed;
34803       }
34804       assert( (pPager->state==PAGER_SHARED)
34805            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
34806       );
34807     }
34808
34809     if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
34810       /* The shared-lock has just been acquired on the database file
34811       ** and there are already pages in the cache (from a previous
34812       ** read or write transaction).  Check to see if the database
34813       ** has been modified.  If the database has changed, flush the
34814       ** cache.
34815       **
34816       ** Database changes is detected by looking at 15 bytes beginning
34817       ** at offset 24 into the file.  The first 4 of these 16 bytes are
34818       ** a 32-bit counter that is incremented with each change.  The
34819       ** other bytes change randomly with each file change when
34820       ** a codec is in use.
34821       ** 
34822       ** There is a vanishingly small chance that a change will not be 
34823       ** detected.  The chance of an undetected change is so small that
34824       ** it can be neglected.
34825       */
34826       char dbFileVers[sizeof(pPager->dbFileVers)];
34827       sqlite3PagerPagecount(pPager, 0);
34828
34829       if( pPager->errCode ){
34830         rc = pPager->errCode;
34831         goto failed;
34832       }
34833
34834       assert( pPager->dbSizeValid );
34835       if( pPager->dbSize>0 ){
34836         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
34837         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
34838         if( rc!=SQLITE_OK ){
34839           goto failed;
34840         }
34841       }else{
34842         memset(dbFileVers, 0, sizeof(dbFileVers));
34843       }
34844
34845       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
34846         pager_reset(pPager);
34847       }
34848     }
34849     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
34850   }
34851
34852  failed:
34853   if( rc!=SQLITE_OK ){
34854     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
34855     pager_unlock(pPager);
34856   }
34857   return rc;
34858 }
34859
34860 /*
34861 ** If the reference count has reached zero, rollback any active
34862 ** transaction and unlock the pager.
34863 */ 
34864 static void pagerUnlockIfUnused(Pager *pPager){
34865   if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
34866     pagerUnlockAndRollback(pPager);
34867   }
34868 }
34869
34870 /*
34871 ** Drop a page from the cache using sqlite3PcacheDrop().
34872 **
34873 ** If this means there are now no pages with references to them, a rollback
34874 ** occurs and the lock on the database is removed.
34875 */
34876 static void pagerDropPage(DbPage *pPg){
34877   Pager *pPager = pPg->pPager;
34878   sqlite3PcacheDrop(pPg);
34879   pagerUnlockIfUnused(pPager);
34880 }
34881
34882 /*
34883 ** Acquire a reference to page number pgno in pager pPager (a page
34884 ** reference has type DbPage*). If the requested reference is 
34885 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
34886 **
34887 ** This function calls pagerSharedLock() to obtain a SHARED lock on
34888 ** the database file if such a lock or greater is not already held.
34889 ** This may cause hot-journal rollback or a cache purge. See comments
34890 ** above function pagerSharedLock() for details.
34891 **
34892 ** If the requested page is already in the cache, it is returned. 
34893 ** Otherwise, a new page object is allocated and populated with data
34894 ** read from the database file. In some cases, the pcache module may
34895 ** choose not to allocate a new page object and may reuse an existing
34896 ** object with no outstanding references.
34897 **
34898 ** The extra data appended to a page is always initialized to zeros the 
34899 ** first time a page is loaded into memory. If the page requested is 
34900 ** already in the cache when this function is called, then the extra
34901 ** data is left as it was when the page object was last used.
34902 **
34903 ** If the database image is smaller than the requested page or if a 
34904 ** non-zero value is passed as the noContent parameter and the 
34905 ** requested page is not already stored in the cache, then no 
34906 ** actual disk read occurs. In this case the memory image of the 
34907 ** page is initialized to all zeros. 
34908 **
34909 ** If noContent is true, it means that we do not care about the contents
34910 ** of the page. This occurs in two seperate scenarios:
34911 **
34912 **   a) When reading a free-list leaf page from the database, and
34913 **
34914 **   b) When a savepoint is being rolled back and we need to load
34915 **      a new page into the cache to populate with the data read
34916 **      from the savepoint journal.
34917 **
34918 ** If noContent is true, then the data returned is zeroed instead of
34919 ** being read from the database. Additionally, the bits corresponding
34920 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
34921 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
34922 ** savepoints are set. This means if the page is made writable at any
34923 ** point in the future, using a call to sqlite3PagerWrite(), its contents
34924 ** will not be journaled. This saves IO.
34925 **
34926 ** The acquisition might fail for several reasons.  In all cases,
34927 ** an appropriate error code is returned and *ppPage is set to NULL.
34928 **
34929 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
34930 ** to find a page in the in-memory cache first.  If the page is not already
34931 ** in memory, this routine goes to disk to read it in whereas Lookup()
34932 ** just returns 0.  This routine acquires a read-lock the first time it
34933 ** has to go to disk, and could also playback an old journal if necessary.
34934 ** Since Lookup() never goes to disk, it never has to deal with locks
34935 ** or journal files.
34936 */
34937 SQLITE_PRIVATE int sqlite3PagerAcquire(
34938   Pager *pPager,      /* The pager open on the database file */
34939   Pgno pgno,          /* Page number to fetch */
34940   DbPage **ppPage,    /* Write a pointer to the page here */
34941   int noContent       /* Do not bother reading content from disk if true */
34942 ){
34943   PgHdr *pPg = 0;
34944   int rc;
34945
34946   assert( assert_pager_state(pPager) );
34947   assert( pPager->state==PAGER_UNLOCK 
34948        || sqlite3PcacheRefCount(pPager->pPCache)>0 
34949        || pgno==1
34950   );
34951
34952   /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
34953   ** number greater than this, or zero, is requested.
34954   */
34955   if( pgno>PAGER_MAX_PGNO || pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
34956     return SQLITE_CORRUPT_BKPT;
34957   }
34958
34959   /* Make sure we have not hit any critical errors.
34960   */ 
34961   assert( pPager!=0 );
34962   *ppPage = 0;
34963
34964   /* If this is the first page accessed, then get a SHARED lock
34965   ** on the database file. pagerSharedLock() is a no-op if 
34966   ** a database lock is already held.
34967   */
34968   rc = pagerSharedLock(pPager);
34969   if( rc!=SQLITE_OK ){
34970     return rc;
34971   }
34972   assert( pPager->state!=PAGER_UNLOCK );
34973
34974   rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
34975   if( rc!=SQLITE_OK ){
34976     return rc;
34977   }
34978   assert( pPg->pgno==pgno );
34979   assert( pPg->pPager==pPager || pPg->pPager==0 );
34980   if( pPg->pPager==0 ){
34981     /* The pager cache has created a new page. Its content needs to 
34982     ** be initialized.
34983     */
34984     int nMax;
34985     PAGER_INCR(pPager->nMiss);
34986     pPg->pPager = pPager;
34987
34988     rc = sqlite3PagerPagecount(pPager, &nMax);
34989     if( rc!=SQLITE_OK ){
34990       sqlite3PagerUnref(pPg);
34991       return rc;
34992     }
34993
34994     if( nMax<(int)pgno || MEMDB || noContent ){
34995       if( pgno>pPager->mxPgno ){
34996         sqlite3PagerUnref(pPg);
34997         return SQLITE_FULL;
34998       }
34999       if( noContent ){
35000         /* Failure to set the bits in the InJournal bit-vectors is benign.
35001         ** It merely means that we might do some extra work to journal a 
35002         ** page that does not need to be journaled.  Nevertheless, be sure 
35003         ** to test the case where a malloc error occurs while trying to set 
35004         ** a bit in a bit vector.
35005         */
35006         sqlite3BeginBenignMalloc();
35007         if( pgno<=pPager->dbOrigSize ){
35008           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35009           testcase( rc==SQLITE_NOMEM );
35010         }
35011         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35012         testcase( rc==SQLITE_NOMEM );
35013         sqlite3EndBenignMalloc();
35014       }else{
35015         memset(pPg->pData, 0, pPager->pageSize);
35016       }
35017       IOTRACE(("ZERO %p %d\n", pPager, pgno));
35018     }else{
35019       assert( pPg->pPager==pPager );
35020       rc = readDbPage(pPg);
35021       if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
35022         pagerDropPage(pPg);
35023         return rc;
35024       }
35025     }
35026 #ifdef SQLITE_CHECK_PAGES
35027     pPg->pageHash = pager_pagehash(pPg);
35028 #endif
35029   }else{
35030     /* The requested page is in the page cache. */
35031     PAGER_INCR(pPager->nHit);
35032   }
35033
35034   *ppPage = pPg;
35035   return SQLITE_OK;
35036 }
35037
35038 /*
35039 ** Acquire a page if it is already in the in-memory cache.  Do
35040 ** not read the page from disk.  Return a pointer to the page,
35041 ** or 0 if the page is not in cache. Also, return 0 if the 
35042 ** pager is in PAGER_UNLOCK state when this function is called,
35043 ** or if the pager is in an error state other than SQLITE_FULL.
35044 **
35045 ** See also sqlite3PagerGet().  The difference between this routine
35046 ** and sqlite3PagerGet() is that _get() will go to the disk and read
35047 ** in the page if the page is not already in cache.  This routine
35048 ** returns NULL if the page is not in cache or if a disk I/O error 
35049 ** has ever happened.
35050 */
35051 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35052   PgHdr *pPg = 0;
35053   assert( pPager!=0 );
35054   assert( pgno!=0 );
35055
35056   if( (pPager->state!=PAGER_UNLOCK)
35057    && (pPager->errCode==SQLITE_OK || pPager->errCode==SQLITE_FULL)
35058   ){
35059     sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35060   }
35061
35062   return pPg;
35063 }
35064
35065 /*
35066 ** Release a page reference.
35067 **
35068 ** If the number of references to the page drop to zero, then the
35069 ** page is added to the LRU list.  When all references to all pages
35070 ** are released, a rollback occurs and the lock on the database is
35071 ** removed.
35072 */
35073 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35074   if( pPg ){
35075     Pager *pPager = pPg->pPager;
35076     sqlite3PcacheRelease(pPg);
35077     pagerUnlockIfUnused(pPager);
35078   }
35079 }
35080
35081 /*
35082 ** If the main journal file has already been opened, ensure that the
35083 ** sub-journal file is open too. If the main journal is not open,
35084 ** this function is a no-op.
35085 **
35086 ** SQLITE_OK is returned if everything goes according to plan. 
35087 ** An SQLITE_IOERR_XXX error code is returned if a call to 
35088 ** sqlite3OsOpen() fails.
35089 */
35090 static int openSubJournal(Pager *pPager){
35091   int rc = SQLITE_OK;
35092   if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35093     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35094       sqlite3MemJournalOpen(pPager->sjfd);
35095     }else{
35096       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35097     }
35098   }
35099   return rc;
35100 }
35101
35102 /*
35103 ** This function is called at the start of every write transaction.
35104 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
35105 ** file when this routine is called.
35106 **
35107 ** Open the journal file for pager pPager and write a journal header
35108 ** to the start of it. If there are active savepoints, open the sub-journal
35109 ** as well. This function is only used when the journal file is being 
35110 ** opened to write a rollback log for a transaction. It is not used 
35111 ** when opening a hot journal file to roll it back.
35112 **
35113 ** If the journal file is already open (as it may be in exclusive mode),
35114 ** then this function just writes a journal header to the start of the
35115 ** already open file. 
35116 **
35117 ** Whether or not the journal file is opened by this function, the
35118 ** Pager.pInJournal bitvec structure is allocated.
35119 **
35120 ** Return SQLITE_OK if everything is successful. Otherwise, return 
35121 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
35122 ** an IO error code if opening or writing the journal file fails.
35123 */
35124 static int pager_open_journal(Pager *pPager){
35125   int rc = SQLITE_OK;                        /* Return code */
35126   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35127
35128   assert( pPager->state>=PAGER_RESERVED );
35129   assert( pPager->useJournal );
35130   assert( pPager->pInJournal==0 );
35131   
35132   /* If already in the error state, this function is a no-op. */
35133   if( pPager->errCode ){
35134     return pPager->errCode;
35135   }
35136
35137   /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35138   ** the call to PagerPagecount() can be removed.
35139   */
35140   testcase( pPager->dbSizeValid==0 );
35141   sqlite3PagerPagecount(pPager, 0);
35142
35143   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35144   if( pPager->pInJournal==0 ){
35145     return SQLITE_NOMEM;
35146   }
35147
35148   /* Open the journal file if it is not already open. */
35149   if( !isOpen(pPager->jfd) ){
35150     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35151       sqlite3MemJournalOpen(pPager->jfd);
35152     }else{
35153       const int flags =                   /* VFS flags to open journal file */
35154         SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE|
35155         (pPager->tempFile ? 
35156           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35157           (SQLITE_OPEN_MAIN_JOURNAL)
35158         );
35159 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35160       rc = sqlite3JournalOpen(
35161           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35162       );
35163 #else
35164       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35165 #endif
35166     }
35167     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35168   }
35169
35170
35171   /* Write the first journal header to the journal file and open 
35172   ** the sub-journal if necessary.
35173   */
35174   if( rc==SQLITE_OK ){
35175     /* TODO: Check if all of these are really required. */
35176     pPager->dbOrigSize = pPager->dbSize;
35177     pPager->journalStarted = 0;
35178     pPager->needSync = 0;
35179     pPager->nRec = 0;
35180     pPager->journalOff = 0;
35181     pPager->setMaster = 0;
35182     pPager->journalHdr = 0;
35183     rc = writeJournalHdr(pPager);
35184   }
35185   if( rc==SQLITE_OK && pPager->nSavepoint ){
35186     rc = openSubJournal(pPager);
35187   }
35188
35189   if( rc!=SQLITE_OK ){
35190     sqlite3BitvecDestroy(pPager->pInJournal);
35191     pPager->pInJournal = 0;
35192   }
35193   return rc;
35194 }
35195
35196 /*
35197 ** Begin a write-transaction on the specified pager object. If a 
35198 ** write-transaction has already been opened, this function is a no-op.
35199 **
35200 ** If the exFlag argument is false, then acquire at least a RESERVED
35201 ** lock on the database file. If exFlag is true, then acquire at least
35202 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
35203 ** functions need be called.
35204 **
35205 ** If this is not a temporary or in-memory file and, the journal file is 
35206 ** opened if it has not been already. For a temporary file, the opening 
35207 ** of the journal file is deferred until there is an actual need to 
35208 ** write to the journal. TODO: Why handle temporary files differently?
35209 **
35210 ** If the journal file is opened (or if it is already open), then a
35211 ** journal-header is written to the start of it.
35212 */
35213 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag){
35214   int rc = SQLITE_OK;
35215   assert( pPager->state!=PAGER_UNLOCK );
35216   if( pPager->state==PAGER_SHARED ){
35217     assert( pPager->pInJournal==0 );
35218     assert( !MEMDB && !pPager->tempFile );
35219
35220     /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35221     ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35222     ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35223     ** lock, but not when obtaining the RESERVED lock.
35224     */
35225     rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35226     if( rc==SQLITE_OK ){
35227       pPager->state = PAGER_RESERVED;
35228       if( exFlag ){
35229         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35230       }
35231     }
35232
35233     /* If the required locks were successfully obtained, open the journal
35234     ** file and write the first journal-header to it.
35235     */
35236     if( rc==SQLITE_OK && pPager->useJournal
35237      && pPager->journalMode!=PAGER_JOURNALMODE_OFF 
35238     ){
35239       rc = pager_open_journal(pPager);
35240     }
35241   }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35242     /* This happens when the pager was in exclusive-access mode the last
35243     ** time a (read or write) transaction was successfully concluded
35244     ** by this connection. Instead of deleting the journal file it was 
35245     ** kept open and either was truncated to 0 bytes or its header was
35246     ** overwritten with zeros.
35247     */
35248     assert( pPager->nRec==0 );
35249     assert( pPager->dbOrigSize==0 );
35250     assert( pPager->pInJournal==0 );
35251     rc = pager_open_journal(pPager);
35252   }
35253
35254   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35255   assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35256   return rc;
35257 }
35258
35259 /*
35260 ** Mark a single data page as writeable. The page is written into the 
35261 ** main journal or sub-journal as required. If the page is written into
35262 ** one of the journals, the corresponding bit is set in the 
35263 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35264 ** of any open savepoints as appropriate.
35265 */
35266 static int pager_write(PgHdr *pPg){
35267   void *pData = pPg->pData;
35268   Pager *pPager = pPg->pPager;
35269   int rc = SQLITE_OK;
35270
35271   /* Check for errors
35272   */
35273   if( pPager->errCode ){ 
35274     return pPager->errCode;
35275   }
35276   if( pPager->readOnly ){
35277     return SQLITE_PERM;
35278   }
35279
35280   assert( !pPager->setMaster );
35281
35282   CHECK_PAGE(pPg);
35283
35284   /* Mark the page as dirty.  If the page has already been written
35285   ** to the journal then we can return right away.
35286   */
35287   sqlite3PcacheMakeDirty(pPg);
35288   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35289     pPager->dbModified = 1;
35290   }else{
35291
35292     /* If we get this far, it means that the page needs to be
35293     ** written to the transaction journal or the ckeckpoint journal
35294     ** or both.
35295     **
35296     ** First check to see that the transaction journal exists and
35297     ** create it if it does not.
35298     */
35299     assert( pPager->state!=PAGER_UNLOCK );
35300     rc = sqlite3PagerBegin(pPager, 0);
35301     if( rc!=SQLITE_OK ){
35302       return rc;
35303     }
35304     assert( pPager->state>=PAGER_RESERVED );
35305     if( !isOpen(pPager->jfd) && pPager->useJournal
35306           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35307       rc = pager_open_journal(pPager);
35308       if( rc!=SQLITE_OK ) return rc;
35309     }
35310     pPager->dbModified = 1;
35311   
35312     /* The transaction journal now exists and we have a RESERVED or an
35313     ** EXCLUSIVE lock on the main database file.  Write the current page to
35314     ** the transaction journal if it is not there already.
35315     */
35316     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35317       if( pPg->pgno<=pPager->dbOrigSize ){
35318         u32 cksum;
35319         char *pData2;
35320
35321         /* We should never write to the journal file the page that
35322         ** contains the database locks.  The following assert verifies
35323         ** that we do not. */
35324         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35325         pData2 = CODEC2(pPager, pData, pPg->pgno, 7);
35326         cksum = pager_cksum(pPager, (u8*)pData2);
35327         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35328         if( rc==SQLITE_OK ){
35329           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35330                               pPager->journalOff + 4);
35331           pPager->journalOff += pPager->pageSize+4;
35332         }
35333         if( rc==SQLITE_OK ){
35334           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35335           pPager->journalOff += 4;
35336         }
35337         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
35338                  pPager->journalOff, pPager->pageSize));
35339         PAGER_INCR(sqlite3_pager_writej_count);
35340         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35341              PAGERID(pPager), pPg->pgno, 
35342              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35343
35344         /* Even if an IO or diskfull error occurred while journalling the
35345         ** page in the block above, set the need-sync flag for the page.
35346         ** Otherwise, when the transaction is rolled back, the logic in
35347         ** playback_one_page() will think that the page needs to be restored
35348         ** in the database file. And if an IO error occurs while doing so,
35349         ** then corruption may follow.
35350         */
35351         if( !pPager->noSync ){
35352           pPg->flags |= PGHDR_NEED_SYNC;
35353           pPager->needSync = 1;
35354         }
35355
35356         /* An error has occured writing to the journal file. The 
35357         ** transaction will be rolled back by the layer above.
35358         */
35359         if( rc!=SQLITE_OK ){
35360           return rc;
35361         }
35362
35363         pPager->nRec++;
35364         assert( pPager->pInJournal!=0 );
35365         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35366         testcase( rc==SQLITE_NOMEM );
35367         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35368         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35369         if( rc!=SQLITE_OK ){
35370           assert( rc==SQLITE_NOMEM );
35371           return rc;
35372         }
35373       }else{
35374         if( !pPager->journalStarted && !pPager->noSync ){
35375           pPg->flags |= PGHDR_NEED_SYNC;
35376           pPager->needSync = 1;
35377         }
35378         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35379                 PAGERID(pPager), pPg->pgno,
35380                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35381       }
35382     }
35383   
35384     /* If the statement journal is open and the page is not in it,
35385     ** then write the current page to the statement journal.  Note that
35386     ** the statement journal format differs from the standard journal format
35387     ** in that it omits the checksums and the header.
35388     */
35389     if( subjRequiresPage(pPg) ){
35390       rc = subjournalPage(pPg);
35391     }
35392   }
35393
35394   /* Update the database size and return.
35395   */
35396   assert( pPager->state>=PAGER_SHARED );
35397   if( pPager->dbSize<pPg->pgno ){
35398     pPager->dbSize = pPg->pgno;
35399   }
35400   return rc;
35401 }
35402
35403 /*
35404 ** Mark a data page as writeable. This routine must be called before 
35405 ** making changes to a page. The caller must check the return value 
35406 ** of this function and be careful not to change any page data unless 
35407 ** this routine returns SQLITE_OK.
35408 **
35409 ** The difference between this function and pager_write() is that this
35410 ** function also deals with the special case where 2 or more pages
35411 ** fit on a single disk sector. In this case all co-resident pages
35412 ** must have been written to the journal file before returning.
35413 **
35414 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35415 ** as appropriate. Otherwise, SQLITE_OK.
35416 */
35417 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35418   int rc = SQLITE_OK;
35419
35420   PgHdr *pPg = pDbPage;
35421   Pager *pPager = pPg->pPager;
35422   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35423
35424   if( nPagePerSector>1 ){
35425     Pgno nPageCount;          /* Total number of pages in database file */
35426     Pgno pg1;                 /* First page of the sector pPg is located on. */
35427     int nPage;                /* Number of pages starting at pg1 to journal */
35428     int ii;                   /* Loop counter */
35429     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35430
35431     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35432     ** header to be written between the pages journaled by this function.
35433     */
35434     assert( !MEMDB );
35435     assert( pPager->doNotSync==0 );
35436     pPager->doNotSync = 1;
35437
35438     /* This trick assumes that both the page-size and sector-size are
35439     ** an integer power of 2. It sets variable pg1 to the identifier
35440     ** of the first page of the sector pPg is located on.
35441     */
35442     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35443
35444     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35445     if( pPg->pgno>nPageCount ){
35446       nPage = (pPg->pgno - pg1)+1;
35447     }else if( (pg1+nPagePerSector-1)>nPageCount ){
35448       nPage = nPageCount+1-pg1;
35449     }else{
35450       nPage = nPagePerSector;
35451     }
35452     assert(nPage>0);
35453     assert(pg1<=pPg->pgno);
35454     assert((pg1+nPage)>pPg->pgno);
35455
35456     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35457       Pgno pg = pg1+ii;
35458       PgHdr *pPage;
35459       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35460         if( pg!=PAGER_MJ_PGNO(pPager) ){
35461           rc = sqlite3PagerGet(pPager, pg, &pPage);
35462           if( rc==SQLITE_OK ){
35463             rc = pager_write(pPage);
35464             if( pPage->flags&PGHDR_NEED_SYNC ){
35465               needSync = 1;
35466               assert(pPager->needSync);
35467             }
35468             sqlite3PagerUnref(pPage);
35469           }
35470         }
35471       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35472         if( pPage->flags&PGHDR_NEED_SYNC ){
35473           needSync = 1;
35474         }
35475         sqlite3PagerUnref(pPage);
35476       }
35477     }
35478
35479     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
35480     ** starting at pg1, then it needs to be set for all of them. Because
35481     ** writing to any of these nPage pages may damage the others, the
35482     ** journal file must contain sync()ed copies of all of them
35483     ** before any of them can be written out to the database file.
35484     */
35485     if( needSync ){
35486       assert( !MEMDB && pPager->noSync==0 );
35487       for(ii=0; ii<nPage && needSync; ii++){
35488         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35489         if( pPage ){
35490           pPage->flags |= PGHDR_NEED_SYNC;
35491           sqlite3PagerUnref(pPage);
35492         }
35493       }
35494       assert(pPager->needSync);
35495     }
35496
35497     assert( pPager->doNotSync==1 );
35498     pPager->doNotSync = 0;
35499   }else{
35500     rc = pager_write(pDbPage);
35501   }
35502   return rc;
35503 }
35504
35505 /*
35506 ** Return TRUE if the page given in the argument was previously passed
35507 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35508 ** to change the content of the page.
35509 */
35510 #ifndef NDEBUG
35511 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35512   return pPg->flags&PGHDR_DIRTY;
35513 }
35514 #endif
35515
35516 /*
35517 ** A call to this routine tells the pager that it is not necessary to
35518 ** write the information on page pPg back to the disk, even though
35519 ** that page might be marked as dirty.  This happens, for example, when
35520 ** the page has been added as a leaf of the freelist and so its
35521 ** content no longer matters.
35522 **
35523 ** The overlying software layer calls this routine when all of the data
35524 ** on the given page is unused. The pager marks the page as clean so
35525 ** that it does not get written to disk.
35526 **
35527 ** Tests show that this optimization can quadruple the speed of large 
35528 ** DELETE operations.
35529 */
35530 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35531   Pager *pPager = pPg->pPager;
35532   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35533     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35534     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35535     pPg->flags |= PGHDR_DONT_WRITE;
35536 #ifdef SQLITE_CHECK_PAGES
35537     pPg->pageHash = pager_pagehash(pPg);
35538 #endif
35539   }
35540 }
35541
35542 /*
35543 ** This routine is called to increment the value of the database file 
35544 ** change-counter, stored as a 4-byte big-endian integer starting at 
35545 ** byte offset 24 of the pager file.
35546 **
35547 ** If the isDirect flag is zero, then this is done by calling 
35548 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
35549 ** page data. In this case the file will be updated when the current
35550 ** transaction is committed.
35551 **
35552 ** The isDirect flag may only be non-zero if the library was compiled
35553 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35554 ** if isDirect is non-zero, then the database file is updated directly
35555 ** by writing an updated version of page 1 using a call to the 
35556 ** sqlite3OsWrite() function.
35557 */
35558 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35559   int rc = SQLITE_OK;
35560
35561   /* Declare and initialize constant integer 'isDirect'. If the
35562   ** atomic-write optimization is enabled in this build, then isDirect
35563   ** is initialized to the value passed as the isDirectMode parameter
35564   ** to this function. Otherwise, it is always set to zero.
35565   **
35566   ** The idea is that if the atomic-write optimization is not
35567   ** enabled at compile time, the compiler can omit the tests of
35568   ** 'isDirect' below, as well as the block enclosed in the
35569   ** "if( isDirect )" condition.
35570   */
35571 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
35572   const int isDirect = 0;
35573   assert( isDirectMode==0 );
35574   UNUSED_PARAMETER(isDirectMode);
35575 #else
35576   const int isDirect = isDirectMode;
35577 #endif
35578
35579   assert( pPager->state>=PAGER_RESERVED );
35580   if( !pPager->changeCountDone && pPager->dbSize>0 ){
35581     PgHdr *pPgHdr;                /* Reference to page 1 */
35582     u32 change_counter;           /* Initial value of change-counter field */
35583
35584     assert( !pPager->tempFile && isOpen(pPager->fd) );
35585
35586     /* Open page 1 of the file for writing. */
35587     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35588     assert( pPgHdr==0 || rc==SQLITE_OK );
35589
35590     /* If page one was fetched successfully, and this function is not
35591     ** operating in direct-mode, make page 1 writable.
35592     */
35593     if( rc==SQLITE_OK && !isDirect ){
35594       rc = sqlite3PagerWrite(pPgHdr);
35595     }
35596
35597     if( rc==SQLITE_OK ){
35598       /* Increment the value just read and write it back to byte 24. */
35599       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35600       change_counter++;
35601       put32bits(((char*)pPgHdr->pData)+24, change_counter);
35602
35603       /* If running in direct mode, write the contents of page 1 to the file. */
35604       if( isDirect ){
35605         const void *zBuf = pPgHdr->pData;
35606         assert( pPager->dbFileSize>0 );
35607         rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35608       }
35609
35610       /* If everything worked, set the changeCountDone flag. */
35611       if( rc==SQLITE_OK ){
35612         pPager->changeCountDone = 1;
35613       }
35614     }
35615
35616     /* Release the page reference. */
35617     sqlite3PagerUnref(pPgHdr);
35618   }
35619   return rc;
35620 }
35621
35622 /*
35623 ** Sync the pager file to disk. This is a no-op for in-memory files
35624 ** or pages with the Pager.noSync flag set.
35625 **
35626 ** If successful, or called on a pager for which it is a no-op, this
35627 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35628 */
35629 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35630   int rc;                              /* Return code */
35631   if( MEMDB || pPager->noSync ){
35632     rc = SQLITE_OK;
35633   }else{
35634     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35635   }
35636   return rc;
35637 }
35638
35639 /*
35640 ** Sync the database file for the pager pPager. zMaster points to the name
35641 ** of a master journal file that should be written into the individual
35642 ** journal file. zMaster may be NULL, which is interpreted as no master
35643 ** journal (a single database transaction).
35644 **
35645 ** This routine ensures that:
35646 **
35647 **   * The database file change-counter is updated,
35648 **   * the journal is synced (unless the atomic-write optimization is used),
35649 **   * all dirty pages are written to the database file, 
35650 **   * the database file is truncated (if required), and
35651 **   * the database file synced. 
35652 **
35653 ** The only thing that remains to commit the transaction is to finalize 
35654 ** (delete, truncate or zero the first part of) the journal file (or 
35655 ** delete the master journal file if specified).
35656 **
35657 ** Note that if zMaster==NULL, this does not overwrite a previous value
35658 ** passed to an sqlite3PagerCommitPhaseOne() call.
35659 **
35660 ** If the final parameter - noSync - is true, then the database file itself
35661 ** is not synced. The caller must call sqlite3PagerSync() directly to
35662 ** sync the database file before calling CommitPhaseTwo() to delete the
35663 ** journal file in this case.
35664 */
35665 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35666   Pager *pPager,                  /* Pager object */
35667   const char *zMaster,            /* If not NULL, the master journal name */
35668   int noSync                      /* True to omit the xSync on the db file */
35669 ){
35670   int rc = SQLITE_OK;             /* Return code */
35671
35672   if( pPager->errCode ){
35673     return pPager->errCode;
35674   }
35675
35676   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
35677       pPager->zFilename, zMaster, pPager->dbSize));
35678
35679   /* If this is an in-memory db, or no pages have been written to, or this
35680   ** function has already been called, it is a no-op.
35681   */
35682   if( MEMDB && pPager->dbModified ){
35683     sqlite3BackupRestart(pPager->pBackup);
35684   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
35685
35686     /* The following block updates the change-counter. Exactly how it
35687     ** does this depends on whether or not the atomic-update optimization
35688     ** was enabled at compile time, and if this transaction meets the 
35689     ** runtime criteria to use the operation: 
35690     **
35691     **    * The file-system supports the atomic-write property for
35692     **      blocks of size page-size, and 
35693     **    * This commit is not part of a multi-file transaction, and
35694     **    * Exactly one page has been modified and store in the journal file.
35695     **
35696     ** If the optimization was not enabled at compile time, then the
35697     ** pager_incr_changecounter() function is called to update the change
35698     ** counter in 'indirect-mode'. If the optimization is compiled in but
35699     ** is not applicable to this transaction, call sqlite3JournalCreate()
35700     ** to make sure the journal file has actually been created, then call
35701     ** pager_incr_changecounter() to update the change-counter in indirect
35702     ** mode. 
35703     **
35704     ** Otherwise, if the optimization is both enabled and applicable,
35705     ** then call pager_incr_changecounter() to update the change-counter
35706     ** in 'direct' mode. In this case the journal file will never be
35707     ** created for this transaction.
35708     */
35709 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35710     PgHdr *pPg;
35711     assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
35712     if( !zMaster && isOpen(pPager->jfd) 
35713      && pPager->journalOff==jrnlBufferSize(pPager) 
35714      && pPager->dbSize>=pPager->dbFileSize
35715      && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
35716     ){
35717       /* Update the db file change counter via the direct-write method. The 
35718       ** following call will modify the in-memory representation of page 1 
35719       ** to include the updated change counter and then write page 1 
35720       ** directly to the database file. Because of the atomic-write 
35721       ** property of the host file-system, this is safe.
35722       */
35723       rc = pager_incr_changecounter(pPager, 1);
35724     }else{
35725       rc = sqlite3JournalCreate(pPager->jfd);
35726       if( rc==SQLITE_OK ){
35727         rc = pager_incr_changecounter(pPager, 0);
35728       }
35729     }
35730 #else
35731     rc = pager_incr_changecounter(pPager, 0);
35732 #endif
35733     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35734
35735     /* If this transaction has made the database smaller, then all pages
35736     ** being discarded by the truncation must be written to the journal
35737     ** file. This can only happen in auto-vacuum mode.
35738     **
35739     ** Before reading the pages with page numbers larger than the 
35740     ** current value of Pager.dbSize, set dbSize back to the value
35741     ** that it took at the start of the transaction. Otherwise, the
35742     ** calls to sqlite3PagerGet() return zeroed pages instead of 
35743     ** reading data from the database file.
35744     */
35745 #ifndef SQLITE_OMIT_AUTOVACUUM
35746     if( pPager->dbSize<pPager->dbOrigSize
35747      && pPager->journalMode!=PAGER_JOURNALMODE_OFF 
35748     ){
35749       Pgno i;                                   /* Iterator variable */
35750       const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
35751       const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
35752       pPager->dbSize = pPager->dbOrigSize;
35753       for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
35754         if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
35755           PgHdr *pPage;             /* Page to journal */
35756           rc = sqlite3PagerGet(pPager, i, &pPage);
35757           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35758           rc = sqlite3PagerWrite(pPage);
35759           sqlite3PagerUnref(pPage);
35760           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35761         }
35762       } 
35763       pPager->dbSize = dbSize;
35764     }
35765 #endif
35766
35767     /* Write the master journal name into the journal file. If a master 
35768     ** journal file name has already been written to the journal file, 
35769     ** or if zMaster is NULL (no master journal), then this call is a no-op.
35770     */
35771     rc = writeMasterJournal(pPager, zMaster);
35772     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35773
35774     /* Sync the journal file. If the atomic-update optimization is being
35775     ** used, this call will not create the journal file or perform any
35776     ** real IO.
35777     */
35778     rc = syncJournal(pPager);
35779     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35780
35781     /* Write all dirty pages to the database file. */
35782     rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
35783     if( rc!=SQLITE_OK ){
35784       assert( rc!=SQLITE_IOERR_BLOCKED );
35785       goto commit_phase_one_exit;
35786     }
35787     sqlite3PcacheCleanAll(pPager->pPCache);
35788
35789     /* If the file on disk is not the same size as the database image,
35790     ** then use pager_truncate to grow or shrink the file here.
35791     */
35792     if( pPager->dbSize!=pPager->dbFileSize ){
35793       Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
35794       assert( pPager->state>=PAGER_EXCLUSIVE );
35795       rc = pager_truncate(pPager, nNew);
35796       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35797     }
35798
35799     /* Finally, sync the database file. */
35800     if( !pPager->noSync && !noSync ){
35801       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35802     }
35803     IOTRACE(("DBSYNC %p\n", pPager))
35804
35805     pPager->state = PAGER_SYNCED;
35806   }
35807
35808 commit_phase_one_exit:
35809   if( rc==SQLITE_IOERR_BLOCKED ){
35810     /* pager_incr_changecounter() may attempt to obtain an exclusive
35811     ** lock to spill the cache and return IOERR_BLOCKED. But since 
35812     ** there is no chance the cache is inconsistent, it is
35813     ** better to return SQLITE_BUSY.
35814     **/
35815     rc = SQLITE_BUSY;
35816   }
35817   return rc;
35818 }
35819
35820
35821 /*
35822 ** When this function is called, the database file has been completely
35823 ** updated to reflect the changes made by the current transaction and
35824 ** synced to disk. The journal file still exists in the file-system 
35825 ** though, and if a failure occurs at this point it will eventually
35826 ** be used as a hot-journal and the current transaction rolled back.
35827 **
35828 ** This function finalizes the journal file, either by deleting, 
35829 ** truncating or partially zeroing it, so that it cannot be used 
35830 ** for hot-journal rollback. Once this is done the transaction is
35831 ** irrevocably committed.
35832 **
35833 ** If an error occurs, an IO error code is returned and the pager
35834 ** moves into the error state. Otherwise, SQLITE_OK is returned.
35835 */
35836 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
35837   int rc = SQLITE_OK;                  /* Return code */
35838
35839   /* Do not proceed if the pager is already in the error state. */
35840   if( pPager->errCode ){
35841     return pPager->errCode;
35842   }
35843
35844   /* This function should not be called if the pager is not in at least
35845   ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
35846   ** nice to have this defensive block here anyway.
35847   */
35848   if( NEVER(pPager->state<PAGER_RESERVED) ){
35849     return SQLITE_ERROR;
35850   }
35851
35852   /* An optimization. If the database was not actually modified during
35853   ** this transaction, the pager is running in exclusive-mode and is
35854   ** using persistent journals, then this function is a no-op.
35855   **
35856   ** The start of the journal file currently contains a single journal 
35857   ** header with the nRec field set to 0. If such a journal is used as
35858   ** a hot-journal during hot-journal rollback, 0 changes will be made
35859   ** to the database file. So there is no need to zero the journal 
35860   ** header. Since the pager is in exclusive mode, there is no need
35861   ** to drop any locks either.
35862   */
35863   if( pPager->dbModified==0 && pPager->exclusiveMode 
35864    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
35865   ){
35866     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35867     return SQLITE_OK;
35868   }
35869
35870   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
35871   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
35872   rc = pager_end_transaction(pPager, pPager->setMaster);
35873   return pager_error(pPager, rc);
35874 }
35875
35876 /*
35877 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
35878 **
35879 ** This function performs two tasks:
35880 **
35881 **   1) It rolls back the journal file, restoring all database file and 
35882 **      in-memory cache pages to the state they were in when the transaction
35883 **      was opened, and
35884 **   2) It finalizes the journal file, so that it is not used for hot
35885 **      rollback at any point in the future.
35886 **
35887 ** subject to the following qualifications:
35888 **
35889 ** * If the journal file is not yet open when this function is called,
35890 **   then only (2) is performed. In this case there is no journal file
35891 **   to roll back.
35892 **
35893 ** * If in an error state other than SQLITE_FULL, then task (1) is 
35894 **   performed. If successful, task (2). Regardless of the outcome
35895 **   of either, the error state error code is returned to the caller
35896 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
35897 **
35898 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
35899 **   or not (1) is succussful, also attempt (2). If successful, return
35900 **   SQLITE_OK. Otherwise, enter the error state and return the first 
35901 **   error code encountered. 
35902 **
35903 **   In this case there is no chance that the database was written to. 
35904 **   So is safe to finalize the journal file even if the playback 
35905 **   (operation 1) failed. However the pager must enter the error state
35906 **   as the contents of the in-memory cache are now suspect.
35907 **
35908 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
35909 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
35910 **   otherwise enter the error state and return the error code from the 
35911 **   failing operation.
35912 **
35913 **   In this case the database file may have been written to. So if the
35914 **   playback operation did not succeed it would not be safe to finalize
35915 **   the journal file. It needs to be left in the file-system so that
35916 **   some other process can use it to restore the database state (by
35917 **   hot-journal rollback).
35918 */
35919 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
35920   int rc = SQLITE_OK;                  /* Return code */
35921   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
35922   if( !pPager->dbModified || !isOpen(pPager->jfd) ){
35923     rc = pager_end_transaction(pPager, pPager->setMaster);
35924   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
35925     if( pPager->state>=PAGER_EXCLUSIVE ){
35926       pager_playback(pPager, 0);
35927     }
35928     rc = pPager->errCode;
35929   }else{
35930     if( pPager->state==PAGER_RESERVED ){
35931       int rc2;
35932       rc = pager_playback(pPager, 0);
35933       rc2 = pager_end_transaction(pPager, pPager->setMaster);
35934       if( rc==SQLITE_OK ){
35935         rc = rc2;
35936       }
35937     }else{
35938       rc = pager_playback(pPager, 0);
35939     }
35940
35941     if( !MEMDB ){
35942       pPager->dbSizeValid = 0;
35943     }
35944
35945     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
35946     ** cache. So call pager_error() on the way out to make any error 
35947     ** persistent.
35948     */
35949     rc = pager_error(pPager, rc);
35950   }
35951   return rc;
35952 }
35953
35954 /*
35955 ** Return TRUE if the database file is opened read-only.  Return FALSE
35956 ** if the database is (in theory) writable.
35957 */
35958 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
35959   return pPager->readOnly;
35960 }
35961
35962 /*
35963 ** Return the number of references to the pager.
35964 */
35965 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
35966   return sqlite3PcacheRefCount(pPager->pPCache);
35967 }
35968
35969 /*
35970 ** Return the number of references to the specified page.
35971 */
35972 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
35973   return sqlite3PcachePageRefcount(pPage);
35974 }
35975
35976 #ifdef SQLITE_TEST
35977 /*
35978 ** This routine is used for testing and analysis only.
35979 */
35980 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
35981   static int a[11];
35982   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
35983   a[1] = sqlite3PcachePagecount(pPager->pPCache);
35984   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
35985   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
35986   a[4] = pPager->state;
35987   a[5] = pPager->errCode;
35988   a[6] = pPager->nHit;
35989   a[7] = pPager->nMiss;
35990   a[8] = 0;  /* Used to be pPager->nOvfl */
35991   a[9] = pPager->nRead;
35992   a[10] = pPager->nWrite;
35993   return a;
35994 }
35995 #endif
35996
35997 /*
35998 ** Return true if this is an in-memory pager.
35999 */
36000 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36001   return MEMDB;
36002 }
36003
36004 /*
36005 ** Check that there are at least nSavepoint savepoints open. If there are
36006 ** currently less than nSavepoints open, then open one or more savepoints
36007 ** to make up the difference. If the number of savepoints is already
36008 ** equal to nSavepoint, then this function is a no-op.
36009 **
36010 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
36011 ** occurs while opening the sub-journal file, then an IO error code is
36012 ** returned. Otherwise, SQLITE_OK.
36013 */
36014 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36015   int rc = SQLITE_OK;                       /* Return code */
36016   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36017
36018   if( nSavepoint>nCurrent && pPager->useJournal ){
36019     int ii;                                 /* Iterator variable */
36020     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36021
36022     /* Either there is no active journal or the sub-journal is open or 
36023     ** the journal is always stored in memory */
36024     assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36025             pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36026
36027     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36028     ** if the allocation fails. Otherwise, zero the new portion in case a 
36029     ** malloc failure occurs while populating it in the for(...) loop below.
36030     */
36031     aNew = (PagerSavepoint *)sqlite3Realloc(
36032         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36033     );
36034     if( !aNew ){
36035       return SQLITE_NOMEM;
36036     }
36037     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36038     pPager->aSavepoint = aNew;
36039     pPager->nSavepoint = nSavepoint;
36040
36041     /* Populate the PagerSavepoint structures just allocated. */
36042     for(ii=nCurrent; ii<nSavepoint; ii++){
36043       assert( pPager->dbSizeValid );
36044       aNew[ii].nOrig = pPager->dbSize;
36045       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
36046         aNew[ii].iOffset = pPager->journalOff;
36047       }else{
36048         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36049       }
36050       aNew[ii].iSubRec = pPager->nSubRec;
36051       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36052       if( !aNew[ii].pInSavepoint ){
36053         return SQLITE_NOMEM;
36054       }
36055     }
36056
36057     /* Open the sub-journal, if it is not already opened. */
36058     rc = openSubJournal(pPager);
36059   }
36060
36061   return rc;
36062 }
36063
36064 /*
36065 ** This function is called to rollback or release (commit) a savepoint.
36066 ** The savepoint to release or rollback need not be the most recently 
36067 ** created savepoint.
36068 **
36069 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36070 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36071 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36072 ** that have occured since the specified savepoint was created.
36073 **
36074 ** The savepoint to rollback or release is identified by parameter 
36075 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
36076 ** (the first created). A value of (Pager.nSavepoint-1) means operate
36077 ** on the most recently created savepoint. If iSavepoint is greater than
36078 ** (Pager.nSavepoint-1), then this function is a no-op.
36079 **
36080 ** If a negative value is passed to this function, then the current
36081 ** transaction is rolled back. This is different to calling 
36082 ** sqlite3PagerRollback() because this function does not terminate
36083 ** the transaction or unlock the database, it just restores the 
36084 ** contents of the database to its original state. 
36085 **
36086 ** In any case, all savepoints with an index greater than iSavepoint 
36087 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36088 ** then savepoint iSavepoint is also destroyed.
36089 **
36090 ** This function may return SQLITE_NOMEM if a memory allocation fails,
36091 ** or an IO error code if an IO error occurs while rolling back a 
36092 ** savepoint. If no errors occur, SQLITE_OK is returned.
36093 */ 
36094 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36095   int rc = SQLITE_OK;
36096
36097   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36098   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36099
36100   if( iSavepoint<pPager->nSavepoint ){
36101     int ii;            /* Iterator variable */
36102     int nNew;          /* Number of remaining savepoints after this op. */
36103
36104     /* Figure out how many savepoints will still be active after this
36105     ** operation. Store this value in nNew. Then free resources associated 
36106     ** with any savepoints that are destroyed by this operation.
36107     */
36108     nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
36109     for(ii=nNew; ii<pPager->nSavepoint; ii++){
36110       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36111     }
36112     pPager->nSavepoint = nNew;
36113
36114     /* If this is a rollback operation, playback the specified savepoint.
36115     ** If this is a temp-file, it is possible that the journal file has
36116     ** not yet been opened. In this case there have been no changes to
36117     ** the database file, so the playback operation can be skipped.
36118     */
36119     if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
36120       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36121       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36122       assert(rc!=SQLITE_DONE);
36123     }
36124   
36125     /* If this is a release of the outermost savepoint, truncate 
36126     ** the sub-journal to zero bytes in size. */
36127     if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
36128       assert( rc==SQLITE_OK );
36129       rc = sqlite3OsTruncate(pPager->sjfd, 0);
36130       pPager->nSubRec = 0;
36131     }
36132   }
36133   return rc;
36134 }
36135
36136 /*
36137 ** Return the full pathname of the database file.
36138 */
36139 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36140   return pPager->zFilename;
36141 }
36142
36143 /*
36144 ** Return the VFS structure for the pager.
36145 */
36146 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36147   return pPager->pVfs;
36148 }
36149
36150 /*
36151 ** Return the file handle for the database file associated
36152 ** with the pager.  This might return NULL if the file has
36153 ** not yet been opened.
36154 */
36155 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36156   return pPager->fd;
36157 }
36158
36159 /*
36160 ** Return the full pathname of the journal file.
36161 */
36162 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36163   return pPager->zJournal;
36164 }
36165
36166 /*
36167 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
36168 ** if fsync()s are executed normally.
36169 */
36170 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36171   return pPager->noSync;
36172 }
36173
36174 #ifdef SQLITE_HAS_CODEC
36175 /*
36176 ** Set the codec for this pager
36177 */
36178 SQLITE_PRIVATE void sqlite3PagerSetCodec(
36179   Pager *pPager,
36180   void *(*xCodec)(void*,void*,Pgno,int),
36181   void *pCodecArg
36182 ){
36183   pPager->xCodec = xCodec;
36184   pPager->pCodecArg = pCodecArg;
36185 }
36186 #endif
36187
36188 #ifndef SQLITE_OMIT_AUTOVACUUM
36189 /*
36190 ** Move the page pPg to location pgno in the file.
36191 **
36192 ** There must be no references to the page previously located at
36193 ** pgno (which we call pPgOld) though that page is allowed to be
36194 ** in cache.  If the page previously located at pgno is not already
36195 ** in the rollback journal, it is not put there by by this routine.
36196 **
36197 ** References to the page pPg remain valid. Updating any
36198 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36199 ** allocated along with the page) is the responsibility of the caller.
36200 **
36201 ** A transaction must be active when this routine is called. It used to be
36202 ** required that a statement transaction was not active, but this restriction
36203 ** has been removed (CREATE INDEX needs to move a page when a statement
36204 ** transaction is active).
36205 **
36206 ** If the fourth argument, isCommit, is non-zero, then this page is being
36207 ** moved as part of a database reorganization just before the transaction 
36208 ** is being committed. In this case, it is guaranteed that the database page 
36209 ** pPg refers to will not be written to again within this transaction.
36210 **
36211 ** This function may return SQLITE_NOMEM or an IO error code if an error
36212 ** occurs. Otherwise, it returns SQLITE_OK.
36213 */
36214 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36215   PgHdr *pPgOld;               /* The page being overwritten. */
36216   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36217   int rc;                      /* Return code */
36218
36219   assert( pPg->nRef>0 );
36220
36221   /* If the page being moved is dirty and has not been saved by the latest
36222   ** savepoint, then save the current contents of the page into the 
36223   ** sub-journal now. This is required to handle the following scenario:
36224   **
36225   **   BEGIN;
36226   **     <journal page X, then modify it in memory>
36227   **     SAVEPOINT one;
36228   **       <Move page X to location Y>
36229   **     ROLLBACK TO one;
36230   **
36231   ** If page X were not written to the sub-journal here, it would not
36232   ** be possible to restore its contents when the "ROLLBACK TO one"
36233   ** statement were is processed.
36234   **
36235   ** subjournalPage() may need to allocate space to store pPg->pgno into
36236   ** one or more savepoint bitvecs. This is the reason this function
36237   ** may return SQLITE_NOMEM.
36238   */
36239   if( pPg->flags&PGHDR_DIRTY 
36240    && subjRequiresPage(pPg)
36241    && SQLITE_OK!=(rc = subjournalPage(pPg))
36242   ){
36243     return rc;
36244   }
36245
36246   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
36247       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36248   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36249
36250   /* If the journal needs to be sync()ed before page pPg->pgno can
36251   ** be written to, store pPg->pgno in local variable needSyncPgno.
36252   **
36253   ** If the isCommit flag is set, there is no need to remember that
36254   ** the journal needs to be sync()ed before database page pPg->pgno 
36255   ** can be written to. The caller has already promised not to write to it.
36256   */
36257   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36258     needSyncPgno = pPg->pgno;
36259     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36260     assert( pPg->flags&PGHDR_DIRTY );
36261     assert( pPager->needSync );
36262   }
36263
36264   /* If the cache contains a page with page-number pgno, remove it
36265   ** from its hash chain. Also, if the PgHdr.needSync was set for 
36266   ** page pgno before the 'move' operation, it needs to be retained 
36267   ** for the page moved there.
36268   */
36269   pPg->flags &= ~PGHDR_NEED_SYNC;
36270   pPgOld = pager_lookup(pPager, pgno);
36271   assert( !pPgOld || pPgOld->nRef==1 );
36272   if( pPgOld ){
36273     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36274   }
36275
36276   sqlite3PcacheMove(pPg, pgno);
36277   if( pPgOld ){
36278     sqlite3PcacheDrop(pPgOld);
36279   }
36280
36281   sqlite3PcacheMakeDirty(pPg);
36282   pPager->dbModified = 1;
36283
36284   if( needSyncPgno ){
36285     /* If needSyncPgno is non-zero, then the journal file needs to be 
36286     ** sync()ed before any data is written to database file page needSyncPgno.
36287     ** Currently, no such page exists in the page-cache and the 
36288     ** "is journaled" bitvec flag has been set. This needs to be remedied by
36289     ** loading the page into the pager-cache and setting the PgHdr.needSync 
36290     ** flag.
36291     **
36292     ** If the attempt to load the page into the page-cache fails, (due
36293     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36294     ** array. Otherwise, if the page is loaded and written again in
36295     ** this transaction, it may be written to the database file before
36296     ** it is synced into the journal file. This way, it may end up in
36297     ** the journal file twice, but that is not a problem.
36298     **
36299     ** The sqlite3PagerGet() call may cause the journal to sync. So make
36300     ** sure the Pager.needSync flag is set too.
36301     */
36302     PgHdr *pPgHdr;
36303     assert( pPager->needSync );
36304     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36305     if( rc!=SQLITE_OK ){
36306       if( pPager->pInJournal && needSyncPgno<=pPager->dbOrigSize ){
36307         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno);
36308       }
36309       return rc;
36310     }
36311     pPager->needSync = 1;
36312     assert( pPager->noSync==0 && !MEMDB );
36313     pPgHdr->flags |= PGHDR_NEED_SYNC;
36314     sqlite3PcacheMakeDirty(pPgHdr);
36315     sqlite3PagerUnref(pPgHdr);
36316   }
36317
36318   return SQLITE_OK;
36319 }
36320 #endif
36321
36322 /*
36323 ** Return a pointer to the data for the specified page.
36324 */
36325 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36326   assert( pPg->nRef>0 || pPg->pPager->memDb );
36327   return pPg->pData;
36328 }
36329
36330 /*
36331 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
36332 ** allocated along with the specified page.
36333 */
36334 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36335   Pager *pPager = pPg->pPager;
36336   return (pPager?pPg->pExtra:0);
36337 }
36338
36339 /*
36340 ** Get/set the locking-mode for this pager. Parameter eMode must be one
36341 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
36342 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36343 ** the locking-mode is set to the value specified.
36344 **
36345 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36346 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36347 ** locking-mode.
36348 */
36349 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36350   assert( eMode==PAGER_LOCKINGMODE_QUERY
36351             || eMode==PAGER_LOCKINGMODE_NORMAL
36352             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36353   assert( PAGER_LOCKINGMODE_QUERY<0 );
36354   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36355   if( eMode>=0 && !pPager->tempFile ){
36356     pPager->exclusiveMode = (u8)eMode;
36357   }
36358   return (int)pPager->exclusiveMode;
36359 }
36360
36361 /*
36362 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36363 **
36364 **    PAGER_JOURNALMODE_QUERY
36365 **    PAGER_JOURNALMODE_DELETE
36366 **    PAGER_JOURNALMODE_TRUNCATE
36367 **    PAGER_JOURNALMODE_PERSIST
36368 **    PAGER_JOURNALMODE_OFF
36369 **    PAGER_JOURNALMODE_MEMORY
36370 **
36371 ** If the parameter is not _QUERY, then the journal-mode is set to the
36372 ** value specified.
36373 **
36374 ** The returned indicate the current (possibly updated) journal-mode.
36375 */
36376 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36377   if( !MEMDB ){
36378     assert( eMode==PAGER_JOURNALMODE_QUERY
36379               || eMode==PAGER_JOURNALMODE_DELETE
36380               || eMode==PAGER_JOURNALMODE_TRUNCATE
36381               || eMode==PAGER_JOURNALMODE_PERSIST
36382               || eMode==PAGER_JOURNALMODE_OFF 
36383               || eMode==PAGER_JOURNALMODE_MEMORY );
36384     assert( PAGER_JOURNALMODE_QUERY<0 );
36385     if( eMode>=0 ){
36386       pPager->journalMode = (u8)eMode;
36387     }else{
36388       assert( eMode==PAGER_JOURNALMODE_QUERY );
36389     }
36390   }
36391   return (int)pPager->journalMode;
36392 }
36393
36394 /*
36395 ** Get/set the size-limit used for persistent journal files.
36396 */
36397 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36398   if( iLimit>=-1 ){
36399     pPager->journalSizeLimit = iLimit;
36400   }
36401   return pPager->journalSizeLimit;
36402 }
36403
36404 /*
36405 ** Return a pointer to the pPager->pBackup variable. The backup module
36406 ** in backup.c maintains the content of this variable. This module
36407 ** uses it opaquely as an argument to sqlite3BackupRestart() and
36408 ** sqlite3BackupUpdate() only.
36409 */
36410 sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36411   return &pPager->pBackup;
36412 }
36413
36414 #endif /* SQLITE_OMIT_DISKIO */
36415
36416 /************** End of pager.c ***********************************************/
36417 /************** Begin file btmutex.c *****************************************/
36418 /*
36419 ** 2007 August 27
36420 **
36421 ** The author disclaims copyright to this source code.  In place of
36422 ** a legal notice, here is a blessing:
36423 **
36424 **    May you do good and not evil.
36425 **    May you find forgiveness for yourself and forgive others.
36426 **    May you share freely, never taking more than you give.
36427 **
36428 *************************************************************************
36429 **
36430 ** $Id: btmutex.c,v 1.12 2008/11/17 19:18:55 danielk1977 Exp $
36431 **
36432 ** This file contains code used to implement mutexes on Btree objects.
36433 ** This code really belongs in btree.c.  But btree.c is getting too
36434 ** big and we want to break it down some.  This packaged seemed like
36435 ** a good breakout.
36436 */
36437 /************** Include btreeInt.h in the middle of btmutex.c ****************/
36438 /************** Begin file btreeInt.h ****************************************/
36439 /*
36440 ** 2004 April 6
36441 **
36442 ** The author disclaims copyright to this source code.  In place of
36443 ** a legal notice, here is a blessing:
36444 **
36445 **    May you do good and not evil.
36446 **    May you find forgiveness for yourself and forgive others.
36447 **    May you share freely, never taking more than you give.
36448 **
36449 *************************************************************************
36450 ** $Id: btreeInt.h,v 1.42 2009/02/03 16:51:25 danielk1977 Exp $
36451 **
36452 ** This file implements a external (disk-based) database using BTrees.
36453 ** For a detailed discussion of BTrees, refer to
36454 **
36455 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36456 **     "Sorting And Searching", pages 473-480. Addison-Wesley
36457 **     Publishing Company, Reading, Massachusetts.
36458 **
36459 ** The basic idea is that each page of the file contains N database
36460 ** entries and N+1 pointers to subpages.
36461 **
36462 **   ----------------------------------------------------------------
36463 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36464 **   ----------------------------------------------------------------
36465 **
36466 ** All of the keys on the page that Ptr(0) points to have values less
36467 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36468 ** values greater than Key(0) and less than Key(1).  All of the keys
36469 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36470 ** so forth.
36471 **
36472 ** Finding a particular key requires reading O(log(M)) pages from the 
36473 ** disk where M is the number of entries in the tree.
36474 **
36475 ** In this implementation, a single file can hold one or more separate 
36476 ** BTrees.  Each BTree is identified by the index of its root page.  The
36477 ** key and data for any entry are combined to form the "payload".  A
36478 ** fixed amount of payload can be carried directly on the database
36479 ** page.  If the payload is larger than the preset amount then surplus
36480 ** bytes are stored on overflow pages.  The payload for an entry
36481 ** and the preceding pointer are combined to form a "Cell".  Each 
36482 ** page has a small header which contains the Ptr(N) pointer and other
36483 ** information such as the size of key and data.
36484 **
36485 ** FORMAT DETAILS
36486 **
36487 ** The file is divided into pages.  The first page is called page 1,
36488 ** the second is page 2, and so forth.  A page number of zero indicates
36489 ** "no such page".  The page size can be anything between 512 and 65536.
36490 ** Each page can be either a btree page, a freelist page or an overflow
36491 ** page.
36492 **
36493 ** The first page is always a btree page.  The first 100 bytes of the first
36494 ** page contain a special header (the "file header") that describes the file.
36495 ** The format of the file header is as follows:
36496 **
36497 **   OFFSET   SIZE    DESCRIPTION
36498 **      0      16     Header string: "SQLite format 3\000"
36499 **     16       2     Page size in bytes.  
36500 **     18       1     File format write version
36501 **     19       1     File format read version
36502 **     20       1     Bytes of unused space at the end of each page
36503 **     21       1     Max embedded payload fraction
36504 **     22       1     Min embedded payload fraction
36505 **     23       1     Min leaf payload fraction
36506 **     24       4     File change counter
36507 **     28       4     Reserved for future use
36508 **     32       4     First freelist page
36509 **     36       4     Number of freelist pages in the file
36510 **     40      60     15 4-byte meta values passed to higher layers
36511 **
36512 ** All of the integer values are big-endian (most significant byte first).
36513 **
36514 ** The file change counter is incremented when the database is changed
36515 ** This counter allows other processes to know when the file has changed
36516 ** and thus when they need to flush their cache.
36517 **
36518 ** The max embedded payload fraction is the amount of the total usable
36519 ** space in a page that can be consumed by a single cell for standard
36520 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36521 ** is to limit the maximum cell size so that at least 4 cells will fit
36522 ** on one page.  Thus the default max embedded payload fraction is 64.
36523 **
36524 ** If the payload for a cell is larger than the max payload, then extra
36525 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
36526 ** as many bytes as possible are moved into the overflow pages without letting
36527 ** the cell size drop below the min embedded payload fraction.
36528 **
36529 ** The min leaf payload fraction is like the min embedded payload fraction
36530 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36531 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36532 ** not specified in the header.
36533 **
36534 ** Each btree pages is divided into three sections:  The header, the
36535 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36536 ** file header that occurs before the page header.
36537 **
36538 **      |----------------|
36539 **      | file header    |   100 bytes.  Page 1 only.
36540 **      |----------------|
36541 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36542 **      |----------------|
36543 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36544 **      | array          |   |  Grows downward
36545 **      |                |   v
36546 **      |----------------|
36547 **      | unallocated    |
36548 **      | space          |
36549 **      |----------------|   ^  Grows upwards
36550 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36551 **      | area           |   |  and free space fragments.
36552 **      |----------------|
36553 **
36554 ** The page headers looks like this:
36555 **
36556 **   OFFSET   SIZE     DESCRIPTION
36557 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36558 **      1       2      byte offset to the first freeblock
36559 **      3       2      number of cells on this page
36560 **      5       2      first byte of the cell content area
36561 **      7       1      number of fragmented free bytes
36562 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36563 **
36564 ** The flags define the format of this btree page.  The leaf flag means that
36565 ** this page has no children.  The zerodata flag means that this page carries
36566 ** only keys and no data.  The intkey flag means that the key is a integer
36567 ** which is stored in the key size entry of the cell header rather than in
36568 ** the payload area.
36569 **
36570 ** The cell pointer array begins on the first byte after the page header.
36571 ** The cell pointer array contains zero or more 2-byte numbers which are
36572 ** offsets from the beginning of the page to the cell content in the cell
36573 ** content area.  The cell pointers occur in sorted order.  The system strives
36574 ** to keep free space after the last cell pointer so that new cells can
36575 ** be easily added without having to defragment the page.
36576 **
36577 ** Cell content is stored at the very end of the page and grows toward the
36578 ** beginning of the page.
36579 **
36580 ** Unused space within the cell content area is collected into a linked list of
36581 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36582 ** to the first freeblock is given in the header.  Freeblocks occur in
36583 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
36584 ** any group of 3 or fewer unused bytes in the cell content area cannot
36585 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36586 ** a fragment.  The total number of bytes in all fragments is recorded.
36587 ** in the page header at offset 7.
36588 **
36589 **    SIZE    DESCRIPTION
36590 **      2     Byte offset of the next freeblock
36591 **      2     Bytes in this freeblock
36592 **
36593 ** Cells are of variable length.  Cells are stored in the cell content area at
36594 ** the end of the page.  Pointers to the cells are in the cell pointer array
36595 ** that immediately follows the page header.  Cells is not necessarily
36596 ** contiguous or in order, but cell pointers are contiguous and in order.
36597 **
36598 ** Cell content makes use of variable length integers.  A variable
36599 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
36600 ** byte are used.  The integer consists of all bytes that have bit 8 set and
36601 ** the first byte with bit 8 clear.  The most significant byte of the integer
36602 ** appears first.  A variable-length integer may not be more than 9 bytes long.
36603 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
36604 ** allows a 64-bit integer to be encoded in 9 bytes.
36605 **
36606 **    0x00                      becomes  0x00000000
36607 **    0x7f                      becomes  0x0000007f
36608 **    0x81 0x00                 becomes  0x00000080
36609 **    0x82 0x00                 becomes  0x00000100
36610 **    0x80 0x7f                 becomes  0x0000007f
36611 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36612 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36613 **
36614 ** Variable length integers are used for rowids and to hold the number of
36615 ** bytes of key and data in a btree cell.
36616 **
36617 ** The content of a cell looks like this:
36618 **
36619 **    SIZE    DESCRIPTION
36620 **      4     Page number of the left child. Omitted if leaf flag is set.
36621 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
36622 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
36623 **      *     Payload
36624 **      4     First page of the overflow chain.  Omitted if no overflow
36625 **
36626 ** Overflow pages form a linked list.  Each page except the last is completely
36627 ** filled with data (pagesize - 4 bytes).  The last page can have as little
36628 ** as 1 byte of data.
36629 **
36630 **    SIZE    DESCRIPTION
36631 **      4     Page number of next overflow page
36632 **      *     Data
36633 **
36634 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
36635 ** file header points to the first in a linked list of trunk page.  Each trunk
36636 ** page points to multiple leaf pages.  The content of a leaf page is
36637 ** unspecified.  A trunk page looks like this:
36638 **
36639 **    SIZE    DESCRIPTION
36640 **      4     Page number of next trunk page
36641 **      4     Number of leaf pointers on this page
36642 **      *     zero or more pages numbers of leaves
36643 */
36644
36645 /* Round up a number to the next larger multiple of 8.  This is used
36646 ** to force 8-byte alignment on 64-bit architectures.
36647 */
36648 #define ROUND8(x)   ((x+7)&~7)
36649
36650
36651 /* The following value is the maximum cell size assuming a maximum page
36652 ** size give above.
36653 */
36654 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
36655
36656 /* The maximum number of cells on a single page of the database.  This
36657 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
36658 ** plus 2 bytes for the index to the cell in the page header).  Such
36659 ** small cells will be rare, but they are possible.
36660 */
36661 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
36662
36663 /* Forward declarations */
36664 typedef struct MemPage MemPage;
36665 typedef struct BtLock BtLock;
36666
36667 /*
36668 ** This is a magic string that appears at the beginning of every
36669 ** SQLite database in order to identify the file as a real database.
36670 **
36671 ** You can change this value at compile-time by specifying a
36672 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
36673 ** header must be exactly 16 bytes including the zero-terminator so
36674 ** the string itself should be 15 characters long.  If you change
36675 ** the header, then your custom library will not be able to read 
36676 ** databases generated by the standard tools and the standard tools
36677 ** will not be able to read databases created by your custom library.
36678 */
36679 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
36680 #  define SQLITE_FILE_HEADER "SQLite format 3"
36681 #endif
36682
36683 /*
36684 ** Page type flags.  An ORed combination of these flags appear as the
36685 ** first byte of on-disk image of every BTree page.
36686 */
36687 #define PTF_INTKEY    0x01
36688 #define PTF_ZERODATA  0x02
36689 #define PTF_LEAFDATA  0x04
36690 #define PTF_LEAF      0x08
36691
36692 /*
36693 ** As each page of the file is loaded into memory, an instance of the following
36694 ** structure is appended and initialized to zero.  This structure stores
36695 ** information about the page that is decoded from the raw file page.
36696 **
36697 ** The pParent field points back to the parent page.  This allows us to
36698 ** walk up the BTree from any leaf to the root.  Care must be taken to
36699 ** unref() the parent page pointer when this page is no longer referenced.
36700 ** The pageDestructor() routine handles that chore.
36701 **
36702 ** Access to all fields of this structure is controlled by the mutex
36703 ** stored in MemPage.pBt->mutex.
36704 */
36705 struct MemPage {
36706   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
36707   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
36708   u8 intKey;           /* True if intkey flag is set */
36709   u8 leaf;             /* True if leaf flag is set */
36710   u8 hasData;          /* True if this page stores data */
36711   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
36712   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
36713   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
36714   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
36715   u16 cellOffset;      /* Index in aData of first cell pointer */
36716   u16 nFree;           /* Number of free bytes on the page */
36717   u16 nCell;           /* Number of cells on this page, local and ovfl */
36718   u16 maskPage;        /* Mask for page offset */
36719   struct _OvflCell {   /* Cells that will not fit on aData[] */
36720     u8 *pCell;          /* Pointers to the body of the overflow cell */
36721     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
36722   } aOvfl[5];
36723   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
36724   u8 *aData;           /* Pointer to disk image of the page data */
36725   DbPage *pDbPage;     /* Pager page handle */
36726   Pgno pgno;           /* Page number for this page */
36727 };
36728
36729 /*
36730 ** The in-memory image of a disk page has the auxiliary information appended
36731 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
36732 ** that extra information.
36733 */
36734 #define EXTRA_SIZE sizeof(MemPage)
36735
36736 /* A Btree handle
36737 **
36738 ** A database connection contains a pointer to an instance of
36739 ** this object for every database file that it has open.  This structure
36740 ** is opaque to the database connection.  The database connection cannot
36741 ** see the internals of this structure and only deals with pointers to
36742 ** this structure.
36743 **
36744 ** For some database files, the same underlying database cache might be 
36745 ** shared between multiple connections.  In that case, each contection
36746 ** has it own pointer to this object.  But each instance of this object
36747 ** points to the same BtShared object.  The database cache and the
36748 ** schema associated with the database file are all contained within
36749 ** the BtShared object.
36750 **
36751 ** All fields in this structure are accessed under sqlite3.mutex.
36752 ** The pBt pointer itself may not be changed while there exists cursors 
36753 ** in the referenced BtShared that point back to this Btree since those
36754 ** cursors have to do go through this Btree to find their BtShared and
36755 ** they often do so without holding sqlite3.mutex.
36756 */
36757 struct Btree {
36758   sqlite3 *db;       /* The database connection holding this btree */
36759   BtShared *pBt;     /* Sharable content of this btree */
36760   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
36761   u8 sharable;       /* True if we can share pBt with another db */
36762   u8 locked;         /* True if db currently has pBt locked */
36763   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
36764   int nBackup;       /* Number of backup operations reading this btree */
36765   Btree *pNext;      /* List of other sharable Btrees from the same db */
36766   Btree *pPrev;      /* Back pointer of the same list */
36767 };
36768
36769 /*
36770 ** Btree.inTrans may take one of the following values.
36771 **
36772 ** If the shared-data extension is enabled, there may be multiple users
36773 ** of the Btree structure. At most one of these may open a write transaction,
36774 ** but any number may have active read transactions.
36775 */
36776 #define TRANS_NONE  0
36777 #define TRANS_READ  1
36778 #define TRANS_WRITE 2
36779
36780 /*
36781 ** An instance of this object represents a single database file.
36782 ** 
36783 ** A single database file can be in use as the same time by two
36784 ** or more database connections.  When two or more connections are
36785 ** sharing the same database file, each connection has it own
36786 ** private Btree object for the file and each of those Btrees points
36787 ** to this one BtShared object.  BtShared.nRef is the number of
36788 ** connections currently sharing this database file.
36789 **
36790 ** Fields in this structure are accessed under the BtShared.mutex
36791 ** mutex, except for nRef and pNext which are accessed under the
36792 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
36793 ** may not be modified once it is initially set as long as nRef>0.
36794 ** The pSchema field may be set once under BtShared.mutex and
36795 ** thereafter is unchanged as long as nRef>0.
36796 */
36797 struct BtShared {
36798   Pager *pPager;        /* The page cache */
36799   sqlite3 *db;          /* Database connection currently using this Btree */
36800   BtCursor *pCursor;    /* A list of all open cursors */
36801   MemPage *pPage1;      /* First page of the database */
36802   u8 inStmt;            /* True if we are in a statement subtransaction */
36803   u8 readOnly;          /* True if the underlying file is readonly */
36804   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
36805 #ifndef SQLITE_OMIT_AUTOVACUUM
36806   u8 autoVacuum;        /* True if auto-vacuum is enabled */
36807   u8 incrVacuum;        /* True if incr-vacuum is enabled */
36808 #endif
36809   u16 pageSize;         /* Total number of bytes on a page */
36810   u16 usableSize;       /* Number of usable bytes on each page */
36811   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
36812   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
36813   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
36814   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
36815   u8 inTransaction;     /* Transaction state */
36816   int nTransaction;     /* Number of open transactions (read + write) */
36817   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
36818   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
36819   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
36820   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
36821 #ifndef SQLITE_OMIT_SHARED_CACHE
36822   int nRef;             /* Number of references to this structure */
36823   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
36824   BtLock *pLock;        /* List of locks held on this shared-btree struct */
36825   Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
36826 #endif
36827   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
36828 };
36829
36830 /*
36831 ** An instance of the following structure is used to hold information
36832 ** about a cell.  The parseCellPtr() function fills in this structure
36833 ** based on information extract from the raw disk page.
36834 */
36835 typedef struct CellInfo CellInfo;
36836 struct CellInfo {
36837   u8 *pCell;     /* Pointer to the start of cell content */
36838   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
36839   u32 nData;     /* Number of bytes of data */
36840   u32 nPayload;  /* Total amount of payload */
36841   u16 nHeader;   /* Size of the cell content header in bytes */
36842   u16 nLocal;    /* Amount of payload held locally */
36843   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
36844   u16 nSize;     /* Size of the cell content on the main b-tree page */
36845 };
36846
36847 /*
36848 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
36849 ** this will be declared corrupt. This value is calculated based on a
36850 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
36851 ** root-node and 3 for all other internal nodes.
36852 **
36853 ** If a tree that appears to be taller than this is encountered, it is
36854 ** assumed that the database is corrupt.
36855 */
36856 #define BTCURSOR_MAX_DEPTH 20
36857
36858 /*
36859 ** A cursor is a pointer to a particular entry within a particular
36860 ** b-tree within a database file.
36861 **
36862 ** The entry is identified by its MemPage and the index in
36863 ** MemPage.aCell[] of the entry.
36864 **
36865 ** When a single database file can shared by two more database connections,
36866 ** but cursors cannot be shared.  Each cursor is associated with a
36867 ** particular database connection identified BtCursor.pBtree.db.
36868 **
36869 ** Fields in this structure are accessed under the BtShared.mutex
36870 ** found at self->pBt->mutex. 
36871 */
36872 struct BtCursor {
36873   Btree *pBtree;            /* The Btree to which this cursor belongs */
36874   BtShared *pBt;            /* The BtShared this cursor points to */
36875   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
36876   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
36877   Pgno pgnoRoot;            /* The root page of this tree */
36878   CellInfo info;            /* A parse of the cell we are pointing at */
36879   u8 wrFlag;                /* True if writable */
36880   u8 atLast;                /* Cursor pointing to the last entry */
36881   u8 validNKey;             /* True if info.nKey is valid */
36882   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
36883   void *pKey;      /* Saved key that was cursor's last known position */
36884   i64 nKey;        /* Size of pKey, or last integer key */
36885   int skip;        /* (skip<0) -> Prev() is a no-op. (skip>0) -> Next() is */
36886 #ifndef SQLITE_OMIT_INCRBLOB
36887   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
36888   Pgno *aOverflow;          /* Cache of overflow page locations */
36889 #endif
36890 #ifndef NDEBUG
36891   u8 pagesShuffled;         /* True if Btree pages are rearranged by balance()*/
36892 #endif
36893   i16 iPage;                            /* Index of current page in apPage */
36894   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
36895   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
36896 };
36897
36898 /*
36899 ** Potential values for BtCursor.eState.
36900 **
36901 ** CURSOR_VALID:
36902 **   Cursor points to a valid entry. getPayload() etc. may be called.
36903 **
36904 ** CURSOR_INVALID:
36905 **   Cursor does not point to a valid entry. This can happen (for example) 
36906 **   because the table is empty or because BtreeCursorFirst() has not been
36907 **   called.
36908 **
36909 ** CURSOR_REQUIRESEEK:
36910 **   The table that this cursor was opened on still exists, but has been 
36911 **   modified since the cursor was last used. The cursor position is saved
36912 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
36913 **   this state, restoreCursorPosition() can be called to attempt to
36914 **   seek the cursor to the saved position.
36915 **
36916 ** CURSOR_FAULT:
36917 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
36918 **   on a different connection that shares the BtShared cache with this
36919 **   cursor.  The error has left the cache in an inconsistent state.
36920 **   Do nothing else with this cursor.  Any attempt to use the cursor
36921 **   should return the error code stored in BtCursor.skip
36922 */
36923 #define CURSOR_INVALID           0
36924 #define CURSOR_VALID             1
36925 #define CURSOR_REQUIRESEEK       2
36926 #define CURSOR_FAULT             3
36927
36928 /* 
36929 ** The database page the PENDING_BYTE occupies. This page is never used.
36930 */
36931 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
36932
36933 /*
36934 ** A linked list of the following structures is stored at BtShared.pLock.
36935 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
36936 ** is opened on the table with root page BtShared.iTable. Locks are removed
36937 ** from this list when a transaction is committed or rolled back, or when
36938 ** a btree handle is closed.
36939 */
36940 struct BtLock {
36941   Btree *pBtree;        /* Btree handle holding this lock */
36942   Pgno iTable;          /* Root page of table */
36943   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
36944   BtLock *pNext;        /* Next in BtShared.pLock list */
36945 };
36946
36947 /* Candidate values for BtLock.eLock */
36948 #define READ_LOCK     1
36949 #define WRITE_LOCK    2
36950
36951 /*
36952 ** These macros define the location of the pointer-map entry for a 
36953 ** database page. The first argument to each is the number of usable
36954 ** bytes on each page of the database (often 1024). The second is the
36955 ** page number to look up in the pointer map.
36956 **
36957 ** PTRMAP_PAGENO returns the database page number of the pointer-map
36958 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
36959 ** the offset of the requested map entry.
36960 **
36961 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
36962 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
36963 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
36964 ** this test.
36965 */
36966 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
36967 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
36968 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
36969
36970 /*
36971 ** The pointer map is a lookup table that identifies the parent page for
36972 ** each child page in the database file.  The parent page is the page that
36973 ** contains a pointer to the child.  Every page in the database contains
36974 ** 0 or 1 parent pages.  (In this context 'database page' refers
36975 ** to any page that is not part of the pointer map itself.)  Each pointer map
36976 ** entry consists of a single byte 'type' and a 4 byte parent page number.
36977 ** The PTRMAP_XXX identifiers below are the valid types.
36978 **
36979 ** The purpose of the pointer map is to facility moving pages from one
36980 ** position in the file to another as part of autovacuum.  When a page
36981 ** is moved, the pointer in its parent must be updated to point to the
36982 ** new location.  The pointer map is used to locate the parent page quickly.
36983 **
36984 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
36985 **                  used in this case.
36986 **
36987 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
36988 **                  is not used in this case.
36989 **
36990 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
36991 **                   overflow pages. The page number identifies the page that
36992 **                   contains the cell with a pointer to this overflow page.
36993 **
36994 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
36995 **                   overflow pages. The page-number identifies the previous
36996 **                   page in the overflow page list.
36997 **
36998 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
36999 **               identifies the parent page in the btree.
37000 */
37001 #define PTRMAP_ROOTPAGE 1
37002 #define PTRMAP_FREEPAGE 2
37003 #define PTRMAP_OVERFLOW1 3
37004 #define PTRMAP_OVERFLOW2 4
37005 #define PTRMAP_BTREE 5
37006
37007 /* A bunch of assert() statements to check the transaction state variables
37008 ** of handle p (type Btree*) are internally consistent.
37009 */
37010 #define btreeIntegrity(p) \
37011   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37012   assert( p->pBt->inTransaction>=p->inTrans ); 
37013
37014
37015 /*
37016 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37017 ** if the database supports auto-vacuum or not. Because it is used
37018 ** within an expression that is an argument to another macro 
37019 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
37020 ** So, this macro is defined instead.
37021 */
37022 #ifndef SQLITE_OMIT_AUTOVACUUM
37023 #define ISAUTOVACUUM (pBt->autoVacuum)
37024 #else
37025 #define ISAUTOVACUUM 0
37026 #endif
37027
37028
37029 /*
37030 ** This structure is passed around through all the sanity checking routines
37031 ** in order to keep track of some global state information.
37032 */
37033 typedef struct IntegrityCk IntegrityCk;
37034 struct IntegrityCk {
37035   BtShared *pBt;    /* The tree being checked out */
37036   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37037   Pgno nPage;       /* Number of pages in the database */
37038   int *anRef;       /* Number of times each page is referenced */
37039   int mxErr;        /* Stop accumulating errors when this reaches zero */
37040   int nErr;         /* Number of messages written to zErrMsg so far */
37041   int mallocFailed; /* A memory allocation error has occurred */
37042   StrAccum errMsg;  /* Accumulate the error message text here */
37043 };
37044
37045 /*
37046 ** Read or write a two- and four-byte big-endian integer values.
37047 */
37048 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
37049 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37050 #define get4byte sqlite3Get4byte
37051 #define put4byte sqlite3Put4byte
37052
37053 /*
37054 ** Internal routines that should be accessed by the btree layer only.
37055 */
37056 SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
37057 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage);
37058 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
37059 SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
37060 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur);
37061 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
37062 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
37063 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);
37064
37065 /************** End of btreeInt.h ********************************************/
37066 /************** Continuing where we left off in btmutex.c ********************/
37067 #if SQLITE_THREADSAFE && !defined(SQLITE_OMIT_SHARED_CACHE)
37068
37069
37070 /*
37071 ** Enter a mutex on the given BTree object.
37072 **
37073 ** If the object is not sharable, then no mutex is ever required
37074 ** and this routine is a no-op.  The underlying mutex is non-recursive.
37075 ** But we keep a reference count in Btree.wantToLock so the behavior
37076 ** of this interface is recursive.
37077 **
37078 ** To avoid deadlocks, multiple Btrees are locked in the same order
37079 ** by all database connections.  The p->pNext is a list of other
37080 ** Btrees belonging to the same database connection as the p Btree
37081 ** which need to be locked after p.  If we cannot get a lock on
37082 ** p, then first unlock all of the others on p->pNext, then wait
37083 ** for the lock to become available on p, then relock all of the
37084 ** subsequent Btrees that desire a lock.
37085 */
37086 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37087   Btree *pLater;
37088
37089   /* Some basic sanity checking on the Btree.  The list of Btrees
37090   ** connected by pNext and pPrev should be in sorted order by
37091   ** Btree.pBt value. All elements of the list should belong to
37092   ** the same connection. Only shared Btrees are on the list. */
37093   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37094   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37095   assert( p->pNext==0 || p->pNext->db==p->db );
37096   assert( p->pPrev==0 || p->pPrev->db==p->db );
37097   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37098
37099   /* Check for locking consistency */
37100   assert( !p->locked || p->wantToLock>0 );
37101   assert( p->sharable || p->wantToLock==0 );
37102
37103   /* We should already hold a lock on the database connection */
37104   assert( sqlite3_mutex_held(p->db->mutex) );
37105
37106   if( !p->sharable ) return;
37107   p->wantToLock++;
37108   if( p->locked ) return;
37109
37110   /* In most cases, we should be able to acquire the lock we
37111   ** want without having to go throught the ascending lock
37112   ** procedure that follows.  Just be sure not to block.
37113   */
37114   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37115     p->locked = 1;
37116     return;
37117   }
37118
37119   /* To avoid deadlock, first release all locks with a larger
37120   ** BtShared address.  Then acquire our lock.  Then reacquire
37121   ** the other BtShared locks that we used to hold in ascending
37122   ** order.
37123   */
37124   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37125     assert( pLater->sharable );
37126     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37127     assert( !pLater->locked || pLater->wantToLock>0 );
37128     if( pLater->locked ){
37129       sqlite3_mutex_leave(pLater->pBt->mutex);
37130       pLater->locked = 0;
37131     }
37132   }
37133   sqlite3_mutex_enter(p->pBt->mutex);
37134   p->locked = 1;
37135   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37136     if( pLater->wantToLock ){
37137       sqlite3_mutex_enter(pLater->pBt->mutex);
37138       pLater->locked = 1;
37139     }
37140   }
37141 }
37142
37143 /*
37144 ** Exit the recursive mutex on a Btree.
37145 */
37146 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37147   if( p->sharable ){
37148     assert( p->wantToLock>0 );
37149     p->wantToLock--;
37150     if( p->wantToLock==0 ){
37151       assert( p->locked );
37152       sqlite3_mutex_leave(p->pBt->mutex);
37153       p->locked = 0;
37154     }
37155   }
37156 }
37157
37158 #ifndef NDEBUG
37159 /*
37160 ** Return true if the BtShared mutex is held on the btree.  
37161 **
37162 ** This routine makes no determination one why or another if the
37163 ** database connection mutex is held.
37164 **
37165 ** This routine is used only from within assert() statements.
37166 */
37167 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37168   return (p->sharable==0 ||
37169              (p->locked && p->wantToLock && sqlite3_mutex_held(p->pBt->mutex)));
37170 }
37171 #endif
37172
37173
37174 #ifndef SQLITE_OMIT_INCRBLOB
37175 /*
37176 ** Enter and leave a mutex on a Btree given a cursor owned by that
37177 ** Btree.  These entry points are used by incremental I/O and can be
37178 ** omitted if that module is not used.
37179 */
37180 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37181   sqlite3BtreeEnter(pCur->pBtree);
37182 }
37183 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37184   sqlite3BtreeLeave(pCur->pBtree);
37185 }
37186 #endif /* SQLITE_OMIT_INCRBLOB */
37187
37188
37189 /*
37190 ** Enter the mutex on every Btree associated with a database
37191 ** connection.  This is needed (for example) prior to parsing
37192 ** a statement since we will be comparing table and column names
37193 ** against all schemas and we do not want those schemas being
37194 ** reset out from under us.
37195 **
37196 ** There is a corresponding leave-all procedures.
37197 **
37198 ** Enter the mutexes in accending order by BtShared pointer address
37199 ** to avoid the possibility of deadlock when two threads with
37200 ** two or more btrees in common both try to lock all their btrees
37201 ** at the same instant.
37202 */
37203 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37204   int i;
37205   Btree *p, *pLater;
37206   assert( sqlite3_mutex_held(db->mutex) );
37207   for(i=0; i<db->nDb; i++){
37208     p = db->aDb[i].pBt;
37209     if( p && p->sharable ){
37210       p->wantToLock++;
37211       if( !p->locked ){
37212         assert( p->wantToLock==1 );
37213         while( p->pPrev ) p = p->pPrev;
37214         while( p->locked && p->pNext ) p = p->pNext;
37215         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37216           if( pLater->locked ){
37217             sqlite3_mutex_leave(pLater->pBt->mutex);
37218             pLater->locked = 0;
37219           }
37220         }
37221         while( p ){
37222           sqlite3_mutex_enter(p->pBt->mutex);
37223           p->locked++;
37224           p = p->pNext;
37225         }
37226       }
37227     }
37228   }
37229 }
37230 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37231   int i;
37232   Btree *p;
37233   assert( sqlite3_mutex_held(db->mutex) );
37234   for(i=0; i<db->nDb; i++){
37235     p = db->aDb[i].pBt;
37236     if( p && p->sharable ){
37237       assert( p->wantToLock>0 );
37238       p->wantToLock--;
37239       if( p->wantToLock==0 ){
37240         assert( p->locked );
37241         sqlite3_mutex_leave(p->pBt->mutex);
37242         p->locked = 0;
37243       }
37244     }
37245   }
37246 }
37247
37248 #ifndef NDEBUG
37249 /*
37250 ** Return true if the current thread holds the database connection
37251 ** mutex and all required BtShared mutexes.
37252 **
37253 ** This routine is used inside assert() statements only.
37254 */
37255 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37256   int i;
37257   if( !sqlite3_mutex_held(db->mutex) ){
37258     return 0;
37259   }
37260   for(i=0; i<db->nDb; i++){
37261     Btree *p;
37262     p = db->aDb[i].pBt;
37263     if( p && p->sharable &&
37264          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37265       return 0;
37266     }
37267   }
37268   return 1;
37269 }
37270 #endif /* NDEBUG */
37271
37272 /*
37273 ** Add a new Btree pointer to a BtreeMutexArray. 
37274 ** if the pointer can possibly be shared with
37275 ** another database connection.
37276 **
37277 ** The pointers are kept in sorted order by pBtree->pBt.  That
37278 ** way when we go to enter all the mutexes, we can enter them
37279 ** in order without every having to backup and retry and without
37280 ** worrying about deadlock.
37281 **
37282 ** The number of shared btrees will always be small (usually 0 or 1)
37283 ** so an insertion sort is an adequate algorithm here.
37284 */
37285 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37286   int i, j;
37287   BtShared *pBt;
37288   if( pBtree==0 || pBtree->sharable==0 ) return;
37289 #ifndef NDEBUG
37290   {
37291     for(i=0; i<pArray->nMutex; i++){
37292       assert( pArray->aBtree[i]!=pBtree );
37293     }
37294   }
37295 #endif
37296   assert( pArray->nMutex>=0 );
37297   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37298   pBt = pBtree->pBt;
37299   for(i=0; i<pArray->nMutex; i++){
37300     assert( pArray->aBtree[i]!=pBtree );
37301     if( pArray->aBtree[i]->pBt>pBt ){
37302       for(j=pArray->nMutex; j>i; j--){
37303         pArray->aBtree[j] = pArray->aBtree[j-1];
37304       }
37305       pArray->aBtree[i] = pBtree;
37306       pArray->nMutex++;
37307       return;
37308     }
37309   }
37310   pArray->aBtree[pArray->nMutex++] = pBtree;
37311 }
37312
37313 /*
37314 ** Enter the mutex of every btree in the array.  This routine is
37315 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
37316 ** exited at the end of the same function.
37317 */
37318 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37319   int i;
37320   for(i=0; i<pArray->nMutex; i++){
37321     Btree *p = pArray->aBtree[i];
37322     /* Some basic sanity checking */
37323     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37324     assert( !p->locked || p->wantToLock>0 );
37325
37326     /* We should already hold a lock on the database connection */
37327     assert( sqlite3_mutex_held(p->db->mutex) );
37328
37329     p->wantToLock++;
37330     if( !p->locked && p->sharable ){
37331       sqlite3_mutex_enter(p->pBt->mutex);
37332       p->locked = 1;
37333     }
37334   }
37335 }
37336
37337 /*
37338 ** Leave the mutex of every btree in the group.
37339 */
37340 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37341   int i;
37342   for(i=0; i<pArray->nMutex; i++){
37343     Btree *p = pArray->aBtree[i];
37344     /* Some basic sanity checking */
37345     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37346     assert( p->locked || !p->sharable );
37347     assert( p->wantToLock>0 );
37348
37349     /* We should already hold a lock on the database connection */
37350     assert( sqlite3_mutex_held(p->db->mutex) );
37351
37352     p->wantToLock--;
37353     if( p->wantToLock==0 && p->locked ){
37354       sqlite3_mutex_leave(p->pBt->mutex);
37355       p->locked = 0;
37356     }
37357   }
37358 }
37359
37360
37361 #endif  /* SQLITE_THREADSAFE && !SQLITE_OMIT_SHARED_CACHE */
37362
37363 /************** End of btmutex.c *********************************************/
37364 /************** Begin file btree.c *******************************************/
37365 /*
37366 ** 2004 April 6
37367 **
37368 ** The author disclaims copyright to this source code.  In place of
37369 ** a legal notice, here is a blessing:
37370 **
37371 **    May you do good and not evil.
37372 **    May you find forgiveness for yourself and forgive others.
37373 **    May you share freely, never taking more than you give.
37374 **
37375 *************************************************************************
37376 ** $Id: btree.c,v 1.565 2009/02/04 01:49:30 shane Exp $
37377 **
37378 ** This file implements a external (disk-based) database using BTrees.
37379 ** See the header comment on "btreeInt.h" for additional information.
37380 ** Including a description of file format and an overview of operation.
37381 */
37382
37383 /*
37384 ** The header string that appears at the beginning of every
37385 ** SQLite database.
37386 */
37387 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37388
37389 /*
37390 ** Set this global variable to 1 to enable tracing using the TRACE
37391 ** macro.
37392 */
37393 #if 0
37394 int sqlite3BtreeTrace=0;  /* True to enable tracing */
37395 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37396 #else
37397 # define TRACE(X)
37398 #endif
37399
37400
37401
37402 #ifndef SQLITE_OMIT_SHARED_CACHE
37403 /*
37404 ** A list of BtShared objects that are eligible for participation
37405 ** in shared cache.  This variable has file scope during normal builds,
37406 ** but the test harness needs to access it so we make it global for 
37407 ** test builds.
37408 */
37409 #ifdef SQLITE_TEST
37410 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37411 #else
37412 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37413 #endif
37414 #endif /* SQLITE_OMIT_SHARED_CACHE */
37415
37416 #ifndef SQLITE_OMIT_SHARED_CACHE
37417 /*
37418 ** Enable or disable the shared pager and schema features.
37419 **
37420 ** This routine has no effect on existing database connections.
37421 ** The shared cache setting effects only future calls to
37422 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37423 */
37424 SQLITE_API int sqlite3_enable_shared_cache(int enable){
37425   sqlite3GlobalConfig.sharedCacheEnabled = enable;
37426   return SQLITE_OK;
37427 }
37428 #endif
37429
37430
37431 /*
37432 ** Forward declaration
37433 */
37434 static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
37435
37436
37437 #ifdef SQLITE_OMIT_SHARED_CACHE
37438   /*
37439   ** The functions queryTableLock(), lockTable() and unlockAllTables()
37440   ** manipulate entries in the BtShared.pLock linked list used to store
37441   ** shared-cache table level locks. If the library is compiled with the
37442   ** shared-cache feature disabled, then there is only ever one user
37443   ** of each BtShared structure and so this locking is not necessary. 
37444   ** So define the lock related functions as no-ops.
37445   */
37446   #define queryTableLock(a,b,c) SQLITE_OK
37447   #define lockTable(a,b,c) SQLITE_OK
37448   #define unlockAllTables(a)
37449 #endif
37450
37451 #ifndef SQLITE_OMIT_SHARED_CACHE
37452 /*
37453 ** Query to see if btree handle p may obtain a lock of type eLock 
37454 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37455 ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
37456 ** SQLITE_LOCKED if not.
37457 */
37458 static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
37459   BtShared *pBt = p->pBt;
37460   BtLock *pIter;
37461
37462   assert( sqlite3BtreeHoldsMutex(p) );
37463   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37464   assert( p->db!=0 );
37465   
37466   /* This is a no-op if the shared-cache is not enabled */
37467   if( !p->sharable ){
37468     return SQLITE_OK;
37469   }
37470
37471   /* If some other connection is holding an exclusive lock, the
37472   ** requested lock may not be obtained.
37473   */
37474   if( pBt->pExclusive && pBt->pExclusive!=p ){
37475     return SQLITE_LOCKED;
37476   }
37477
37478   /* This (along with lockTable()) is where the ReadUncommitted flag is
37479   ** dealt with. If the caller is querying for a read-lock and the flag is
37480   ** set, it is unconditionally granted - even if there are write-locks
37481   ** on the table. If a write-lock is requested, the ReadUncommitted flag
37482   ** is not considered.
37483   **
37484   ** In function lockTable(), if a read-lock is demanded and the 
37485   ** ReadUncommitted flag is set, no entry is added to the locks list 
37486   ** (BtShared.pLock).
37487   **
37488   ** To summarize: If the ReadUncommitted flag is set, then read cursors do
37489   ** not create or respect table locks. The locking procedure for a 
37490   ** write-cursor does not change.
37491   */
37492   if( 
37493     0==(p->db->flags&SQLITE_ReadUncommitted) || 
37494     eLock==WRITE_LOCK ||
37495     iTab==MASTER_ROOT
37496   ){
37497     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37498       if( pIter->pBtree!=p && pIter->iTable==iTab && 
37499           (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
37500         return SQLITE_LOCKED;
37501       }
37502     }
37503   }
37504   return SQLITE_OK;
37505 }
37506 #endif /* !SQLITE_OMIT_SHARED_CACHE */
37507
37508 #ifndef SQLITE_OMIT_SHARED_CACHE
37509 /*
37510 ** Add a lock on the table with root-page iTable to the shared-btree used
37511 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
37512 ** WRITE_LOCK.
37513 **
37514 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
37515 ** SQLITE_NOMEM may also be returned.
37516 */
37517 static int lockTable(Btree *p, Pgno iTable, u8 eLock){
37518   BtShared *pBt = p->pBt;
37519   BtLock *pLock = 0;
37520   BtLock *pIter;
37521
37522   assert( sqlite3BtreeHoldsMutex(p) );
37523   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37524   assert( p->db!=0 );
37525
37526   /* This is a no-op if the shared-cache is not enabled */
37527   if( !p->sharable ){
37528     return SQLITE_OK;
37529   }
37530
37531   assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
37532
37533   /* If the read-uncommitted flag is set and a read-lock is requested,
37534   ** return early without adding an entry to the BtShared.pLock list. See
37535   ** comment in function queryTableLock() for more info on handling 
37536   ** the ReadUncommitted flag.
37537   */
37538   if( 
37539     (p->db->flags&SQLITE_ReadUncommitted) && 
37540     (eLock==READ_LOCK) &&
37541     iTable!=MASTER_ROOT
37542   ){
37543     return SQLITE_OK;
37544   }
37545
37546   /* First search the list for an existing lock on this table. */
37547   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37548     if( pIter->iTable==iTable && pIter->pBtree==p ){
37549       pLock = pIter;
37550       break;
37551     }
37552   }
37553
37554   /* If the above search did not find a BtLock struct associating Btree p
37555   ** with table iTable, allocate one and link it into the list.
37556   */
37557   if( !pLock ){
37558     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
37559     if( !pLock ){
37560       return SQLITE_NOMEM;
37561     }
37562     pLock->iTable = iTable;
37563     pLock->pBtree = p;
37564     pLock->pNext = pBt->pLock;
37565     pBt->pLock = pLock;
37566   }
37567
37568   /* Set the BtLock.eLock variable to the maximum of the current lock
37569   ** and the requested lock. This means if a write-lock was already held
37570   ** and a read-lock requested, we don't incorrectly downgrade the lock.
37571   */
37572   assert( WRITE_LOCK>READ_LOCK );
37573   if( eLock>pLock->eLock ){
37574     pLock->eLock = eLock;
37575   }
37576
37577   return SQLITE_OK;
37578 }
37579 #endif /* !SQLITE_OMIT_SHARED_CACHE */
37580
37581 #ifndef SQLITE_OMIT_SHARED_CACHE
37582 /*
37583 ** Release all the table locks (locks obtained via calls to the lockTable()
37584 ** procedure) held by Btree handle p.
37585 */
37586 static void unlockAllTables(Btree *p){
37587   BtShared *pBt = p->pBt;
37588   BtLock **ppIter = &pBt->pLock;
37589
37590   assert( sqlite3BtreeHoldsMutex(p) );
37591   assert( p->sharable || 0==*ppIter );
37592
37593   while( *ppIter ){
37594     BtLock *pLock = *ppIter;
37595     assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
37596     if( pLock->pBtree==p ){
37597       *ppIter = pLock->pNext;
37598       sqlite3_free(pLock);
37599     }else{
37600       ppIter = &pLock->pNext;
37601     }
37602   }
37603
37604   if( pBt->pExclusive==p ){
37605     pBt->pExclusive = 0;
37606   }
37607 }
37608 #endif /* SQLITE_OMIT_SHARED_CACHE */
37609
37610 static void releasePage(MemPage *pPage);  /* Forward reference */
37611
37612 /*
37613 ** Verify that the cursor holds a mutex on the BtShared
37614 */
37615 #ifndef NDEBUG
37616 static int cursorHoldsMutex(BtCursor *p){
37617   return sqlite3_mutex_held(p->pBt->mutex);
37618 }
37619 #endif
37620
37621
37622 #ifndef SQLITE_OMIT_INCRBLOB
37623 /*
37624 ** Invalidate the overflow page-list cache for cursor pCur, if any.
37625 */
37626 static void invalidateOverflowCache(BtCursor *pCur){
37627   assert( cursorHoldsMutex(pCur) );
37628   sqlite3_free(pCur->aOverflow);
37629   pCur->aOverflow = 0;
37630 }
37631
37632 /*
37633 ** Invalidate the overflow page-list cache for all cursors opened
37634 ** on the shared btree structure pBt.
37635 */
37636 static void invalidateAllOverflowCache(BtShared *pBt){
37637   BtCursor *p;
37638   assert( sqlite3_mutex_held(pBt->mutex) );
37639   for(p=pBt->pCursor; p; p=p->pNext){
37640     invalidateOverflowCache(p);
37641   }
37642 }
37643 #else
37644   #define invalidateOverflowCache(x)
37645   #define invalidateAllOverflowCache(x)
37646 #endif
37647
37648 /*
37649 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
37650 ** when a page that previously contained data becomes a free-list leaf 
37651 ** page.
37652 **
37653 ** The BtShared.pHasContent bitvec exists to work around an obscure
37654 ** bug caused by the interaction of two useful IO optimizations surrounding
37655 ** free-list leaf pages:
37656 **
37657 **   1) When all data is deleted from a page and the page becomes
37658 **      a free-list leaf page, the page is not written to the database
37659 **      (as free-list leaf pages contain no meaningful data). Sometimes
37660 **      such a page is not even journalled (as it will not be modified,
37661 **      why bother journalling it?).
37662 **
37663 **   2) When a free-list leaf page is reused, its content is not read
37664 **      from the database or written to the journal file (why should it
37665 **      be, if it is not at all meaningful?).
37666 **
37667 ** By themselves, these optimizations work fine and provide a handy
37668 ** performance boost to bulk delete or insert operations. However, if
37669 ** a page is moved to the free-list and then reused within the same
37670 ** transaction, a problem comes up. If the page is not journalled when
37671 ** it is moved to the free-list and it is also not journalled when it
37672 ** is extracted from the free-list and reused, then the original data
37673 ** may be lost. In the event of a rollback, it may not be possible
37674 ** to restore the database to its original configuration.
37675 **
37676 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
37677 ** moved to become a free-list leaf page, the corresponding bit is
37678 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
37679 ** optimization 2 above is ommitted if the corresponding bit is already
37680 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
37681 ** at the end of every transaction.
37682 */
37683 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
37684   int rc = SQLITE_OK;
37685   if( !pBt->pHasContent ){
37686     int nPage;
37687     rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
37688     if( rc==SQLITE_OK ){
37689       pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
37690       if( !pBt->pHasContent ){
37691         rc = SQLITE_NOMEM;
37692       }
37693     }
37694   }
37695   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
37696     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
37697   }
37698   return rc;
37699 }
37700
37701 /*
37702 ** Query the BtShared.pHasContent vector.
37703 **
37704 ** This function is called when a free-list leaf page is removed from the
37705 ** free-list for reuse. It returns false if it is safe to retrieve the
37706 ** page from the pager layer with the 'no-content' flag set. True otherwise.
37707 */
37708 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
37709   Bitvec *p = pBt->pHasContent;
37710   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
37711 }
37712
37713 /*
37714 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
37715 ** invoked at the conclusion of each write-transaction.
37716 */
37717 static void btreeClearHasContent(BtShared *pBt){
37718   sqlite3BitvecDestroy(pBt->pHasContent);
37719   pBt->pHasContent = 0;
37720 }
37721
37722 /*
37723 ** Save the current cursor position in the variables BtCursor.nKey 
37724 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
37725 */
37726 static int saveCursorPosition(BtCursor *pCur){
37727   int rc;
37728
37729   assert( CURSOR_VALID==pCur->eState );
37730   assert( 0==pCur->pKey );
37731   assert( cursorHoldsMutex(pCur) );
37732
37733   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
37734
37735   /* If this is an intKey table, then the above call to BtreeKeySize()
37736   ** stores the integer key in pCur->nKey. In this case this value is
37737   ** all that is required. Otherwise, if pCur is not open on an intKey
37738   ** table, then malloc space for and store the pCur->nKey bytes of key 
37739   ** data.
37740   */
37741   if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
37742     void *pKey = sqlite3Malloc( (int)pCur->nKey );
37743     if( pKey ){
37744       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
37745       if( rc==SQLITE_OK ){
37746         pCur->pKey = pKey;
37747       }else{
37748         sqlite3_free(pKey);
37749       }
37750     }else{
37751       rc = SQLITE_NOMEM;
37752     }
37753   }
37754   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
37755
37756   if( rc==SQLITE_OK ){
37757     int i;
37758     for(i=0; i<=pCur->iPage; i++){
37759       releasePage(pCur->apPage[i]);
37760       pCur->apPage[i] = 0;
37761     }
37762     pCur->iPage = -1;
37763     pCur->eState = CURSOR_REQUIRESEEK;
37764   }
37765
37766   invalidateOverflowCache(pCur);
37767   return rc;
37768 }
37769
37770 /*
37771 ** Save the positions of all cursors except pExcept open on the table 
37772 ** with root-page iRoot. Usually, this is called just before cursor
37773 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
37774 */
37775 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
37776   BtCursor *p;
37777   assert( sqlite3_mutex_held(pBt->mutex) );
37778   assert( pExcept==0 || pExcept->pBt==pBt );
37779   for(p=pBt->pCursor; p; p=p->pNext){
37780     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
37781         p->eState==CURSOR_VALID ){
37782       int rc = saveCursorPosition(p);
37783       if( SQLITE_OK!=rc ){
37784         return rc;
37785       }
37786     }
37787   }
37788   return SQLITE_OK;
37789 }
37790
37791 /*
37792 ** Clear the current cursor position.
37793 */
37794 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
37795   assert( cursorHoldsMutex(pCur) );
37796   sqlite3_free(pCur->pKey);
37797   pCur->pKey = 0;
37798   pCur->eState = CURSOR_INVALID;
37799 }
37800
37801 /*
37802 ** Restore the cursor to the position it was in (or as close to as possible)
37803 ** when saveCursorPosition() was called. Note that this call deletes the 
37804 ** saved position info stored by saveCursorPosition(), so there can be
37805 ** at most one effective restoreCursorPosition() call after each 
37806 ** saveCursorPosition().
37807 */
37808 SQLITE_PRIVATE int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
37809   int rc;
37810   assert( cursorHoldsMutex(pCur) );
37811   assert( pCur->eState>=CURSOR_REQUIRESEEK );
37812   if( pCur->eState==CURSOR_FAULT ){
37813     return pCur->skip;
37814   }
37815   pCur->eState = CURSOR_INVALID;
37816   rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
37817   if( rc==SQLITE_OK ){
37818     sqlite3_free(pCur->pKey);
37819     pCur->pKey = 0;
37820     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
37821   }
37822   return rc;
37823 }
37824
37825 #define restoreCursorPosition(p) \
37826   (p->eState>=CURSOR_REQUIRESEEK ? \
37827          sqlite3BtreeRestoreCursorPosition(p) : \
37828          SQLITE_OK)
37829
37830 /*
37831 ** Determine whether or not a cursor has moved from the position it
37832 ** was last placed at.  Cursors can move when the row they are pointing
37833 ** at is deleted out from under them.
37834 **
37835 ** This routine returns an error code if something goes wrong.  The
37836 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
37837 */
37838 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
37839   int rc;
37840
37841   rc = restoreCursorPosition(pCur);
37842   if( rc ){
37843     *pHasMoved = 1;
37844     return rc;
37845   }
37846   if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
37847     *pHasMoved = 1;
37848   }else{
37849     *pHasMoved = 0;
37850   }
37851   return SQLITE_OK;
37852 }
37853
37854 #ifndef SQLITE_OMIT_AUTOVACUUM
37855 /*
37856 ** Given a page number of a regular database page, return the page
37857 ** number for the pointer-map page that contains the entry for the
37858 ** input page number.
37859 */
37860 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
37861   int nPagesPerMapPage;
37862   Pgno iPtrMap, ret;
37863   assert( sqlite3_mutex_held(pBt->mutex) );
37864   nPagesPerMapPage = (pBt->usableSize/5)+1;
37865   iPtrMap = (pgno-2)/nPagesPerMapPage;
37866   ret = (iPtrMap*nPagesPerMapPage) + 2; 
37867   if( ret==PENDING_BYTE_PAGE(pBt) ){
37868     ret++;
37869   }
37870   return ret;
37871 }
37872
37873 /*
37874 ** Write an entry into the pointer map.
37875 **
37876 ** This routine updates the pointer map entry for page number 'key'
37877 ** so that it maps to type 'eType' and parent page number 'pgno'.
37878 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
37879 */
37880 static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
37881   DbPage *pDbPage;  /* The pointer map page */
37882   u8 *pPtrmap;      /* The pointer map data */
37883   Pgno iPtrmap;     /* The pointer map page number */
37884   int offset;       /* Offset in pointer map page */
37885   int rc;
37886
37887   assert( sqlite3_mutex_held(pBt->mutex) );
37888   /* The master-journal page number must never be used as a pointer map page */
37889   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
37890
37891   assert( pBt->autoVacuum );
37892   if( key==0 ){
37893     return SQLITE_CORRUPT_BKPT;
37894   }
37895   iPtrmap = PTRMAP_PAGENO(pBt, key);
37896   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
37897   if( rc!=SQLITE_OK ){
37898     return rc;
37899   }
37900   offset = PTRMAP_PTROFFSET(iPtrmap, key);
37901   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
37902
37903   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
37904     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
37905     rc = sqlite3PagerWrite(pDbPage);
37906     if( rc==SQLITE_OK ){
37907       pPtrmap[offset] = eType;
37908       put4byte(&pPtrmap[offset+1], parent);
37909     }
37910   }
37911
37912   sqlite3PagerUnref(pDbPage);
37913   return rc;
37914 }
37915
37916 /*
37917 ** Read an entry from the pointer map.
37918 **
37919 ** This routine retrieves the pointer map entry for page 'key', writing
37920 ** the type and parent page number to *pEType and *pPgno respectively.
37921 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
37922 */
37923 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
37924   DbPage *pDbPage;   /* The pointer map page */
37925   int iPtrmap;       /* Pointer map page index */
37926   u8 *pPtrmap;       /* Pointer map page data */
37927   int offset;        /* Offset of entry in pointer map */
37928   int rc;
37929
37930   assert( sqlite3_mutex_held(pBt->mutex) );
37931
37932   iPtrmap = PTRMAP_PAGENO(pBt, key);
37933   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
37934   if( rc!=0 ){
37935     return rc;
37936   }
37937   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
37938
37939   offset = PTRMAP_PTROFFSET(iPtrmap, key);
37940   assert( pEType!=0 );
37941   *pEType = pPtrmap[offset];
37942   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
37943
37944   sqlite3PagerUnref(pDbPage);
37945   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
37946   return SQLITE_OK;
37947 }
37948
37949 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
37950   #define ptrmapPut(w,x,y,z) SQLITE_OK
37951   #define ptrmapGet(w,x,y,z) SQLITE_OK
37952   #define ptrmapPutOvfl(y,z) SQLITE_OK
37953 #endif
37954
37955 /*
37956 ** Given a btree page and a cell index (0 means the first cell on
37957 ** the page, 1 means the second cell, and so forth) return a pointer
37958 ** to the cell content.
37959 **
37960 ** This routine works only for pages that do not contain overflow cells.
37961 */
37962 #define findCell(P,I) \
37963   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
37964
37965 /*
37966 ** This a more complex version of findCell() that works for
37967 ** pages that do contain overflow cells.  See insert
37968 */
37969 static u8 *findOverflowCell(MemPage *pPage, int iCell){
37970   int i;
37971   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
37972   for(i=pPage->nOverflow-1; i>=0; i--){
37973     int k;
37974     struct _OvflCell *pOvfl;
37975     pOvfl = &pPage->aOvfl[i];
37976     k = pOvfl->idx;
37977     if( k<=iCell ){
37978       if( k==iCell ){
37979         return pOvfl->pCell;
37980       }
37981       iCell--;
37982     }
37983   }
37984   return findCell(pPage, iCell);
37985 }
37986
37987 /*
37988 ** Parse a cell content block and fill in the CellInfo structure.  There
37989 ** are two versions of this function.  sqlite3BtreeParseCell() takes a 
37990 ** cell index as the second argument and sqlite3BtreeParseCellPtr() 
37991 ** takes a pointer to the body of the cell as its second argument.
37992 **
37993 ** Within this file, the parseCell() macro can be called instead of
37994 ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
37995 */
37996 SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
37997   MemPage *pPage,         /* Page containing the cell */
37998   u8 *pCell,              /* Pointer to the cell text. */
37999   CellInfo *pInfo         /* Fill in this structure */
38000 ){
38001   u16 n;                  /* Number bytes in cell content header */
38002   u32 nPayload;           /* Number of bytes of cell payload */
38003
38004   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38005
38006   pInfo->pCell = pCell;
38007   assert( pPage->leaf==0 || pPage->leaf==1 );
38008   n = pPage->childPtrSize;
38009   assert( n==4-4*pPage->leaf );
38010   if( pPage->intKey ){
38011     if( pPage->hasData ){
38012       n += getVarint32(&pCell[n], nPayload);
38013     }else{
38014       nPayload = 0;
38015     }
38016     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38017     pInfo->nData = nPayload;
38018   }else{
38019     pInfo->nData = 0;
38020     n += getVarint32(&pCell[n], nPayload);
38021     pInfo->nKey = nPayload;
38022   }
38023   pInfo->nPayload = nPayload;
38024   pInfo->nHeader = n;
38025   if( likely(nPayload<=pPage->maxLocal) ){
38026     /* This is the (easy) common case where the entire payload fits
38027     ** on the local page.  No overflow is required.
38028     */
38029     int nSize;          /* Total size of cell content in bytes */
38030     nSize = nPayload + n;
38031     pInfo->nLocal = (u16)nPayload;
38032     pInfo->iOverflow = 0;
38033     if( (nSize & ~3)==0 ){
38034       nSize = 4;        /* Minimum cell size is 4 */
38035     }
38036     pInfo->nSize = (u16)nSize;
38037   }else{
38038     /* If the payload will not fit completely on the local page, we have
38039     ** to decide how much to store locally and how much to spill onto
38040     ** overflow pages.  The strategy is to minimize the amount of unused
38041     ** space on overflow pages while keeping the amount of local storage
38042     ** in between minLocal and maxLocal.
38043     **
38044     ** Warning:  changing the way overflow payload is distributed in any
38045     ** way will result in an incompatible file format.
38046     */
38047     int minLocal;  /* Minimum amount of payload held locally */
38048     int maxLocal;  /* Maximum amount of payload held locally */
38049     int surplus;   /* Overflow payload available for local storage */
38050
38051     minLocal = pPage->minLocal;
38052     maxLocal = pPage->maxLocal;
38053     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38054     if( surplus <= maxLocal ){
38055       pInfo->nLocal = (u16)surplus;
38056     }else{
38057       pInfo->nLocal = (u16)minLocal;
38058     }
38059     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38060     pInfo->nSize = pInfo->iOverflow + 4;
38061   }
38062 }
38063 #define parseCell(pPage, iCell, pInfo) \
38064   sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38065 SQLITE_PRIVATE void sqlite3BtreeParseCell(
38066   MemPage *pPage,         /* Page containing the cell */
38067   int iCell,              /* The cell index.  First cell is 0 */
38068   CellInfo *pInfo         /* Fill in this structure */
38069 ){
38070   parseCell(pPage, iCell, pInfo);
38071 }
38072
38073 /*
38074 ** Compute the total number of bytes that a Cell needs in the cell
38075 ** data area of the btree-page.  The return number includes the cell
38076 ** data header and the local payload, but not any overflow page or
38077 ** the space used by the cell pointer.
38078 */
38079 #ifndef NDEBUG
38080 static u16 cellSize(MemPage *pPage, int iCell){
38081   CellInfo info;
38082   sqlite3BtreeParseCell(pPage, iCell, &info);
38083   return info.nSize;
38084 }
38085 #endif
38086 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38087   CellInfo info;
38088   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38089   return info.nSize;
38090 }
38091
38092 #ifndef SQLITE_OMIT_AUTOVACUUM
38093 /*
38094 ** If the cell pCell, part of page pPage contains a pointer
38095 ** to an overflow page, insert an entry into the pointer-map
38096 ** for the overflow page.
38097 */
38098 static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
38099   CellInfo info;
38100   assert( pCell!=0 );
38101   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
38102   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38103   if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
38104     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38105     return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
38106   }
38107   return SQLITE_OK;
38108 }
38109 /*
38110 ** If the cell with index iCell on page pPage contains a pointer
38111 ** to an overflow page, insert an entry into the pointer-map
38112 ** for the overflow page.
38113 */
38114 static int ptrmapPutOvfl(MemPage *pPage, int iCell){
38115   u8 *pCell;
38116   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38117   pCell = findOverflowCell(pPage, iCell);
38118   return ptrmapPutOvflPtr(pPage, pCell);
38119 }
38120 #endif
38121
38122
38123 /*
38124 ** Defragment the page given.  All Cells are moved to the
38125 ** end of the page and all free space is collected into one
38126 ** big FreeBlk that occurs in between the header and cell
38127 ** pointer array and the cell content area.
38128 */
38129 static int defragmentPage(MemPage *pPage){
38130   int i;                     /* Loop counter */
38131   int pc;                    /* Address of a i-th cell */
38132   int addr;                  /* Offset of first byte after cell pointer array */
38133   int hdr;                   /* Offset to the page header */
38134   int size;                  /* Size of a cell */
38135   int usableSize;            /* Number of usable bytes on a page */
38136   int cellOffset;            /* Offset to the cell pointer array */
38137   int cbrk;                  /* Offset to the cell content area */
38138   int nCell;                 /* Number of cells on the page */
38139   unsigned char *data;       /* The page data */
38140   unsigned char *temp;       /* Temp area for cell content */
38141
38142   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38143   assert( pPage->pBt!=0 );
38144   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38145   assert( pPage->nOverflow==0 );
38146   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38147   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38148   data = pPage->aData;
38149   hdr = pPage->hdrOffset;
38150   cellOffset = pPage->cellOffset;
38151   nCell = pPage->nCell;
38152   assert( nCell==get2byte(&data[hdr+3]) );
38153   usableSize = pPage->pBt->usableSize;
38154   cbrk = get2byte(&data[hdr+5]);
38155   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38156   cbrk = usableSize;
38157   for(i=0; i<nCell; i++){
38158     u8 *pAddr;     /* The i-th cell pointer */
38159     pAddr = &data[cellOffset + i*2];
38160     pc = get2byte(pAddr);
38161     if( pc>=usableSize ){
38162       return SQLITE_CORRUPT_BKPT;
38163     }
38164     size = cellSizePtr(pPage, &temp[pc]);
38165     cbrk -= size;
38166     if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
38167       return SQLITE_CORRUPT_BKPT;
38168     }
38169     assert( cbrk+size<=usableSize && cbrk>=0 );
38170     memcpy(&data[cbrk], &temp[pc], size);
38171     put2byte(pAddr, cbrk);
38172   }
38173   assert( cbrk>=cellOffset+2*nCell );
38174   put2byte(&data[hdr+5], cbrk);
38175   data[hdr+1] = 0;
38176   data[hdr+2] = 0;
38177   data[hdr+7] = 0;
38178   addr = cellOffset+2*nCell;
38179   memset(&data[addr], 0, cbrk-addr);
38180   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38181   if( cbrk-addr!=pPage->nFree ){
38182     return SQLITE_CORRUPT_BKPT;
38183   }
38184   return SQLITE_OK;
38185 }
38186
38187 /*
38188 ** Allocate nByte bytes of space on a page.
38189 **
38190 ** Return the index into pPage->aData[] of the first byte of
38191 ** the new allocation.  The caller guarantees that there is enough
38192 ** space.  This routine will never fail.
38193 **
38194 ** If the page contains nBytes of free space but does not contain
38195 ** nBytes of contiguous free space, then this routine automatically
38196 ** calls defragementPage() to consolidate all free space before 
38197 ** allocating the new chunk.
38198 */
38199 static int allocateSpace(MemPage *pPage, int nByte){
38200   int addr, pc, hdr;
38201   int size;
38202   int nFrag;
38203   int top;
38204   int nCell;
38205   int cellOffset;
38206   unsigned char *data;
38207   
38208   data = pPage->aData;
38209   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38210   assert( pPage->pBt );
38211   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38212   assert( nByte>=0 );  /* Minimum cell size is 4 */
38213   assert( pPage->nFree>=nByte );
38214   assert( pPage->nOverflow==0 );
38215   pPage->nFree -= (u16)nByte;
38216   hdr = pPage->hdrOffset;
38217
38218   nFrag = data[hdr+7];
38219   if( nFrag<60 ){
38220     /* Search the freelist looking for a slot big enough to satisfy the
38221     ** space request. */
38222     addr = hdr+1;
38223     while( (pc = get2byte(&data[addr]))>0 ){
38224       size = get2byte(&data[pc+2]);
38225       if( size>=nByte ){
38226         int x = size - nByte;
38227         if( size<nByte+4 ){
38228           memcpy(&data[addr], &data[pc], 2);
38229           data[hdr+7] = (u8)(nFrag + x);
38230           return pc;
38231         }else{
38232           put2byte(&data[pc+2], x);
38233           return pc + x;
38234         }
38235       }
38236       addr = pc;
38237     }
38238   }
38239
38240   /* Allocate memory from the gap in between the cell pointer array
38241   ** and the cell content area.
38242   */
38243   top = get2byte(&data[hdr+5]);
38244   nCell = get2byte(&data[hdr+3]);
38245   cellOffset = pPage->cellOffset;
38246   if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
38247     defragmentPage(pPage);
38248     top = get2byte(&data[hdr+5]);
38249   }
38250   top -= nByte;
38251   assert( cellOffset + 2*nCell <= top );
38252   put2byte(&data[hdr+5], top);
38253   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38254   return top;
38255 }
38256
38257 /*
38258 ** Return a section of the pPage->aData to the freelist.
38259 ** The first byte of the new free block is pPage->aDisk[start]
38260 ** and the size of the block is "size" bytes.
38261 **
38262 ** Most of the effort here is involved in coalesing adjacent
38263 ** free blocks into a single big free block.
38264 */
38265 static int freeSpace(MemPage *pPage, int start, int size){
38266   int addr, pbegin, hdr;
38267   unsigned char *data = pPage->aData;
38268
38269   assert( pPage->pBt!=0 );
38270   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38271   assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
38272   assert( (start + size)<=pPage->pBt->usableSize );
38273   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38274   assert( size>=0 );   /* Minimum cell size is 4 */
38275
38276 #ifdef SQLITE_SECURE_DELETE
38277   /* Overwrite deleted information with zeros when the SECURE_DELETE 
38278   ** option is enabled at compile-time */
38279   memset(&data[start], 0, size);
38280 #endif
38281
38282   /* Add the space back into the linked list of freeblocks */
38283   hdr = pPage->hdrOffset;
38284   addr = hdr + 1;
38285   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
38286     assert( pbegin<=pPage->pBt->usableSize-4 );
38287     if( pbegin<=addr ) {
38288       return SQLITE_CORRUPT_BKPT;
38289     }
38290     addr = pbegin;
38291   }
38292   if ( pbegin>pPage->pBt->usableSize-4 ) {
38293     return SQLITE_CORRUPT_BKPT;
38294   }
38295   assert( pbegin>addr || pbegin==0 );
38296   put2byte(&data[addr], start);
38297   put2byte(&data[start], pbegin);
38298   put2byte(&data[start+2], size);
38299   pPage->nFree += (u16)size;
38300
38301   /* Coalesce adjacent free blocks */
38302   addr = pPage->hdrOffset + 1;
38303   while( (pbegin = get2byte(&data[addr]))>0 ){
38304     int pnext, psize, x;
38305     assert( pbegin>addr );
38306     assert( pbegin<=pPage->pBt->usableSize-4 );
38307     pnext = get2byte(&data[pbegin]);
38308     psize = get2byte(&data[pbegin+2]);
38309     if( pbegin + psize + 3 >= pnext && pnext>0 ){
38310       int frag = pnext - (pbegin+psize);
38311       if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
38312         return SQLITE_CORRUPT_BKPT;
38313       }
38314       data[pPage->hdrOffset+7] -= (u8)frag;
38315       x = get2byte(&data[pnext]);
38316       put2byte(&data[pbegin], x);
38317       x = pnext + get2byte(&data[pnext+2]) - pbegin;
38318       put2byte(&data[pbegin+2], x);
38319     }else{
38320       addr = pbegin;
38321     }
38322   }
38323
38324   /* If the cell content area begins with a freeblock, remove it. */
38325   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
38326     int top;
38327     pbegin = get2byte(&data[hdr+1]);
38328     memcpy(&data[hdr+1], &data[pbegin], 2);
38329     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
38330     put2byte(&data[hdr+5], top);
38331   }
38332   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38333   return SQLITE_OK;
38334 }
38335
38336 /*
38337 ** Decode the flags byte (the first byte of the header) for a page
38338 ** and initialize fields of the MemPage structure accordingly.
38339 **
38340 ** Only the following combinations are supported.  Anything different
38341 ** indicates a corrupt database files:
38342 **
38343 **         PTF_ZERODATA
38344 **         PTF_ZERODATA | PTF_LEAF
38345 **         PTF_LEAFDATA | PTF_INTKEY
38346 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
38347 */
38348 static int decodeFlags(MemPage *pPage, int flagByte){
38349   BtShared *pBt;     /* A copy of pPage->pBt */
38350
38351   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
38352   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38353   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
38354   flagByte &= ~PTF_LEAF;
38355   pPage->childPtrSize = 4-4*pPage->leaf;
38356   pBt = pPage->pBt;
38357   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
38358     pPage->intKey = 1;
38359     pPage->hasData = pPage->leaf;
38360     pPage->maxLocal = pBt->maxLeaf;
38361     pPage->minLocal = pBt->minLeaf;
38362   }else if( flagByte==PTF_ZERODATA ){
38363     pPage->intKey = 0;
38364     pPage->hasData = 0;
38365     pPage->maxLocal = pBt->maxLocal;
38366     pPage->minLocal = pBt->minLocal;
38367   }else{
38368     return SQLITE_CORRUPT_BKPT;
38369   }
38370   return SQLITE_OK;
38371 }
38372
38373 /*
38374 ** Initialize the auxiliary information for a disk block.
38375 **
38376 ** Return SQLITE_OK on success.  If we see that the page does
38377 ** not contain a well-formed database page, then return 
38378 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
38379 ** guarantee that the page is well-formed.  It only shows that
38380 ** we failed to detect any corruption.
38381 */
38382 SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage){
38383
38384   assert( pPage->pBt!=0 );
38385   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38386   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
38387   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
38388   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
38389
38390   if( !pPage->isInit ){
38391     u16 pc;            /* Address of a freeblock within pPage->aData[] */
38392     u8 hdr;            /* Offset to beginning of page header */
38393     u8 *data;          /* Equal to pPage->aData */
38394     BtShared *pBt;        /* The main btree structure */
38395     u16 usableSize;    /* Amount of usable space on each page */
38396     u16 cellOffset;    /* Offset from start of page to first cell pointer */
38397     u16 nFree;         /* Number of unused bytes on the page */
38398     u16 top;           /* First byte of the cell content area */
38399
38400     pBt = pPage->pBt;
38401
38402     hdr = pPage->hdrOffset;
38403     data = pPage->aData;
38404     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
38405     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
38406     pPage->maskPage = pBt->pageSize - 1;
38407     pPage->nOverflow = 0;
38408     usableSize = pBt->usableSize;
38409     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
38410     top = get2byte(&data[hdr+5]);
38411     pPage->nCell = get2byte(&data[hdr+3]);
38412     if( pPage->nCell>MX_CELL(pBt) ){
38413       /* To many cells for a single page.  The page must be corrupt */
38414       return SQLITE_CORRUPT_BKPT;
38415     }
38416   
38417     /* Compute the total free space on the page */
38418     pc = get2byte(&data[hdr+1]);
38419     nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
38420     while( pc>0 ){
38421       u16 next, size;
38422       if( pc>usableSize-4 ){
38423         /* Free block is off the page */
38424         return SQLITE_CORRUPT_BKPT; 
38425       }
38426       next = get2byte(&data[pc]);
38427       size = get2byte(&data[pc+2]);
38428       if( next>0 && next<=pc+size+3 ){
38429         /* Free blocks must be in accending order */
38430         return SQLITE_CORRUPT_BKPT; 
38431       }
38432       nFree += size;
38433       pc = next;
38434     }
38435     pPage->nFree = (u16)nFree;
38436     if( nFree>=usableSize ){
38437       /* Free space cannot exceed total page size */
38438       return SQLITE_CORRUPT_BKPT; 
38439     }
38440
38441 #if 0
38442   /* Check that all the offsets in the cell offset array are within range. 
38443   ** 
38444   ** Omitting this consistency check and using the pPage->maskPage mask
38445   ** to prevent overrunning the page buffer in findCell() results in a
38446   ** 2.5% performance gain.
38447   */
38448   {
38449     u8 *pOff;        /* Iterator used to check all cell offsets are in range */
38450     u8 *pEnd;        /* Pointer to end of cell offset array */
38451     u8 mask;         /* Mask of bits that must be zero in MSB of cell offsets */
38452     mask = ~(((u8)(pBt->pageSize>>8))-1);
38453     pEnd = &data[cellOffset + pPage->nCell*2];
38454     for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
38455     if( pOff!=pEnd ){
38456       return SQLITE_CORRUPT_BKPT;
38457     }
38458   }
38459 #endif
38460
38461     pPage->isInit = 1;
38462   }
38463   return SQLITE_OK;
38464 }
38465
38466 /*
38467 ** Set up a raw page so that it looks like a database page holding
38468 ** no entries.
38469 */
38470 static void zeroPage(MemPage *pPage, int flags){
38471   unsigned char *data = pPage->aData;
38472   BtShared *pBt = pPage->pBt;
38473   u8 hdr = pPage->hdrOffset;
38474   u16 first;
38475
38476   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
38477   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
38478   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
38479   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38480   assert( sqlite3_mutex_held(pBt->mutex) );
38481   /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
38482   data[hdr] = (char)flags;
38483   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
38484   memset(&data[hdr+1], 0, 4);
38485   data[hdr+7] = 0;
38486   put2byte(&data[hdr+5], pBt->usableSize);
38487   pPage->nFree = pBt->usableSize - first;
38488   decodeFlags(pPage, flags);
38489   pPage->hdrOffset = hdr;
38490   pPage->cellOffset = first;
38491   pPage->nOverflow = 0;
38492   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
38493   pPage->maskPage = pBt->pageSize - 1;
38494   pPage->nCell = 0;
38495   pPage->isInit = 1;
38496 }
38497
38498
38499 /*
38500 ** Convert a DbPage obtained from the pager into a MemPage used by
38501 ** the btree layer.
38502 */
38503 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
38504   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
38505   pPage->aData = sqlite3PagerGetData(pDbPage);
38506   pPage->pDbPage = pDbPage;
38507   pPage->pBt = pBt;
38508   pPage->pgno = pgno;
38509   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
38510   return pPage; 
38511 }
38512
38513 /*
38514 ** Get a page from the pager.  Initialize the MemPage.pBt and
38515 ** MemPage.aData elements if needed.
38516 **
38517 ** If the noContent flag is set, it means that we do not care about
38518 ** the content of the page at this time.  So do not go to the disk
38519 ** to fetch the content.  Just fill in the content with zeros for now.
38520 ** If in the future we call sqlite3PagerWrite() on this page, that
38521 ** means we have started to be concerned about content and the disk
38522 ** read should occur at that point.
38523 */
38524 SQLITE_PRIVATE int sqlite3BtreeGetPage(
38525   BtShared *pBt,       /* The btree */
38526   Pgno pgno,           /* Number of the page to fetch */
38527   MemPage **ppPage,    /* Return the page in this parameter */
38528   int noContent        /* Do not load page content if true */
38529 ){
38530   int rc;
38531   DbPage *pDbPage;
38532
38533   assert( sqlite3_mutex_held(pBt->mutex) );
38534   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
38535   if( rc ) return rc;
38536   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
38537   return SQLITE_OK;
38538 }
38539
38540 /*
38541 ** Retrieve a page from the pager cache. If the requested page is not
38542 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
38543 ** MemPage.aData elements if needed.
38544 */
38545 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
38546   DbPage *pDbPage;
38547   assert( sqlite3_mutex_held(pBt->mutex) );
38548   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
38549   if( pDbPage ){
38550     return btreePageFromDbPage(pDbPage, pgno, pBt);
38551   }
38552   return 0;
38553 }
38554
38555 /*
38556 ** Return the size of the database file in pages. If there is any kind of
38557 ** error, return ((unsigned int)-1).
38558 */
38559 static Pgno pagerPagecount(BtShared *pBt){
38560   int nPage = -1;
38561   int rc;
38562   assert( pBt->pPage1 );
38563   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
38564   assert( rc==SQLITE_OK || nPage==-1 );
38565   return (Pgno)nPage;
38566 }
38567
38568 /*
38569 ** Get a page from the pager and initialize it.  This routine
38570 ** is just a convenience wrapper around separate calls to
38571 ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
38572 */
38573 static int getAndInitPage(
38574   BtShared *pBt,          /* The database file */
38575   Pgno pgno,           /* Number of the page to get */
38576   MemPage **ppPage     /* Write the page pointer here */
38577 ){
38578   int rc;
38579   MemPage *pPage;
38580
38581   assert( sqlite3_mutex_held(pBt->mutex) );
38582   if( pgno==0 ){
38583     return SQLITE_CORRUPT_BKPT; 
38584   }
38585
38586   /* It is often the case that the page we want is already in cache.
38587   ** If so, get it directly.  This saves us from having to call
38588   ** pagerPagecount() to make sure pgno is within limits, which results
38589   ** in a measureable performance improvements.
38590   */
38591   *ppPage = pPage = btreePageLookup(pBt, pgno);
38592   if( pPage ){
38593     /* Page is already in cache */
38594     rc = SQLITE_OK;
38595   }else{
38596     /* Page not in cache.  Acquire it. */
38597     if( pgno>pagerPagecount(pBt) ){
38598       return SQLITE_CORRUPT_BKPT; 
38599     }
38600     rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
38601     if( rc ) return rc;
38602     pPage = *ppPage;
38603   }
38604   if( !pPage->isInit ){
38605     rc = sqlite3BtreeInitPage(pPage);
38606   }
38607   if( rc!=SQLITE_OK ){
38608     releasePage(pPage);
38609     *ppPage = 0;
38610   }
38611   return rc;
38612 }
38613
38614 /*
38615 ** Release a MemPage.  This should be called once for each prior
38616 ** call to sqlite3BtreeGetPage.
38617 */
38618 static void releasePage(MemPage *pPage){
38619   if( pPage ){
38620     assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
38621     assert( pPage->aData );
38622     assert( pPage->pBt );
38623     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
38624     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
38625     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38626     sqlite3PagerUnref(pPage->pDbPage);
38627   }
38628 }
38629
38630 /*
38631 ** During a rollback, when the pager reloads information into the cache
38632 ** so that the cache is restored to its original state at the start of
38633 ** the transaction, for each page restored this routine is called.
38634 **
38635 ** This routine needs to reset the extra data section at the end of the
38636 ** page to agree with the restored data.
38637 */
38638 static void pageReinit(DbPage *pData){
38639   MemPage *pPage;
38640   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
38641   if( pPage->isInit ){
38642     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38643     pPage->isInit = 0;
38644     if( sqlite3PagerPageRefcount(pData)>0 ){
38645       sqlite3BtreeInitPage(pPage);
38646     }
38647   }
38648 }
38649
38650 /*
38651 ** Invoke the busy handler for a btree.
38652 */
38653 static int btreeInvokeBusyHandler(void *pArg){
38654   BtShared *pBt = (BtShared*)pArg;
38655   assert( pBt->db );
38656   assert( sqlite3_mutex_held(pBt->db->mutex) );
38657   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
38658 }
38659
38660 /*
38661 ** Open a database file.
38662 ** 
38663 ** zFilename is the name of the database file.  If zFilename is NULL
38664 ** a new database with a random name is created.  This randomly named
38665 ** database file will be deleted when sqlite3BtreeClose() is called.
38666 ** If zFilename is ":memory:" then an in-memory database is created
38667 ** that is automatically destroyed when it is closed.
38668 */
38669 SQLITE_PRIVATE int sqlite3BtreeOpen(
38670   const char *zFilename,  /* Name of the file containing the BTree database */
38671   sqlite3 *db,            /* Associated database handle */
38672   Btree **ppBtree,        /* Pointer to new Btree object written here */
38673   int flags,              /* Options */
38674   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
38675 ){
38676   sqlite3_vfs *pVfs;      /* The VFS to use for this btree */
38677   BtShared *pBt = 0;      /* Shared part of btree structure */
38678   Btree *p;               /* Handle to return */
38679   int rc = SQLITE_OK;
38680   u8 nReserve;
38681   unsigned char zDbHeader[100];
38682
38683   /* Set the variable isMemdb to true for an in-memory database, or 
38684   ** false for a file-based database. This symbol is only required if
38685   ** either of the shared-data or autovacuum features are compiled 
38686   ** into the library.
38687   */
38688 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
38689   #ifdef SQLITE_OMIT_MEMORYDB
38690     const int isMemdb = 0;
38691   #else
38692     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
38693   #endif
38694 #endif
38695
38696   assert( db!=0 );
38697   assert( sqlite3_mutex_held(db->mutex) );
38698
38699   pVfs = db->pVfs;
38700   p = sqlite3MallocZero(sizeof(Btree));
38701   if( !p ){
38702     return SQLITE_NOMEM;
38703   }
38704   p->inTrans = TRANS_NONE;
38705   p->db = db;
38706
38707 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
38708   /*
38709   ** If this Btree is a candidate for shared cache, try to find an
38710   ** existing BtShared object that we can share with
38711   */
38712   if( isMemdb==0
38713    && (db->flags & SQLITE_Vtab)==0
38714    && zFilename && zFilename[0]
38715   ){
38716     if( sqlite3GlobalConfig.sharedCacheEnabled ){
38717       int nFullPathname = pVfs->mxPathname+1;
38718       char *zFullPathname = sqlite3Malloc(nFullPathname);
38719       sqlite3_mutex *mutexShared;
38720       p->sharable = 1;
38721       db->flags |= SQLITE_SharedCache;
38722       if( !zFullPathname ){
38723         sqlite3_free(p);
38724         return SQLITE_NOMEM;
38725       }
38726       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
38727       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
38728       sqlite3_mutex_enter(mutexShared);
38729       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
38730         assert( pBt->nRef>0 );
38731         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
38732                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
38733           p->pBt = pBt;
38734           pBt->nRef++;
38735           break;
38736         }
38737       }
38738       sqlite3_mutex_leave(mutexShared);
38739       sqlite3_free(zFullPathname);
38740     }
38741 #ifdef SQLITE_DEBUG
38742     else{
38743       /* In debug mode, we mark all persistent databases as sharable
38744       ** even when they are not.  This exercises the locking code and
38745       ** gives more opportunity for asserts(sqlite3_mutex_held())
38746       ** statements to find locking problems.
38747       */
38748       p->sharable = 1;
38749     }
38750 #endif
38751   }
38752 #endif
38753   if( pBt==0 ){
38754     /*
38755     ** The following asserts make sure that structures used by the btree are
38756     ** the right size.  This is to guard against size changes that result
38757     ** when compiling on a different architecture.
38758     */
38759     assert( sizeof(i64)==8 || sizeof(i64)==4 );
38760     assert( sizeof(u64)==8 || sizeof(u64)==4 );
38761     assert( sizeof(u32)==4 );
38762     assert( sizeof(u16)==2 );
38763     assert( sizeof(Pgno)==4 );
38764   
38765     pBt = sqlite3MallocZero( sizeof(*pBt) );
38766     if( pBt==0 ){
38767       rc = SQLITE_NOMEM;
38768       goto btree_open_out;
38769     }
38770     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
38771                           EXTRA_SIZE, flags, vfsFlags);
38772     if( rc==SQLITE_OK ){
38773       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
38774     }
38775     if( rc!=SQLITE_OK ){
38776       goto btree_open_out;
38777     }
38778     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
38779     p->pBt = pBt;
38780   
38781     sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
38782     pBt->pCursor = 0;
38783     pBt->pPage1 = 0;
38784     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
38785     pBt->pageSize = get2byte(&zDbHeader[16]);
38786     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
38787          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
38788       pBt->pageSize = 0;
38789       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38790 #ifndef SQLITE_OMIT_AUTOVACUUM
38791       /* If the magic name ":memory:" will create an in-memory database, then
38792       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
38793       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
38794       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
38795       ** regular file-name. In this case the auto-vacuum applies as per normal.
38796       */
38797       if( zFilename && !isMemdb ){
38798         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
38799         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
38800       }
38801 #endif
38802       nReserve = 0;
38803     }else{
38804       nReserve = zDbHeader[20];
38805       pBt->pageSizeFixed = 1;
38806 #ifndef SQLITE_OMIT_AUTOVACUUM
38807       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
38808       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
38809 #endif
38810     }
38811     pBt->usableSize = pBt->pageSize - nReserve;
38812     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
38813     sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38814    
38815 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
38816     /* Add the new BtShared object to the linked list sharable BtShareds.
38817     */
38818     if( p->sharable ){
38819       sqlite3_mutex *mutexShared;
38820       pBt->nRef = 1;
38821       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
38822       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
38823         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
38824         if( pBt->mutex==0 ){
38825           rc = SQLITE_NOMEM;
38826           db->mallocFailed = 0;
38827           goto btree_open_out;
38828         }
38829       }
38830       sqlite3_mutex_enter(mutexShared);
38831       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
38832       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
38833       sqlite3_mutex_leave(mutexShared);
38834     }
38835 #endif
38836   }
38837
38838 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
38839   /* If the new Btree uses a sharable pBtShared, then link the new
38840   ** Btree into the list of all sharable Btrees for the same connection.
38841   ** The list is kept in ascending order by pBt address.
38842   */
38843   if( p->sharable ){
38844     int i;
38845     Btree *pSib;
38846     for(i=0; i<db->nDb; i++){
38847       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
38848         while( pSib->pPrev ){ pSib = pSib->pPrev; }
38849         if( p->pBt<pSib->pBt ){
38850           p->pNext = pSib;
38851           p->pPrev = 0;
38852           pSib->pPrev = p;
38853         }else{
38854           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
38855             pSib = pSib->pNext;
38856           }
38857           p->pNext = pSib->pNext;
38858           p->pPrev = pSib;
38859           if( p->pNext ){
38860             p->pNext->pPrev = p;
38861           }
38862           pSib->pNext = p;
38863         }
38864         break;
38865       }
38866     }
38867   }
38868 #endif
38869   *ppBtree = p;
38870
38871 btree_open_out:
38872   if( rc!=SQLITE_OK ){
38873     if( pBt && pBt->pPager ){
38874       sqlite3PagerClose(pBt->pPager);
38875     }
38876     sqlite3_free(pBt);
38877     sqlite3_free(p);
38878     *ppBtree = 0;
38879   }
38880   return rc;
38881 }
38882
38883 /*
38884 ** Decrement the BtShared.nRef counter.  When it reaches zero,
38885 ** remove the BtShared structure from the sharing list.  Return
38886 ** true if the BtShared.nRef counter reaches zero and return
38887 ** false if it is still positive.
38888 */
38889 static int removeFromSharingList(BtShared *pBt){
38890 #ifndef SQLITE_OMIT_SHARED_CACHE
38891   sqlite3_mutex *pMaster;
38892   BtShared *pList;
38893   int removed = 0;
38894
38895   assert( sqlite3_mutex_notheld(pBt->mutex) );
38896   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
38897   sqlite3_mutex_enter(pMaster);
38898   pBt->nRef--;
38899   if( pBt->nRef<=0 ){
38900     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
38901       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
38902     }else{
38903       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
38904       while( ALWAYS(pList) && pList->pNext!=pBt ){
38905         pList=pList->pNext;
38906       }
38907       if( ALWAYS(pList) ){
38908         pList->pNext = pBt->pNext;
38909       }
38910     }
38911     if( SQLITE_THREADSAFE ){
38912       sqlite3_mutex_free(pBt->mutex);
38913     }
38914     removed = 1;
38915   }
38916   sqlite3_mutex_leave(pMaster);
38917   return removed;
38918 #else
38919   return 1;
38920 #endif
38921 }
38922
38923 /*
38924 ** Make sure pBt->pTmpSpace points to an allocation of 
38925 ** MX_CELL_SIZE(pBt) bytes.
38926 */
38927 static void allocateTempSpace(BtShared *pBt){
38928   if( !pBt->pTmpSpace ){
38929     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
38930   }
38931 }
38932
38933 /*
38934 ** Free the pBt->pTmpSpace allocation
38935 */
38936 static void freeTempSpace(BtShared *pBt){
38937   sqlite3PageFree( pBt->pTmpSpace);
38938   pBt->pTmpSpace = 0;
38939 }
38940
38941 /*
38942 ** Close an open database and invalidate all cursors.
38943 */
38944 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
38945   BtShared *pBt = p->pBt;
38946   BtCursor *pCur;
38947
38948   /* Close all cursors opened via this handle.  */
38949   assert( sqlite3_mutex_held(p->db->mutex) );
38950   sqlite3BtreeEnter(p);
38951   pBt->db = p->db;
38952   pCur = pBt->pCursor;
38953   while( pCur ){
38954     BtCursor *pTmp = pCur;
38955     pCur = pCur->pNext;
38956     if( pTmp->pBtree==p ){
38957       sqlite3BtreeCloseCursor(pTmp);
38958     }
38959   }
38960
38961   /* Rollback any active transaction and free the handle structure.
38962   ** The call to sqlite3BtreeRollback() drops any table-locks held by
38963   ** this handle.
38964   */
38965   sqlite3BtreeRollback(p);
38966   sqlite3BtreeLeave(p);
38967
38968   /* If there are still other outstanding references to the shared-btree
38969   ** structure, return now. The remainder of this procedure cleans 
38970   ** up the shared-btree.
38971   */
38972   assert( p->wantToLock==0 && p->locked==0 );
38973   if( !p->sharable || removeFromSharingList(pBt) ){
38974     /* The pBt is no longer on the sharing list, so we can access
38975     ** it without having to hold the mutex.
38976     **
38977     ** Clean out and delete the BtShared object.
38978     */
38979     assert( !pBt->pCursor );
38980     sqlite3PagerClose(pBt->pPager);
38981     if( pBt->xFreeSchema && pBt->pSchema ){
38982       pBt->xFreeSchema(pBt->pSchema);
38983     }
38984     sqlite3_free(pBt->pSchema);
38985     freeTempSpace(pBt);
38986     sqlite3_free(pBt);
38987   }
38988
38989 #ifndef SQLITE_OMIT_SHARED_CACHE
38990   assert( p->wantToLock==0 );
38991   assert( p->locked==0 );
38992   if( p->pPrev ) p->pPrev->pNext = p->pNext;
38993   if( p->pNext ) p->pNext->pPrev = p->pPrev;
38994 #endif
38995
38996   sqlite3_free(p);
38997   return SQLITE_OK;
38998 }
38999
39000 /*
39001 ** Change the limit on the number of pages allowed in the cache.
39002 **
39003 ** The maximum number of cache pages is set to the absolute
39004 ** value of mxPage.  If mxPage is negative, the pager will
39005 ** operate asynchronously - it will not stop to do fsync()s
39006 ** to insure data is written to the disk surface before
39007 ** continuing.  Transactions still work if synchronous is off,
39008 ** and the database cannot be corrupted if this program
39009 ** crashes.  But if the operating system crashes or there is
39010 ** an abrupt power failure when synchronous is off, the database
39011 ** could be left in an inconsistent and unrecoverable state.
39012 ** Synchronous is on by default so database corruption is not
39013 ** normally a worry.
39014 */
39015 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39016   BtShared *pBt = p->pBt;
39017   assert( sqlite3_mutex_held(p->db->mutex) );
39018   sqlite3BtreeEnter(p);
39019   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39020   sqlite3BtreeLeave(p);
39021   return SQLITE_OK;
39022 }
39023
39024 /*
39025 ** Change the way data is synced to disk in order to increase or decrease
39026 ** how well the database resists damage due to OS crashes and power
39027 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39028 ** there is a high probability of damage)  Level 2 is the default.  There
39029 ** is a very low but non-zero probability of damage.  Level 3 reduces the
39030 ** probability of damage to near zero but with a write performance reduction.
39031 */
39032 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39033 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39034   BtShared *pBt = p->pBt;
39035   assert( sqlite3_mutex_held(p->db->mutex) );
39036   sqlite3BtreeEnter(p);
39037   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39038   sqlite3BtreeLeave(p);
39039   return SQLITE_OK;
39040 }
39041 #endif
39042
39043 /*
39044 ** Return TRUE if the given btree is set to safety level 1.  In other
39045 ** words, return TRUE if no sync() occurs on the disk files.
39046 */
39047 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39048   BtShared *pBt = p->pBt;
39049   int rc;
39050   assert( sqlite3_mutex_held(p->db->mutex) );  
39051   sqlite3BtreeEnter(p);
39052   assert( pBt && pBt->pPager );
39053   rc = sqlite3PagerNosync(pBt->pPager);
39054   sqlite3BtreeLeave(p);
39055   return rc;
39056 }
39057
39058 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39059 /*
39060 ** Change the default pages size and the number of reserved bytes per page.
39061 **
39062 ** The page size must be a power of 2 between 512 and 65536.  If the page
39063 ** size supplied does not meet this constraint then the page size is not
39064 ** changed.
39065 **
39066 ** Page sizes are constrained to be a power of two so that the region
39067 ** of the database file used for locking (beginning at PENDING_BYTE,
39068 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
39069 ** at the beginning of a page.
39070 **
39071 ** If parameter nReserve is less than zero, then the number of reserved
39072 ** bytes per page is left unchanged.
39073 */
39074 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
39075   int rc = SQLITE_OK;
39076   BtShared *pBt = p->pBt;
39077   assert( nReserve>=-1 && nReserve<=255 );
39078   sqlite3BtreeEnter(p);
39079   if( pBt->pageSizeFixed ){
39080     sqlite3BtreeLeave(p);
39081     return SQLITE_READONLY;
39082   }
39083   if( nReserve<0 ){
39084     nReserve = pBt->pageSize - pBt->usableSize;
39085   }
39086   assert( nReserve>=0 && nReserve<=255 );
39087   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39088         ((pageSize-1)&pageSize)==0 ){
39089     assert( (pageSize & 7)==0 );
39090     assert( !pBt->pPage1 && !pBt->pCursor );
39091     pBt->pageSize = (u16)pageSize;
39092     freeTempSpace(pBt);
39093     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
39094   }
39095   pBt->usableSize = pBt->pageSize - (u16)nReserve;
39096   sqlite3BtreeLeave(p);
39097   return rc;
39098 }
39099
39100 /*
39101 ** Return the currently defined page size
39102 */
39103 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39104   return p->pBt->pageSize;
39105 }
39106 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39107   int n;
39108   sqlite3BtreeEnter(p);
39109   n = p->pBt->pageSize - p->pBt->usableSize;
39110   sqlite3BtreeLeave(p);
39111   return n;
39112 }
39113
39114 /*
39115 ** Set the maximum page count for a database if mxPage is positive.
39116 ** No changes are made if mxPage is 0 or negative.
39117 ** Regardless of the value of mxPage, return the maximum page count.
39118 */
39119 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39120   int n;
39121   sqlite3BtreeEnter(p);
39122   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39123   sqlite3BtreeLeave(p);
39124   return n;
39125 }
39126 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39127
39128 /*
39129 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39130 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39131 ** is disabled. The default value for the auto-vacuum property is 
39132 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39133 */
39134 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39135 #ifdef SQLITE_OMIT_AUTOVACUUM
39136   return SQLITE_READONLY;
39137 #else
39138   BtShared *pBt = p->pBt;
39139   int rc = SQLITE_OK;
39140   u8 av = autoVacuum ?1:0;
39141
39142   sqlite3BtreeEnter(p);
39143   if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
39144     rc = SQLITE_READONLY;
39145   }else{
39146     pBt->autoVacuum = av;
39147   }
39148   sqlite3BtreeLeave(p);
39149   return rc;
39150 #endif
39151 }
39152
39153 /*
39154 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
39155 ** enabled 1 is returned. Otherwise 0.
39156 */
39157 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39158 #ifdef SQLITE_OMIT_AUTOVACUUM
39159   return BTREE_AUTOVACUUM_NONE;
39160 #else
39161   int rc;
39162   sqlite3BtreeEnter(p);
39163   rc = (
39164     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39165     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39166     BTREE_AUTOVACUUM_INCR
39167   );
39168   sqlite3BtreeLeave(p);
39169   return rc;
39170 #endif
39171 }
39172
39173
39174 /*
39175 ** Get a reference to pPage1 of the database file.  This will
39176 ** also acquire a readlock on that file.
39177 **
39178 ** SQLITE_OK is returned on success.  If the file is not a
39179 ** well-formed database file, then SQLITE_CORRUPT is returned.
39180 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
39181 ** is returned if we run out of memory. 
39182 */
39183 static int lockBtree(BtShared *pBt){
39184   int rc;
39185   MemPage *pPage1;
39186   int nPage;
39187
39188   assert( sqlite3_mutex_held(pBt->mutex) );
39189   if( pBt->pPage1 ) return SQLITE_OK;
39190   rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
39191   if( rc!=SQLITE_OK ) return rc;
39192
39193   /* Do some checking to help insure the file we opened really is
39194   ** a valid database file. 
39195   */
39196   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39197   if( rc!=SQLITE_OK ){
39198     goto page1_init_failed;
39199   }else if( nPage>0 ){
39200     int pageSize;
39201     int usableSize;
39202     u8 *page1 = pPage1->aData;
39203     rc = SQLITE_NOTADB;
39204     if( memcmp(page1, zMagicHeader, 16)!=0 ){
39205       goto page1_init_failed;
39206     }
39207     if( page1[18]>1 ){
39208       pBt->readOnly = 1;
39209     }
39210     if( page1[19]>1 ){
39211       goto page1_init_failed;
39212     }
39213
39214     /* The maximum embedded fraction must be exactly 25%.  And the minimum
39215     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
39216     ** The original design allowed these amounts to vary, but as of
39217     ** version 3.6.0, we require them to be fixed.
39218     */
39219     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
39220       goto page1_init_failed;
39221     }
39222     pageSize = get2byte(&page1[16]);
39223     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
39224         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
39225     ){
39226       goto page1_init_failed;
39227     }
39228     assert( (pageSize & 7)==0 );
39229     usableSize = pageSize - page1[20];
39230     if( pageSize!=pBt->pageSize ){
39231       /* After reading the first page of the database assuming a page size
39232       ** of BtShared.pageSize, we have discovered that the page-size is
39233       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
39234       ** zero and return SQLITE_OK. The caller will call this function
39235       ** again with the correct page-size.
39236       */
39237       releasePage(pPage1);
39238       pBt->usableSize = (u16)usableSize;
39239       pBt->pageSize = (u16)pageSize;
39240       freeTempSpace(pBt);
39241       sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
39242       return SQLITE_OK;
39243     }
39244     if( usableSize<500 ){
39245       goto page1_init_failed;
39246     }
39247     pBt->pageSize = (u16)pageSize;
39248     pBt->usableSize = (u16)usableSize;
39249 #ifndef SQLITE_OMIT_AUTOVACUUM
39250     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
39251     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
39252 #endif
39253   }
39254
39255   /* maxLocal is the maximum amount of payload to store locally for
39256   ** a cell.  Make sure it is small enough so that at least minFanout
39257   ** cells can will fit on one page.  We assume a 10-byte page header.
39258   ** Besides the payload, the cell must store:
39259   **     2-byte pointer to the cell
39260   **     4-byte child pointer
39261   **     9-byte nKey value
39262   **     4-byte nData value
39263   **     4-byte overflow page pointer
39264   ** So a cell consists of a 2-byte poiner, a header which is as much as
39265   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
39266   ** page pointer.
39267   */
39268   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
39269   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
39270   pBt->maxLeaf = pBt->usableSize - 35;
39271   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
39272   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
39273   pBt->pPage1 = pPage1;
39274   return SQLITE_OK;
39275
39276 page1_init_failed:
39277   releasePage(pPage1);
39278   pBt->pPage1 = 0;
39279   return rc;
39280 }
39281
39282 /*
39283 ** This routine works like lockBtree() except that it also invokes the
39284 ** busy callback if there is lock contention.
39285 */
39286 static int lockBtreeWithRetry(Btree *pRef){
39287   int rc = SQLITE_OK;
39288
39289   assert( sqlite3BtreeHoldsMutex(pRef) );
39290   if( pRef->inTrans==TRANS_NONE ){
39291     u8 inTransaction = pRef->pBt->inTransaction;
39292     btreeIntegrity(pRef);
39293     rc = sqlite3BtreeBeginTrans(pRef, 0);
39294     pRef->pBt->inTransaction = inTransaction;
39295     pRef->inTrans = TRANS_NONE;
39296     if( rc==SQLITE_OK ){
39297       pRef->pBt->nTransaction--;
39298     }
39299     btreeIntegrity(pRef);
39300   }
39301   return rc;
39302 }
39303        
39304
39305 /*
39306 ** If there are no outstanding cursors and we are not in the middle
39307 ** of a transaction but there is a read lock on the database, then
39308 ** this routine unrefs the first page of the database file which 
39309 ** has the effect of releasing the read lock.
39310 **
39311 ** If there are any outstanding cursors, this routine is a no-op.
39312 **
39313 ** If there is a transaction in progress, this routine is a no-op.
39314 */
39315 static void unlockBtreeIfUnused(BtShared *pBt){
39316   assert( sqlite3_mutex_held(pBt->mutex) );
39317   if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
39318     if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
39319       assert( pBt->pPage1->aData );
39320 #if 0
39321       if( pBt->pPage1->aData==0 ){
39322         MemPage *pPage = pBt->pPage1;
39323         pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
39324         pPage->pBt = pBt;
39325         pPage->pgno = 1;
39326       }
39327 #endif
39328       releasePage(pBt->pPage1);
39329     }
39330     pBt->pPage1 = 0;
39331     pBt->inStmt = 0;
39332   }
39333 }
39334
39335 /*
39336 ** Create a new database by initializing the first page of the
39337 ** file.
39338 */
39339 static int newDatabase(BtShared *pBt){
39340   MemPage *pP1;
39341   unsigned char *data;
39342   int rc;
39343   int nPage;
39344
39345   assert( sqlite3_mutex_held(pBt->mutex) );
39346   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39347   if( rc!=SQLITE_OK || nPage>0 ){
39348     return rc;
39349   }
39350   pP1 = pBt->pPage1;
39351   assert( pP1!=0 );
39352   data = pP1->aData;
39353   rc = sqlite3PagerWrite(pP1->pDbPage);
39354   if( rc ) return rc;
39355   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
39356   assert( sizeof(zMagicHeader)==16 );
39357   put2byte(&data[16], pBt->pageSize);
39358   data[18] = 1;
39359   data[19] = 1;
39360   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
39361   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
39362   data[21] = 64;
39363   data[22] = 32;
39364   data[23] = 32;
39365   memset(&data[24], 0, 100-24);
39366   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
39367   pBt->pageSizeFixed = 1;
39368 #ifndef SQLITE_OMIT_AUTOVACUUM
39369   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
39370   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
39371   put4byte(&data[36 + 4*4], pBt->autoVacuum);
39372   put4byte(&data[36 + 7*4], pBt->incrVacuum);
39373 #endif
39374   return SQLITE_OK;
39375 }
39376
39377 /*
39378 ** Attempt to start a new transaction. A write-transaction
39379 ** is started if the second argument is nonzero, otherwise a read-
39380 ** transaction.  If the second argument is 2 or more and exclusive
39381 ** transaction is started, meaning that no other process is allowed
39382 ** to access the database.  A preexisting transaction may not be
39383 ** upgraded to exclusive by calling this routine a second time - the
39384 ** exclusivity flag only works for a new transaction.
39385 **
39386 ** A write-transaction must be started before attempting any 
39387 ** changes to the database.  None of the following routines 
39388 ** will work unless a transaction is started first:
39389 **
39390 **      sqlite3BtreeCreateTable()
39391 **      sqlite3BtreeCreateIndex()
39392 **      sqlite3BtreeClearTable()
39393 **      sqlite3BtreeDropTable()
39394 **      sqlite3BtreeInsert()
39395 **      sqlite3BtreeDelete()
39396 **      sqlite3BtreeUpdateMeta()
39397 **
39398 ** If an initial attempt to acquire the lock fails because of lock contention
39399 ** and the database was previously unlocked, then invoke the busy handler
39400 ** if there is one.  But if there was previously a read-lock, do not
39401 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
39402 ** returned when there is already a read-lock in order to avoid a deadlock.
39403 **
39404 ** Suppose there are two processes A and B.  A has a read lock and B has
39405 ** a reserved lock.  B tries to promote to exclusive but is blocked because
39406 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
39407 ** One or the other of the two processes must give way or there can be
39408 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
39409 ** when A already has a read lock, we encourage A to give up and let B
39410 ** proceed.
39411 */
39412 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
39413   BtShared *pBt = p->pBt;
39414   int rc = SQLITE_OK;
39415
39416   sqlite3BtreeEnter(p);
39417   pBt->db = p->db;
39418   btreeIntegrity(p);
39419
39420   /* If the btree is already in a write-transaction, or it
39421   ** is already in a read-transaction and a read-transaction
39422   ** is requested, this is a no-op.
39423   */
39424   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
39425     goto trans_begun;
39426   }
39427
39428   /* Write transactions are not possible on a read-only database */
39429   if( pBt->readOnly && wrflag ){
39430     rc = SQLITE_READONLY;
39431     goto trans_begun;
39432   }
39433
39434   /* If another database handle has already opened a write transaction 
39435   ** on this shared-btree structure and a second write transaction is
39436   ** requested, return SQLITE_BUSY.
39437   */
39438   if( pBt->inTransaction==TRANS_WRITE && wrflag ){
39439     rc = SQLITE_BUSY;
39440     goto trans_begun;
39441   }
39442
39443 #ifndef SQLITE_OMIT_SHARED_CACHE
39444   if( wrflag>1 ){
39445     BtLock *pIter;
39446     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
39447       if( pIter->pBtree!=p ){
39448         rc = SQLITE_BUSY;
39449         goto trans_begun;
39450       }
39451     }
39452   }
39453 #endif
39454
39455   do {
39456     if( pBt->pPage1==0 ){
39457       do{
39458         rc = lockBtree(pBt);
39459       }while( pBt->pPage1==0 && rc==SQLITE_OK );
39460     }
39461
39462     if( rc==SQLITE_OK && wrflag ){
39463       if( pBt->readOnly ){
39464         rc = SQLITE_READONLY;
39465       }else{
39466         rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
39467         if( rc==SQLITE_OK ){
39468           rc = newDatabase(pBt);
39469         }
39470       }
39471     }
39472   
39473     if( rc==SQLITE_OK ){
39474       if( wrflag ) pBt->inStmt = 0;
39475     }else{
39476       unlockBtreeIfUnused(pBt);
39477     }
39478   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
39479           btreeInvokeBusyHandler(pBt) );
39480
39481   if( rc==SQLITE_OK ){
39482     if( p->inTrans==TRANS_NONE ){
39483       pBt->nTransaction++;
39484     }
39485     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
39486     if( p->inTrans>pBt->inTransaction ){
39487       pBt->inTransaction = p->inTrans;
39488     }
39489 #ifndef SQLITE_OMIT_SHARED_CACHE
39490     if( wrflag>1 ){
39491       assert( !pBt->pExclusive );
39492       pBt->pExclusive = p;
39493     }
39494 #endif
39495   }
39496
39497
39498 trans_begun:
39499   if( rc==SQLITE_OK && wrflag ){
39500     /* This call makes sure that the pager has the correct number of
39501     ** open savepoints. If the second parameter is greater than 0 and
39502     ** the sub-journal is not already open, then it will be opened here.
39503     */
39504     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
39505   }
39506
39507   btreeIntegrity(p);
39508   sqlite3BtreeLeave(p);
39509   return rc;
39510 }
39511
39512 #ifndef SQLITE_OMIT_AUTOVACUUM
39513
39514 /*
39515 ** Set the pointer-map entries for all children of page pPage. Also, if
39516 ** pPage contains cells that point to overflow pages, set the pointer
39517 ** map entries for the overflow pages as well.
39518 */
39519 static int setChildPtrmaps(MemPage *pPage){
39520   int i;                             /* Counter variable */
39521   int nCell;                         /* Number of cells in page pPage */
39522   int rc;                            /* Return code */
39523   BtShared *pBt = pPage->pBt;
39524   u8 isInitOrig = pPage->isInit;
39525   Pgno pgno = pPage->pgno;
39526
39527   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39528   rc = sqlite3BtreeInitPage(pPage);
39529   if( rc!=SQLITE_OK ){
39530     goto set_child_ptrmaps_out;
39531   }
39532   nCell = pPage->nCell;
39533
39534   for(i=0; i<nCell; i++){
39535     u8 *pCell = findCell(pPage, i);
39536
39537     rc = ptrmapPutOvflPtr(pPage, pCell);
39538     if( rc!=SQLITE_OK ){
39539       goto set_child_ptrmaps_out;
39540     }
39541
39542     if( !pPage->leaf ){
39543       Pgno childPgno = get4byte(pCell);
39544       rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
39545       if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
39546     }
39547   }
39548
39549   if( !pPage->leaf ){
39550     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
39551     rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
39552   }
39553
39554 set_child_ptrmaps_out:
39555   pPage->isInit = isInitOrig;
39556   return rc;
39557 }
39558
39559 /*
39560 ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
39561 ** page, is a pointer to page iFrom. Modify this pointer so that it points to
39562 ** iTo. Parameter eType describes the type of pointer to be modified, as 
39563 ** follows:
39564 **
39565 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
39566 **                   page of pPage.
39567 **
39568 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
39569 **                   page pointed to by one of the cells on pPage.
39570 **
39571 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
39572 **                   overflow page in the list.
39573 */
39574 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
39575   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39576   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39577   if( eType==PTRMAP_OVERFLOW2 ){
39578     /* The pointer is always the first 4 bytes of the page in this case.  */
39579     if( get4byte(pPage->aData)!=iFrom ){
39580       return SQLITE_CORRUPT_BKPT;
39581     }
39582     put4byte(pPage->aData, iTo);
39583   }else{
39584     u8 isInitOrig = pPage->isInit;
39585     int i;
39586     int nCell;
39587
39588     sqlite3BtreeInitPage(pPage);
39589     nCell = pPage->nCell;
39590
39591     for(i=0; i<nCell; i++){
39592       u8 *pCell = findCell(pPage, i);
39593       if( eType==PTRMAP_OVERFLOW1 ){
39594         CellInfo info;
39595         sqlite3BtreeParseCellPtr(pPage, pCell, &info);
39596         if( info.iOverflow ){
39597           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
39598             put4byte(&pCell[info.iOverflow], iTo);
39599             break;
39600           }
39601         }
39602       }else{
39603         if( get4byte(pCell)==iFrom ){
39604           put4byte(pCell, iTo);
39605           break;
39606         }
39607       }
39608     }
39609   
39610     if( i==nCell ){
39611       if( eType!=PTRMAP_BTREE || 
39612           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
39613         return SQLITE_CORRUPT_BKPT;
39614       }
39615       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
39616     }
39617
39618     pPage->isInit = isInitOrig;
39619   }
39620   return SQLITE_OK;
39621 }
39622
39623
39624 /*
39625 ** Move the open database page pDbPage to location iFreePage in the 
39626 ** database. The pDbPage reference remains valid.
39627 */
39628 static int relocatePage(
39629   BtShared *pBt,           /* Btree */
39630   MemPage *pDbPage,        /* Open page to move */
39631   u8 eType,                /* Pointer map 'type' entry for pDbPage */
39632   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
39633   Pgno iFreePage,          /* The location to move pDbPage to */
39634   int isCommit
39635 ){
39636   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
39637   Pgno iDbPage = pDbPage->pgno;
39638   Pager *pPager = pBt->pPager;
39639   int rc;
39640
39641   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
39642       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
39643   assert( sqlite3_mutex_held(pBt->mutex) );
39644   assert( pDbPage->pBt==pBt );
39645
39646   /* Move page iDbPage from its current location to page number iFreePage */
39647   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
39648       iDbPage, iFreePage, iPtrPage, eType));
39649   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
39650   if( rc!=SQLITE_OK ){
39651     return rc;
39652   }
39653   pDbPage->pgno = iFreePage;
39654
39655   /* If pDbPage was a btree-page, then it may have child pages and/or cells
39656   ** that point to overflow pages. The pointer map entries for all these
39657   ** pages need to be changed.
39658   **
39659   ** If pDbPage is an overflow page, then the first 4 bytes may store a
39660   ** pointer to a subsequent overflow page. If this is the case, then
39661   ** the pointer map needs to be updated for the subsequent overflow page.
39662   */
39663   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
39664     rc = setChildPtrmaps(pDbPage);
39665     if( rc!=SQLITE_OK ){
39666       return rc;
39667     }
39668   }else{
39669     Pgno nextOvfl = get4byte(pDbPage->aData);
39670     if( nextOvfl!=0 ){
39671       rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
39672       if( rc!=SQLITE_OK ){
39673         return rc;
39674       }
39675     }
39676   }
39677
39678   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
39679   ** that it points at iFreePage. Also fix the pointer map entry for
39680   ** iPtrPage.
39681   */
39682   if( eType!=PTRMAP_ROOTPAGE ){
39683     rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
39684     if( rc!=SQLITE_OK ){
39685       return rc;
39686     }
39687     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
39688     if( rc!=SQLITE_OK ){
39689       releasePage(pPtrPage);
39690       return rc;
39691     }
39692     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
39693     releasePage(pPtrPage);
39694     if( rc==SQLITE_OK ){
39695       rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
39696     }
39697   }
39698   return rc;
39699 }
39700
39701 /* Forward declaration required by incrVacuumStep(). */
39702 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
39703
39704 /*
39705 ** Perform a single step of an incremental-vacuum. If successful,
39706 ** return SQLITE_OK. If there is no work to do (and therefore no
39707 ** point in calling this function again), return SQLITE_DONE.
39708 **
39709 ** More specificly, this function attempts to re-organize the 
39710 ** database so that the last page of the file currently in use
39711 ** is no longer in use.
39712 **
39713 ** If the nFin parameter is non-zero, the implementation assumes
39714 ** that the caller will keep calling incrVacuumStep() until
39715 ** it returns SQLITE_DONE or an error, and that nFin is the
39716 ** number of pages the database file will contain after this 
39717 ** process is complete.
39718 */
39719 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
39720   Pgno nFreeList;           /* Number of pages still on the free-list */
39721
39722   assert( sqlite3_mutex_held(pBt->mutex) );
39723
39724   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
39725     int rc;
39726     u8 eType;
39727     Pgno iPtrPage;
39728
39729     nFreeList = get4byte(&pBt->pPage1->aData[36]);
39730     if( nFreeList==0 || nFin==iLastPg ){
39731       return SQLITE_DONE;
39732     }
39733
39734     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
39735     if( rc!=SQLITE_OK ){
39736       return rc;
39737     }
39738     if( eType==PTRMAP_ROOTPAGE ){
39739       return SQLITE_CORRUPT_BKPT;
39740     }
39741
39742     if( eType==PTRMAP_FREEPAGE ){
39743       if( nFin==0 ){
39744         /* Remove the page from the files free-list. This is not required
39745         ** if nFin is non-zero. In that case, the free-list will be
39746         ** truncated to zero after this function returns, so it doesn't 
39747         ** matter if it still contains some garbage entries.
39748         */
39749         Pgno iFreePg;
39750         MemPage *pFreePg;
39751         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
39752         if( rc!=SQLITE_OK ){
39753           return rc;
39754         }
39755         assert( iFreePg==iLastPg );
39756         releasePage(pFreePg);
39757       }
39758     } else {
39759       Pgno iFreePg;             /* Index of free page to move pLastPg to */
39760       MemPage *pLastPg;
39761
39762       rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
39763       if( rc!=SQLITE_OK ){
39764         return rc;
39765       }
39766
39767       /* If nFin is zero, this loop runs exactly once and page pLastPg
39768       ** is swapped with the first free page pulled off the free list.
39769       **
39770       ** On the other hand, if nFin is greater than zero, then keep
39771       ** looping until a free-page located within the first nFin pages
39772       ** of the file is found.
39773       */
39774       do {
39775         MemPage *pFreePg;
39776         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
39777         if( rc!=SQLITE_OK ){
39778           releasePage(pLastPg);
39779           return rc;
39780         }
39781         releasePage(pFreePg);
39782       }while( nFin!=0 && iFreePg>nFin );
39783       assert( iFreePg<iLastPg );
39784       
39785       rc = sqlite3PagerWrite(pLastPg->pDbPage);
39786       if( rc==SQLITE_OK ){
39787         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
39788       }
39789       releasePage(pLastPg);
39790       if( rc!=SQLITE_OK ){
39791         return rc;
39792       }
39793     }
39794   }
39795
39796   if( nFin==0 ){
39797     iLastPg--;
39798     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
39799       iLastPg--;
39800     }
39801     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
39802   }
39803   return SQLITE_OK;
39804 }
39805
39806 /*
39807 ** A write-transaction must be opened before calling this function.
39808 ** It performs a single unit of work towards an incremental vacuum.
39809 **
39810 ** If the incremental vacuum is finished after this function has run,
39811 ** SQLITE_DONE is returned. If it is not finished, but no error occured,
39812 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
39813 */
39814 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
39815   int rc;
39816   BtShared *pBt = p->pBt;
39817
39818   sqlite3BtreeEnter(p);
39819   pBt->db = p->db;
39820   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
39821   if( !pBt->autoVacuum ){
39822     rc = SQLITE_DONE;
39823   }else{
39824     invalidateAllOverflowCache(pBt);
39825     rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
39826   }
39827   sqlite3BtreeLeave(p);
39828   return rc;
39829 }
39830
39831 /*
39832 ** This routine is called prior to sqlite3PagerCommit when a transaction
39833 ** is commited for an auto-vacuum database.
39834 **
39835 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
39836 ** the database file should be truncated to during the commit process. 
39837 ** i.e. the database has been reorganized so that only the first *pnTrunc
39838 ** pages are in use.
39839 */
39840 static int autoVacuumCommit(BtShared *pBt){
39841   int rc = SQLITE_OK;
39842   Pager *pPager = pBt->pPager;
39843   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
39844
39845   assert( sqlite3_mutex_held(pBt->mutex) );
39846   invalidateAllOverflowCache(pBt);
39847   assert(pBt->autoVacuum);
39848   if( !pBt->incrVacuum ){
39849     Pgno nFin;
39850     Pgno nFree;
39851     Pgno nPtrmap;
39852     Pgno iFree;
39853     const int pgsz = pBt->pageSize;
39854     Pgno nOrig = pagerPagecount(pBt);
39855
39856     if( PTRMAP_ISPAGE(pBt, nOrig) ){
39857       return SQLITE_CORRUPT_BKPT;
39858     }
39859     if( nOrig==PENDING_BYTE_PAGE(pBt) ){
39860       nOrig--;
39861     }
39862     nFree = get4byte(&pBt->pPage1->aData[36]);
39863     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
39864     nFin = nOrig - nFree - nPtrmap;
39865     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
39866       nFin--;
39867     }
39868     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
39869       nFin--;
39870     }
39871
39872     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
39873       rc = incrVacuumStep(pBt, nFin, iFree);
39874     }
39875     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
39876       rc = SQLITE_OK;
39877       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
39878       put4byte(&pBt->pPage1->aData[32], 0);
39879       put4byte(&pBt->pPage1->aData[36], 0);
39880       sqlite3PagerTruncateImage(pBt->pPager, nFin);
39881     }
39882     if( rc!=SQLITE_OK ){
39883       sqlite3PagerRollback(pPager);
39884     }
39885   }
39886
39887   assert( nRef==sqlite3PagerRefcount(pPager) );
39888   return rc;
39889 }
39890
39891 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
39892
39893 /*
39894 ** This routine does the first phase of a two-phase commit.  This routine
39895 ** causes a rollback journal to be created (if it does not already exist)
39896 ** and populated with enough information so that if a power loss occurs
39897 ** the database can be restored to its original state by playing back
39898 ** the journal.  Then the contents of the journal are flushed out to
39899 ** the disk.  After the journal is safely on oxide, the changes to the
39900 ** database are written into the database file and flushed to oxide.
39901 ** At the end of this call, the rollback journal still exists on the
39902 ** disk and we are still holding all locks, so the transaction has not
39903 ** committed.  See sqlite3BtreeCommit() for the second phase of the
39904 ** commit process.
39905 **
39906 ** This call is a no-op if no write-transaction is currently active on pBt.
39907 **
39908 ** Otherwise, sync the database file for the btree pBt. zMaster points to
39909 ** the name of a master journal file that should be written into the
39910 ** individual journal file, or is NULL, indicating no master journal file 
39911 ** (single database transaction).
39912 **
39913 ** When this is called, the master journal should already have been
39914 ** created, populated with this journal pointer and synced to disk.
39915 **
39916 ** Once this is routine has returned, the only thing required to commit
39917 ** the write-transaction for this database file is to delete the journal.
39918 */
39919 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
39920   int rc = SQLITE_OK;
39921   if( p->inTrans==TRANS_WRITE ){
39922     BtShared *pBt = p->pBt;
39923     sqlite3BtreeEnter(p);
39924     pBt->db = p->db;
39925 #ifndef SQLITE_OMIT_AUTOVACUUM
39926     if( pBt->autoVacuum ){
39927       rc = autoVacuumCommit(pBt);
39928       if( rc!=SQLITE_OK ){
39929         sqlite3BtreeLeave(p);
39930         return rc;
39931       }
39932     }
39933 #endif
39934     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
39935     sqlite3BtreeLeave(p);
39936   }
39937   return rc;
39938 }
39939
39940 /*
39941 ** Commit the transaction currently in progress.
39942 **
39943 ** This routine implements the second phase of a 2-phase commit.  The
39944 ** sqlite3BtreeSync() routine does the first phase and should be invoked
39945 ** prior to calling this routine.  The sqlite3BtreeSync() routine did
39946 ** all the work of writing information out to disk and flushing the
39947 ** contents so that they are written onto the disk platter.  All this
39948 ** routine has to do is delete or truncate the rollback journal
39949 ** (which causes the transaction to commit) and drop locks.
39950 **
39951 ** This will release the write lock on the database file.  If there
39952 ** are no active cursors, it also releases the read lock.
39953 */
39954 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
39955   BtShared *pBt = p->pBt;
39956
39957   sqlite3BtreeEnter(p);
39958   pBt->db = p->db;
39959   btreeIntegrity(p);
39960
39961   /* If the handle has a write-transaction open, commit the shared-btrees 
39962   ** transaction and set the shared state to TRANS_READ.
39963   */
39964   if( p->inTrans==TRANS_WRITE ){
39965     int rc;
39966     assert( pBt->inTransaction==TRANS_WRITE );
39967     assert( pBt->nTransaction>0 );
39968     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
39969     if( rc!=SQLITE_OK ){
39970       sqlite3BtreeLeave(p);
39971       return rc;
39972     }
39973     pBt->inTransaction = TRANS_READ;
39974     pBt->inStmt = 0;
39975   }
39976   unlockAllTables(p);
39977
39978   /* If the handle has any kind of transaction open, decrement the transaction
39979   ** count of the shared btree. If the transaction count reaches 0, set
39980   ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
39981   ** will unlock the pager.
39982   */
39983   if( p->inTrans!=TRANS_NONE ){
39984     pBt->nTransaction--;
39985     if( 0==pBt->nTransaction ){
39986       pBt->inTransaction = TRANS_NONE;
39987     }
39988   }
39989
39990   /* Set the handles current transaction state to TRANS_NONE and unlock
39991   ** the pager if this call closed the only read or write transaction.
39992   */
39993   btreeClearHasContent(pBt);
39994   p->inTrans = TRANS_NONE;
39995   unlockBtreeIfUnused(pBt);
39996
39997   btreeIntegrity(p);
39998   sqlite3BtreeLeave(p);
39999   return SQLITE_OK;
40000 }
40001
40002 /*
40003 ** Do both phases of a commit.
40004 */
40005 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40006   int rc;
40007   sqlite3BtreeEnter(p);
40008   rc = sqlite3BtreeCommitPhaseOne(p, 0);
40009   if( rc==SQLITE_OK ){
40010     rc = sqlite3BtreeCommitPhaseTwo(p);
40011   }
40012   sqlite3BtreeLeave(p);
40013   return rc;
40014 }
40015
40016 #ifndef NDEBUG
40017 /*
40018 ** Return the number of write-cursors open on this handle. This is for use
40019 ** in assert() expressions, so it is only compiled if NDEBUG is not
40020 ** defined.
40021 **
40022 ** For the purposes of this routine, a write-cursor is any cursor that
40023 ** is capable of writing to the databse.  That means the cursor was
40024 ** originally opened for writing and the cursor has not be disabled
40025 ** by having its state changed to CURSOR_FAULT.
40026 */
40027 static int countWriteCursors(BtShared *pBt){
40028   BtCursor *pCur;
40029   int r = 0;
40030   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40031     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
40032   }
40033   return r;
40034 }
40035 #endif
40036
40037 /*
40038 ** This routine sets the state to CURSOR_FAULT and the error
40039 ** code to errCode for every cursor on BtShared that pBtree
40040 ** references.
40041 **
40042 ** Every cursor is tripped, including cursors that belong
40043 ** to other database connections that happen to be sharing
40044 ** the cache with pBtree.
40045 **
40046 ** This routine gets called when a rollback occurs.
40047 ** All cursors using the same cache must be tripped
40048 ** to prevent them from trying to use the btree after
40049 ** the rollback.  The rollback may have deleted tables
40050 ** or moved root pages, so it is not sufficient to
40051 ** save the state of the cursor.  The cursor must be
40052 ** invalidated.
40053 */
40054 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40055   BtCursor *p;
40056   sqlite3BtreeEnter(pBtree);
40057   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40058     int i;
40059     sqlite3BtreeClearCursor(p);
40060     p->eState = CURSOR_FAULT;
40061     p->skip = errCode;
40062     for(i=0; i<=p->iPage; i++){
40063       releasePage(p->apPage[i]);
40064       p->apPage[i] = 0;
40065     }
40066   }
40067   sqlite3BtreeLeave(pBtree);
40068 }
40069
40070 /*
40071 ** Rollback the transaction in progress.  All cursors will be
40072 ** invalided by this operation.  Any attempt to use a cursor
40073 ** that was open at the beginning of this operation will result
40074 ** in an error.
40075 **
40076 ** This will release the write lock on the database file.  If there
40077 ** are no active cursors, it also releases the read lock.
40078 */
40079 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40080   int rc;
40081   BtShared *pBt = p->pBt;
40082   MemPage *pPage1;
40083
40084   sqlite3BtreeEnter(p);
40085   pBt->db = p->db;
40086   rc = saveAllCursors(pBt, 0, 0);
40087 #ifndef SQLITE_OMIT_SHARED_CACHE
40088   if( rc!=SQLITE_OK ){
40089     /* This is a horrible situation. An IO or malloc() error occured whilst
40090     ** trying to save cursor positions. If this is an automatic rollback (as
40091     ** the result of a constraint, malloc() failure or IO error) then 
40092     ** the cache may be internally inconsistent (not contain valid trees) so
40093     ** we cannot simply return the error to the caller. Instead, abort 
40094     ** all queries that may be using any of the cursors that failed to save.
40095     */
40096     sqlite3BtreeTripAllCursors(p, rc);
40097   }
40098 #endif
40099   btreeIntegrity(p);
40100   unlockAllTables(p);
40101
40102   if( p->inTrans==TRANS_WRITE ){
40103     int rc2;
40104
40105     assert( TRANS_WRITE==pBt->inTransaction );
40106     rc2 = sqlite3PagerRollback(pBt->pPager);
40107     if( rc2!=SQLITE_OK ){
40108       rc = rc2;
40109     }
40110
40111     /* The rollback may have destroyed the pPage1->aData value.  So
40112     ** call sqlite3BtreeGetPage() on page 1 again to make
40113     ** sure pPage1->aData is set correctly. */
40114     if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40115       releasePage(pPage1);
40116     }
40117     assert( countWriteCursors(pBt)==0 );
40118     pBt->inTransaction = TRANS_READ;
40119   }
40120
40121   if( p->inTrans!=TRANS_NONE ){
40122     assert( pBt->nTransaction>0 );
40123     pBt->nTransaction--;
40124     if( 0==pBt->nTransaction ){
40125       pBt->inTransaction = TRANS_NONE;
40126     }
40127   }
40128
40129   btreeClearHasContent(pBt);
40130   p->inTrans = TRANS_NONE;
40131   pBt->inStmt = 0;
40132   unlockBtreeIfUnused(pBt);
40133
40134   btreeIntegrity(p);
40135   sqlite3BtreeLeave(p);
40136   return rc;
40137 }
40138
40139 /*
40140 ** Start a statement subtransaction.  The subtransaction can
40141 ** can be rolled back independently of the main transaction.
40142 ** You must start a transaction before starting a subtransaction.
40143 ** The subtransaction is ended automatically if the main transaction
40144 ** commits or rolls back.
40145 **
40146 ** Only one subtransaction may be active at a time.  It is an error to try
40147 ** to start a new subtransaction if another subtransaction is already active.
40148 **
40149 ** Statement subtransactions are used around individual SQL statements
40150 ** that are contained within a BEGIN...COMMIT block.  If a constraint
40151 ** error occurs within the statement, the effect of that one statement
40152 ** can be rolled back without having to rollback the entire transaction.
40153 */
40154 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
40155   int rc;
40156   BtShared *pBt = p->pBt;
40157   sqlite3BtreeEnter(p);
40158   pBt->db = p->db;
40159   assert( p->inTrans==TRANS_WRITE );
40160   assert( !pBt->inStmt );
40161   assert( pBt->readOnly==0 );
40162   if( NEVER(p->inTrans!=TRANS_WRITE || pBt->inStmt || pBt->readOnly) ){
40163     rc = SQLITE_INTERNAL;
40164   }else{
40165     assert( pBt->inTransaction==TRANS_WRITE );
40166     /* At the pager level, a statement transaction is a savepoint with
40167     ** an index greater than all savepoints created explicitly using
40168     ** SQL statements. It is illegal to open, release or rollback any
40169     ** such savepoints while the statement transaction savepoint is active.
40170     */
40171     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint+1);
40172     pBt->inStmt = 1;
40173   }
40174   sqlite3BtreeLeave(p);
40175   return rc;
40176 }
40177
40178 /*
40179 ** Commit the statment subtransaction currently in progress.  If no
40180 ** subtransaction is active, this is a no-op.
40181 */
40182 SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
40183   int rc;
40184   BtShared *pBt = p->pBt;
40185   sqlite3BtreeEnter(p);
40186   pBt->db = p->db;
40187   assert( pBt->readOnly==0 );
40188   if( pBt->inStmt ){
40189     int iStmtpoint = p->db->nSavepoint;
40190     rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
40191   }else{
40192     rc = SQLITE_OK;
40193   }
40194   pBt->inStmt = 0;
40195   sqlite3BtreeLeave(p);
40196   return rc;
40197 }
40198
40199 /*
40200 ** Rollback the active statement subtransaction.  If no subtransaction
40201 ** is active this routine is a no-op.
40202 **
40203 ** All cursors will be invalidated by this operation.  Any attempt
40204 ** to use a cursor that was open at the beginning of this operation
40205 ** will result in an error.
40206 */
40207 SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
40208   int rc = SQLITE_OK;
40209   BtShared *pBt = p->pBt;
40210   sqlite3BtreeEnter(p);
40211   pBt->db = p->db;
40212   assert( pBt->readOnly==0 );
40213   if( pBt->inStmt ){
40214     int iStmtpoint = p->db->nSavepoint;
40215     rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_ROLLBACK, iStmtpoint);
40216     if( rc==SQLITE_OK ){
40217       rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
40218     }
40219     pBt->inStmt = 0;
40220   }
40221   sqlite3BtreeLeave(p);
40222   return rc;
40223 }
40224
40225 /*
40226 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
40227 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
40228 ** savepoint identified by parameter iSavepoint, depending on the value 
40229 ** of op.
40230 **
40231 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
40232 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
40233 ** contents of the entire transaction are rolled back. This is different
40234 ** from a normal transaction rollback, as no locks are released and the
40235 ** transaction remains open.
40236 */
40237 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
40238   int rc = SQLITE_OK;
40239   if( p && p->inTrans==TRANS_WRITE ){
40240     BtShared *pBt = p->pBt;
40241     assert( pBt->inStmt==0 );
40242     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40243     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
40244     sqlite3BtreeEnter(p);
40245     pBt->db = p->db;
40246     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
40247     if( rc==SQLITE_OK ){
40248       rc = newDatabase(pBt);
40249     }
40250     sqlite3BtreeLeave(p);
40251   }
40252   return rc;
40253 }
40254
40255 /*
40256 ** Create a new cursor for the BTree whose root is on the page
40257 ** iTable.  The act of acquiring a cursor gets a read lock on 
40258 ** the database file.
40259 **
40260 ** If wrFlag==0, then the cursor can only be used for reading.
40261 ** If wrFlag==1, then the cursor can be used for reading or for
40262 ** writing if other conditions for writing are also met.  These
40263 ** are the conditions that must be met in order for writing to
40264 ** be allowed:
40265 **
40266 ** 1:  The cursor must have been opened with wrFlag==1
40267 **
40268 ** 2:  Other database connections that share the same pager cache
40269 **     but which are not in the READ_UNCOMMITTED state may not have
40270 **     cursors open with wrFlag==0 on the same table.  Otherwise
40271 **     the changes made by this write cursor would be visible to
40272 **     the read cursors in the other database connection.
40273 **
40274 ** 3:  The database must be writable (not on read-only media)
40275 **
40276 ** 4:  There must be an active transaction.
40277 **
40278 ** No checking is done to make sure that page iTable really is the
40279 ** root page of a b-tree.  If it is not, then the cursor acquired
40280 ** will not work correctly.
40281 **
40282 ** It is assumed that the sqlite3BtreeCursorSize() bytes of memory 
40283 ** pointed to by pCur have been zeroed by the caller.
40284 */
40285 static int btreeCursor(
40286   Btree *p,                              /* The btree */
40287   int iTable,                            /* Root page of table to open */
40288   int wrFlag,                            /* 1 to write. 0 read-only */
40289   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
40290   BtCursor *pCur                         /* Space for new cursor */
40291 ){
40292   int rc;
40293   Pgno nPage;
40294   BtShared *pBt = p->pBt;
40295
40296   assert( sqlite3BtreeHoldsMutex(p) );
40297   assert( wrFlag==0 || wrFlag==1 );
40298   if( wrFlag ){
40299     assert( !pBt->readOnly );
40300     if( NEVER(pBt->readOnly) ){
40301       return SQLITE_READONLY;
40302     }
40303     if( checkReadLocks(p, iTable, 0, 0) ){
40304       return SQLITE_LOCKED;
40305     }
40306   }
40307
40308   if( pBt->pPage1==0 ){
40309     rc = lockBtreeWithRetry(p);
40310     if( rc!=SQLITE_OK ){
40311       return rc;
40312     }
40313   }
40314   pCur->pgnoRoot = (Pgno)iTable;
40315   rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage); 
40316   if( rc!=SQLITE_OK ){
40317     return rc;
40318   }
40319   if( iTable==1 && nPage==0 ){
40320     rc = SQLITE_EMPTY;
40321     goto create_cursor_exception;
40322   }
40323   rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
40324   if( rc!=SQLITE_OK ){
40325     goto create_cursor_exception;
40326   }
40327
40328   /* Now that no other errors can occur, finish filling in the BtCursor
40329   ** variables, link the cursor into the BtShared list and set *ppCur (the
40330   ** output argument to this function).
40331   */
40332   pCur->pKeyInfo = pKeyInfo;
40333   pCur->pBtree = p;
40334   pCur->pBt = pBt;
40335   pCur->wrFlag = (u8)wrFlag;
40336   pCur->pNext = pBt->pCursor;
40337   if( pCur->pNext ){
40338     pCur->pNext->pPrev = pCur;
40339   }
40340   pBt->pCursor = pCur;
40341   pCur->eState = CURSOR_INVALID;
40342
40343   return SQLITE_OK;
40344
40345 create_cursor_exception:
40346   releasePage(pCur->apPage[0]);
40347   unlockBtreeIfUnused(pBt);
40348   return rc;
40349 }
40350 SQLITE_PRIVATE int sqlite3BtreeCursor(
40351   Btree *p,                                   /* The btree */
40352   int iTable,                                 /* Root page of table to open */
40353   int wrFlag,                                 /* 1 to write. 0 read-only */
40354   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
40355   BtCursor *pCur                              /* Write new cursor here */
40356 ){
40357   int rc;
40358   sqlite3BtreeEnter(p);
40359   p->pBt->db = p->db;
40360   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
40361   sqlite3BtreeLeave(p);
40362   return rc;
40363 }
40364 SQLITE_PRIVATE int sqlite3BtreeCursorSize(){
40365   return sizeof(BtCursor);
40366 }
40367
40368
40369
40370 /*
40371 ** Close a cursor.  The read lock on the database file is released
40372 ** when the last cursor is closed.
40373 */
40374 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
40375   Btree *pBtree = pCur->pBtree;
40376   if( pBtree ){
40377     int i;
40378     BtShared *pBt = pCur->pBt;
40379     sqlite3BtreeEnter(pBtree);
40380     pBt->db = pBtree->db;
40381     sqlite3BtreeClearCursor(pCur);
40382     if( pCur->pPrev ){
40383       pCur->pPrev->pNext = pCur->pNext;
40384     }else{
40385       pBt->pCursor = pCur->pNext;
40386     }
40387     if( pCur->pNext ){
40388       pCur->pNext->pPrev = pCur->pPrev;
40389     }
40390     for(i=0; i<=pCur->iPage; i++){
40391       releasePage(pCur->apPage[i]);
40392     }
40393     unlockBtreeIfUnused(pBt);
40394     invalidateOverflowCache(pCur);
40395     /* sqlite3_free(pCur); */
40396     sqlite3BtreeLeave(pBtree);
40397   }
40398   return SQLITE_OK;
40399 }
40400
40401 /*
40402 ** Make a temporary cursor by filling in the fields of pTempCur.
40403 ** The temporary cursor is not on the cursor list for the Btree.
40404 */
40405 SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
40406   int i;
40407   assert( cursorHoldsMutex(pCur) );
40408   memcpy(pTempCur, pCur, sizeof(BtCursor));
40409   pTempCur->pNext = 0;
40410   pTempCur->pPrev = 0;
40411   for(i=0; i<=pTempCur->iPage; i++){
40412     sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
40413   }
40414   assert( pTempCur->pKey==0 );
40415 }
40416
40417 /*
40418 ** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
40419 ** function above.
40420 */
40421 SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
40422   int i;
40423   assert( cursorHoldsMutex(pCur) );
40424   for(i=0; i<=pCur->iPage; i++){
40425     sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
40426   }
40427   sqlite3_free(pCur->pKey);
40428 }
40429
40430 /*
40431 ** Make sure the BtCursor* given in the argument has a valid
40432 ** BtCursor.info structure.  If it is not already valid, call
40433 ** sqlite3BtreeParseCell() to fill it in.
40434 **
40435 ** BtCursor.info is a cache of the information in the current cell.
40436 ** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
40437 **
40438 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
40439 ** compiler to crash when getCellInfo() is implemented as a macro.
40440 ** But there is a measureable speed advantage to using the macro on gcc
40441 ** (when less compiler optimizations like -Os or -O0 are used and the
40442 ** compiler is not doing agressive inlining.)  So we use a real function
40443 ** for MSVC and a macro for everything else.  Ticket #2457.
40444 */
40445 #ifndef NDEBUG
40446   static void assertCellInfo(BtCursor *pCur){
40447     CellInfo info;
40448     int iPage = pCur->iPage;
40449     memset(&info, 0, sizeof(info));
40450     sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
40451     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
40452   }
40453 #else
40454   #define assertCellInfo(x)
40455 #endif
40456 #ifdef _MSC_VER
40457   /* Use a real function in MSVC to work around bugs in that compiler. */
40458   static void getCellInfo(BtCursor *pCur){
40459     if( pCur->info.nSize==0 ){
40460       int iPage = pCur->iPage;
40461       sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
40462       pCur->validNKey = 1;
40463     }else{
40464       assertCellInfo(pCur);
40465     }
40466   }
40467 #else /* if not _MSC_VER */
40468   /* Use a macro in all other compilers so that the function is inlined */
40469 #define getCellInfo(pCur)                                                      \
40470   if( pCur->info.nSize==0 ){                                                   \
40471     int iPage = pCur->iPage;                                                   \
40472     sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
40473     pCur->validNKey = 1;                                                       \
40474   }else{                                                                       \
40475     assertCellInfo(pCur);                                                      \
40476   }
40477 #endif /* _MSC_VER */
40478
40479 /*
40480 ** Set *pSize to the size of the buffer needed to hold the value of
40481 ** the key for the current entry.  If the cursor is not pointing
40482 ** to a valid entry, *pSize is set to 0. 
40483 **
40484 ** For a table with the INTKEY flag set, this routine returns the key
40485 ** itself, not the number of bytes in the key.
40486 */
40487 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
40488   int rc;
40489
40490   assert( cursorHoldsMutex(pCur) );
40491   rc = restoreCursorPosition(pCur);
40492   if( rc==SQLITE_OK ){
40493     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
40494     if( pCur->eState==CURSOR_INVALID ){
40495       *pSize = 0;
40496     }else{
40497       getCellInfo(pCur);
40498       *pSize = pCur->info.nKey;
40499     }
40500   }
40501   return rc;
40502 }
40503
40504 /*
40505 ** Set *pSize to the number of bytes of data in the entry the
40506 ** cursor currently points to.  Always return SQLITE_OK.
40507 ** Failure is not possible.  If the cursor is not currently
40508 ** pointing to an entry (which can happen, for example, if
40509 ** the database is empty) then *pSize is set to 0.
40510 */
40511 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
40512   int rc;
40513
40514   assert( cursorHoldsMutex(pCur) );
40515   rc = restoreCursorPosition(pCur);
40516   if( rc==SQLITE_OK ){
40517     assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
40518     if( pCur->eState==CURSOR_INVALID ){
40519       /* Not pointing at a valid entry - set *pSize to 0. */
40520       *pSize = 0;
40521     }else{
40522       getCellInfo(pCur);
40523       *pSize = pCur->info.nData;
40524     }
40525   }
40526   return rc;
40527 }
40528
40529 /*
40530 ** Given the page number of an overflow page in the database (parameter
40531 ** ovfl), this function finds the page number of the next page in the 
40532 ** linked list of overflow pages. If possible, it uses the auto-vacuum
40533 ** pointer-map data instead of reading the content of page ovfl to do so. 
40534 **
40535 ** If an error occurs an SQLite error code is returned. Otherwise:
40536 **
40537 ** The page number of the next overflow page in the linked list is 
40538 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
40539 ** list, *pPgnoNext is set to zero. 
40540 **
40541 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
40542 ** to page number pOvfl was obtained, then *ppPage is set to point to that
40543 ** reference. It is the responsibility of the caller to call releasePage()
40544 ** on *ppPage to free the reference. In no reference was obtained (because
40545 ** the pointer-map was used to obtain the value for *pPgnoNext), then
40546 ** *ppPage is set to zero.
40547 */
40548 static int getOverflowPage(
40549   BtShared *pBt, 
40550   Pgno ovfl,                   /* Overflow page */
40551   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
40552   Pgno *pPgnoNext              /* OUT: Next overflow page number */
40553 ){
40554   Pgno next = 0;
40555   MemPage *pPage = 0;
40556   int rc = SQLITE_OK;
40557
40558   assert( sqlite3_mutex_held(pBt->mutex) );
40559   assert(pPgnoNext);
40560
40561 #ifndef SQLITE_OMIT_AUTOVACUUM
40562   /* Try to find the next page in the overflow list using the
40563   ** autovacuum pointer-map pages. Guess that the next page in 
40564   ** the overflow list is page number (ovfl+1). If that guess turns 
40565   ** out to be wrong, fall back to loading the data of page 
40566   ** number ovfl to determine the next page number.
40567   */
40568   if( pBt->autoVacuum ){
40569     Pgno pgno;
40570     Pgno iGuess = ovfl+1;
40571     u8 eType;
40572
40573     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
40574       iGuess++;
40575     }
40576
40577     if( iGuess<=pagerPagecount(pBt) ){
40578       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
40579       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
40580         next = iGuess;
40581         rc = SQLITE_DONE;
40582       }
40583     }
40584   }
40585 #endif
40586
40587   if( rc==SQLITE_OK ){
40588     rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
40589     assert(rc==SQLITE_OK || pPage==0);
40590     if( next==0 && rc==SQLITE_OK ){
40591       next = get4byte(pPage->aData);
40592     }
40593   }
40594
40595   *pPgnoNext = next;
40596   if( ppPage ){
40597     *ppPage = pPage;
40598   }else{
40599     releasePage(pPage);
40600   }
40601   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
40602 }
40603
40604 /*
40605 ** Copy data from a buffer to a page, or from a page to a buffer.
40606 **
40607 ** pPayload is a pointer to data stored on database page pDbPage.
40608 ** If argument eOp is false, then nByte bytes of data are copied
40609 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
40610 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
40611 ** of data are copied from the buffer pBuf to pPayload.
40612 **
40613 ** SQLITE_OK is returned on success, otherwise an error code.
40614 */
40615 static int copyPayload(
40616   void *pPayload,           /* Pointer to page data */
40617   void *pBuf,               /* Pointer to buffer */
40618   int nByte,                /* Number of bytes to copy */
40619   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
40620   DbPage *pDbPage           /* Page containing pPayload */
40621 ){
40622   if( eOp ){
40623     /* Copy data from buffer to page (a write operation) */
40624     int rc = sqlite3PagerWrite(pDbPage);
40625     if( rc!=SQLITE_OK ){
40626       return rc;
40627     }
40628     memcpy(pPayload, pBuf, nByte);
40629   }else{
40630     /* Copy data from page to buffer (a read operation) */
40631     memcpy(pBuf, pPayload, nByte);
40632   }
40633   return SQLITE_OK;
40634 }
40635
40636 /*
40637 ** This function is used to read or overwrite payload information
40638 ** for the entry that the pCur cursor is pointing to. If the eOp
40639 ** parameter is 0, this is a read operation (data copied into
40640 ** buffer pBuf). If it is non-zero, a write (data copied from
40641 ** buffer pBuf).
40642 **
40643 ** A total of "amt" bytes are read or written beginning at "offset".
40644 ** Data is read to or from the buffer pBuf.
40645 **
40646 ** This routine does not make a distinction between key and data.
40647 ** It just reads or writes bytes from the payload area.  Data might 
40648 ** appear on the main page or be scattered out on multiple overflow 
40649 ** pages.
40650 **
40651 ** If the BtCursor.isIncrblobHandle flag is set, and the current
40652 ** cursor entry uses one or more overflow pages, this function
40653 ** allocates space for and lazily popluates the overflow page-list 
40654 ** cache array (BtCursor.aOverflow). Subsequent calls use this
40655 ** cache to make seeking to the supplied offset more efficient.
40656 **
40657 ** Once an overflow page-list cache has been allocated, it may be
40658 ** invalidated if some other cursor writes to the same table, or if
40659 ** the cursor is moved to a different row. Additionally, in auto-vacuum
40660 ** mode, the following events may invalidate an overflow page-list cache.
40661 **
40662 **   * An incremental vacuum,
40663 **   * A commit in auto_vacuum="full" mode,
40664 **   * Creating a table (may require moving an overflow page).
40665 */
40666 static int accessPayload(
40667   BtCursor *pCur,      /* Cursor pointing to entry to read from */
40668   u32 offset,          /* Begin reading this far into payload */
40669   u32 amt,             /* Read this many bytes */
40670   unsigned char *pBuf, /* Write the bytes into this buffer */ 
40671   int skipKey,         /* offset begins at data if this is true */
40672   int eOp              /* zero to read. non-zero to write. */
40673 ){
40674   unsigned char *aPayload;
40675   int rc = SQLITE_OK;
40676   u32 nKey;
40677   int iIdx = 0;
40678   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
40679   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
40680
40681   assert( pPage );
40682   assert( pCur->eState==CURSOR_VALID );
40683   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
40684   assert( cursorHoldsMutex(pCur) );
40685
40686   getCellInfo(pCur);
40687   aPayload = pCur->info.pCell + pCur->info.nHeader;
40688   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
40689
40690   if( skipKey ){
40691     offset += nKey;
40692   }
40693   if( offset+amt > nKey+pCur->info.nData 
40694    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
40695   ){
40696     /* Trying to read or write past the end of the data is an error */
40697     return SQLITE_CORRUPT_BKPT;
40698   }
40699
40700   /* Check if data must be read/written to/from the btree page itself. */
40701   if( offset<pCur->info.nLocal ){
40702     int a = amt;
40703     if( a+offset>pCur->info.nLocal ){
40704       a = pCur->info.nLocal - offset;
40705     }
40706     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
40707     offset = 0;
40708     pBuf += a;
40709     amt -= a;
40710   }else{
40711     offset -= pCur->info.nLocal;
40712   }
40713
40714   if( rc==SQLITE_OK && amt>0 ){
40715     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
40716     Pgno nextPage;
40717
40718     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
40719
40720 #ifndef SQLITE_OMIT_INCRBLOB
40721     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
40722     ** has not been allocated, allocate it now. The array is sized at
40723     ** one entry for each overflow page in the overflow chain. The
40724     ** page number of the first overflow page is stored in aOverflow[0],
40725     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
40726     ** (the cache is lazily populated).
40727     */
40728     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
40729       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
40730       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
40731       if( nOvfl && !pCur->aOverflow ){
40732         rc = SQLITE_NOMEM;
40733       }
40734     }
40735
40736     /* If the overflow page-list cache has been allocated and the
40737     ** entry for the first required overflow page is valid, skip
40738     ** directly to it.
40739     */
40740     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
40741       iIdx = (offset/ovflSize);
40742       nextPage = pCur->aOverflow[iIdx];
40743       offset = (offset%ovflSize);
40744     }
40745 #endif
40746
40747     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
40748
40749 #ifndef SQLITE_OMIT_INCRBLOB
40750       /* If required, populate the overflow page-list cache. */
40751       if( pCur->aOverflow ){
40752         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
40753         pCur->aOverflow[iIdx] = nextPage;
40754       }
40755 #endif
40756
40757       if( offset>=ovflSize ){
40758         /* The only reason to read this page is to obtain the page
40759         ** number for the next page in the overflow chain. The page
40760         ** data is not required. So first try to lookup the overflow
40761         ** page-list cache, if any, then fall back to the getOverflowPage()
40762         ** function.
40763         */
40764 #ifndef SQLITE_OMIT_INCRBLOB
40765         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
40766           nextPage = pCur->aOverflow[iIdx+1];
40767         } else 
40768 #endif
40769           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
40770         offset -= ovflSize;
40771       }else{
40772         /* Need to read this page properly. It contains some of the
40773         ** range of data that is being read (eOp==0) or written (eOp!=0).
40774         */
40775         DbPage *pDbPage;
40776         int a = amt;
40777         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
40778         if( rc==SQLITE_OK ){
40779           aPayload = sqlite3PagerGetData(pDbPage);
40780           nextPage = get4byte(aPayload);
40781           if( a + offset > ovflSize ){
40782             a = ovflSize - offset;
40783           }
40784           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
40785           sqlite3PagerUnref(pDbPage);
40786           offset = 0;
40787           amt -= a;
40788           pBuf += a;
40789         }
40790       }
40791     }
40792   }
40793
40794   if( rc==SQLITE_OK && amt>0 ){
40795     return SQLITE_CORRUPT_BKPT;
40796   }
40797   return rc;
40798 }
40799
40800 /*
40801 ** Read part of the key associated with cursor pCur.  Exactly
40802 ** "amt" bytes will be transfered into pBuf[].  The transfer
40803 ** begins at "offset".
40804 **
40805 ** Return SQLITE_OK on success or an error code if anything goes
40806 ** wrong.  An error is returned if "offset+amt" is larger than
40807 ** the available payload.
40808 */
40809 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
40810   int rc;
40811
40812   assert( cursorHoldsMutex(pCur) );
40813   rc = restoreCursorPosition(pCur);
40814   if( rc==SQLITE_OK ){
40815     assert( pCur->eState==CURSOR_VALID );
40816     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
40817     if( pCur->apPage[0]->intKey ){
40818       return SQLITE_CORRUPT_BKPT;
40819     }
40820     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
40821     rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
40822   }
40823   return rc;
40824 }
40825
40826 /*
40827 ** Read part of the data associated with cursor pCur.  Exactly
40828 ** "amt" bytes will be transfered into pBuf[].  The transfer
40829 ** begins at "offset".
40830 **
40831 ** Return SQLITE_OK on success or an error code if anything goes
40832 ** wrong.  An error is returned if "offset+amt" is larger than
40833 ** the available payload.
40834 */
40835 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
40836   int rc;
40837
40838 #ifndef SQLITE_OMIT_INCRBLOB
40839   if ( pCur->eState==CURSOR_INVALID ){
40840     return SQLITE_ABORT;
40841   }
40842 #endif
40843
40844   assert( cursorHoldsMutex(pCur) );
40845   rc = restoreCursorPosition(pCur);
40846   if( rc==SQLITE_OK ){
40847     assert( pCur->eState==CURSOR_VALID );
40848     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
40849     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
40850     rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
40851   }
40852   return rc;
40853 }
40854
40855 /*
40856 ** Return a pointer to payload information from the entry that the 
40857 ** pCur cursor is pointing to.  The pointer is to the beginning of
40858 ** the key if skipKey==0 and it points to the beginning of data if
40859 ** skipKey==1.  The number of bytes of available key/data is written
40860 ** into *pAmt.  If *pAmt==0, then the value returned will not be
40861 ** a valid pointer.
40862 **
40863 ** This routine is an optimization.  It is common for the entire key
40864 ** and data to fit on the local page and for there to be no overflow
40865 ** pages.  When that is so, this routine can be used to access the
40866 ** key and data without making a copy.  If the key and/or data spills
40867 ** onto overflow pages, then accessPayload() must be used to reassembly
40868 ** the key/data and copy it into a preallocated buffer.
40869 **
40870 ** The pointer returned by this routine looks directly into the cached
40871 ** page of the database.  The data might change or move the next time
40872 ** any btree routine is called.
40873 */
40874 static const unsigned char *fetchPayload(
40875   BtCursor *pCur,      /* Cursor pointing to entry to read from */
40876   int *pAmt,           /* Write the number of available bytes here */
40877   int skipKey          /* read beginning at data if this is true */
40878 ){
40879   unsigned char *aPayload;
40880   MemPage *pPage;
40881   u32 nKey;
40882   u32 nLocal;
40883
40884   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
40885   assert( pCur->eState==CURSOR_VALID );
40886   assert( cursorHoldsMutex(pCur) );
40887   pPage = pCur->apPage[pCur->iPage];
40888   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
40889   getCellInfo(pCur);
40890   aPayload = pCur->info.pCell;
40891   aPayload += pCur->info.nHeader;
40892   if( pPage->intKey ){
40893     nKey = 0;
40894   }else{
40895     nKey = (int)pCur->info.nKey;
40896   }
40897   if( skipKey ){
40898     aPayload += nKey;
40899     nLocal = pCur->info.nLocal - nKey;
40900   }else{
40901     nLocal = pCur->info.nLocal;
40902     if( nLocal>nKey ){
40903       nLocal = nKey;
40904     }
40905   }
40906   *pAmt = nLocal;
40907   return aPayload;
40908 }
40909
40910
40911 /*
40912 ** For the entry that cursor pCur is point to, return as
40913 ** many bytes of the key or data as are available on the local
40914 ** b-tree page.  Write the number of available bytes into *pAmt.
40915 **
40916 ** The pointer returned is ephemeral.  The key/data may move
40917 ** or be destroyed on the next call to any Btree routine,
40918 ** including calls from other threads against the same cache.
40919 ** Hence, a mutex on the BtShared should be held prior to calling
40920 ** this routine.
40921 **
40922 ** These routines is used to get quick access to key and data
40923 ** in the common case where no overflow pages are used.
40924 */
40925 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
40926   assert( cursorHoldsMutex(pCur) );
40927   if( pCur->eState==CURSOR_VALID ){
40928     return (const void*)fetchPayload(pCur, pAmt, 0);
40929   }
40930   return 0;
40931 }
40932 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
40933   assert( cursorHoldsMutex(pCur) );
40934   if( pCur->eState==CURSOR_VALID ){
40935     return (const void*)fetchPayload(pCur, pAmt, 1);
40936   }
40937   return 0;
40938 }
40939
40940
40941 /*
40942 ** Move the cursor down to a new child page.  The newPgno argument is the
40943 ** page number of the child page to move to.
40944 */
40945 static int moveToChild(BtCursor *pCur, u32 newPgno){
40946   int rc;
40947   int i = pCur->iPage;
40948   MemPage *pNewPage;
40949   BtShared *pBt = pCur->pBt;
40950
40951   assert( cursorHoldsMutex(pCur) );
40952   assert( pCur->eState==CURSOR_VALID );
40953   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
40954   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
40955     return SQLITE_CORRUPT_BKPT;
40956   }
40957   rc = getAndInitPage(pBt, newPgno, &pNewPage);
40958   if( rc ) return rc;
40959   pCur->apPage[i+1] = pNewPage;
40960   pCur->aiIdx[i+1] = 0;
40961   pCur->iPage++;
40962
40963   pCur->info.nSize = 0;
40964   pCur->validNKey = 0;
40965   if( pNewPage->nCell<1 ){
40966     return SQLITE_CORRUPT_BKPT;
40967   }
40968   return SQLITE_OK;
40969 }
40970
40971 #ifndef NDEBUG
40972 /*
40973 ** Page pParent is an internal (non-leaf) tree page. This function 
40974 ** asserts that page number iChild is the left-child if the iIdx'th
40975 ** cell in page pParent. Or, if iIdx is equal to the total number of
40976 ** cells in pParent, that page number iChild is the right-child of
40977 ** the page.
40978 */
40979 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
40980   assert( iIdx<=pParent->nCell );
40981   if( iIdx==pParent->nCell ){
40982     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
40983   }else{
40984     assert( get4byte(findCell(pParent, iIdx))==iChild );
40985   }
40986 }
40987 #else
40988 #  define assertParentIndex(x,y,z) 
40989 #endif
40990
40991 /*
40992 ** Move the cursor up to the parent page.
40993 **
40994 ** pCur->idx is set to the cell index that contains the pointer
40995 ** to the page we are coming from.  If we are coming from the
40996 ** right-most child page then pCur->idx is set to one more than
40997 ** the largest cell index.
40998 */
40999 SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
41000   assert( cursorHoldsMutex(pCur) );
41001   assert( pCur->eState==CURSOR_VALID );
41002   assert( pCur->iPage>0 );
41003   assert( pCur->apPage[pCur->iPage] );
41004   assertParentIndex(
41005     pCur->apPage[pCur->iPage-1], 
41006     pCur->aiIdx[pCur->iPage-1], 
41007     pCur->apPage[pCur->iPage]->pgno
41008   );
41009   releasePage(pCur->apPage[pCur->iPage]);
41010   pCur->iPage--;
41011   pCur->info.nSize = 0;
41012   pCur->validNKey = 0;
41013 }
41014
41015 /*
41016 ** Move the cursor to the root page
41017 */
41018 static int moveToRoot(BtCursor *pCur){
41019   MemPage *pRoot;
41020   int rc = SQLITE_OK;
41021   Btree *p = pCur->pBtree;
41022   BtShared *pBt = p->pBt;
41023
41024   assert( cursorHoldsMutex(pCur) );
41025   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41026   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41027   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41028   if( pCur->eState>=CURSOR_REQUIRESEEK ){
41029     if( pCur->eState==CURSOR_FAULT ){
41030       return pCur->skip;
41031     }
41032     sqlite3BtreeClearCursor(pCur);
41033   }
41034
41035   if( pCur->iPage>=0 ){
41036     int i;
41037     for(i=1; i<=pCur->iPage; i++){
41038       releasePage(pCur->apPage[i]);
41039     }
41040   }else{
41041     if( 
41042       SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
41043     ){
41044       pCur->eState = CURSOR_INVALID;
41045       return rc;
41046     }
41047   }
41048
41049   pRoot = pCur->apPage[0];
41050   assert( pRoot->pgno==pCur->pgnoRoot );
41051   pCur->iPage = 0;
41052   pCur->aiIdx[0] = 0;
41053   pCur->info.nSize = 0;
41054   pCur->atLast = 0;
41055   pCur->validNKey = 0;
41056
41057   if( pRoot->nCell==0 && !pRoot->leaf ){
41058     Pgno subpage;
41059     assert( pRoot->pgno==1 );
41060     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41061     assert( subpage>0 );
41062     pCur->eState = CURSOR_VALID;
41063     rc = moveToChild(pCur, subpage);
41064   }else{
41065     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41066   }
41067   return rc;
41068 }
41069
41070 /*
41071 ** Move the cursor down to the left-most leaf entry beneath the
41072 ** entry to which it is currently pointing.
41073 **
41074 ** The left-most leaf is the one with the smallest key - the first
41075 ** in ascending order.
41076 */
41077 static int moveToLeftmost(BtCursor *pCur){
41078   Pgno pgno;
41079   int rc = SQLITE_OK;
41080   MemPage *pPage;
41081
41082   assert( cursorHoldsMutex(pCur) );
41083   assert( pCur->eState==CURSOR_VALID );
41084   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41085     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41086     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41087     rc = moveToChild(pCur, pgno);
41088   }
41089   return rc;
41090 }
41091
41092 /*
41093 ** Move the cursor down to the right-most leaf entry beneath the
41094 ** page to which it is currently pointing.  Notice the difference
41095 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41096 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41097 ** finds the right-most entry beneath the *page*.
41098 **
41099 ** The right-most entry is the one with the largest key - the last
41100 ** key in ascending order.
41101 */
41102 static int moveToRightmost(BtCursor *pCur){
41103   Pgno pgno;
41104   int rc = SQLITE_OK;
41105   MemPage *pPage = 0;
41106
41107   assert( cursorHoldsMutex(pCur) );
41108   assert( pCur->eState==CURSOR_VALID );
41109   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41110     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41111     pCur->aiIdx[pCur->iPage] = pPage->nCell;
41112     rc = moveToChild(pCur, pgno);
41113   }
41114   if( rc==SQLITE_OK ){
41115     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41116     pCur->info.nSize = 0;
41117     pCur->validNKey = 0;
41118   }
41119   return rc;
41120 }
41121
41122 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
41123 ** on success.  Set *pRes to 0 if the cursor actually points to something
41124 ** or set *pRes to 1 if the table is empty.
41125 */
41126 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41127   int rc;
41128
41129   assert( cursorHoldsMutex(pCur) );
41130   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41131   rc = moveToRoot(pCur);
41132   if( rc==SQLITE_OK ){
41133     if( pCur->eState==CURSOR_INVALID ){
41134       assert( pCur->apPage[pCur->iPage]->nCell==0 );
41135       *pRes = 1;
41136       rc = SQLITE_OK;
41137     }else{
41138       assert( pCur->apPage[pCur->iPage]->nCell>0 );
41139       *pRes = 0;
41140       rc = moveToLeftmost(pCur);
41141     }
41142   }
41143   return rc;
41144 }
41145
41146 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
41147 ** on success.  Set *pRes to 0 if the cursor actually points to something
41148 ** or set *pRes to 1 if the table is empty.
41149 */
41150 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41151   int rc;
41152  
41153   assert( cursorHoldsMutex(pCur) );
41154   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41155   rc = moveToRoot(pCur);
41156   if( rc==SQLITE_OK ){
41157     if( CURSOR_INVALID==pCur->eState ){
41158       assert( pCur->apPage[pCur->iPage]->nCell==0 );
41159       *pRes = 1;
41160     }else{
41161       assert( pCur->eState==CURSOR_VALID );
41162       *pRes = 0;
41163       rc = moveToRightmost(pCur);
41164       getCellInfo(pCur);
41165       pCur->atLast = rc==SQLITE_OK ?1:0;
41166     }
41167   }
41168   return rc;
41169 }
41170
41171 /* Move the cursor so that it points to an entry near the key 
41172 ** specified by pIdxKey or intKey.   Return a success code.
41173 **
41174 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
41175 ** must be NULL.  For index tables, pIdxKey is used and intKey
41176 ** is ignored.
41177 **
41178 ** If an exact match is not found, then the cursor is always
41179 ** left pointing at a leaf page which would hold the entry if it
41180 ** were present.  The cursor might point to an entry that comes
41181 ** before or after the key.
41182 **
41183 ** An integer is written into *pRes which is the result of
41184 ** comparing the key with the entry to which the cursor is 
41185 ** pointing.  The meaning of the integer written into
41186 ** *pRes is as follows:
41187 **
41188 **     *pRes<0      The cursor is left pointing at an entry that
41189 **                  is smaller than intKey/pIdxKey or if the table is empty
41190 **                  and the cursor is therefore left point to nothing.
41191 **
41192 **     *pRes==0     The cursor is left pointing at an entry that
41193 **                  exactly matches intKey/pIdxKey.
41194 **
41195 **     *pRes>0      The cursor is left pointing at an entry that
41196 **                  is larger than intKey/pIdxKey.
41197 **
41198 */
41199 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
41200   BtCursor *pCur,          /* The cursor to be moved */
41201   UnpackedRecord *pIdxKey, /* Unpacked index key */
41202   i64 intKey,              /* The table key */
41203   int biasRight,           /* If true, bias the search to the high end */
41204   int *pRes                /* Write search results here */
41205 ){
41206   int rc;
41207
41208   assert( cursorHoldsMutex(pCur) );
41209   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41210
41211   /* If the cursor is already positioned at the point we are trying
41212   ** to move to, then just return without doing any work */
41213   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
41214    && pCur->apPage[0]->intKey 
41215   ){
41216     if( pCur->info.nKey==intKey ){
41217       *pRes = 0;
41218       return SQLITE_OK;
41219     }
41220     if( pCur->atLast && pCur->info.nKey<intKey ){
41221       *pRes = -1;
41222       return SQLITE_OK;
41223     }
41224   }
41225
41226   rc = moveToRoot(pCur);
41227   if( rc ){
41228     return rc;
41229   }
41230   assert( pCur->apPage[pCur->iPage] );
41231   assert( pCur->apPage[pCur->iPage]->isInit );
41232   if( pCur->eState==CURSOR_INVALID ){
41233     *pRes = -1;
41234     assert( pCur->apPage[pCur->iPage]->nCell==0 );
41235     return SQLITE_OK;
41236   }
41237   assert( pCur->apPage[0]->intKey || pIdxKey );
41238   for(;;){
41239     int lwr, upr;
41240     Pgno chldPg;
41241     MemPage *pPage = pCur->apPage[pCur->iPage];
41242     int c = -1;  /* pRes return if table is empty must be -1 */
41243     lwr = 0;
41244     upr = pPage->nCell-1;
41245     if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
41246       rc = SQLITE_CORRUPT_BKPT;
41247       goto moveto_finish;
41248     }
41249     if( biasRight ){
41250       pCur->aiIdx[pCur->iPage] = (u16)upr;
41251     }else{
41252       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
41253     }
41254     for(;;){
41255       void *pCellKey;
41256       i64 nCellKey;
41257       int idx = pCur->aiIdx[pCur->iPage];
41258       pCur->info.nSize = 0;
41259       pCur->validNKey = 1;
41260       if( pPage->intKey ){
41261         u8 *pCell;
41262         pCell = findCell(pPage, idx) + pPage->childPtrSize;
41263         if( pPage->hasData ){
41264           u32 dummy;
41265           pCell += getVarint32(pCell, dummy);
41266         }
41267         getVarint(pCell, (u64*)&nCellKey);
41268         if( nCellKey==intKey ){
41269           c = 0;
41270         }else if( nCellKey<intKey ){
41271           c = -1;
41272         }else{
41273           assert( nCellKey>intKey );
41274           c = +1;
41275         }
41276       }else{
41277         int available;
41278         pCellKey = (void *)fetchPayload(pCur, &available, 0);
41279         nCellKey = pCur->info.nKey;
41280         if( available>=nCellKey ){
41281           c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
41282         }else{
41283           pCellKey = sqlite3Malloc( (int)nCellKey );
41284           if( pCellKey==0 ){
41285             rc = SQLITE_NOMEM;
41286             goto moveto_finish;
41287           }
41288           rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
41289           c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
41290           sqlite3_free(pCellKey);
41291           if( rc ) goto moveto_finish;
41292         }
41293       }
41294       if( c==0 ){
41295         pCur->info.nKey = nCellKey;
41296         if( pPage->intKey && !pPage->leaf ){
41297           lwr = idx;
41298           upr = lwr - 1;
41299           break;
41300         }else{
41301           *pRes = 0;
41302           rc = SQLITE_OK;
41303           goto moveto_finish;
41304         }
41305       }
41306       if( c<0 ){
41307         lwr = idx+1;
41308       }else{
41309         upr = idx-1;
41310       }
41311       if( lwr>upr ){
41312         pCur->info.nKey = nCellKey;
41313         break;
41314       }
41315       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
41316     }
41317     assert( lwr==upr+1 );
41318     assert( pPage->isInit );
41319     if( pPage->leaf ){
41320       chldPg = 0;
41321     }else if( lwr>=pPage->nCell ){
41322       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41323     }else{
41324       chldPg = get4byte(findCell(pPage, lwr));
41325     }
41326     if( chldPg==0 ){
41327       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41328       if( pRes ) *pRes = c;
41329       rc = SQLITE_OK;
41330       goto moveto_finish;
41331     }
41332     pCur->aiIdx[pCur->iPage] = (u16)lwr;
41333     pCur->info.nSize = 0;
41334     pCur->validNKey = 0;
41335     rc = moveToChild(pCur, chldPg);
41336     if( rc ) goto moveto_finish;
41337   }
41338 moveto_finish:
41339   return rc;
41340 }
41341
41342 /*
41343 ** In this version of BtreeMoveto, pKey is a packed index record
41344 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
41345 ** record and then call BtreeMovetoUnpacked() to do the work.
41346 */
41347 SQLITE_PRIVATE int sqlite3BtreeMoveto(
41348   BtCursor *pCur,     /* Cursor open on the btree to be searched */
41349   const void *pKey,   /* Packed key if the btree is an index */
41350   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
41351   int bias,           /* Bias search to the high end */
41352   int *pRes           /* Write search results here */
41353 ){
41354   int rc;                    /* Status code */
41355   UnpackedRecord *pIdxKey;   /* Unpacked index key */
41356   UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
41357
41358   if( pKey ){
41359     assert( nKey==(i64)(int)nKey );
41360     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
41361                                       aSpace, sizeof(aSpace));
41362     if( pIdxKey==0 ) return SQLITE_NOMEM;
41363   }else{
41364     pIdxKey = 0;
41365   }
41366   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
41367   if( pKey ){
41368     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
41369   }
41370   return rc;
41371 }
41372
41373
41374 /*
41375 ** Return TRUE if the cursor is not pointing at an entry of the table.
41376 **
41377 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
41378 ** past the last entry in the table or sqlite3BtreePrev() moves past
41379 ** the first entry.  TRUE is also returned if the table is empty.
41380 */
41381 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
41382   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
41383   ** have been deleted? This API will need to change to return an error code
41384   ** as well as the boolean result value.
41385   */
41386   return (CURSOR_VALID!=pCur->eState);
41387 }
41388
41389 /*
41390 ** Return the database connection handle for a cursor.
41391 */
41392 SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
41393   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41394   return pCur->pBtree->db;
41395 }
41396
41397 /*
41398 ** Advance the cursor to the next entry in the database.  If
41399 ** successful then set *pRes=0.  If the cursor
41400 ** was already pointing to the last entry in the database before
41401 ** this routine was called, then set *pRes=1.
41402 */
41403 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
41404   int rc;
41405   int idx;
41406   MemPage *pPage;
41407
41408   assert( cursorHoldsMutex(pCur) );
41409   rc = restoreCursorPosition(pCur);
41410   if( rc!=SQLITE_OK ){
41411     return rc;
41412   }
41413   assert( pRes!=0 );
41414   if( CURSOR_INVALID==pCur->eState ){
41415     *pRes = 1;
41416     return SQLITE_OK;
41417   }
41418   if( pCur->skip>0 ){
41419     pCur->skip = 0;
41420     *pRes = 0;
41421     return SQLITE_OK;
41422   }
41423   pCur->skip = 0;
41424
41425   pPage = pCur->apPage[pCur->iPage];
41426   idx = ++pCur->aiIdx[pCur->iPage];
41427   assert( pPage->isInit );
41428   assert( idx<=pPage->nCell );
41429
41430   pCur->info.nSize = 0;
41431   pCur->validNKey = 0;
41432   if( idx>=pPage->nCell ){
41433     if( !pPage->leaf ){
41434       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
41435       if( rc ) return rc;
41436       rc = moveToLeftmost(pCur);
41437       *pRes = 0;
41438       return rc;
41439     }
41440     do{
41441       if( pCur->iPage==0 ){
41442         *pRes = 1;
41443         pCur->eState = CURSOR_INVALID;
41444         return SQLITE_OK;
41445       }
41446       sqlite3BtreeMoveToParent(pCur);
41447       pPage = pCur->apPage[pCur->iPage];
41448     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
41449     *pRes = 0;
41450     if( pPage->intKey ){
41451       rc = sqlite3BtreeNext(pCur, pRes);
41452     }else{
41453       rc = SQLITE_OK;
41454     }
41455     return rc;
41456   }
41457   *pRes = 0;
41458   if( pPage->leaf ){
41459     return SQLITE_OK;
41460   }
41461   rc = moveToLeftmost(pCur);
41462   return rc;
41463 }
41464
41465
41466 /*
41467 ** Step the cursor to the back to the previous entry in the database.  If
41468 ** successful then set *pRes=0.  If the cursor
41469 ** was already pointing to the first entry in the database before
41470 ** this routine was called, then set *pRes=1.
41471 */
41472 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
41473   int rc;
41474   MemPage *pPage;
41475
41476   assert( cursorHoldsMutex(pCur) );
41477   rc = restoreCursorPosition(pCur);
41478   if( rc!=SQLITE_OK ){
41479     return rc;
41480   }
41481   pCur->atLast = 0;
41482   if( CURSOR_INVALID==pCur->eState ){
41483     *pRes = 1;
41484     return SQLITE_OK;
41485   }
41486   if( pCur->skip<0 ){
41487     pCur->skip = 0;
41488     *pRes = 0;
41489     return SQLITE_OK;
41490   }
41491   pCur->skip = 0;
41492
41493   pPage = pCur->apPage[pCur->iPage];
41494   assert( pPage->isInit );
41495   if( !pPage->leaf ){
41496     int idx = pCur->aiIdx[pCur->iPage];
41497     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
41498     if( rc ){
41499       return rc;
41500     }
41501     rc = moveToRightmost(pCur);
41502   }else{
41503     while( pCur->aiIdx[pCur->iPage]==0 ){
41504       if( pCur->iPage==0 ){
41505         pCur->eState = CURSOR_INVALID;
41506         *pRes = 1;
41507         return SQLITE_OK;
41508       }
41509       sqlite3BtreeMoveToParent(pCur);
41510     }
41511     pCur->info.nSize = 0;
41512     pCur->validNKey = 0;
41513
41514     pCur->aiIdx[pCur->iPage]--;
41515     pPage = pCur->apPage[pCur->iPage];
41516     if( pPage->intKey && !pPage->leaf ){
41517       rc = sqlite3BtreePrevious(pCur, pRes);
41518     }else{
41519       rc = SQLITE_OK;
41520     }
41521   }
41522   *pRes = 0;
41523   return rc;
41524 }
41525
41526 /*
41527 ** Allocate a new page from the database file.
41528 **
41529 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
41530 ** has already been called on the new page.)  The new page has also
41531 ** been referenced and the calling routine is responsible for calling
41532 ** sqlite3PagerUnref() on the new page when it is done.
41533 **
41534 ** SQLITE_OK is returned on success.  Any other return value indicates
41535 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
41536 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
41537 **
41538 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
41539 ** locate a page close to the page number "nearby".  This can be used in an
41540 ** attempt to keep related pages close to each other in the database file,
41541 ** which in turn can make database access faster.
41542 **
41543 ** If the "exact" parameter is not 0, and the page-number nearby exists 
41544 ** anywhere on the free-list, then it is guarenteed to be returned. This
41545 ** is only used by auto-vacuum databases when allocating a new table.
41546 */
41547 static int allocateBtreePage(
41548   BtShared *pBt, 
41549   MemPage **ppPage, 
41550   Pgno *pPgno, 
41551   Pgno nearby,
41552   u8 exact
41553 ){
41554   MemPage *pPage1;
41555   int rc;
41556   int n;     /* Number of pages on the freelist */
41557   int k;     /* Number of leaves on the trunk of the freelist */
41558   MemPage *pTrunk = 0;
41559   MemPage *pPrevTrunk = 0;
41560
41561   assert( sqlite3_mutex_held(pBt->mutex) );
41562   pPage1 = pBt->pPage1;
41563   n = get4byte(&pPage1->aData[36]);
41564   if( n>0 ){
41565     /* There are pages on the freelist.  Reuse one of those pages. */
41566     Pgno iTrunk;
41567     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
41568     
41569     /* If the 'exact' parameter was true and a query of the pointer-map
41570     ** shows that the page 'nearby' is somewhere on the free-list, then
41571     ** the entire-list will be searched for that page.
41572     */
41573 #ifndef SQLITE_OMIT_AUTOVACUUM
41574     if( exact && nearby<=pagerPagecount(pBt) ){
41575       u8 eType;
41576       assert( nearby>0 );
41577       assert( pBt->autoVacuum );
41578       rc = ptrmapGet(pBt, nearby, &eType, 0);
41579       if( rc ) return rc;
41580       if( eType==PTRMAP_FREEPAGE ){
41581         searchList = 1;
41582       }
41583       *pPgno = nearby;
41584     }
41585 #endif
41586
41587     /* Decrement the free-list count by 1. Set iTrunk to the index of the
41588     ** first free-list trunk page. iPrevTrunk is initially 1.
41589     */
41590     rc = sqlite3PagerWrite(pPage1->pDbPage);
41591     if( rc ) return rc;
41592     put4byte(&pPage1->aData[36], n-1);
41593
41594     /* The code within this loop is run only once if the 'searchList' variable
41595     ** is not true. Otherwise, it runs once for each trunk-page on the
41596     ** free-list until the page 'nearby' is located.
41597     */
41598     do {
41599       pPrevTrunk = pTrunk;
41600       if( pPrevTrunk ){
41601         iTrunk = get4byte(&pPrevTrunk->aData[0]);
41602       }else{
41603         iTrunk = get4byte(&pPage1->aData[32]);
41604       }
41605       rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
41606       if( rc ){
41607         pTrunk = 0;
41608         goto end_allocate_page;
41609       }
41610
41611       k = get4byte(&pTrunk->aData[4]);
41612       if( k==0 && !searchList ){
41613         /* The trunk has no leaves and the list is not being searched. 
41614         ** So extract the trunk page itself and use it as the newly 
41615         ** allocated page */
41616         assert( pPrevTrunk==0 );
41617         rc = sqlite3PagerWrite(pTrunk->pDbPage);
41618         if( rc ){
41619           goto end_allocate_page;
41620         }
41621         *pPgno = iTrunk;
41622         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
41623         *ppPage = pTrunk;
41624         pTrunk = 0;
41625         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
41626       }else if( k>pBt->usableSize/4 - 2 ){
41627         /* Value of k is out of range.  Database corruption */
41628         rc = SQLITE_CORRUPT_BKPT;
41629         goto end_allocate_page;
41630 #ifndef SQLITE_OMIT_AUTOVACUUM
41631       }else if( searchList && nearby==iTrunk ){
41632         /* The list is being searched and this trunk page is the page
41633         ** to allocate, regardless of whether it has leaves.
41634         */
41635         assert( *pPgno==iTrunk );
41636         *ppPage = pTrunk;
41637         searchList = 0;
41638         rc = sqlite3PagerWrite(pTrunk->pDbPage);
41639         if( rc ){
41640           goto end_allocate_page;
41641         }
41642         if( k==0 ){
41643           if( !pPrevTrunk ){
41644             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
41645           }else{
41646             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
41647           }
41648         }else{
41649           /* The trunk page is required by the caller but it contains 
41650           ** pointers to free-list leaves. The first leaf becomes a trunk
41651           ** page in this case.
41652           */
41653           MemPage *pNewTrunk;
41654           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
41655           rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
41656           if( rc!=SQLITE_OK ){
41657             goto end_allocate_page;
41658           }
41659           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
41660           if( rc!=SQLITE_OK ){
41661             releasePage(pNewTrunk);
41662             goto end_allocate_page;
41663           }
41664           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
41665           put4byte(&pNewTrunk->aData[4], k-1);
41666           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
41667           releasePage(pNewTrunk);
41668           if( !pPrevTrunk ){
41669             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
41670             put4byte(&pPage1->aData[32], iNewTrunk);
41671           }else{
41672             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
41673             if( rc ){
41674               goto end_allocate_page;
41675             }
41676             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
41677           }
41678         }
41679         pTrunk = 0;
41680         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
41681 #endif
41682       }else{
41683         /* Extract a leaf from the trunk */
41684         int closest;
41685         Pgno iPage;
41686         unsigned char *aData = pTrunk->aData;
41687         rc = sqlite3PagerWrite(pTrunk->pDbPage);
41688         if( rc ){
41689           goto end_allocate_page;
41690         }
41691         if( nearby>0 ){
41692           int i, dist;
41693           closest = 0;
41694           dist = get4byte(&aData[8]) - nearby;
41695           if( dist<0 ) dist = -dist;
41696           for(i=1; i<k; i++){
41697             int d2 = get4byte(&aData[8+i*4]) - nearby;
41698             if( d2<0 ) d2 = -d2;
41699             if( d2<dist ){
41700               closest = i;
41701               dist = d2;
41702             }
41703           }
41704         }else{
41705           closest = 0;
41706         }
41707
41708         iPage = get4byte(&aData[8+closest*4]);
41709         if( !searchList || iPage==nearby ){
41710           int noContent;
41711           Pgno nPage;
41712           *pPgno = iPage;
41713           nPage = pagerPagecount(pBt);
41714           if( *pPgno>nPage ){
41715             /* Free page off the end of the file */
41716             rc = SQLITE_CORRUPT_BKPT;
41717             goto end_allocate_page;
41718           }
41719           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
41720                  ": %d more free pages\n",
41721                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
41722           if( closest<k-1 ){
41723             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
41724           }
41725           put4byte(&aData[4], k-1);
41726           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
41727           noContent = !btreeGetHasContent(pBt, *pPgno);
41728           rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
41729           if( rc==SQLITE_OK ){
41730             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
41731             if( rc!=SQLITE_OK ){
41732               releasePage(*ppPage);
41733             }
41734           }
41735           searchList = 0;
41736         }
41737       }
41738       releasePage(pPrevTrunk);
41739       pPrevTrunk = 0;
41740     }while( searchList );
41741   }else{
41742     /* There are no pages on the freelist, so create a new page at the
41743     ** end of the file */
41744     int nPage = pagerPagecount(pBt);
41745     *pPgno = nPage + 1;
41746
41747     if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
41748       (*pPgno)++;
41749     }
41750
41751 #ifndef SQLITE_OMIT_AUTOVACUUM
41752     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
41753       /* If *pPgno refers to a pointer-map page, allocate two new pages
41754       ** at the end of the file instead of one. The first allocated page
41755       ** becomes a new pointer-map page, the second is used by the caller.
41756       */
41757       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
41758       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
41759       (*pPgno)++;
41760       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
41761     }
41762 #endif
41763
41764     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
41765     rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
41766     if( rc ) return rc;
41767     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
41768     if( rc!=SQLITE_OK ){
41769       releasePage(*ppPage);
41770     }
41771     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
41772   }
41773
41774   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
41775
41776 end_allocate_page:
41777   releasePage(pTrunk);
41778   releasePage(pPrevTrunk);
41779   if( rc==SQLITE_OK ){
41780     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
41781       releasePage(*ppPage);
41782       return SQLITE_CORRUPT_BKPT;
41783     }
41784     (*ppPage)->isInit = 0;
41785   }
41786   return rc;
41787 }
41788
41789 /*
41790 ** This function is used to add page iPage to the database file free-list. 
41791 ** It is assumed that the page is not already a part of the free-list.
41792 **
41793 ** The value passed as the second argument to this function is optional.
41794 ** If the caller happens to have a pointer to the MemPage object 
41795 ** corresponding to page iPage handy, it may pass it as the second value. 
41796 ** Otherwise, it may pass NULL.
41797 **
41798 ** If a pointer to a MemPage object is passed as the second argument,
41799 ** its reference count is not altered by this function.
41800 */
41801 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
41802   MemPage *pTrunk = 0;                /* Free-list trunk page */
41803   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
41804   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
41805   MemPage *pPage;                     /* Page being freed. May be NULL. */
41806   int rc;                             /* Return Code */
41807   int nFree;                          /* Initial number of pages on free-list */
41808
41809   assert( sqlite3_mutex_held(pBt->mutex) );
41810   assert( iPage>1 );
41811   assert( !pMemPage || pMemPage->pgno==iPage );
41812
41813   if( pMemPage ){
41814     pPage = pMemPage;
41815     sqlite3PagerRef(pPage->pDbPage);
41816   }else{
41817     pPage = btreePageLookup(pBt, iPage);
41818   }
41819
41820   /* Increment the free page count on pPage1 */
41821   rc = sqlite3PagerWrite(pPage1->pDbPage);
41822   if( rc ) goto freepage_out;
41823   nFree = get4byte(&pPage1->aData[36]);
41824   put4byte(&pPage1->aData[36], nFree+1);
41825
41826 #ifdef SQLITE_SECURE_DELETE
41827   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
41828   ** always fully overwrite deleted information with zeros.
41829   */
41830   if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
41831    ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
41832   ){
41833     goto freepage_out;
41834   }
41835   memset(pPage->aData, 0, pPage->pBt->pageSize);
41836 #endif
41837
41838   /* If the database supports auto-vacuum, write an entry in the pointer-map
41839   ** to indicate that the page is free.
41840   */
41841   if( ISAUTOVACUUM ){
41842     rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
41843     if( rc ) goto freepage_out;
41844   }
41845
41846   /* Now manipulate the actual database free-list structure. There are two
41847   ** possibilities. If the free-list is currently empty, or if the first
41848   ** trunk page in the free-list is full, then this page will become a
41849   ** new free-list trunk page. Otherwise, it will become a leaf of the
41850   ** first trunk page in the current free-list. This block tests if it
41851   ** is possible to add the page as a new free-list leaf.
41852   */
41853   if( nFree!=0 ){
41854     int nLeaf;                /* Initial number of leaf cells on trunk page */
41855
41856     iTrunk = get4byte(&pPage1->aData[32]);
41857     rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
41858     if( rc!=SQLITE_OK ){
41859       goto freepage_out;
41860     }
41861
41862     nLeaf = get4byte(&pTrunk->aData[4]);
41863     if( nLeaf<0 ){
41864       rc = SQLITE_CORRUPT_BKPT;
41865       goto freepage_out;
41866     }
41867     if( nLeaf<pBt->usableSize/4 - 8 ){
41868       /* In this case there is room on the trunk page to insert the page
41869       ** being freed as a new leaf.
41870       **
41871       ** Note that the trunk page is not really full until it contains
41872       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
41873       ** coded.  But due to a coding error in versions of SQLite prior to
41874       ** 3.6.0, databases with freelist trunk pages holding more than
41875       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
41876       ** to maintain backwards compatibility with older versions of SQLite,
41877       ** we will contain to restrict the number of entries to usableSize/4 - 8
41878       ** for now.  At some point in the future (once everyone has upgraded
41879       ** to 3.6.0 or later) we should consider fixing the conditional above
41880       ** to read "usableSize/4-2" instead of "usableSize/4-8".
41881       */
41882       rc = sqlite3PagerWrite(pTrunk->pDbPage);
41883       if( rc==SQLITE_OK ){
41884         put4byte(&pTrunk->aData[4], nLeaf+1);
41885         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
41886 #ifndef SQLITE_SECURE_DELETE
41887         if( pPage ){
41888           sqlite3PagerDontWrite(pPage->pDbPage);
41889         }
41890 #endif
41891         rc = btreeSetHasContent(pBt, iPage);
41892       }
41893       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
41894       goto freepage_out;
41895     }
41896   }
41897
41898   /* If control flows to this point, then it was not possible to add the
41899   ** the page being freed as a leaf page of the first trunk in the free-list.
41900   ** Possibly because the free-list is empty, or possibly because the 
41901   ** first trunk in the free-list is full. Either way, the page being freed
41902   ** will become the new first trunk page in the free-list.
41903   */
41904   if(   ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
41905      || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
41906   ){
41907     goto freepage_out;
41908   }
41909   put4byte(pPage->aData, iTrunk);
41910   put4byte(&pPage->aData[4], 0);
41911   put4byte(&pPage1->aData[32], iPage);
41912   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
41913
41914 freepage_out:
41915   if( pPage ){
41916     pPage->isInit = 0;
41917   }
41918   releasePage(pPage);
41919   releasePage(pTrunk);
41920   return rc;
41921 }
41922 static int freePage(MemPage *pPage){
41923   return freePage2(pPage->pBt, pPage, pPage->pgno);
41924 }
41925
41926 /*
41927 ** Free any overflow pages associated with the given Cell.
41928 */
41929 static int clearCell(MemPage *pPage, unsigned char *pCell){
41930   BtShared *pBt = pPage->pBt;
41931   CellInfo info;
41932   Pgno ovflPgno;
41933   int rc;
41934   int nOvfl;
41935   u16 ovflPageSize;
41936
41937   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
41938   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
41939   if( info.iOverflow==0 ){
41940     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
41941   }
41942   ovflPgno = get4byte(&pCell[info.iOverflow]);
41943   assert( pBt->usableSize > 4 );
41944   ovflPageSize = pBt->usableSize - 4;
41945   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
41946   assert( ovflPgno==0 || nOvfl>0 );
41947   while( nOvfl-- ){
41948     Pgno iNext = 0;
41949     MemPage *pOvfl = 0;
41950     if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
41951       return SQLITE_CORRUPT_BKPT;
41952     }
41953     if( nOvfl ){
41954       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
41955       if( rc ) return rc;
41956     }
41957     rc = freePage2(pBt, pOvfl, ovflPgno);
41958     if( pOvfl ){
41959       sqlite3PagerUnref(pOvfl->pDbPage);
41960     }
41961     if( rc ) return rc;
41962     ovflPgno = iNext;
41963   }
41964   return SQLITE_OK;
41965 }
41966
41967 /*
41968 ** Create the byte sequence used to represent a cell on page pPage
41969 ** and write that byte sequence into pCell[].  Overflow pages are
41970 ** allocated and filled in as necessary.  The calling procedure
41971 ** is responsible for making sure sufficient space has been allocated
41972 ** for pCell[].
41973 **
41974 ** Note that pCell does not necessary need to point to the pPage->aData
41975 ** area.  pCell might point to some temporary storage.  The cell will
41976 ** be constructed in this temporary area then copied into pPage->aData
41977 ** later.
41978 */
41979 static int fillInCell(
41980   MemPage *pPage,                /* The page that contains the cell */
41981   unsigned char *pCell,          /* Complete text of the cell */
41982   const void *pKey, i64 nKey,    /* The key */
41983   const void *pData,int nData,   /* The data */
41984   int nZero,                     /* Extra zero bytes to append to pData */
41985   int *pnSize                    /* Write cell size here */
41986 ){
41987   int nPayload;
41988   const u8 *pSrc;
41989   int nSrc, n, rc;
41990   int spaceLeft;
41991   MemPage *pOvfl = 0;
41992   MemPage *pToRelease = 0;
41993   unsigned char *pPrior;
41994   unsigned char *pPayload;
41995   BtShared *pBt = pPage->pBt;
41996   Pgno pgnoOvfl = 0;
41997   int nHeader;
41998   CellInfo info;
41999
42000   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42001
42002   /* pPage is not necessarily writeable since pCell might be auxiliary
42003   ** buffer space that is separate from the pPage buffer area */
42004   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42005             || sqlite3PagerIswriteable(pPage->pDbPage) );
42006
42007   /* Fill in the header. */
42008   nHeader = 0;
42009   if( !pPage->leaf ){
42010     nHeader += 4;
42011   }
42012   if( pPage->hasData ){
42013     nHeader += putVarint(&pCell[nHeader], nData+nZero);
42014   }else{
42015     nData = nZero = 0;
42016   }
42017   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42018   sqlite3BtreeParseCellPtr(pPage, pCell, &info);
42019   assert( info.nHeader==nHeader );
42020   assert( info.nKey==nKey );
42021   assert( info.nData==(u32)(nData+nZero) );
42022   
42023   /* Fill in the payload */
42024   nPayload = nData + nZero;
42025   if( pPage->intKey ){
42026     pSrc = pData;
42027     nSrc = nData;
42028     nData = 0;
42029   }else{ 
42030     if( nKey>0x7fffffff || pKey==0 ){
42031       return SQLITE_CORRUPT;
42032     }
42033     nPayload += (int)nKey;
42034     pSrc = pKey;
42035     nSrc = (int)nKey;
42036   }
42037   *pnSize = info.nSize;
42038   spaceLeft = info.nLocal;
42039   pPayload = &pCell[nHeader];
42040   pPrior = &pCell[info.iOverflow];
42041
42042   while( nPayload>0 ){
42043     if( spaceLeft==0 ){
42044 #ifndef SQLITE_OMIT_AUTOVACUUM
42045       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42046       if( pBt->autoVacuum ){
42047         do{
42048           pgnoOvfl++;
42049         } while( 
42050           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
42051         );
42052       }
42053 #endif
42054       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42055 #ifndef SQLITE_OMIT_AUTOVACUUM
42056       /* If the database supports auto-vacuum, and the second or subsequent
42057       ** overflow page is being allocated, add an entry to the pointer-map
42058       ** for that page now. 
42059       **
42060       ** If this is the first overflow page, then write a partial entry 
42061       ** to the pointer-map. If we write nothing to this pointer-map slot,
42062       ** then the optimistic overflow chain processing in clearCell()
42063       ** may misinterpret the uninitialised values and delete the
42064       ** wrong pages from the database.
42065       */
42066       if( pBt->autoVacuum && rc==SQLITE_OK ){
42067         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42068         rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
42069         if( rc ){
42070           releasePage(pOvfl);
42071         }
42072       }
42073 #endif
42074       if( rc ){
42075         releasePage(pToRelease);
42076         return rc;
42077       }
42078
42079       /* If pToRelease is not zero than pPrior points into the data area
42080       ** of pToRelease.  Make sure pToRelease is still writeable. */
42081       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42082
42083       /* If pPrior is part of the data area of pPage, then make sure pPage
42084       ** is still writeable */
42085       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42086             || sqlite3PagerIswriteable(pPage->pDbPage) );
42087
42088       put4byte(pPrior, pgnoOvfl);
42089       releasePage(pToRelease);
42090       pToRelease = pOvfl;
42091       pPrior = pOvfl->aData;
42092       put4byte(pPrior, 0);
42093       pPayload = &pOvfl->aData[4];
42094       spaceLeft = pBt->usableSize - 4;
42095     }
42096     n = nPayload;
42097     if( n>spaceLeft ) n = spaceLeft;
42098
42099     /* If pToRelease is not zero than pPayload points into the data area
42100     ** of pToRelease.  Make sure pToRelease is still writeable. */
42101     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42102
42103     /* If pPayload is part of the data area of pPage, then make sure pPage
42104     ** is still writeable */
42105     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42106             || sqlite3PagerIswriteable(pPage->pDbPage) );
42107
42108     if( nSrc>0 ){
42109       if( n>nSrc ) n = nSrc;
42110       assert( pSrc );
42111       memcpy(pPayload, pSrc, n);
42112     }else{
42113       memset(pPayload, 0, n);
42114     }
42115     nPayload -= n;
42116     pPayload += n;
42117     pSrc += n;
42118     nSrc -= n;
42119     spaceLeft -= n;
42120     if( nSrc==0 ){
42121       nSrc = nData;
42122       pSrc = pData;
42123     }
42124   }
42125   releasePage(pToRelease);
42126   return SQLITE_OK;
42127 }
42128
42129 /*
42130 ** Remove the i-th cell from pPage.  This routine effects pPage only.
42131 ** The cell content is not freed or deallocated.  It is assumed that
42132 ** the cell content has been copied someplace else.  This routine just
42133 ** removes the reference to the cell from pPage.
42134 **
42135 ** "sz" must be the number of bytes in the cell.
42136 */
42137 static int dropCell(MemPage *pPage, int idx, int sz){
42138   int i;          /* Loop counter */
42139   int pc;         /* Offset to cell content of cell being deleted */
42140   u8 *data;       /* pPage->aData */
42141   u8 *ptr;        /* Used to move bytes around within data[] */
42142   int rc;         /* The return code */
42143
42144   assert( idx>=0 && idx<pPage->nCell );
42145   assert( sz==cellSize(pPage, idx) );
42146   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42147   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42148   data = pPage->aData;
42149   ptr = &data[pPage->cellOffset + 2*idx];
42150   pc = get2byte(ptr);
42151   if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
42152      || (pc+sz>pPage->pBt->usableSize) ){
42153     return SQLITE_CORRUPT_BKPT;
42154   }
42155   rc = freeSpace(pPage, pc, sz);
42156   if( rc!=SQLITE_OK ){
42157     return rc;
42158   }
42159   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
42160     ptr[0] = ptr[2];
42161     ptr[1] = ptr[3];
42162   }
42163   pPage->nCell--;
42164   put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
42165   pPage->nFree += 2;
42166   return SQLITE_OK;
42167 }
42168
42169 /*
42170 ** Insert a new cell on pPage at cell index "i".  pCell points to the
42171 ** content of the cell.
42172 **
42173 ** If the cell content will fit on the page, then put it there.  If it
42174 ** will not fit, then make a copy of the cell content into pTemp if
42175 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
42176 ** in pPage->aOvfl[] and make it point to the cell content (either
42177 ** in pTemp or the original pCell) and also record its index. 
42178 ** Allocating a new entry in pPage->aCell[] implies that 
42179 ** pPage->nOverflow is incremented.
42180 **
42181 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
42182 ** cell. The caller will overwrite them after this function returns. If
42183 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
42184 ** (but pCell+nSkip is always valid).
42185 */
42186 static int insertCell(
42187   MemPage *pPage,   /* Page into which we are copying */
42188   int i,            /* New cell becomes the i-th cell of the page */
42189   u8 *pCell,        /* Content of the new cell */
42190   int sz,           /* Bytes of content in pCell */
42191   u8 *pTemp,        /* Temp storage space for pCell, if needed */
42192   u8 nSkip          /* Do not write the first nSkip bytes of the cell */
42193 ){
42194   int idx;          /* Where to write new cell content in data[] */
42195   int j;            /* Loop counter */
42196   int top;          /* First byte of content for any cell in data[] */
42197   int end;          /* First byte past the last cell pointer in data[] */
42198   int ins;          /* Index in data[] where new cell pointer is inserted */
42199   int hdr;          /* Offset into data[] of the page header */
42200   int cellOffset;   /* Address of first cell pointer in data[] */
42201   u8 *data;         /* The content of the whole page */
42202   u8 *ptr;          /* Used for moving information around in data[] */
42203
42204   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
42205   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42206   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
42207   assert( sz==cellSizePtr(pPage, pCell) );
42208   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42209   if( pPage->nOverflow || sz+2>pPage->nFree ){
42210     if( pTemp ){
42211       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
42212       pCell = pTemp;
42213     }
42214     j = pPage->nOverflow++;
42215     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
42216     pPage->aOvfl[j].pCell = pCell;
42217     pPage->aOvfl[j].idx = (u16)i;
42218     pPage->nFree = 0;
42219   }else{
42220     int rc = sqlite3PagerWrite(pPage->pDbPage);
42221     if( rc!=SQLITE_OK ){
42222       return rc;
42223     }
42224     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42225     data = pPage->aData;
42226     hdr = pPage->hdrOffset;
42227     top = get2byte(&data[hdr+5]);
42228     cellOffset = pPage->cellOffset;
42229     end = cellOffset + 2*pPage->nCell + 2;
42230     ins = cellOffset + 2*i;
42231     if( end > top - sz ){
42232       rc = defragmentPage(pPage);
42233       if( rc!=SQLITE_OK ){
42234         return rc;
42235       }
42236       top = get2byte(&data[hdr+5]);
42237       assert( end + sz <= top );
42238     }
42239     idx = allocateSpace(pPage, sz);
42240     assert( idx>0 );
42241     assert( end <= get2byte(&data[hdr+5]) );
42242     if (idx+sz > pPage->pBt->usableSize) {
42243       return SQLITE_CORRUPT_BKPT;
42244     }
42245     pPage->nCell++;
42246     pPage->nFree -= 2;
42247     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
42248     for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
42249       ptr[0] = ptr[-2];
42250       ptr[1] = ptr[-1];
42251     }
42252     put2byte(&data[ins], idx);
42253     put2byte(&data[hdr+3], pPage->nCell);
42254 #ifndef SQLITE_OMIT_AUTOVACUUM
42255     if( pPage->pBt->autoVacuum ){
42256       /* The cell may contain a pointer to an overflow page. If so, write
42257       ** the entry for the overflow page into the pointer map.
42258       */
42259       CellInfo info;
42260       sqlite3BtreeParseCellPtr(pPage, pCell, &info);
42261       assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
42262       if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
42263         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
42264         rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
42265         if( rc!=SQLITE_OK ) return rc;
42266       }
42267     }
42268 #endif
42269   }
42270
42271   return SQLITE_OK;
42272 }
42273
42274 /*
42275 ** Add a list of cells to a page.  The page should be initially empty.
42276 ** The cells are guaranteed to fit on the page.
42277 */
42278 static void assemblePage(
42279   MemPage *pPage,   /* The page to be assemblied */
42280   int nCell,        /* The number of cells to add to this page */
42281   u8 **apCell,      /* Pointers to cell bodies */
42282   u16 *aSize        /* Sizes of the cells */
42283 ){
42284   int i;            /* Loop counter */
42285   int totalSize;    /* Total size of all cells */
42286   int hdr;          /* Index of page header */
42287   int cellptr;      /* Address of next cell pointer */
42288   int cellbody;     /* Address of next cell body */
42289   u8 *data;         /* Data for the page */
42290
42291   assert( pPage->nOverflow==0 );
42292   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42293   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42294   totalSize = 0;
42295   for(i=0; i<nCell; i++){
42296     totalSize += aSize[i];
42297   }
42298   assert( totalSize+2*nCell<=pPage->nFree );
42299   assert( pPage->nCell==0 );
42300   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42301   cellptr = pPage->cellOffset;
42302   data = pPage->aData;
42303   hdr = pPage->hdrOffset;
42304   put2byte(&data[hdr+3], nCell);
42305   if( nCell ){
42306     cellbody = allocateSpace(pPage, totalSize);
42307     assert( cellbody>0 );
42308     assert( pPage->nFree >= 2*nCell );
42309     pPage->nFree -= 2*nCell;
42310     for(i=0; i<nCell; i++){
42311       put2byte(&data[cellptr], cellbody);
42312       memcpy(&data[cellbody], apCell[i], aSize[i]);
42313       cellptr += 2;
42314       cellbody += aSize[i];
42315     }
42316     assert( cellbody==pPage->pBt->usableSize );
42317   }
42318   pPage->nCell = (u16)nCell;
42319 }
42320
42321 /*
42322 ** The following parameters determine how many adjacent pages get involved
42323 ** in a balancing operation.  NN is the number of neighbors on either side
42324 ** of the page that participate in the balancing operation.  NB is the
42325 ** total number of pages that participate, including the target page and
42326 ** NN neighbors on either side.
42327 **
42328 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
42329 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
42330 ** in exchange for a larger degradation in INSERT and UPDATE performance.
42331 ** The value of NN appears to give the best results overall.
42332 */
42333 #define NN 1             /* Number of neighbors on either side of pPage */
42334 #define NB (NN*2+1)      /* Total pages involved in the balance */
42335
42336 /* Forward reference */
42337 static int balance(BtCursor*, int);
42338
42339 #ifndef SQLITE_OMIT_QUICKBALANCE
42340 /*
42341 ** This version of balance() handles the common special case where
42342 ** a new entry is being inserted on the extreme right-end of the
42343 ** tree, in other words, when the new entry will become the largest
42344 ** entry in the tree.
42345 **
42346 ** Instead of trying balance the 3 right-most leaf pages, just add
42347 ** a new page to the right-hand side and put the one new entry in
42348 ** that page.  This leaves the right side of the tree somewhat
42349 ** unbalanced.  But odds are that we will be inserting new entries
42350 ** at the end soon afterwards so the nearly empty page will quickly
42351 ** fill up.  On average.
42352 **
42353 ** pPage is the leaf page which is the right-most page in the tree.
42354 ** pParent is its parent.  pPage must have a single overflow entry
42355 ** which is also the right-most entry on the page.
42356 */
42357 static int balance_quick(BtCursor *pCur){
42358   int rc;
42359   MemPage *pNew = 0;
42360   Pgno pgnoNew;
42361   u8 *pCell;
42362   u16 szCell;
42363   CellInfo info;
42364   MemPage *pPage = pCur->apPage[pCur->iPage];
42365   MemPage *pParent = pCur->apPage[pCur->iPage-1];
42366   BtShared *pBt = pPage->pBt;
42367   int parentIdx = pParent->nCell;   /* pParent new divider cell index */
42368   int parentSize;                   /* Size of new divider cell */
42369   u8 parentCell[64];                /* Space for the new divider cell */
42370
42371   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42372
42373   /* Allocate a new page. Insert the overflow cell from pPage
42374   ** into it. Then remove the overflow cell from pPage.
42375   */
42376   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
42377   if( rc==SQLITE_OK ){
42378     pCell = pPage->aOvfl[0].pCell;
42379     szCell = cellSizePtr(pPage, pCell);
42380     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
42381     zeroPage(pNew, pPage->aData[0]);
42382     assemblePage(pNew, 1, &pCell, &szCell);
42383     pPage->nOverflow = 0;
42384   
42385     /* pPage is currently the right-child of pParent. Change this
42386     ** so that the right-child is the new page allocated above and
42387     ** pPage is the next-to-right child. 
42388     **
42389     ** Ignore the return value of the call to fillInCell(). fillInCell()
42390     ** may only return other than SQLITE_OK if it is required to allocate
42391     ** one or more overflow pages. Since an internal table B-Tree cell 
42392     ** may never spill over onto an overflow page (it is a maximum of 
42393     ** 13 bytes in size), it is not neccessary to check the return code.
42394     **
42395     ** Similarly, the insertCell() function cannot fail if the page
42396     ** being inserted into is already writable and the cell does not 
42397     ** contain an overflow pointer. So ignore this return code too.
42398     */
42399     assert( pPage->nCell>0 );
42400     pCell = findCell(pPage, pPage->nCell-1);
42401     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
42402     fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
42403     assert( parentSize<64 );
42404     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
42405     insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
42406     put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
42407     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
42408   
42409     /* If this is an auto-vacuum database, update the pointer map
42410     ** with entries for the new page, and any pointer from the 
42411     ** cell on the page to an overflow page.
42412     */
42413     if( ISAUTOVACUUM ){
42414       rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
42415       if( rc==SQLITE_OK ){
42416         rc = ptrmapPutOvfl(pNew, 0);
42417       }
42418     }
42419
42420     /* Release the reference to the new page. */
42421     releasePage(pNew);
42422   }
42423
42424   /* At this point the pPage->nFree variable is not set correctly with
42425   ** respect to the content of the page (because it was set to 0 by 
42426   ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
42427   ** correct.
42428   **
42429   ** This has to be done even if an error will be returned. Normally, if
42430   ** an error occurs during tree balancing, the contents of MemPage are
42431   ** not important, as they will be recalculated when the page is rolled
42432   ** back. But here, in balance_quick(), it is possible that pPage has 
42433   ** not yet been marked dirty or written into the journal file. Therefore
42434   ** it will not be rolled back and so it is important to make sure that
42435   ** the page data and contents of MemPage are consistent.
42436   */
42437   pPage->isInit = 0;
42438   sqlite3BtreeInitPage(pPage);
42439   assert( pPage->nOverflow==0 );
42440
42441   /* If everything else succeeded, balance the parent page, in 
42442   ** case the divider cell inserted caused it to become overfull.
42443   */
42444   if( rc==SQLITE_OK ){
42445     releasePage(pPage);
42446     pCur->iPage--;
42447     rc = balance(pCur, 0);
42448   }
42449   return rc;
42450 }
42451 #endif /* SQLITE_OMIT_QUICKBALANCE */
42452
42453 /*
42454 ** This routine redistributes Cells on pPage and up to NN*2 siblings
42455 ** of pPage so that all pages have about the same amount of free space.
42456 ** Usually NN siblings on either side of pPage is used in the balancing,
42457 ** though more siblings might come from one side if pPage is the first
42458 ** or last child of its parent.  If pPage has fewer than 2*NN siblings
42459 ** (something which can only happen if pPage is the root page or a 
42460 ** child of root) then all available siblings participate in the balancing.
42461 **
42462 ** The number of siblings of pPage might be increased or decreased by one or
42463 ** two in an effort to keep pages nearly full but not over full. The root page
42464 ** is special and is allowed to be nearly empty. If pPage is 
42465 ** the root page, then the depth of the tree might be increased
42466 ** or decreased by one, as necessary, to keep the root page from being
42467 ** overfull or completely empty.
42468 **
42469 ** Note that when this routine is called, some of the Cells on pPage
42470 ** might not actually be stored in pPage->aData[].  This can happen
42471 ** if the page is overfull.  Part of the job of this routine is to
42472 ** make sure all Cells for pPage once again fit in pPage->aData[].
42473 **
42474 ** In the course of balancing the siblings of pPage, the parent of pPage
42475 ** might become overfull or underfull.  If that happens, then this routine
42476 ** is called recursively on the parent.
42477 **
42478 ** If this routine fails for any reason, it might leave the database
42479 ** in a corrupted state.  So if this routine fails, the database should
42480 ** be rolled back.
42481 */
42482 static int balance_nonroot(BtCursor *pCur){
42483   MemPage *pPage;              /* The over or underfull page to balance */
42484   MemPage *pParent;            /* The parent of pPage */
42485   BtShared *pBt;               /* The whole database */
42486   int nCell = 0;               /* Number of cells in apCell[] */
42487   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
42488   int nOld = 0;                /* Number of pages in apOld[] */
42489   int nNew = 0;                /* Number of pages in apNew[] */
42490   int nDiv;                    /* Number of cells in apDiv[] */
42491   int i, j, k;                 /* Loop counters */
42492   int idx;                     /* Index of pPage in pParent->aCell[] */
42493   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
42494   int rc;                      /* The return code */
42495   int leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
42496   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
42497   int usableSpace;             /* Bytes in pPage beyond the header */
42498   int pageFlags;               /* Value of pPage->aData[0] */
42499   int subtotal;                /* Subtotal of bytes in cells on one page */
42500   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
42501   int iSpace2 = 0;             /* First unused byte of aSpace2[] */
42502   int szScratch;               /* Size of scratch memory requested */
42503   MemPage *apOld[NB];          /* pPage and up to two siblings */
42504   Pgno pgnoOld[NB];            /* Page numbers for each page in apOld[] */
42505   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
42506   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
42507   Pgno pgnoNew[NB+2];          /* Page numbers for each page in apNew[] */
42508   u8 *apDiv[NB];               /* Divider cells in pParent */
42509   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
42510   int szNew[NB+2];             /* Combined size of cells place on i-th page */
42511   u8 **apCell = 0;             /* All cells begin balanced */
42512   u16 *szCell;                 /* Local size of all cells in apCell[] */
42513   u8 *aCopy[NB];         /* Space for holding data of apCopy[] */
42514   u8 *aSpace1;           /* Space for copies of dividers cells before balance */
42515   u8 *aSpace2 = 0;       /* Space for overflow dividers cells after balance */
42516   u8 *aFrom = 0;
42517
42518   pPage = pCur->apPage[pCur->iPage];
42519   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42520   VVA_ONLY( pCur->pagesShuffled = 1 );
42521
42522   /* 
42523   ** Find the parent page.
42524   */
42525   assert( pCur->iPage>0 );
42526   assert( pPage->isInit );
42527   assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
42528   pBt = pPage->pBt;
42529   pParent = pCur->apPage[pCur->iPage-1];
42530   assert( pParent );
42531   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
42532     goto balance_cleanup;
42533   }
42534
42535   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
42536
42537 #ifndef SQLITE_OMIT_QUICKBALANCE
42538   /*
42539   ** A special case:  If a new entry has just been inserted into a
42540   ** table (that is, a btree with integer keys and all data at the leaves)
42541   ** and the new entry is the right-most entry in the tree (it has the
42542   ** largest key) then use the special balance_quick() routine for
42543   ** balancing.  balance_quick() is much faster and results in a tighter
42544   ** packing of data in the common case.
42545   */
42546   if( pPage->leaf &&
42547       pPage->intKey &&
42548       pPage->nOverflow==1 &&
42549       pPage->aOvfl[0].idx==pPage->nCell &&
42550       pParent->pgno!=1 &&
42551       get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
42552   ){
42553     assert( pPage->intKey );
42554     /*
42555     ** TODO: Check the siblings to the left of pPage. It may be that
42556     ** they are not full and no new page is required.
42557     */
42558     return balance_quick(pCur);
42559   }
42560 #endif
42561
42562   if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
42563     goto balance_cleanup;
42564   }
42565
42566   /*
42567   ** Find the cell in the parent page whose left child points back
42568   ** to pPage.  The "idx" variable is the index of that cell.  If pPage
42569   ** is the rightmost child of pParent then set idx to pParent->nCell 
42570   */
42571   idx = pCur->aiIdx[pCur->iPage-1];
42572   assertParentIndex(pParent, idx, pPage->pgno);
42573
42574   /*
42575   ** Find sibling pages to pPage and the cells in pParent that divide
42576   ** the siblings.  An attempt is made to find NN siblings on either
42577   ** side of pPage.  More siblings are taken from one side, however, if
42578   ** pPage there are fewer than NN siblings on the other side.  If pParent
42579   ** has NB or fewer children then all children of pParent are taken.
42580   */
42581   nxDiv = idx - NN;
42582   if( nxDiv + NB > pParent->nCell ){
42583     nxDiv = pParent->nCell - NB + 1;
42584   }
42585   if( nxDiv<0 ){
42586     nxDiv = 0;
42587   }
42588   nDiv = 0;
42589   for(i=0, k=nxDiv; i<NB; i++, k++){
42590     if( k<pParent->nCell ){
42591       apDiv[i] = findCell(pParent, k);
42592       nDiv++;
42593       assert( !pParent->leaf );
42594       pgnoOld[i] = get4byte(apDiv[i]);
42595     }else if( k==pParent->nCell ){
42596       pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
42597     }else{
42598       break;
42599     }
42600     rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
42601     if( rc ) goto balance_cleanup;
42602     /* apOld[i]->idxParent = k; */
42603     apCopy[i] = 0;
42604     assert( i==nOld );
42605     nOld++;
42606     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
42607   }
42608
42609   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
42610   ** alignment */
42611   nMaxCells = (nMaxCells + 3)&~3;
42612
42613   /*
42614   ** Allocate space for memory structures
42615   */
42616   szScratch =
42617        nMaxCells*sizeof(u8*)                       /* apCell */
42618      + nMaxCells*sizeof(u16)                       /* szCell */
42619      + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB  /* aCopy */
42620      + pBt->pageSize                               /* aSpace1 */
42621      + (ISAUTOVACUUM ? nMaxCells : 0);             /* aFrom */
42622   apCell = sqlite3ScratchMalloc( szScratch ); 
42623   if( apCell==0 ){
42624     rc = SQLITE_NOMEM;
42625     goto balance_cleanup;
42626   }
42627   szCell = (u16*)&apCell[nMaxCells];
42628   aCopy[0] = (u8*)&szCell[nMaxCells];
42629   assert( ((aCopy[0] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
42630   for(i=1; i<NB; i++){
42631     aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
42632     assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
42633   }
42634   aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
42635   assert( ((aSpace1 - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
42636   if( ISAUTOVACUUM ){
42637     aFrom = &aSpace1[pBt->pageSize];
42638   }
42639   aSpace2 = sqlite3PageMalloc(pBt->pageSize);
42640   if( aSpace2==0 ){
42641     rc = SQLITE_NOMEM;
42642     goto balance_cleanup;
42643   }
42644   
42645   /*
42646   ** Make copies of the content of pPage and its siblings into aOld[].
42647   ** The rest of this function will use data from the copies rather
42648   ** that the original pages since the original pages will be in the
42649   ** process of being overwritten.
42650   */
42651   for(i=0; i<nOld; i++){
42652     MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
42653     memcpy(p, apOld[i], sizeof(MemPage));
42654     p->aData = (void*)&p[1];
42655     memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
42656   }
42657
42658   /*
42659   ** Load pointers to all cells on sibling pages and the divider cells
42660   ** into the local apCell[] array.  Make copies of the divider cells
42661   ** into space obtained form aSpace1[] and remove the the divider Cells
42662   ** from pParent.
42663   **
42664   ** If the siblings are on leaf pages, then the child pointers of the
42665   ** divider cells are stripped from the cells before they are copied
42666   ** into aSpace1[].  In this way, all cells in apCell[] are without
42667   ** child pointers.  If siblings are not leaves, then all cell in
42668   ** apCell[] include child pointers.  Either way, all cells in apCell[]
42669   ** are alike.
42670   **
42671   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
42672   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
42673   */
42674   nCell = 0;
42675   leafCorrection = pPage->leaf*4;
42676   leafData = pPage->hasData;
42677   for(i=0; i<nOld; i++){
42678     MemPage *pOld = apCopy[i];
42679     int limit = pOld->nCell+pOld->nOverflow;
42680     for(j=0; j<limit; j++){
42681       assert( nCell<nMaxCells );
42682       apCell[nCell] = findOverflowCell(pOld, j);
42683       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
42684       if( ISAUTOVACUUM ){
42685         int a;
42686         aFrom[nCell] = (u8)i;   assert( i>=0 && i<6 );
42687         for(a=0; a<pOld->nOverflow; a++){
42688           if( pOld->aOvfl[a].pCell==apCell[nCell] ){
42689             aFrom[nCell] = 0xFF;
42690             break;
42691           }
42692         }
42693       }
42694       nCell++;
42695     }
42696     if( i<nOld-1 ){
42697       u16 sz = cellSizePtr(pParent, apDiv[i]);
42698       if( leafData ){
42699         /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
42700         ** are duplicates of keys on the child pages.  We need to remove
42701         ** the divider cells from pParent, but the dividers cells are not
42702         ** added to apCell[] because they are duplicates of child cells.
42703         */
42704         dropCell(pParent, nxDiv, sz);
42705       }else{
42706         u8 *pTemp;
42707         assert( nCell<nMaxCells );
42708         szCell[nCell] = sz;
42709         pTemp = &aSpace1[iSpace1];
42710         iSpace1 += sz;
42711         assert( sz<=pBt->pageSize/4 );
42712         assert( iSpace1<=pBt->pageSize );
42713         memcpy(pTemp, apDiv[i], sz);
42714         apCell[nCell] = pTemp+leafCorrection;
42715         if( ISAUTOVACUUM ){
42716           aFrom[nCell] = 0xFF;
42717         }
42718         dropCell(pParent, nxDiv, sz);
42719         assert( leafCorrection==0 || leafCorrection==4 );
42720         szCell[nCell] -= (u16)leafCorrection;
42721         assert( get4byte(pTemp)==pgnoOld[i] );
42722         if( !pOld->leaf ){
42723           assert( leafCorrection==0 );
42724           /* The right pointer of the child page pOld becomes the left
42725           ** pointer of the divider cell */
42726           memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
42727         }else{
42728           assert( leafCorrection==4 );
42729           if( szCell[nCell]<4 ){
42730             /* Do not allow any cells smaller than 4 bytes. */
42731             szCell[nCell] = 4;
42732           }
42733         }
42734         nCell++;
42735       }
42736     }
42737   }
42738
42739   /*
42740   ** Figure out the number of pages needed to hold all nCell cells.
42741   ** Store this number in "k".  Also compute szNew[] which is the total
42742   ** size of all cells on the i-th page and cntNew[] which is the index
42743   ** in apCell[] of the cell that divides page i from page i+1.  
42744   ** cntNew[k] should equal nCell.
42745   **
42746   ** Values computed by this block:
42747   **
42748   **           k: The total number of sibling pages
42749   **    szNew[i]: Spaced used on the i-th sibling page.
42750   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
42751   **              the right of the i-th sibling page.
42752   ** usableSpace: Number of bytes of space available on each sibling.
42753   ** 
42754   */
42755   usableSpace = pBt->usableSize - 12 + leafCorrection;
42756   for(subtotal=k=i=0; i<nCell; i++){
42757     assert( i<nMaxCells );
42758     subtotal += szCell[i] + 2;
42759     if( subtotal > usableSpace ){
42760       szNew[k] = subtotal - szCell[i];
42761       cntNew[k] = i;
42762       if( leafData ){ i--; }
42763       subtotal = 0;
42764       k++;
42765     }
42766   }
42767   szNew[k] = subtotal;
42768   cntNew[k] = nCell;
42769   k++;
42770
42771   /*
42772   ** The packing computed by the previous block is biased toward the siblings
42773   ** on the left side.  The left siblings are always nearly full, while the
42774   ** right-most sibling might be nearly empty.  This block of code attempts
42775   ** to adjust the packing of siblings to get a better balance.
42776   **
42777   ** This adjustment is more than an optimization.  The packing above might
42778   ** be so out of balance as to be illegal.  For example, the right-most
42779   ** sibling might be completely empty.  This adjustment is not optional.
42780   */
42781   for(i=k-1; i>0; i--){
42782     int szRight = szNew[i];  /* Size of sibling on the right */
42783     int szLeft = szNew[i-1]; /* Size of sibling on the left */
42784     int r;              /* Index of right-most cell in left sibling */
42785     int d;              /* Index of first cell to the left of right sibling */
42786
42787     r = cntNew[i-1] - 1;
42788     d = r + 1 - leafData;
42789     assert( d<nMaxCells );
42790     assert( r<nMaxCells );
42791     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
42792       szRight += szCell[d] + 2;
42793       szLeft -= szCell[r] + 2;
42794       cntNew[i-1]--;
42795       r = cntNew[i-1] - 1;
42796       d = r + 1 - leafData;
42797     }
42798     szNew[i] = szRight;
42799     szNew[i-1] = szLeft;
42800   }
42801
42802   /* Either we found one or more cells (cntnew[0])>0) or we are the
42803   ** a virtual root page.  A virtual root page is when the real root
42804   ** page is page 1 and we are the only child of that page.
42805   */
42806   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
42807
42808   /*
42809   ** Allocate k new pages.  Reuse old pages where possible.
42810   */
42811   assert( pPage->pgno>1 );
42812   pageFlags = pPage->aData[0];
42813   for(i=0; i<k; i++){
42814     MemPage *pNew;
42815     if( i<nOld ){
42816       pNew = apNew[i] = apOld[i];
42817       pgnoNew[i] = pgnoOld[i];
42818       apOld[i] = 0;
42819       rc = sqlite3PagerWrite(pNew->pDbPage);
42820       nNew++;
42821       if( rc ) goto balance_cleanup;
42822     }else{
42823       assert( i>0 );
42824       rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
42825       if( rc ) goto balance_cleanup;
42826       apNew[i] = pNew;
42827       nNew++;
42828     }
42829   }
42830
42831   /* Free any old pages that were not reused as new pages.
42832   */
42833   while( i<nOld ){
42834     rc = freePage(apOld[i]);
42835     if( rc ) goto balance_cleanup;
42836     releasePage(apOld[i]);
42837     apOld[i] = 0;
42838     i++;
42839   }
42840
42841   /*
42842   ** Put the new pages in accending order.  This helps to
42843   ** keep entries in the disk file in order so that a scan
42844   ** of the table is a linear scan through the file.  That
42845   ** in turn helps the operating system to deliver pages
42846   ** from the disk more rapidly.
42847   **
42848   ** An O(n^2) insertion sort algorithm is used, but since
42849   ** n is never more than NB (a small constant), that should
42850   ** not be a problem.
42851   **
42852   ** When NB==3, this one optimization makes the database
42853   ** about 25% faster for large insertions and deletions.
42854   */
42855   for(i=0; i<k-1; i++){
42856     int minV = pgnoNew[i];
42857     int minI = i;
42858     for(j=i+1; j<k; j++){
42859       if( pgnoNew[j]<(unsigned)minV ){
42860         minI = j;
42861         minV = pgnoNew[j];
42862       }
42863     }
42864     if( minI>i ){
42865       int t;
42866       MemPage *pT;
42867       t = pgnoNew[i];
42868       pT = apNew[i];
42869       pgnoNew[i] = pgnoNew[minI];
42870       apNew[i] = apNew[minI];
42871       pgnoNew[minI] = t;
42872       apNew[minI] = pT;
42873     }
42874   }
42875   TRACE(("BALANCE: old: %d %d %d  new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
42876     pgnoOld[0], 
42877     nOld>=2 ? pgnoOld[1] : 0,
42878     nOld>=3 ? pgnoOld[2] : 0,
42879     pgnoNew[0], szNew[0],
42880     nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
42881     nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
42882     nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
42883     nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
42884
42885   /*
42886   ** Evenly distribute the data in apCell[] across the new pages.
42887   ** Insert divider cells into pParent as necessary.
42888   */
42889   j = 0;
42890   for(i=0; i<nNew; i++){
42891     /* Assemble the new sibling page. */
42892     MemPage *pNew = apNew[i];
42893     assert( j<nMaxCells );
42894     assert( pNew->pgno==pgnoNew[i] );
42895     zeroPage(pNew, pageFlags);
42896     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
42897     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
42898     assert( pNew->nOverflow==0 );
42899
42900     /* If this is an auto-vacuum database, update the pointer map entries
42901     ** that point to the siblings that were rearranged. These can be: left
42902     ** children of cells, the right-child of the page, or overflow pages
42903     ** pointed to by cells.
42904     */
42905     if( ISAUTOVACUUM ){
42906       for(k=j; k<cntNew[i]; k++){
42907         assert( k<nMaxCells );
42908         if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
42909           rc = ptrmapPutOvfl(pNew, k-j);
42910           if( rc==SQLITE_OK && leafCorrection==0 ){
42911             rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
42912           }
42913           if( rc!=SQLITE_OK ){
42914             goto balance_cleanup;
42915           }
42916         }
42917       }
42918     }
42919
42920     j = cntNew[i];
42921
42922     /* If the sibling page assembled above was not the right-most sibling,
42923     ** insert a divider cell into the parent page.
42924     */
42925     if( i<nNew-1 && j<nCell ){
42926       u8 *pCell;
42927       u8 *pTemp;
42928       int sz;
42929
42930       assert( j<nMaxCells );
42931       pCell = apCell[j];
42932       sz = szCell[j] + leafCorrection;
42933       pTemp = &aSpace2[iSpace2];
42934       if( !pNew->leaf ){
42935         memcpy(&pNew->aData[8], pCell, 4);
42936         if( ISAUTOVACUUM 
42937          && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
42938         ){
42939           rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
42940           if( rc!=SQLITE_OK ){
42941             goto balance_cleanup;
42942           }
42943         }
42944       }else if( leafData ){
42945         /* If the tree is a leaf-data tree, and the siblings are leaves, 
42946         ** then there is no divider cell in apCell[]. Instead, the divider 
42947         ** cell consists of the integer key for the right-most cell of 
42948         ** the sibling-page assembled above only.
42949         */
42950         CellInfo info;
42951         j--;
42952         sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
42953         pCell = pTemp;
42954         rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
42955         if( rc!=SQLITE_OK ){
42956           goto balance_cleanup;
42957         }
42958         pTemp = 0;
42959       }else{
42960         pCell -= 4;
42961         /* Obscure case for non-leaf-data trees: If the cell at pCell was
42962         ** previously stored on a leaf node, and its reported size was 4
42963         ** bytes, then it may actually be smaller than this 
42964         ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
42965         ** any cell). But it is important to pass the correct size to 
42966         ** insertCell(), so reparse the cell now.
42967         **
42968         ** Note that this can never happen in an SQLite data file, as all
42969         ** cells are at least 4 bytes. It only happens in b-trees used
42970         ** to evaluate "IN (SELECT ...)" and similar clauses.
42971         */
42972         if( szCell[j]==4 ){
42973           assert(leafCorrection==4);
42974           sz = cellSizePtr(pParent, pCell);
42975         }
42976       }
42977       iSpace2 += sz;
42978       assert( sz<=pBt->pageSize/4 );
42979       assert( iSpace2<=pBt->pageSize );
42980       rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
42981       if( rc!=SQLITE_OK ) goto balance_cleanup;
42982       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
42983       put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
42984
42985       /* If this is an auto-vacuum database, and not a leaf-data tree,
42986       ** then update the pointer map with an entry for the overflow page
42987       ** that the cell just inserted points to (if any).
42988       */
42989       if( ISAUTOVACUUM && !leafData ){
42990         rc = ptrmapPutOvfl(pParent, nxDiv);
42991         if( rc!=SQLITE_OK ){
42992           goto balance_cleanup;
42993         }
42994       }
42995       j++;
42996       nxDiv++;
42997     }
42998
42999     /* Set the pointer-map entry for the new sibling page. */
43000     if( ISAUTOVACUUM ){
43001       rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
43002       if( rc!=SQLITE_OK ){
43003         goto balance_cleanup;
43004       }
43005     }
43006   }
43007   assert( j==nCell );
43008   assert( nOld>0 );
43009   assert( nNew>0 );
43010   if( (pageFlags & PTF_LEAF)==0 ){
43011     u8 *zChild = &apCopy[nOld-1]->aData[8];
43012     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43013     if( ISAUTOVACUUM ){
43014       rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
43015       if( rc!=SQLITE_OK ){
43016         goto balance_cleanup;
43017       }
43018     }
43019   }
43020   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43021   if( nxDiv==pParent->nCell+pParent->nOverflow ){
43022     /* Right-most sibling is the right-most child of pParent */
43023     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
43024   }else{
43025     /* Right-most sibling is the left child of the first entry in pParent
43026     ** past the right-most divider entry */
43027     put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
43028   }
43029
43030   /*
43031   ** Balance the parent page.  Note that the current page (pPage) might
43032   ** have been added to the freelist so it might no longer be initialized.
43033   ** But the parent page will always be initialized.
43034   */
43035   assert( pParent->isInit );
43036   sqlite3ScratchFree(apCell);
43037   apCell = 0;
43038   TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
43039           pPage->pgno, nOld, nNew, nCell));
43040   pPage->nOverflow = 0;
43041   releasePage(pPage);
43042   pCur->iPage--;
43043   rc = balance(pCur, 0);
43044   
43045   /*
43046   ** Cleanup before returning.
43047   */
43048 balance_cleanup:
43049   sqlite3PageFree(aSpace2);
43050   sqlite3ScratchFree(apCell);
43051   for(i=0; i<nOld; i++){
43052     releasePage(apOld[i]);
43053   }
43054   for(i=0; i<nNew; i++){
43055     releasePage(apNew[i]);
43056   }
43057   pCur->apPage[pCur->iPage]->nOverflow = 0;
43058
43059   return rc;
43060 }
43061
43062 /*
43063 ** This routine is called for the root page of a btree when the root
43064 ** page contains no cells.  This is an opportunity to make the tree
43065 ** shallower by one level.
43066 */
43067 static int balance_shallower(BtCursor *pCur){
43068   MemPage *pPage;              /* Root page of B-Tree */
43069   MemPage *pChild;             /* The only child page of pPage */
43070   Pgno pgnoChild;              /* Page number for pChild */
43071   int rc = SQLITE_OK;          /* Return code from subprocedures */
43072   BtShared *pBt;                  /* The main BTree structure */
43073   int mxCellPerPage;           /* Maximum number of cells per page */
43074   u8 **apCell;                 /* All cells from pages being balanced */
43075   u16 *szCell;                 /* Local size of all cells */
43076
43077   assert( pCur->iPage==0 );
43078   pPage = pCur->apPage[0];
43079
43080   assert( pPage->nCell==0 );
43081   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43082   pBt = pPage->pBt;
43083   mxCellPerPage = MX_CELL(pBt);
43084   apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
43085   if( apCell==0 ) return SQLITE_NOMEM;
43086   szCell = (u16*)&apCell[mxCellPerPage];
43087   if( pPage->leaf ){
43088     /* The table is completely empty */
43089     TRACE(("BALANCE: empty table %d\n", pPage->pgno));
43090   }else{
43091     /* The root page is empty but has one child.  Transfer the
43092     ** information from that one child into the root page if it 
43093     ** will fit.  This reduces the depth of the tree by one.
43094     **
43095     ** If the root page is page 1, it has less space available than
43096     ** its child (due to the 100 byte header that occurs at the beginning
43097     ** of the database fle), so it might not be able to hold all of the 
43098     ** information currently contained in the child.  If this is the 
43099     ** case, then do not do the transfer.  Leave page 1 empty except
43100     ** for the right-pointer to the child page.  The child page becomes
43101     ** the virtual root of the tree.
43102     */
43103     VVA_ONLY( pCur->pagesShuffled = 1 );
43104     pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43105     assert( pgnoChild>0 );
43106     assert( pgnoChild<=pagerPagecount(pPage->pBt) );
43107     rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
43108     if( rc ) goto end_shallow_balance;
43109     if( pPage->pgno==1 ){
43110       rc = sqlite3BtreeInitPage(pChild);
43111       if( rc ) goto end_shallow_balance;
43112       assert( pChild->nOverflow==0 );
43113       if( pChild->nFree>=100 ){
43114         /* The child information will fit on the root page, so do the
43115         ** copy */
43116         int i;
43117         zeroPage(pPage, pChild->aData[0]);
43118         for(i=0; i<pChild->nCell; i++){
43119           apCell[i] = findCell(pChild,i);
43120           szCell[i] = cellSizePtr(pChild, apCell[i]);
43121         }
43122         assemblePage(pPage, pChild->nCell, apCell, szCell);
43123         /* Copy the right-pointer of the child to the parent. */
43124         assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43125         put4byte(&pPage->aData[pPage->hdrOffset+8], 
43126             get4byte(&pChild->aData[pChild->hdrOffset+8]));
43127         rc = freePage(pChild);
43128         TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
43129       }else{
43130         /* The child has more information that will fit on the root.
43131         ** The tree is already balanced.  Do nothing. */
43132         TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
43133       }
43134     }else{
43135       memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
43136       pPage->isInit = 0;
43137       rc = sqlite3BtreeInitPage(pPage);
43138       assert( rc==SQLITE_OK );
43139       freePage(pChild);
43140       TRACE(("BALANCE: transfer child %d into root %d\n",
43141               pChild->pgno, pPage->pgno));
43142     }
43143     assert( pPage->nOverflow==0 );
43144 #ifndef SQLITE_OMIT_AUTOVACUUM
43145     if( ISAUTOVACUUM && rc==SQLITE_OK ){
43146       rc = setChildPtrmaps(pPage);
43147     }
43148 #endif
43149     releasePage(pChild);
43150   }
43151 end_shallow_balance:
43152   sqlite3_free(apCell);
43153   return rc;
43154 }
43155
43156
43157 /*
43158 ** The root page is overfull
43159 **
43160 ** When this happens, Create a new child page and copy the
43161 ** contents of the root into the child.  Then make the root
43162 ** page an empty page with rightChild pointing to the new
43163 ** child.   Finally, call balance_internal() on the new child
43164 ** to cause it to split.
43165 */
43166 static int balance_deeper(BtCursor *pCur){
43167   int rc;             /* Return value from subprocedures */
43168   MemPage *pPage;     /* Pointer to the root page */
43169   MemPage *pChild;    /* Pointer to a new child page */
43170   Pgno pgnoChild;     /* Page number of the new child page */
43171   BtShared *pBt;         /* The BTree */
43172   int usableSize;     /* Total usable size of a page */
43173   u8 *data;           /* Content of the parent page */
43174   u8 *cdata;          /* Content of the child page */
43175   int hdr;            /* Offset to page header in parent */
43176   int cbrk;           /* Offset to content of first cell in parent */
43177
43178   assert( pCur->iPage==0 );
43179   assert( pCur->apPage[0]->nOverflow>0 );
43180
43181   VVA_ONLY( pCur->pagesShuffled = 1 );
43182   pPage = pCur->apPage[0];
43183   pBt = pPage->pBt;
43184   assert( sqlite3_mutex_held(pBt->mutex) );
43185   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43186   rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
43187   if( rc ) return rc;
43188   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
43189   usableSize = pBt->usableSize;
43190   data = pPage->aData;
43191   hdr = pPage->hdrOffset;
43192   cbrk = get2byte(&data[hdr+5]);
43193   cdata = pChild->aData;
43194   memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
43195   memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
43196
43197   assert( pChild->isInit==0 );
43198   rc = sqlite3BtreeInitPage(pChild);
43199   if( rc==SQLITE_OK ){
43200     int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
43201     memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
43202     pChild->nOverflow = pPage->nOverflow;
43203     if( pChild->nOverflow ){
43204       pChild->nFree = 0;
43205     }
43206     assert( pChild->nCell==pPage->nCell );
43207     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43208     zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
43209     put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
43210     TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
43211     if( ISAUTOVACUUM ){
43212       rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
43213 #ifndef SQLITE_OMIT_AUTOVACUUM
43214       if( rc==SQLITE_OK ){
43215         rc = setChildPtrmaps(pChild);
43216       }
43217       if( rc ){
43218         pChild->nOverflow = 0;
43219       }
43220 #endif
43221     }
43222   }
43223
43224   if( rc==SQLITE_OK ){
43225     pCur->iPage++;
43226     pCur->apPage[1] = pChild;
43227     pCur->aiIdx[0] = 0;
43228     rc = balance_nonroot(pCur);
43229   }else{
43230     releasePage(pChild);
43231   }
43232
43233   return rc;
43234 }
43235
43236 /*
43237 ** The page that pCur currently points to has just been modified in
43238 ** some way. This function figures out if this modification means the
43239 ** tree needs to be balanced, and if so calls the appropriate balancing 
43240 ** routine.
43241 ** 
43242 ** Parameter isInsert is true if a new cell was just inserted into the
43243 ** page, or false otherwise.
43244 */
43245 static int balance(BtCursor *pCur, int isInsert){
43246   int rc = SQLITE_OK;
43247   MemPage *pPage = pCur->apPage[pCur->iPage];
43248
43249   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43250   if( pCur->iPage==0 ){
43251     rc = sqlite3PagerWrite(pPage->pDbPage);
43252     if( rc==SQLITE_OK && pPage->nOverflow>0 ){
43253       rc = balance_deeper(pCur);
43254       assert( pCur->apPage[0]==pPage );
43255       assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
43256     }
43257     if( rc==SQLITE_OK && pPage->nCell==0 ){
43258       rc = balance_shallower(pCur);
43259       assert( pCur->apPage[0]==pPage );
43260       assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
43261     }
43262   }else{
43263     if( pPage->nOverflow>0 || 
43264         (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
43265       rc = balance_nonroot(pCur);
43266     }
43267   }
43268   return rc;
43269 }
43270
43271 /*
43272 ** This routine checks all cursors that point to table pgnoRoot.
43273 ** If any of those cursors were opened with wrFlag==0 in a different
43274 ** database connection (a database connection that shares the pager
43275 ** cache with the current connection) and that other connection 
43276 ** is not in the ReadUncommmitted state, then this routine returns 
43277 ** SQLITE_LOCKED.
43278 **
43279 ** As well as cursors with wrFlag==0, cursors with wrFlag==1 and 
43280 ** isIncrblobHandle==1 are also considered 'read' cursors. Incremental 
43281 ** blob cursors are used for both reading and writing.
43282 **
43283 ** When pgnoRoot is the root page of an intkey table, this function is also
43284 ** responsible for invalidating incremental blob cursors when the table row
43285 ** on which they are opened is deleted or modified. Cursors are invalidated
43286 ** according to the following rules:
43287 **
43288 **   1) When BtreeClearTable() is called to completely delete the contents
43289 **      of a B-Tree table, pExclude is set to zero and parameter iRow is 
43290 **      set to non-zero. In this case all incremental blob cursors open
43291 **      on the table rooted at pgnoRoot are invalidated.
43292 **
43293 **   2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to 
43294 **      modify a table row via an SQL statement, pExclude is set to the 
43295 **      write cursor used to do the modification and parameter iRow is set
43296 **      to the integer row id of the B-Tree entry being modified. Unless
43297 **      pExclude is itself an incremental blob cursor, then all incremental
43298 **      blob cursors open on row iRow of the B-Tree are invalidated.
43299 **
43300 **   3) If both pExclude and iRow are set to zero, no incremental blob 
43301 **      cursors are invalidated.
43302 */
43303 static int checkReadLocks(
43304   Btree *pBtree, 
43305   Pgno pgnoRoot, 
43306   BtCursor *pExclude,
43307   i64 iRow
43308 ){
43309   BtCursor *p;
43310   BtShared *pBt = pBtree->pBt;
43311   sqlite3 *db = pBtree->db;
43312   assert( sqlite3BtreeHoldsMutex(pBtree) );
43313   for(p=pBt->pCursor; p; p=p->pNext){
43314     if( p==pExclude ) continue;
43315     if( p->pgnoRoot!=pgnoRoot ) continue;
43316 #ifndef SQLITE_OMIT_INCRBLOB
43317     if( p->isIncrblobHandle && ( 
43318          (!pExclude && iRow)
43319       || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
43320     )){
43321       p->eState = CURSOR_INVALID;
43322     }
43323 #endif
43324     if( p->eState!=CURSOR_VALID ) continue;
43325     if( p->wrFlag==0 
43326 #ifndef SQLITE_OMIT_INCRBLOB
43327      || p->isIncrblobHandle
43328 #endif
43329     ){
43330       sqlite3 *dbOther = p->pBtree->db;
43331       if( dbOther==0 ||
43332          (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
43333         return SQLITE_LOCKED;
43334       }
43335     }
43336   }
43337   return SQLITE_OK;
43338 }
43339
43340 /*
43341 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
43342 ** and the data is given by (pData,nData).  The cursor is used only to
43343 ** define what table the record should be inserted into.  The cursor
43344 ** is left pointing at a random location.
43345 **
43346 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
43347 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
43348 */
43349 SQLITE_PRIVATE int sqlite3BtreeInsert(
43350   BtCursor *pCur,                /* Insert data into the table of this cursor */
43351   const void *pKey, i64 nKey,    /* The key of the new record */
43352   const void *pData, int nData,  /* The data of the new record */
43353   int nZero,                     /* Number of extra 0 bytes to append to data */
43354   int appendBias                 /* True if this is likely an append */
43355 ){
43356   int rc;
43357   int loc;
43358   int szNew;
43359   int idx;
43360   MemPage *pPage;
43361   Btree *p = pCur->pBtree;
43362   BtShared *pBt = p->pBt;
43363   unsigned char *oldCell;
43364   unsigned char *newCell = 0;
43365
43366   assert( cursorHoldsMutex(pCur) );
43367   assert( pBt->inTransaction==TRANS_WRITE );
43368   assert( !pBt->readOnly );
43369   assert( pCur->wrFlag );
43370   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
43371     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
43372   }
43373   if( pCur->eState==CURSOR_FAULT ){
43374     return pCur->skip;
43375   }
43376
43377   /* Save the positions of any other cursors open on this table */
43378   sqlite3BtreeClearCursor(pCur);
43379   if( 
43380     SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
43381     SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
43382   ){
43383     return rc;
43384   }
43385
43386   pPage = pCur->apPage[pCur->iPage];
43387   assert( pPage->intKey || nKey>=0 );
43388   assert( pPage->leaf || !pPage->intKey );
43389   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
43390           pCur->pgnoRoot, nKey, nData, pPage->pgno,
43391           loc==0 ? "overwrite" : "new entry"));
43392   assert( pPage->isInit );
43393   allocateTempSpace(pBt);
43394   newCell = pBt->pTmpSpace;
43395   if( newCell==0 ) return SQLITE_NOMEM;
43396   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
43397   if( rc ) goto end_insert;
43398   assert( szNew==cellSizePtr(pPage, newCell) );
43399   assert( szNew<=MX_CELL_SIZE(pBt) );
43400   idx = pCur->aiIdx[pCur->iPage];
43401   if( loc==0 && CURSOR_VALID==pCur->eState ){
43402     u16 szOld;
43403     assert( idx<pPage->nCell );
43404     rc = sqlite3PagerWrite(pPage->pDbPage);
43405     if( rc ){
43406       goto end_insert;
43407     }
43408     oldCell = findCell(pPage, idx);
43409     if( !pPage->leaf ){
43410       memcpy(newCell, oldCell, 4);
43411     }
43412     szOld = cellSizePtr(pPage, oldCell);
43413     rc = clearCell(pPage, oldCell);
43414     if( rc ) goto end_insert;
43415     rc = dropCell(pPage, idx, szOld);
43416     if( rc!=SQLITE_OK ) {
43417       goto end_insert;
43418     }
43419   }else if( loc<0 && pPage->nCell>0 ){
43420     assert( pPage->leaf );
43421     idx = ++pCur->aiIdx[pCur->iPage];
43422     pCur->info.nSize = 0;
43423     pCur->validNKey = 0;
43424   }else{
43425     assert( pPage->leaf );
43426   }
43427   rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
43428   if( rc==SQLITE_OK ){
43429     rc = balance(pCur, 1);
43430   }
43431
43432   /* Must make sure nOverflow is reset to zero even if the balance()
43433   ** fails.  Internal data structure corruption will result otherwise. */
43434   pCur->apPage[pCur->iPage]->nOverflow = 0;
43435
43436   if( rc==SQLITE_OK ){
43437     moveToRoot(pCur);
43438   }
43439 end_insert:
43440   return rc;
43441 }
43442
43443 /*
43444 ** Delete the entry that the cursor is pointing to.  The cursor
43445 ** is left pointing at a arbitrary location.
43446 */
43447 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
43448   MemPage *pPage = pCur->apPage[pCur->iPage];
43449   int idx;
43450   unsigned char *pCell;
43451   int rc;
43452   Pgno pgnoChild = 0;
43453   Btree *p = pCur->pBtree;
43454   BtShared *pBt = p->pBt;
43455
43456   assert( cursorHoldsMutex(pCur) );
43457   assert( pPage->isInit );
43458   assert( pBt->inTransaction==TRANS_WRITE );
43459   assert( !pBt->readOnly );
43460   if( pCur->eState==CURSOR_FAULT ){
43461     return pCur->skip;
43462   }
43463   if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
43464     return SQLITE_ERROR;  /* The cursor is not pointing to anything */
43465   }
43466   assert( pCur->wrFlag );
43467   if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
43468     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
43469   }
43470
43471   /* Restore the current cursor position (a no-op if the cursor is not in 
43472   ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors 
43473   ** open on the same table. Then call sqlite3PagerWrite() on the page
43474   ** that the entry will be deleted from.
43475   */
43476   if( 
43477     (rc = restoreCursorPosition(pCur))!=0 ||
43478     (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
43479     (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
43480   ){
43481     return rc;
43482   }
43483
43484   /* Locate the cell within its page and leave pCell pointing to the
43485   ** data. The clearCell() call frees any overflow pages associated with the
43486   ** cell. The cell itself is still intact.
43487   */
43488   idx = pCur->aiIdx[pCur->iPage];
43489   pCell = findCell(pPage, idx);
43490   if( !pPage->leaf ){
43491     pgnoChild = get4byte(pCell);
43492   }
43493   rc = clearCell(pPage, pCell);
43494   if( rc ){
43495     return rc;
43496   }
43497
43498   if( !pPage->leaf ){
43499     /*
43500     ** The entry we are about to delete is not a leaf so if we do not
43501     ** do something we will leave a hole on an internal page.
43502     ** We have to fill the hole by moving in a cell from a leaf.  The
43503     ** next Cell after the one to be deleted is guaranteed to exist and
43504     ** to be a leaf so we can use it.
43505     */
43506     BtCursor leafCur;
43507     MemPage *pLeafPage = 0;
43508
43509     unsigned char *pNext;
43510     int notUsed;
43511     unsigned char *tempCell = 0;
43512     assert( !pPage->intKey );
43513     sqlite3BtreeGetTempCursor(pCur, &leafCur);
43514     rc = sqlite3BtreeNext(&leafCur, &notUsed);
43515     if( rc==SQLITE_OK ){
43516       assert( leafCur.aiIdx[leafCur.iPage]==0 );
43517       pLeafPage = leafCur.apPage[leafCur.iPage];
43518       rc = sqlite3PagerWrite(pLeafPage->pDbPage);
43519     }
43520     if( rc==SQLITE_OK ){
43521       int leafCursorInvalid = 0;
43522       u16 szNext;
43523       TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
43524          pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
43525       dropCell(pPage, idx, cellSizePtr(pPage, pCell));
43526       pNext = findCell(pLeafPage, 0);
43527       szNext = cellSizePtr(pLeafPage, pNext);
43528       assert( MX_CELL_SIZE(pBt)>=szNext+4 );
43529       allocateTempSpace(pBt);
43530       tempCell = pBt->pTmpSpace;
43531       if( tempCell==0 ){
43532         rc = SQLITE_NOMEM;
43533       }
43534       if( rc==SQLITE_OK ){
43535         rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
43536       }
43537
43538
43539       /* The "if" statement in the next code block is critical.  The
43540       ** slightest error in that statement would allow SQLite to operate
43541       ** correctly most of the time but produce very rare failures.  To
43542       ** guard against this, the following macros help to verify that
43543       ** the "if" statement is well tested.
43544       */
43545       testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3 
43546                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
43547       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3 
43548                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
43549       testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1 
43550                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
43551       testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
43552                  && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
43553       testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
43554                  && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
43555
43556
43557       if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
43558           (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
43559       ){
43560         /* This branch is taken if the internal node is now either overflowing
43561         ** or underfull and the leaf node will be underfull after the just cell 
43562         ** copied to the internal node is deleted from it. This is a special
43563         ** case because the call to balance() to correct the internal node
43564         ** may change the tree structure and invalidate the contents of
43565         ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
43566         ** used by the balance() required to correct the underfull leaf
43567         ** node.
43568         **
43569         ** The formula used in the expression above are based on facets of
43570         ** the SQLite file-format that do not change over time.
43571         */
43572         testcase( pPage->nFree==pBt->usableSize*2/3+1 );
43573         testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
43574         leafCursorInvalid = 1;
43575       }        
43576
43577       if( rc==SQLITE_OK ){
43578         assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43579         put4byte(findOverflowCell(pPage, idx), pgnoChild);
43580         VVA_ONLY( pCur->pagesShuffled = 0 );
43581         rc = balance(pCur, 0);
43582       }
43583
43584       if( rc==SQLITE_OK && leafCursorInvalid ){
43585         /* The leaf-node is now underfull and so the tree needs to be 
43586         ** rebalanced. However, the balance() operation on the internal
43587         ** node above may have modified the structure of the B-Tree and
43588         ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
43589         ** may not be trusted.
43590         **
43591         ** It is not possible to copy the ancestry from pCur, as the same
43592         ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
43593         ** arrays. 
43594         **
43595         ** The call to saveCursorPosition() below internally saves the 
43596         ** key that leafCur is currently pointing to. Currently, there
43597         ** are two copies of that key in the tree - one here on the leaf
43598         ** page and one on some internal node in the tree. The copy on
43599         ** the leaf node is always the next key in tree-order after the 
43600         ** copy on the internal node. So, the call to sqlite3BtreeNext()
43601         ** calls restoreCursorPosition() to point the cursor to the copy
43602         ** stored on the internal node, then advances to the next entry,
43603         ** which happens to be the copy of the key on the internal node.
43604         ** Net effect: leafCur is pointing back to the duplicate cell
43605         ** that needs to be removed, and the leafCur.apPage[] and
43606         ** leafCur.aiIdx[] arrays are correct.
43607         */
43608         VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
43609         rc = saveCursorPosition(&leafCur);
43610         if( rc==SQLITE_OK ){
43611           rc = sqlite3BtreeNext(&leafCur, &notUsed);
43612         }
43613         pLeafPage = leafCur.apPage[leafCur.iPage];
43614         assert( pLeafPage->pgno==leafPgno );
43615         assert( leafCur.aiIdx[leafCur.iPage]==0 );
43616       }
43617
43618       if( SQLITE_OK==rc
43619        && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage)) 
43620       ){
43621         dropCell(pLeafPage, 0, szNext);
43622         VVA_ONLY( leafCur.pagesShuffled = 0 );
43623         rc = balance(&leafCur, 0);
43624         assert( leafCursorInvalid || !leafCur.pagesShuffled
43625                                    || !pCur->pagesShuffled );
43626       }
43627     }
43628     sqlite3BtreeReleaseTempCursor(&leafCur);
43629   }else{
43630     TRACE(("DELETE: table=%d delete from leaf %d\n",
43631        pCur->pgnoRoot, pPage->pgno));
43632     rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
43633     if( rc==SQLITE_OK ){
43634       rc = balance(pCur, 0);
43635     }
43636   }
43637   if( rc==SQLITE_OK ){
43638     moveToRoot(pCur);
43639   }
43640   return rc;
43641 }
43642
43643 /*
43644 ** Create a new BTree table.  Write into *piTable the page
43645 ** number for the root page of the new table.
43646 **
43647 ** The type of type is determined by the flags parameter.  Only the
43648 ** following values of flags are currently in use.  Other values for
43649 ** flags might not work:
43650 **
43651 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
43652 **     BTREE_ZERODATA                  Used for SQL indices
43653 */
43654 static int btreeCreateTable(Btree *p, int *piTable, int flags){
43655   BtShared *pBt = p->pBt;
43656   MemPage *pRoot;
43657   Pgno pgnoRoot;
43658   int rc;
43659
43660   assert( sqlite3BtreeHoldsMutex(p) );
43661   assert( pBt->inTransaction==TRANS_WRITE );
43662   assert( !pBt->readOnly );
43663
43664 #ifdef SQLITE_OMIT_AUTOVACUUM
43665   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
43666   if( rc ){
43667     return rc;
43668   }
43669 #else
43670   if( pBt->autoVacuum ){
43671     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
43672     MemPage *pPageMove; /* The page to move to. */
43673
43674     /* Creating a new table may probably require moving an existing database
43675     ** to make room for the new tables root page. In case this page turns
43676     ** out to be an overflow page, delete all overflow page-map caches
43677     ** held by open cursors.
43678     */
43679     invalidateAllOverflowCache(pBt);
43680
43681     /* Read the value of meta[3] from the database to determine where the
43682     ** root page of the new table should go. meta[3] is the largest root-page
43683     ** created so far, so the new root-page is (meta[3]+1).
43684     */
43685     rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
43686     if( rc!=SQLITE_OK ){
43687       return rc;
43688     }
43689     pgnoRoot++;
43690
43691     /* The new root-page may not be allocated on a pointer-map page, or the
43692     ** PENDING_BYTE page.
43693     */
43694     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
43695         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
43696       pgnoRoot++;
43697     }
43698     assert( pgnoRoot>=3 );
43699
43700     /* Allocate a page. The page that currently resides at pgnoRoot will
43701     ** be moved to the allocated page (unless the allocated page happens
43702     ** to reside at pgnoRoot).
43703     */
43704     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
43705     if( rc!=SQLITE_OK ){
43706       return rc;
43707     }
43708
43709     if( pgnoMove!=pgnoRoot ){
43710       /* pgnoRoot is the page that will be used for the root-page of
43711       ** the new table (assuming an error did not occur). But we were
43712       ** allocated pgnoMove. If required (i.e. if it was not allocated
43713       ** by extending the file), the current page at position pgnoMove
43714       ** is already journaled.
43715       */
43716       u8 eType;
43717       Pgno iPtrPage;
43718
43719       releasePage(pPageMove);
43720
43721       /* Move the page currently at pgnoRoot to pgnoMove. */
43722       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
43723       if( rc!=SQLITE_OK ){
43724         return rc;
43725       }
43726       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
43727       if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
43728         releasePage(pRoot);
43729         return rc;
43730       }
43731       assert( eType!=PTRMAP_ROOTPAGE );
43732       assert( eType!=PTRMAP_FREEPAGE );
43733       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
43734       releasePage(pRoot);
43735
43736       /* Obtain the page at pgnoRoot */
43737       if( rc!=SQLITE_OK ){
43738         return rc;
43739       }
43740       rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
43741       if( rc!=SQLITE_OK ){
43742         return rc;
43743       }
43744       rc = sqlite3PagerWrite(pRoot->pDbPage);
43745       if( rc!=SQLITE_OK ){
43746         releasePage(pRoot);
43747         return rc;
43748       }
43749     }else{
43750       pRoot = pPageMove;
43751     } 
43752
43753     /* Update the pointer-map and meta-data with the new root-page number. */
43754     rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
43755     if( rc ){
43756       releasePage(pRoot);
43757       return rc;
43758     }
43759     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
43760     if( rc ){
43761       releasePage(pRoot);
43762       return rc;
43763     }
43764
43765   }else{
43766     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
43767     if( rc ) return rc;
43768   }
43769 #endif
43770   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
43771   zeroPage(pRoot, flags | PTF_LEAF);
43772   sqlite3PagerUnref(pRoot->pDbPage);
43773   *piTable = (int)pgnoRoot;
43774   return SQLITE_OK;
43775 }
43776 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
43777   int rc;
43778   sqlite3BtreeEnter(p);
43779   p->pBt->db = p->db;
43780   rc = btreeCreateTable(p, piTable, flags);
43781   sqlite3BtreeLeave(p);
43782   return rc;
43783 }
43784
43785 /*
43786 ** Erase the given database page and all its children.  Return
43787 ** the page to the freelist.
43788 */
43789 static int clearDatabasePage(
43790   BtShared *pBt,           /* The BTree that contains the table */
43791   Pgno pgno,            /* Page number to clear */
43792   int freePageFlag,     /* Deallocate page if true */
43793   int *pnChange
43794 ){
43795   MemPage *pPage = 0;
43796   int rc;
43797   unsigned char *pCell;
43798   int i;
43799
43800   assert( sqlite3_mutex_held(pBt->mutex) );
43801   if( pgno>pagerPagecount(pBt) ){
43802     return SQLITE_CORRUPT_BKPT;
43803   }
43804
43805   rc = getAndInitPage(pBt, pgno, &pPage);
43806   if( rc ) goto cleardatabasepage_out;
43807   for(i=0; i<pPage->nCell; i++){
43808     pCell = findCell(pPage, i);
43809     if( !pPage->leaf ){
43810       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
43811       if( rc ) goto cleardatabasepage_out;
43812     }
43813     rc = clearCell(pPage, pCell);
43814     if( rc ) goto cleardatabasepage_out;
43815   }
43816   if( !pPage->leaf ){
43817     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
43818     if( rc ) goto cleardatabasepage_out;
43819   }else if( pnChange ){
43820     assert( pPage->intKey );
43821     *pnChange += pPage->nCell;
43822   }
43823   if( freePageFlag ){
43824     rc = freePage(pPage);
43825   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
43826     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
43827   }
43828
43829 cleardatabasepage_out:
43830   releasePage(pPage);
43831   return rc;
43832 }
43833
43834 /*
43835 ** Delete all information from a single table in the database.  iTable is
43836 ** the page number of the root of the table.  After this routine returns,
43837 ** the root page is empty, but still exists.
43838 **
43839 ** This routine will fail with SQLITE_LOCKED if there are any open
43840 ** read cursors on the table.  Open write cursors are moved to the
43841 ** root of the table.
43842 **
43843 ** If pnChange is not NULL, then table iTable must be an intkey table. The
43844 ** integer value pointed to by pnChange is incremented by the number of
43845 ** entries in the table.
43846 */
43847 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
43848   int rc;
43849   BtShared *pBt = p->pBt;
43850   sqlite3BtreeEnter(p);
43851   pBt->db = p->db;
43852   assert( p->inTrans==TRANS_WRITE );
43853   if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
43854     /* nothing to do */
43855   }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
43856     /* nothing to do */
43857   }else{
43858     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
43859   }
43860   sqlite3BtreeLeave(p);
43861   return rc;
43862 }
43863
43864 /*
43865 ** Erase all information in a table and add the root of the table to
43866 ** the freelist.  Except, the root of the principle table (the one on
43867 ** page 1) is never added to the freelist.
43868 **
43869 ** This routine will fail with SQLITE_LOCKED if there are any open
43870 ** cursors on the table.
43871 **
43872 ** If AUTOVACUUM is enabled and the page at iTable is not the last
43873 ** root page in the database file, then the last root page 
43874 ** in the database file is moved into the slot formerly occupied by
43875 ** iTable and that last slot formerly occupied by the last root page
43876 ** is added to the freelist instead of iTable.  In this say, all
43877 ** root pages are kept at the beginning of the database file, which
43878 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
43879 ** page number that used to be the last root page in the file before
43880 ** the move.  If no page gets moved, *piMoved is set to 0.
43881 ** The last root page is recorded in meta[3] and the value of
43882 ** meta[3] is updated by this procedure.
43883 */
43884 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
43885   int rc;
43886   MemPage *pPage = 0;
43887   BtShared *pBt = p->pBt;
43888
43889   assert( sqlite3BtreeHoldsMutex(p) );
43890   assert( p->inTrans==TRANS_WRITE );
43891
43892   /* It is illegal to drop a table if any cursors are open on the
43893   ** database. This is because in auto-vacuum mode the backend may
43894   ** need to move another root-page to fill a gap left by the deleted
43895   ** root page. If an open cursor was using this page a problem would 
43896   ** occur.
43897   */
43898   if( pBt->pCursor ){
43899     return SQLITE_LOCKED;
43900   }
43901
43902   rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
43903   if( rc ) return rc;
43904   rc = sqlite3BtreeClearTable(p, iTable, 0);
43905   if( rc ){
43906     releasePage(pPage);
43907     return rc;
43908   }
43909
43910   *piMoved = 0;
43911
43912   if( iTable>1 ){
43913 #ifdef SQLITE_OMIT_AUTOVACUUM
43914     rc = freePage(pPage);
43915     releasePage(pPage);
43916 #else
43917     if( pBt->autoVacuum ){
43918       Pgno maxRootPgno;
43919       rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
43920       if( rc!=SQLITE_OK ){
43921         releasePage(pPage);
43922         return rc;
43923       }
43924
43925       if( iTable==maxRootPgno ){
43926         /* If the table being dropped is the table with the largest root-page
43927         ** number in the database, put the root page on the free list. 
43928         */
43929         rc = freePage(pPage);
43930         releasePage(pPage);
43931         if( rc!=SQLITE_OK ){
43932           return rc;
43933         }
43934       }else{
43935         /* The table being dropped does not have the largest root-page
43936         ** number in the database. So move the page that does into the 
43937         ** gap left by the deleted root-page.
43938         */
43939         MemPage *pMove;
43940         releasePage(pPage);
43941         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
43942         if( rc!=SQLITE_OK ){
43943           return rc;
43944         }
43945         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
43946         releasePage(pMove);
43947         if( rc!=SQLITE_OK ){
43948           return rc;
43949         }
43950         rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
43951         if( rc!=SQLITE_OK ){
43952           return rc;
43953         }
43954         rc = freePage(pMove);
43955         releasePage(pMove);
43956         if( rc!=SQLITE_OK ){
43957           return rc;
43958         }
43959         *piMoved = maxRootPgno;
43960       }
43961
43962       /* Set the new 'max-root-page' value in the database header. This
43963       ** is the old value less one, less one more if that happens to
43964       ** be a root-page number, less one again if that is the
43965       ** PENDING_BYTE_PAGE.
43966       */
43967       maxRootPgno--;
43968       if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
43969         maxRootPgno--;
43970       }
43971       if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
43972         maxRootPgno--;
43973       }
43974       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
43975
43976       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
43977     }else{
43978       rc = freePage(pPage);
43979       releasePage(pPage);
43980     }
43981 #endif
43982   }else{
43983     /* If sqlite3BtreeDropTable was called on page 1. */
43984     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
43985     releasePage(pPage);
43986   }
43987   return rc;  
43988 }
43989 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
43990   int rc;
43991   sqlite3BtreeEnter(p);
43992   p->pBt->db = p->db;
43993   rc = btreeDropTable(p, iTable, piMoved);
43994   sqlite3BtreeLeave(p);
43995   return rc;
43996 }
43997
43998
43999 /*
44000 ** Read the meta-information out of a database file.  Meta[0]
44001 ** is the number of free pages currently in the database.  Meta[1]
44002 ** through meta[15] are available for use by higher layers.  Meta[0]
44003 ** is read-only, the others are read/write.
44004 ** 
44005 ** The schema layer numbers meta values differently.  At the schema
44006 ** layer (and the SetCookie and ReadCookie opcodes) the number of
44007 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44008 */
44009 SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44010   DbPage *pDbPage = 0;
44011   int rc;
44012   unsigned char *pP1;
44013   BtShared *pBt = p->pBt;
44014
44015   sqlite3BtreeEnter(p);
44016   pBt->db = p->db;
44017
44018   /* Reading a meta-data value requires a read-lock on page 1 (and hence
44019   ** the sqlite_master table. We grab this lock regardless of whether or
44020   ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
44021   ** 1 is treated as a special case by queryTableLock() and lockTable()).
44022   */
44023   rc = queryTableLock(p, 1, READ_LOCK);
44024   if( rc!=SQLITE_OK ){
44025     sqlite3BtreeLeave(p);
44026     return rc;
44027   }
44028
44029   assert( idx>=0 && idx<=15 );
44030   if( pBt->pPage1 ){
44031     /* The b-tree is already holding a reference to page 1 of the database
44032     ** file. In this case the required meta-data value can be read directly
44033     ** from the page data of this reference. This is slightly faster than
44034     ** requesting a new reference from the pager layer.
44035     */
44036     pP1 = (unsigned char *)pBt->pPage1->aData;
44037   }else{
44038     /* The b-tree does not have a reference to page 1 of the database file.
44039     ** Obtain one from the pager layer.
44040     */
44041     rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
44042     if( rc ){
44043       sqlite3BtreeLeave(p);
44044       return rc;
44045     }
44046     pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
44047   }
44048   *pMeta = get4byte(&pP1[36 + idx*4]);
44049
44050   /* If the b-tree is not holding a reference to page 1, then one was 
44051   ** requested from the pager layer in the above block. Release it now.
44052   */
44053   if( !pBt->pPage1 ){
44054     sqlite3PagerUnref(pDbPage);
44055   }
44056
44057   /* If autovacuumed is disabled in this build but we are trying to 
44058   ** access an autovacuumed database, then make the database readonly. 
44059   */
44060 #ifdef SQLITE_OMIT_AUTOVACUUM
44061   if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
44062 #endif
44063
44064   /* Grab the read-lock on page 1. */
44065   rc = lockTable(p, 1, READ_LOCK);
44066   sqlite3BtreeLeave(p);
44067   return rc;
44068 }
44069
44070 /*
44071 ** Write meta-information back into the database.  Meta[0] is
44072 ** read-only and may not be written.
44073 */
44074 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44075   BtShared *pBt = p->pBt;
44076   unsigned char *pP1;
44077   int rc;
44078   assert( idx>=1 && idx<=15 );
44079   sqlite3BtreeEnter(p);
44080   pBt->db = p->db;
44081   assert( p->inTrans==TRANS_WRITE );
44082   assert( pBt->pPage1!=0 );
44083   pP1 = pBt->pPage1->aData;
44084   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44085   if( rc==SQLITE_OK ){
44086     put4byte(&pP1[36 + idx*4], iMeta);
44087 #ifndef SQLITE_OMIT_AUTOVACUUM
44088     if( idx==7 ){
44089       assert( pBt->autoVacuum || iMeta==0 );
44090       assert( iMeta==0 || iMeta==1 );
44091       pBt->incrVacuum = (u8)iMeta;
44092     }
44093 #endif
44094   }
44095   sqlite3BtreeLeave(p);
44096   return rc;
44097 }
44098
44099 /*
44100 ** Return the flag byte at the beginning of the page that the cursor
44101 ** is currently pointing to.
44102 */
44103 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
44104   /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
44105   ** restoreCursorPosition() here.
44106   */
44107   MemPage *pPage;
44108   restoreCursorPosition(pCur);
44109   pPage = pCur->apPage[pCur->iPage];
44110   assert( cursorHoldsMutex(pCur) );
44111   assert( pPage!=0 );
44112   assert( pPage->pBt==pCur->pBt );
44113   return pPage->aData[pPage->hdrOffset];
44114 }
44115
44116
44117 /*
44118 ** Return the pager associated with a BTree.  This routine is used for
44119 ** testing and debugging only.
44120 */
44121 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
44122   return p->pBt->pPager;
44123 }
44124
44125 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44126 /*
44127 ** Append a message to the error message string.
44128 */
44129 static void checkAppendMsg(
44130   IntegrityCk *pCheck,
44131   char *zMsg1,
44132   const char *zFormat,
44133   ...
44134 ){
44135   va_list ap;
44136   if( !pCheck->mxErr ) return;
44137   pCheck->mxErr--;
44138   pCheck->nErr++;
44139   va_start(ap, zFormat);
44140   if( pCheck->errMsg.nChar ){
44141     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
44142   }
44143   if( zMsg1 ){
44144     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
44145   }
44146   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
44147   va_end(ap);
44148   if( pCheck->errMsg.mallocFailed ){
44149     pCheck->mallocFailed = 1;
44150   }
44151 }
44152 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44153
44154 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44155 /*
44156 ** Add 1 to the reference count for page iPage.  If this is the second
44157 ** reference to the page, add an error message to pCheck->zErrMsg.
44158 ** Return 1 if there are 2 ore more references to the page and 0 if
44159 ** if this is the first reference to the page.
44160 **
44161 ** Also check that the page number is in bounds.
44162 */
44163 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
44164   if( iPage==0 ) return 1;
44165   if( iPage>pCheck->nPage ){
44166     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
44167     return 1;
44168   }
44169   if( pCheck->anRef[iPage]==1 ){
44170     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
44171     return 1;
44172   }
44173   return  (pCheck->anRef[iPage]++)>1;
44174 }
44175
44176 #ifndef SQLITE_OMIT_AUTOVACUUM
44177 /*
44178 ** Check that the entry in the pointer-map for page iChild maps to 
44179 ** page iParent, pointer type ptrType. If not, append an error message
44180 ** to pCheck.
44181 */
44182 static void checkPtrmap(
44183   IntegrityCk *pCheck,   /* Integrity check context */
44184   Pgno iChild,           /* Child page number */
44185   u8 eType,              /* Expected pointer map type */
44186   Pgno iParent,          /* Expected pointer map parent page number */
44187   char *zContext         /* Context description (used for error msg) */
44188 ){
44189   int rc;
44190   u8 ePtrmapType;
44191   Pgno iPtrmapParent;
44192
44193   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
44194   if( rc!=SQLITE_OK ){
44195     if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
44196     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
44197     return;
44198   }
44199
44200   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
44201     checkAppendMsg(pCheck, zContext, 
44202       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
44203       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
44204   }
44205 }
44206 #endif
44207
44208 /*
44209 ** Check the integrity of the freelist or of an overflow page list.
44210 ** Verify that the number of pages on the list is N.
44211 */
44212 static void checkList(
44213   IntegrityCk *pCheck,  /* Integrity checking context */
44214   int isFreeList,       /* True for a freelist.  False for overflow page list */
44215   int iPage,            /* Page number for first page in the list */
44216   int N,                /* Expected number of pages in the list */
44217   char *zContext        /* Context for error messages */
44218 ){
44219   int i;
44220   int expected = N;
44221   int iFirst = iPage;
44222   while( N-- > 0 && pCheck->mxErr ){
44223     DbPage *pOvflPage;
44224     unsigned char *pOvflData;
44225     if( iPage<1 ){
44226       checkAppendMsg(pCheck, zContext,
44227          "%d of %d pages missing from overflow list starting at %d",
44228           N+1, expected, iFirst);
44229       break;
44230     }
44231     if( checkRef(pCheck, iPage, zContext) ) break;
44232     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
44233       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
44234       break;
44235     }
44236     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
44237     if( isFreeList ){
44238       int n = get4byte(&pOvflData[4]);
44239 #ifndef SQLITE_OMIT_AUTOVACUUM
44240       if( pCheck->pBt->autoVacuum ){
44241         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
44242       }
44243 #endif
44244       if( n>pCheck->pBt->usableSize/4-2 ){
44245         checkAppendMsg(pCheck, zContext,
44246            "freelist leaf count too big on page %d", iPage);
44247         N--;
44248       }else{
44249         for(i=0; i<n; i++){
44250           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
44251 #ifndef SQLITE_OMIT_AUTOVACUUM
44252           if( pCheck->pBt->autoVacuum ){
44253             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
44254           }
44255 #endif
44256           checkRef(pCheck, iFreePage, zContext);
44257         }
44258         N -= n;
44259       }
44260     }
44261 #ifndef SQLITE_OMIT_AUTOVACUUM
44262     else{
44263       /* If this database supports auto-vacuum and iPage is not the last
44264       ** page in this overflow list, check that the pointer-map entry for
44265       ** the following page matches iPage.
44266       */
44267       if( pCheck->pBt->autoVacuum && N>0 ){
44268         i = get4byte(pOvflData);
44269         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
44270       }
44271     }
44272 #endif
44273     iPage = get4byte(pOvflData);
44274     sqlite3PagerUnref(pOvflPage);
44275   }
44276 }
44277 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44278
44279 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44280 /*
44281 ** Do various sanity checks on a single page of a tree.  Return
44282 ** the tree depth.  Root pages return 0.  Parents of root pages
44283 ** return 1, and so forth.
44284 ** 
44285 ** These checks are done:
44286 **
44287 **      1.  Make sure that cells and freeblocks do not overlap
44288 **          but combine to completely cover the page.
44289 **  NO  2.  Make sure cell keys are in order.
44290 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
44291 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
44292 **      5.  Check the integrity of overflow pages.
44293 **      6.  Recursively call checkTreePage on all children.
44294 **      7.  Verify that the depth of all children is the same.
44295 **      8.  Make sure this page is at least 33% full or else it is
44296 **          the root of the tree.
44297 */
44298 static int checkTreePage(
44299   IntegrityCk *pCheck,  /* Context for the sanity check */
44300   int iPage,            /* Page number of the page to check */
44301   char *zParentContext  /* Parent context */
44302 ){
44303   MemPage *pPage;
44304   int i, rc, depth, d2, pgno, cnt;
44305   int hdr, cellStart;
44306   int nCell;
44307   u8 *data;
44308   BtShared *pBt;
44309   int usableSize;
44310   char zContext[100];
44311   char *hit = 0;
44312
44313   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
44314
44315   /* Check that the page exists
44316   */
44317   pBt = pCheck->pBt;
44318   usableSize = pBt->usableSize;
44319   if( iPage==0 ) return 0;
44320   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
44321   if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
44322     if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
44323     checkAppendMsg(pCheck, zContext,
44324        "unable to get the page. error code=%d", rc);
44325     return 0;
44326   }
44327   if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
44328     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
44329     checkAppendMsg(pCheck, zContext, 
44330                    "sqlite3BtreeInitPage() returns error code %d", rc);
44331     releasePage(pPage);
44332     return 0;
44333   }
44334
44335   /* Check out all the cells.
44336   */
44337   depth = 0;
44338   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
44339     u8 *pCell;
44340     u32 sz;
44341     CellInfo info;
44342
44343     /* Check payload overflow pages
44344     */
44345     sqlite3_snprintf(sizeof(zContext), zContext,
44346              "On tree page %d cell %d: ", iPage, i);
44347     pCell = findCell(pPage,i);
44348     sqlite3BtreeParseCellPtr(pPage, pCell, &info);
44349     sz = info.nData;
44350     if( !pPage->intKey ) sz += (int)info.nKey;
44351     assert( sz==info.nPayload );
44352     if( sz>info.nLocal ){
44353       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
44354       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
44355 #ifndef SQLITE_OMIT_AUTOVACUUM
44356       if( pBt->autoVacuum ){
44357         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
44358       }
44359 #endif
44360       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
44361     }
44362
44363     /* Check sanity of left child page.
44364     */
44365     if( !pPage->leaf ){
44366       pgno = get4byte(pCell);
44367 #ifndef SQLITE_OMIT_AUTOVACUUM
44368       if( pBt->autoVacuum ){
44369         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
44370       }
44371 #endif
44372       d2 = checkTreePage(pCheck, pgno, zContext);
44373       if( i>0 && d2!=depth ){
44374         checkAppendMsg(pCheck, zContext, "Child page depth differs");
44375       }
44376       depth = d2;
44377     }
44378   }
44379   if( !pPage->leaf ){
44380     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
44381     sqlite3_snprintf(sizeof(zContext), zContext, 
44382                      "On page %d at right child: ", iPage);
44383 #ifndef SQLITE_OMIT_AUTOVACUUM
44384     if( pBt->autoVacuum ){
44385       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
44386     }
44387 #endif
44388     checkTreePage(pCheck, pgno, zContext);
44389   }
44390  
44391   /* Check for complete coverage of the page
44392   */
44393   data = pPage->aData;
44394   hdr = pPage->hdrOffset;
44395   hit = sqlite3PageMalloc( pBt->pageSize );
44396   if( hit==0 ){
44397     pCheck->mallocFailed = 1;
44398   }else{
44399     u16 contentOffset = get2byte(&data[hdr+5]);
44400     if (contentOffset > usableSize) {
44401       checkAppendMsg(pCheck, 0, 
44402                      "Corruption detected in header on page %d",iPage,0);
44403       goto check_page_abort;
44404     }
44405     memset(hit+contentOffset, 0, usableSize-contentOffset);
44406     memset(hit, 1, contentOffset);
44407     nCell = get2byte(&data[hdr+3]);
44408     cellStart = hdr + 12 - 4*pPage->leaf;
44409     for(i=0; i<nCell; i++){
44410       int pc = get2byte(&data[cellStart+i*2]);
44411       u16 size = 1024;
44412       int j;
44413       if( pc<=usableSize ){
44414         size = cellSizePtr(pPage, &data[pc]);
44415       }
44416       if( (pc+size-1)>=usableSize || pc<0 ){
44417         checkAppendMsg(pCheck, 0, 
44418             "Corruption detected in cell %d on page %d",i,iPage,0);
44419       }else{
44420         for(j=pc+size-1; j>=pc; j--) hit[j]++;
44421       }
44422     }
44423     for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000; 
44424            cnt++){
44425       int size = get2byte(&data[i+2]);
44426       int j;
44427       if( (i+size-1)>=usableSize || i<0 ){
44428         checkAppendMsg(pCheck, 0,  
44429             "Corruption detected in cell %d on page %d",i,iPage,0);
44430       }else{
44431         for(j=i+size-1; j>=i; j--) hit[j]++;
44432       }
44433       i = get2byte(&data[i]);
44434     }
44435     for(i=cnt=0; i<usableSize; i++){
44436       if( hit[i]==0 ){
44437         cnt++;
44438       }else if( hit[i]>1 ){
44439         checkAppendMsg(pCheck, 0,
44440           "Multiple uses for byte %d of page %d", i, iPage);
44441         break;
44442       }
44443     }
44444     if( cnt!=data[hdr+7] ){
44445       checkAppendMsg(pCheck, 0, 
44446           "Fragmented space is %d byte reported as %d on page %d",
44447           cnt, data[hdr+7], iPage);
44448     }
44449   }
44450 check_page_abort:
44451   if (hit) sqlite3PageFree(hit);
44452
44453   releasePage(pPage);
44454   return depth+1;
44455 }
44456 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44457
44458 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44459 /*
44460 ** This routine does a complete check of the given BTree file.  aRoot[] is
44461 ** an array of pages numbers were each page number is the root page of
44462 ** a table.  nRoot is the number of entries in aRoot.
44463 **
44464 ** Write the number of error seen in *pnErr.  Except for some memory
44465 ** allocation errors,  an error message held in memory obtained from
44466 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
44467 ** returned.  If a memory allocation error occurs, NULL is returned.
44468 */
44469 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
44470   Btree *p,     /* The btree to be checked */
44471   int *aRoot,   /* An array of root pages numbers for individual trees */
44472   int nRoot,    /* Number of entries in aRoot[] */
44473   int mxErr,    /* Stop reporting errors after this many */
44474   int *pnErr    /* Write number of errors seen to this variable */
44475 ){
44476   Pgno i;
44477   int nRef;
44478   IntegrityCk sCheck;
44479   BtShared *pBt = p->pBt;
44480   char zErr[100];
44481
44482   sqlite3BtreeEnter(p);
44483   pBt->db = p->db;
44484   nRef = sqlite3PagerRefcount(pBt->pPager);
44485   if( lockBtreeWithRetry(p)!=SQLITE_OK ){
44486     *pnErr = 1;
44487     sqlite3BtreeLeave(p);
44488     return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
44489   }
44490   sCheck.pBt = pBt;
44491   sCheck.pPager = pBt->pPager;
44492   sCheck.nPage = pagerPagecount(sCheck.pBt);
44493   sCheck.mxErr = mxErr;
44494   sCheck.nErr = 0;
44495   sCheck.mallocFailed = 0;
44496   *pnErr = 0;
44497   if( sCheck.nPage==0 ){
44498     unlockBtreeIfUnused(pBt);
44499     sqlite3BtreeLeave(p);
44500     return 0;
44501   }
44502   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
44503   if( !sCheck.anRef ){
44504     unlockBtreeIfUnused(pBt);
44505     *pnErr = 1;
44506     sqlite3BtreeLeave(p);
44507     return 0;
44508   }
44509   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
44510   i = PENDING_BYTE_PAGE(pBt);
44511   if( i<=sCheck.nPage ){
44512     sCheck.anRef[i] = 1;
44513   }
44514   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
44515
44516   /* Check the integrity of the freelist
44517   */
44518   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
44519             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
44520
44521   /* Check all the tables.
44522   */
44523   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
44524     if( aRoot[i]==0 ) continue;
44525 #ifndef SQLITE_OMIT_AUTOVACUUM
44526     if( pBt->autoVacuum && aRoot[i]>1 ){
44527       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
44528     }
44529 #endif
44530     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
44531   }
44532
44533   /* Make sure every page in the file is referenced
44534   */
44535   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
44536 #ifdef SQLITE_OMIT_AUTOVACUUM
44537     if( sCheck.anRef[i]==0 ){
44538       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
44539     }
44540 #else
44541     /* If the database supports auto-vacuum, make sure no tables contain
44542     ** references to pointer-map pages.
44543     */
44544     if( sCheck.anRef[i]==0 && 
44545        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
44546       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
44547     }
44548     if( sCheck.anRef[i]!=0 && 
44549        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
44550       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
44551     }
44552 #endif
44553   }
44554
44555   /* Make sure this analysis did not leave any unref() pages.
44556   ** This is an internal consistency check; an integrity check
44557   ** of the integrity check.
44558   */
44559   unlockBtreeIfUnused(pBt);
44560   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
44561     checkAppendMsg(&sCheck, 0, 
44562       "Outstanding page count goes from %d to %d during this analysis",
44563       nRef, sqlite3PagerRefcount(pBt->pPager)
44564     );
44565   }
44566
44567   /* Clean  up and report errors.
44568   */
44569   sqlite3BtreeLeave(p);
44570   sqlite3_free(sCheck.anRef);
44571   if( sCheck.mallocFailed ){
44572     sqlite3StrAccumReset(&sCheck.errMsg);
44573     *pnErr = sCheck.nErr+1;
44574     return 0;
44575   }
44576   *pnErr = sCheck.nErr;
44577   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
44578   return sqlite3StrAccumFinish(&sCheck.errMsg);
44579 }
44580 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44581
44582 /*
44583 ** Return the full pathname of the underlying database file.
44584 **
44585 ** The pager filename is invariant as long as the pager is
44586 ** open so it is safe to access without the BtShared mutex.
44587 */
44588 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
44589   assert( p->pBt->pPager!=0 );
44590   return sqlite3PagerFilename(p->pBt->pPager);
44591 }
44592
44593 /*
44594 ** Return the pathname of the journal file for this database. The return
44595 ** value of this routine is the same regardless of whether the journal file
44596 ** has been created or not.
44597 **
44598 ** The pager journal filename is invariant as long as the pager is
44599 ** open so it is safe to access without the BtShared mutex.
44600 */
44601 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
44602   assert( p->pBt->pPager!=0 );
44603   return sqlite3PagerJournalname(p->pBt->pPager);
44604 }
44605
44606 /*
44607 ** Return non-zero if a transaction is active.
44608 */
44609 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
44610   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
44611   return (p && (p->inTrans==TRANS_WRITE));
44612 }
44613
44614 /*
44615 ** Return non-zero if a statement transaction is active.
44616 */
44617 SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
44618   assert( sqlite3BtreeHoldsMutex(p) );
44619   return ALWAYS(p->pBt) && p->pBt->inStmt;
44620 }
44621
44622 /*
44623 ** Return non-zero if a read (or write) transaction is active.
44624 */
44625 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
44626   assert( p );
44627   assert( sqlite3_mutex_held(p->db->mutex) );
44628   return p->inTrans!=TRANS_NONE;
44629 }
44630
44631 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
44632   assert( p );
44633   assert( sqlite3_mutex_held(p->db->mutex) );
44634   return p->nBackup!=0;
44635 }
44636
44637 /*
44638 ** This function returns a pointer to a blob of memory associated with
44639 ** a single shared-btree. The memory is used by client code for its own
44640 ** purposes (for example, to store a high-level schema associated with 
44641 ** the shared-btree). The btree layer manages reference counting issues.
44642 **
44643 ** The first time this is called on a shared-btree, nBytes bytes of memory
44644 ** are allocated, zeroed, and returned to the caller. For each subsequent 
44645 ** call the nBytes parameter is ignored and a pointer to the same blob
44646 ** of memory returned. 
44647 **
44648 ** If the nBytes parameter is 0 and the blob of memory has not yet been
44649 ** allocated, a null pointer is returned. If the blob has already been
44650 ** allocated, it is returned as normal.
44651 **
44652 ** Just before the shared-btree is closed, the function passed as the 
44653 ** xFree argument when the memory allocation was made is invoked on the 
44654 ** blob of allocated memory. This function should not call sqlite3_free()
44655 ** on the memory, the btree layer does that.
44656 */
44657 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
44658   BtShared *pBt = p->pBt;
44659   sqlite3BtreeEnter(p);
44660   if( !pBt->pSchema && nBytes ){
44661     pBt->pSchema = sqlite3MallocZero(nBytes);
44662     pBt->xFreeSchema = xFree;
44663   }
44664   sqlite3BtreeLeave(p);
44665   return pBt->pSchema;
44666 }
44667
44668 /*
44669 ** Return true if another user of the same shared btree as the argument
44670 ** handle holds an exclusive lock on the sqlite_master table.
44671 */
44672 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
44673   int rc;
44674   assert( sqlite3_mutex_held(p->db->mutex) );
44675   sqlite3BtreeEnter(p);
44676   rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
44677   sqlite3BtreeLeave(p);
44678   return rc;
44679 }
44680
44681
44682 #ifndef SQLITE_OMIT_SHARED_CACHE
44683 /*
44684 ** Obtain a lock on the table whose root page is iTab.  The
44685 ** lock is a write lock if isWritelock is true or a read lock
44686 ** if it is false.
44687 */
44688 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
44689   int rc = SQLITE_OK;
44690   if( p->sharable ){
44691     u8 lockType = READ_LOCK + isWriteLock;
44692     assert( READ_LOCK+1==WRITE_LOCK );
44693     assert( isWriteLock==0 || isWriteLock==1 );
44694     sqlite3BtreeEnter(p);
44695     rc = queryTableLock(p, iTab, lockType);
44696     if( rc==SQLITE_OK ){
44697       rc = lockTable(p, iTab, lockType);
44698     }
44699     sqlite3BtreeLeave(p);
44700   }
44701   return rc;
44702 }
44703 #endif
44704
44705 #ifndef SQLITE_OMIT_INCRBLOB
44706 /*
44707 ** Argument pCsr must be a cursor opened for writing on an 
44708 ** INTKEY table currently pointing at a valid table entry. 
44709 ** This function modifies the data stored as part of that entry.
44710 ** Only the data content may only be modified, it is not possible
44711 ** to change the length of the data stored.
44712 */
44713 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
44714   assert( cursorHoldsMutex(pCsr) );
44715   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
44716   assert(pCsr->isIncrblobHandle);
44717
44718   restoreCursorPosition(pCsr);
44719   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
44720   if( pCsr->eState!=CURSOR_VALID ){
44721     return SQLITE_ABORT;
44722   }
44723
44724   /* Check some preconditions: 
44725   **   (a) the cursor is open for writing,
44726   **   (b) there is no read-lock on the table being modified and
44727   **   (c) the cursor points at a valid row of an intKey table.
44728   */
44729   if( !pCsr->wrFlag ){
44730     return SQLITE_READONLY;
44731   }
44732   assert( !pCsr->pBt->readOnly 
44733           && pCsr->pBt->inTransaction==TRANS_WRITE );
44734   if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
44735     return SQLITE_LOCKED; /* The table pCur points to has a read lock */
44736   }
44737   if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
44738     return SQLITE_ERROR;
44739   }
44740
44741   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
44742 }
44743
44744 /* 
44745 ** Set a flag on this cursor to cache the locations of pages from the 
44746 ** overflow list for the current row. This is used by cursors opened
44747 ** for incremental blob IO only.
44748 **
44749 ** This function sets a flag only. The actual page location cache
44750 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
44751 ** accessPayload() (the worker function for sqlite3BtreeData() and
44752 ** sqlite3BtreePutData()).
44753 */
44754 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
44755   assert( cursorHoldsMutex(pCur) );
44756   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
44757   assert(!pCur->isIncrblobHandle);
44758   assert(!pCur->aOverflow);
44759   pCur->isIncrblobHandle = 1;
44760 }
44761 #endif
44762
44763 /************** End of btree.c ***********************************************/
44764 /************** Begin file backup.c ******************************************/
44765 /*
44766 ** 2009 January 28
44767 **
44768 ** The author disclaims copyright to this source code.  In place of
44769 ** a legal notice, here is a blessing:
44770 **
44771 **    May you do good and not evil.
44772 **    May you find forgiveness for yourself and forgive others.
44773 **    May you share freely, never taking more than you give.
44774 **
44775 *************************************************************************
44776 ** This file contains the implementation of the sqlite3_backup_XXX() 
44777 ** API functions and the related features.
44778 **
44779 ** $Id: backup.c,v 1.12 2009/02/16 17:55:47 shane Exp $
44780 */
44781
44782 /* Macro to find the minimum of two numeric values.
44783 */
44784 #ifndef MIN
44785 # define MIN(x,y) ((x)<(y)?(x):(y))
44786 #endif
44787
44788 /*
44789 ** Structure allocated for each backup operation.
44790 */
44791 struct sqlite3_backup {
44792   sqlite3* pDestDb;        /* Destination database handle */
44793   Btree *pDest;            /* Destination b-tree file */
44794   u32 iDestSchema;         /* Original schema cookie in destination */
44795   int bDestLocked;         /* True once a write-transaction is open on pDest */
44796
44797   Pgno iNext;              /* Page number of the next source page to copy */
44798   sqlite3* pSrcDb;         /* Source database handle */
44799   Btree *pSrc;             /* Source b-tree file */
44800
44801   int rc;                  /* Backup process error code */
44802
44803   /* These two variables are set by every call to backup_step(). They are
44804   ** read by calls to backup_remaining() and backup_pagecount().
44805   */
44806   Pgno nRemaining;         /* Number of pages left to copy */
44807   Pgno nPagecount;         /* Total number of pages to copy */
44808
44809   sqlite3_backup *pNext;   /* Next backup associated with source pager */
44810 };
44811
44812 /*
44813 ** THREAD SAFETY NOTES:
44814 **
44815 **   Once it has been created using backup_init(), a single sqlite3_backup
44816 **   structure may be accessed via two groups of thread-safe entry points:
44817 **
44818 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
44819 **       backup_finish(). Both these functions obtain the source database
44820 **       handle mutex and the mutex associated with the source BtShared 
44821 **       structure, in that order.
44822 **
44823 **     * Via the BackupUpdate() and BackupRestart() functions, which are
44824 **       invoked by the pager layer to report various state changes in
44825 **       the page cache associated with the source database. The mutex
44826 **       associated with the source database BtShared structure will always 
44827 **       be held when either of these functions are invoked.
44828 **
44829 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
44830 **   backup_pagecount() are not thread-safe functions. If they are called
44831 **   while some other thread is calling backup_step() or backup_finish(),
44832 **   the values returned may be invalid. There is no way for a call to
44833 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
44834 **   or backup_pagecount().
44835 **
44836 **   Depending on the SQLite configuration, the database handles and/or
44837 **   the Btree objects may have their own mutexes that require locking.
44838 **   Non-sharable Btrees (in-memory databases for example), do not have
44839 **   associated mutexes.
44840 */
44841
44842 /*
44843 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
44844 ** in connection handle pDb. If such a database cannot be found, return
44845 ** a NULL pointer and write an error message to pErrorDb.
44846 **
44847 ** If the "temp" database is requested, it may need to be opened by this 
44848 ** function. If an error occurs while doing so, return 0 and write an 
44849 ** error message to pErrorDb.
44850 */
44851 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
44852   int i = sqlite3FindDbName(pDb, zDb);
44853
44854   if( i==1 ){
44855     Parse sParse;
44856     memset(&sParse, 0, sizeof(sParse));
44857     sParse.db = pDb;
44858     if( sqlite3OpenTempDatabase(&sParse) ){
44859       sqlite3ErrorClear(&sParse);
44860       sqlite3Error(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
44861       return 0;
44862     }
44863     assert( sParse.zErrMsg==0 );
44864   }
44865
44866   if( i<0 ){
44867     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
44868     return 0;
44869   }
44870
44871   return pDb->aDb[i].pBt;
44872 }
44873
44874 /*
44875 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
44876 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
44877 ** a pointer to the new sqlite3_backup object.
44878 **
44879 ** If an error occurs, NULL is returned and an error code and error message
44880 ** stored in database handle pDestDb.
44881 */
44882 SQLITE_API sqlite3_backup *sqlite3_backup_init(
44883   sqlite3* pDestDb,                     /* Database to write to */
44884   const char *zDestDb,                  /* Name of database within pDestDb */
44885   sqlite3* pSrcDb,                      /* Database connection to read from */
44886   const char *zSrcDb                    /* Name of database within pSrcDb */
44887 ){
44888   sqlite3_backup *p;                    /* Value to return */
44889
44890   /* Lock the source database handle. The destination database
44891   ** handle is not locked in this routine, but it is locked in
44892   ** sqlite3_backup_step(). The user is required to ensure that no
44893   ** other thread accesses the destination handle for the duration
44894   ** of the backup operation.  Any attempt to use the destination
44895   ** database connection while a backup is in progress may cause
44896   ** a malfunction or a deadlock.
44897   */
44898   sqlite3_mutex_enter(pSrcDb->mutex);
44899   sqlite3_mutex_enter(pDestDb->mutex);
44900
44901   if( pSrcDb==pDestDb ){
44902     sqlite3Error(
44903         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
44904     );
44905     p = 0;
44906   }else {
44907     /* Allocate space for a new sqlite3_backup object */
44908     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
44909     if( !p ){
44910       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
44911     }
44912   }
44913
44914   /* If the allocation succeeded, populate the new object. */
44915   if( p ){
44916     memset(p, 0, sizeof(sqlite3_backup));
44917     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
44918     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
44919     p->pDestDb = pDestDb;
44920     p->pSrcDb = pSrcDb;
44921     p->iNext = 1;
44922
44923     if( 0==p->pSrc || 0==p->pDest ){
44924       /* One (or both) of the named databases did not exist. An error has
44925       ** already been written into the pDestDb handle. All that is left
44926       ** to do here is free the sqlite3_backup structure.
44927       */
44928       sqlite3_free(p);
44929       p = 0;
44930     }
44931   }
44932
44933   /* If everything has gone as planned, attach the backup object to the
44934   ** source pager. The source pager calls BackupUpdate() and BackupRestart()
44935   ** to notify this module if the source file is modified mid-backup.
44936   */
44937   if( p ){
44938     sqlite3_backup **pp;             /* Pointer to head of pagers backup list */
44939     sqlite3BtreeEnter(p->pSrc);
44940     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
44941     p->pNext = *pp;
44942     *pp = p;
44943     sqlite3BtreeLeave(p->pSrc);
44944     p->pSrc->nBackup++;
44945   }
44946
44947   sqlite3_mutex_leave(pDestDb->mutex);
44948   sqlite3_mutex_leave(pSrcDb->mutex);
44949   return p;
44950 }
44951
44952 /*
44953 ** Argument rc is an SQLite error code. Return true if this error is 
44954 ** considered fatal if encountered during a backup operation. All errors
44955 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
44956 */
44957 static int isFatalError(int rc){
44958   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED);
44959 }
44960
44961 /*
44962 ** Parameter zSrcData points to a buffer containing the data for 
44963 ** page iSrcPg from the source database. Copy this data into the 
44964 ** destination database.
44965 */
44966 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
44967   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
44968   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
44969   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
44970   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
44971   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
44972
44973   int rc = SQLITE_OK;
44974   i64 iOff;
44975
44976   assert( p->bDestLocked );
44977   assert( !isFatalError(p->rc) );
44978   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
44979   assert( zSrcData );
44980
44981   /* Catch the case where the destination is an in-memory database and the
44982   ** page sizes of the source and destination differ. 
44983   */
44984   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
44985     rc = SQLITE_READONLY;
44986   }
44987
44988   /* This loop runs once for each destination page spanned by the source 
44989   ** page. For each iteration, variable iOff is set to the byte offset
44990   ** of the destination page.
44991   */
44992   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
44993     DbPage *pDestPg = 0;
44994     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
44995     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
44996     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
44997      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
44998     ){
44999       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45000       u8 *zDestData = sqlite3PagerGetData(pDestPg);
45001       u8 *zOut = &zDestData[iOff%nDestPgsz];
45002
45003       /* Copy the data from the source page into the destination page.
45004       ** Then clear the Btree layer MemPage.isInit flag. Both this module
45005       ** and the pager code use this trick (clearing the first byte
45006       ** of the page 'extra' space to invalidate the Btree layers
45007       ** cached parse of the page). MemPage.isInit is marked 
45008       ** "MUST BE FIRST" for this purpose.
45009       */
45010       memcpy(zOut, zIn, nCopy);
45011       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45012     }
45013     sqlite3PagerUnref(pDestPg);
45014   }
45015
45016   return rc;
45017 }
45018
45019 /*
45020 ** If pFile is currently larger than iSize bytes, then truncate it to
45021 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45022 ** this function is a no-op.
45023 **
45024 ** Return SQLITE_OK if everything is successful, or an SQLite error 
45025 ** code if an error occurs.
45026 */
45027 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45028   i64 iCurrent;
45029   int rc = sqlite3OsFileSize(pFile, &iCurrent);
45030   if( rc==SQLITE_OK && iCurrent>iSize ){
45031     rc = sqlite3OsTruncate(pFile, iSize);
45032   }
45033   return rc;
45034 }
45035
45036 /*
45037 ** Copy nPage pages from the source b-tree to the destination.
45038 */
45039 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45040   int rc;
45041
45042   sqlite3_mutex_enter(p->pSrcDb->mutex);
45043   sqlite3BtreeEnter(p->pSrc);
45044   if( p->pDestDb ){
45045     sqlite3_mutex_enter(p->pDestDb->mutex);
45046   }
45047
45048   rc = p->rc;
45049   if( !isFatalError(rc) ){
45050     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45051     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45052     int ii;                            /* Iterator variable */
45053     int nSrcPage = -1;                 /* Size of source db in pages */
45054     int bCloseTrans = 0;               /* True if src db requires unlocking */
45055
45056     /* If the source pager is currently in a write-transaction, return
45057     ** SQLITE_LOCKED immediately.
45058     */
45059     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45060       rc = SQLITE_LOCKED;
45061     }else{
45062       rc = SQLITE_OK;
45063     }
45064
45065     /* Lock the destination database, if it is not locked already. */
45066     if( SQLITE_OK==rc && p->bDestLocked==0
45067      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
45068     ){
45069       p->bDestLocked = 1;
45070       rc = sqlite3BtreeGetMeta(p->pDest, 1, &p->iDestSchema);
45071     }
45072
45073     /* If there is no open read-transaction on the source database, open
45074     ** one now. If a transaction is opened here, then it will be closed
45075     ** before this function exits.
45076     */
45077     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
45078       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
45079       bCloseTrans = 1;
45080     }
45081   
45082     /* Now that there is a read-lock on the source database, query the
45083     ** source pager for the number of pages in the database.
45084     */
45085     if( rc==SQLITE_OK ){
45086       rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
45087     }
45088     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
45089       const Pgno iSrcPg = p->iNext;                 /* Source page number */
45090       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
45091         DbPage *pSrcPg;                             /* Source page object */
45092         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45093         if( rc==SQLITE_OK ){
45094           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
45095           sqlite3PagerUnref(pSrcPg);
45096         }
45097       }
45098       p->iNext++;
45099     }
45100     if( rc==SQLITE_OK ){
45101       p->nPagecount = nSrcPage;
45102       p->nRemaining = nSrcPage+1-p->iNext;
45103       if( p->iNext>(Pgno)nSrcPage ){
45104         rc = SQLITE_DONE;
45105       }
45106     }
45107   
45108     if( rc==SQLITE_DONE ){
45109       const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
45110       const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
45111       int nDestTruncate;
45112   
45113       /* Update the schema version field in the destination database. This
45114       ** is to make sure that the schema-version really does change in
45115       ** the case where the source and destination databases have the
45116       ** same schema version.
45117       */
45118       sqlite3BtreeUpdateMeta(p->pDest, 1, p->iDestSchema+1);
45119       if( p->pDestDb ){
45120         sqlite3ResetInternalSchema(p->pDestDb, 0);
45121       }
45122
45123       /* Set nDestTruncate to the final number of pages in the destination
45124       ** database. The complication here is that the destination page
45125       ** size may be different to the source page size. 
45126       **
45127       ** If the source page size is smaller than the destination page size, 
45128       ** round up. In this case the call to sqlite3OsTruncate() below will
45129       ** fix the size of the file. However it is important to call
45130       ** sqlite3PagerTruncateImage() here so that any pages in the 
45131       ** destination file that lie beyond the nDestTruncate page mark are
45132       ** journalled by PagerCommitPhaseOne() before they are destroyed
45133       ** by the file truncation.
45134       */
45135       if( nSrcPagesize<nDestPagesize ){
45136         int ratio = nDestPagesize/nSrcPagesize;
45137         nDestTruncate = (nSrcPage+ratio-1)/ratio;
45138         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
45139           nDestTruncate--;
45140         }
45141       }else{
45142         nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
45143       }
45144       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
45145
45146       if( nSrcPagesize<nDestPagesize ){
45147         /* If the source page-size is smaller than the destination page-size,
45148         ** two extra things may need to happen:
45149         **
45150         **   * The destination may need to be truncated, and
45151         **
45152         **   * Data stored on the pages immediately following the 
45153         **     pending-byte page in the source database may need to be
45154         **     copied into the destination database.
45155         */
45156         const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
45157         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
45158
45159         assert( pFile );
45160         assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
45161               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
45162            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
45163         ));
45164         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
45165          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
45166          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
45167         ){
45168           i64 iOff;
45169           i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
45170           for(
45171             iOff=PENDING_BYTE+nSrcPagesize; 
45172             rc==SQLITE_OK && iOff<iEnd; 
45173             iOff+=nSrcPagesize
45174           ){
45175             PgHdr *pSrcPg = 0;
45176             const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
45177             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45178             if( rc==SQLITE_OK ){
45179               u8 *zData = sqlite3PagerGetData(pSrcPg);
45180               rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
45181             }
45182             sqlite3PagerUnref(pSrcPg);
45183           }
45184         }
45185       }else{
45186         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
45187       }
45188   
45189       /* Finish committing the transaction to the destination database. */
45190       if( SQLITE_OK==rc
45191        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
45192       ){
45193         rc = SQLITE_DONE;
45194       }
45195     }
45196   
45197     /* If bCloseTrans is true, then this function opened a read transaction
45198     ** on the source database. Close the read transaction here. There is
45199     ** no need to check the return values of the btree methods here, as
45200     ** "committing" a read-only transaction cannot fail.
45201     */
45202     if( bCloseTrans ){
45203       TESTONLY( int rc2 );
45204       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
45205       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
45206       assert( rc2==SQLITE_OK );
45207     }
45208   
45209     p->rc = rc;
45210   }
45211   if( p->pDestDb ){
45212     sqlite3_mutex_leave(p->pDestDb->mutex);
45213   }
45214   sqlite3BtreeLeave(p->pSrc);
45215   sqlite3_mutex_leave(p->pSrcDb->mutex);
45216   return rc;
45217 }
45218
45219 /*
45220 ** Release all resources associated with an sqlite3_backup* handle.
45221 */
45222 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
45223   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
45224   sqlite3_mutex *mutex;                /* Mutex to protect source database */
45225   int rc;                              /* Value to return */
45226
45227   /* Enter the mutexes */
45228   sqlite3_mutex_enter(p->pSrcDb->mutex);
45229   sqlite3BtreeEnter(p->pSrc);
45230   mutex = p->pSrcDb->mutex;
45231   if( p->pDestDb ){
45232     sqlite3_mutex_enter(p->pDestDb->mutex);
45233   }
45234
45235   /* Detach this backup from the source pager. */
45236   if( p->pDestDb ){
45237     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45238     while( *pp!=p ){
45239       pp = &(*pp)->pNext;
45240     }
45241     *pp = p->pNext;
45242     p->pSrc->nBackup--;
45243   }
45244
45245   /* If a transaction is still open on the Btree, roll it back. */
45246   sqlite3BtreeRollback(p->pDest);
45247
45248   /* Set the error code of the destination database handle. */
45249   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
45250   sqlite3Error(p->pDestDb, rc, 0);
45251
45252   /* Exit the mutexes and free the backup context structure. */
45253   if( p->pDestDb ){
45254     sqlite3_mutex_leave(p->pDestDb->mutex);
45255   }
45256   sqlite3BtreeLeave(p->pSrc);
45257   if( p->pDestDb ){
45258     sqlite3_free(p);
45259   }
45260   sqlite3_mutex_leave(mutex);
45261   return rc;
45262 }
45263
45264 /*
45265 ** Return the number of pages still to be backed up as of the most recent
45266 ** call to sqlite3_backup_step().
45267 */
45268 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
45269   return p->nRemaining;
45270 }
45271
45272 /*
45273 ** Return the total number of pages in the source database as of the most 
45274 ** recent call to sqlite3_backup_step().
45275 */
45276 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
45277   return p->nPagecount;
45278 }
45279
45280 /*
45281 ** This function is called after the contents of page iPage of the
45282 ** source database have been modified. If page iPage has already been 
45283 ** copied into the destination database, then the data written to the
45284 ** destination is now invalidated. The destination copy of iPage needs
45285 ** to be updated with the new data before the backup operation is
45286 ** complete.
45287 **
45288 ** It is assumed that the mutex associated with the BtShared object
45289 ** corresponding to the source database is held when this function is
45290 ** called.
45291 */
45292 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
45293   sqlite3_backup *p;                   /* Iterator variable */
45294   for(p=pBackup; p; p=p->pNext){
45295     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45296     if( !isFatalError(p->rc) && iPage<p->iNext ){
45297       /* The backup process p has already copied page iPage. But now it
45298       ** has been modified by a transaction on the source pager. Copy
45299       ** the new data into the backup.
45300       */
45301       int rc = backupOnePage(p, iPage, aData);
45302       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
45303       if( rc!=SQLITE_OK ){
45304         p->rc = rc;
45305       }
45306     }
45307   }
45308 }
45309
45310 /*
45311 ** Restart the backup process. This is called when the pager layer
45312 ** detects that the database has been modified by an external database
45313 ** connection. In this case there is no way of knowing which of the
45314 ** pages that have been copied into the destination database are still 
45315 ** valid and which are not, so the entire process needs to be restarted.
45316 **
45317 ** It is assumed that the mutex associated with the BtShared object
45318 ** corresponding to the source database is held when this function is
45319 ** called.
45320 */
45321 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
45322   sqlite3_backup *p;                   /* Iterator variable */
45323   for(p=pBackup; p; p=p->pNext){
45324     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45325     p->iNext = 1;
45326   }
45327 }
45328
45329 #ifndef SQLITE_OMIT_VACUUM
45330 /*
45331 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
45332 ** must be active for both files.
45333 **
45334 ** The size of file pTo may be reduced by this operation. If anything 
45335 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
45336 ** transaction is committed before returning.
45337 */
45338 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
45339   int rc;
45340   sqlite3_backup b;
45341   sqlite3BtreeEnter(pTo);
45342   sqlite3BtreeEnter(pFrom);
45343
45344   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
45345   ** to 0. This is used by the implementations of sqlite3_backup_step()
45346   ** and sqlite3_backup_finish() to detect that they are being called
45347   ** from this function, not directly by the user.
45348   */
45349   memset(&b, 0, sizeof(b));
45350   b.pSrcDb = pFrom->db;
45351   b.pSrc = pFrom;
45352   b.pDest = pTo;
45353   b.iNext = 1;
45354
45355   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
45356   ** file. By passing this as the number of pages to copy to
45357   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
45358   ** within a single call (unless an error occurs). The assert() statement
45359   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
45360   ** or an error code.
45361   */
45362   sqlite3_backup_step(&b, 0x7FFFFFFF);
45363   assert( b.rc!=SQLITE_OK );
45364   rc = sqlite3_backup_finish(&b);
45365   if( rc==SQLITE_OK ){
45366     pTo->pBt->pageSizeFixed = 0;
45367   }
45368
45369   sqlite3BtreeLeave(pFrom);
45370   sqlite3BtreeLeave(pTo);
45371   return rc;
45372 }
45373 #endif /* SQLITE_OMIT_VACUUM */
45374
45375 /************** End of backup.c **********************************************/
45376 /************** Begin file vdbemem.c *****************************************/
45377 /*
45378 ** 2004 May 26
45379 **
45380 ** The author disclaims copyright to this source code.  In place of
45381 ** a legal notice, here is a blessing:
45382 **
45383 **    May you do good and not evil.
45384 **    May you find forgiveness for yourself and forgive others.
45385 **    May you share freely, never taking more than you give.
45386 **
45387 *************************************************************************
45388 **
45389 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
45390 ** stores a single value in the VDBE.  Mem is an opaque structure visible
45391 ** only within the VDBE.  Interface routines refer to a Mem using the
45392 ** name sqlite_value
45393 **
45394 ** $Id: vdbemem.c,v 1.137 2009/02/04 03:59:25 shane Exp $
45395 */
45396
45397 /*
45398 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
45399 ** P if required.
45400 */
45401 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
45402
45403 /*
45404 ** If pMem is an object with a valid string representation, this routine
45405 ** ensures the internal encoding for the string representation is
45406 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
45407 **
45408 ** If pMem is not a string object, or the encoding of the string
45409 ** representation is already stored using the requested encoding, then this
45410 ** routine is a no-op.
45411 **
45412 ** SQLITE_OK is returned if the conversion is successful (or not required).
45413 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
45414 ** between formats.
45415 */
45416 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
45417   int rc;
45418   assert( (pMem->flags&MEM_RowSet)==0 );
45419   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
45420            || desiredEnc==SQLITE_UTF16BE );
45421   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
45422     return SQLITE_OK;
45423   }
45424   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45425 #ifdef SQLITE_OMIT_UTF16
45426   return SQLITE_ERROR;
45427 #else
45428
45429   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
45430   ** then the encoding of the value may not have changed.
45431   */
45432   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
45433   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
45434   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
45435   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
45436   return rc;
45437 #endif
45438 }
45439
45440 /*
45441 ** Make sure pMem->z points to a writable allocation of at least 
45442 ** n bytes.
45443 **
45444 ** If the memory cell currently contains string or blob data
45445 ** and the third argument passed to this function is true, the 
45446 ** current content of the cell is preserved. Otherwise, it may
45447 ** be discarded.  
45448 **
45449 ** This function sets the MEM_Dyn flag and clears any xDel callback.
45450 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
45451 ** not set, Mem.n is zeroed.
45452 */
45453 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
45454   assert( 1 >=
45455     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
45456     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
45457     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
45458     ((pMem->flags&MEM_Static) ? 1 : 0)
45459   );
45460   assert( (pMem->flags&MEM_RowSet)==0 );
45461
45462   if( n<32 ) n = 32;
45463   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
45464     if( preserve && pMem->z==pMem->zMalloc ){
45465       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
45466       preserve = 0;
45467     }else{
45468       sqlite3DbFree(pMem->db, pMem->zMalloc);
45469       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
45470     }
45471   }
45472
45473   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
45474     memcpy(pMem->zMalloc, pMem->z, pMem->n);
45475   }
45476   if( pMem->flags&MEM_Dyn && pMem->xDel ){
45477     pMem->xDel((void *)(pMem->z));
45478   }
45479
45480   pMem->z = pMem->zMalloc;
45481   if( pMem->z==0 ){
45482     pMem->flags = MEM_Null;
45483   }else{
45484     pMem->flags &= ~(MEM_Ephem|MEM_Static);
45485   }
45486   pMem->xDel = 0;
45487   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
45488 }
45489
45490 /*
45491 ** Make the given Mem object MEM_Dyn.  In other words, make it so
45492 ** that any TEXT or BLOB content is stored in memory obtained from
45493 ** malloc().  In this way, we know that the memory is safe to be
45494 ** overwritten or altered.
45495 **
45496 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
45497 */
45498 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
45499   int f;
45500   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45501   assert( (pMem->flags&MEM_RowSet)==0 );
45502   expandBlob(pMem);
45503   f = pMem->flags;
45504   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
45505     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
45506       return SQLITE_NOMEM;
45507     }
45508     pMem->z[pMem->n] = 0;
45509     pMem->z[pMem->n+1] = 0;
45510     pMem->flags |= MEM_Term;
45511   }
45512
45513   return SQLITE_OK;
45514 }
45515
45516 /*
45517 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
45518 ** blob stored in dynamically allocated space.
45519 */
45520 #ifndef SQLITE_OMIT_INCRBLOB
45521 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
45522   if( pMem->flags & MEM_Zero ){
45523     int nByte;
45524     assert( pMem->flags&MEM_Blob );
45525     assert( (pMem->flags&MEM_RowSet)==0 );
45526     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45527
45528     /* Set nByte to the number of bytes required to store the expanded blob. */
45529     nByte = pMem->n + pMem->u.nZero;
45530     if( nByte<=0 ){
45531       nByte = 1;
45532     }
45533     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
45534       return SQLITE_NOMEM;
45535     }
45536
45537     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
45538     pMem->n += pMem->u.nZero;
45539     pMem->flags &= ~(MEM_Zero|MEM_Term);
45540   }
45541   return SQLITE_OK;
45542 }
45543 #endif
45544
45545
45546 /*
45547 ** Make sure the given Mem is \u0000 terminated.
45548 */
45549 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
45550   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45551   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
45552     return SQLITE_OK;   /* Nothing to do */
45553   }
45554   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
45555     return SQLITE_NOMEM;
45556   }
45557   pMem->z[pMem->n] = 0;
45558   pMem->z[pMem->n+1] = 0;
45559   pMem->flags |= MEM_Term;
45560   return SQLITE_OK;
45561 }
45562
45563 /*
45564 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
45565 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
45566 ** is a no-op.
45567 **
45568 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
45569 **
45570 ** A MEM_Null value will never be passed to this function. This function is
45571 ** used for converting values to text for returning to the user (i.e. via
45572 ** sqlite3_value_text()), or for ensuring that values to be used as btree
45573 ** keys are strings. In the former case a NULL pointer is returned the
45574 ** user and the later is an internal programming error.
45575 */
45576 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
45577   int rc = SQLITE_OK;
45578   int fg = pMem->flags;
45579   const int nByte = 32;
45580
45581   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45582   assert( !(fg&MEM_Zero) );
45583   assert( !(fg&(MEM_Str|MEM_Blob)) );
45584   assert( fg&(MEM_Int|MEM_Real) );
45585   assert( (pMem->flags&MEM_RowSet)==0 );
45586
45587
45588   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
45589     return SQLITE_NOMEM;
45590   }
45591
45592   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
45593   ** string representation of the value. Then, if the required encoding
45594   ** is UTF-16le or UTF-16be do a translation.
45595   ** 
45596   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
45597   */
45598   if( fg & MEM_Int ){
45599     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
45600   }else{
45601     assert( fg & MEM_Real );
45602     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
45603   }
45604   pMem->n = sqlite3Strlen30(pMem->z);
45605   pMem->enc = SQLITE_UTF8;
45606   pMem->flags |= MEM_Str|MEM_Term;
45607   sqlite3VdbeChangeEncoding(pMem, enc);
45608   return rc;
45609 }
45610
45611 /*
45612 ** Memory cell pMem contains the context of an aggregate function.
45613 ** This routine calls the finalize method for that function.  The
45614 ** result of the aggregate is stored back into pMem.
45615 **
45616 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
45617 ** otherwise.
45618 */
45619 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
45620   int rc = SQLITE_OK;
45621   if( pFunc && pFunc->xFinalize ){
45622     sqlite3_context ctx;
45623     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
45624     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45625     memset(&ctx, 0, sizeof(ctx));
45626     ctx.s.flags = MEM_Null;
45627     ctx.s.db = pMem->db;
45628     ctx.pMem = pMem;
45629     ctx.pFunc = pFunc;
45630     pFunc->xFinalize(&ctx);
45631     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
45632     sqlite3DbFree(pMem->db, pMem->zMalloc);
45633     memcpy(pMem, &ctx.s, sizeof(ctx.s));
45634     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
45635   }
45636   return rc;
45637 }
45638
45639 /*
45640 ** If the memory cell contains a string value that must be freed by
45641 ** invoking an external callback, free it now. Calling this function
45642 ** does not free any Mem.zMalloc buffer.
45643 */
45644 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
45645   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
45646   if( p->flags&MEM_Agg ){
45647     sqlite3VdbeMemFinalize(p, p->u.pDef);
45648     assert( (p->flags & MEM_Agg)==0 );
45649     sqlite3VdbeMemRelease(p);
45650   }else if( p->flags&MEM_Dyn && p->xDel ){
45651     assert( (p->flags&MEM_RowSet)==0 );
45652     p->xDel((void *)p->z);
45653     p->xDel = 0;
45654   }else if( p->flags&MEM_RowSet ){
45655     sqlite3RowSetClear(p->u.pRowSet);
45656   }
45657 }
45658
45659 /*
45660 ** Release any memory held by the Mem. This may leave the Mem in an
45661 ** inconsistent state, for example with (Mem.z==0) and
45662 ** (Mem.type==SQLITE_TEXT).
45663 */
45664 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
45665   sqlite3VdbeMemReleaseExternal(p);
45666   sqlite3DbFree(p->db, p->zMalloc);
45667   p->z = 0;
45668   p->zMalloc = 0;
45669   p->xDel = 0;
45670 }
45671
45672 /*
45673 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
45674 ** If the double is too large, return 0x8000000000000000.
45675 **
45676 ** Most systems appear to do this simply by assigning
45677 ** variables and without the extra range tests.  But
45678 ** there are reports that windows throws an expection
45679 ** if the floating point value is out of range. (See ticket #2880.)
45680 ** Because we do not completely understand the problem, we will
45681 ** take the conservative approach and always do range tests
45682 ** before attempting the conversion.
45683 */
45684 static i64 doubleToInt64(double r){
45685   /*
45686   ** Many compilers we encounter do not define constants for the
45687   ** minimum and maximum 64-bit integers, or they define them
45688   ** inconsistently.  And many do not understand the "LL" notation.
45689   ** So we define our own static constants here using nothing
45690   ** larger than a 32-bit integer constant.
45691   */
45692   static const i64 maxInt = LARGEST_INT64;
45693   static const i64 minInt = SMALLEST_INT64;
45694
45695   if( r<(double)minInt ){
45696     return minInt;
45697   }else if( r>(double)maxInt ){
45698     return minInt;
45699   }else{
45700     return (i64)r;
45701   }
45702 }
45703
45704 /*
45705 ** Return some kind of integer value which is the best we can do
45706 ** at representing the value that *pMem describes as an integer.
45707 ** If pMem is an integer, then the value is exact.  If pMem is
45708 ** a floating-point then the value returned is the integer part.
45709 ** If pMem is a string or blob, then we make an attempt to convert
45710 ** it into a integer and return that.  If pMem is NULL, return 0.
45711 **
45712 ** If pMem is a string, its encoding might be changed.
45713 */
45714 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
45715   int flags;
45716   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45717   flags = pMem->flags;
45718   if( flags & MEM_Int ){
45719     return pMem->u.i;
45720   }else if( flags & MEM_Real ){
45721     return doubleToInt64(pMem->r);
45722   }else if( flags & (MEM_Str|MEM_Blob) ){
45723     i64 value;
45724     pMem->flags |= MEM_Str;
45725     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
45726        || sqlite3VdbeMemNulTerminate(pMem) ){
45727       return 0;
45728     }
45729     assert( pMem->z );
45730     sqlite3Atoi64(pMem->z, &value);
45731     return value;
45732   }else{
45733     return 0;
45734   }
45735 }
45736
45737 /*
45738 ** Return the best representation of pMem that we can get into a
45739 ** double.  If pMem is already a double or an integer, return its
45740 ** value.  If it is a string or blob, try to convert it to a double.
45741 ** If it is a NULL, return 0.0.
45742 */
45743 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
45744   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45745   if( pMem->flags & MEM_Real ){
45746     return pMem->r;
45747   }else if( pMem->flags & MEM_Int ){
45748     return (double)pMem->u.i;
45749   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
45750     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
45751     double val = (double)0;
45752     pMem->flags |= MEM_Str;
45753     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
45754        || sqlite3VdbeMemNulTerminate(pMem) ){
45755       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
45756       return (double)0;
45757     }
45758     assert( pMem->z );
45759     sqlite3AtoF(pMem->z, &val);
45760     return val;
45761   }else{
45762     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
45763     return (double)0;
45764   }
45765 }
45766
45767 /*
45768 ** The MEM structure is already a MEM_Real.  Try to also make it a
45769 ** MEM_Int if we can.
45770 */
45771 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
45772   assert( pMem->flags & MEM_Real );
45773   assert( (pMem->flags & MEM_RowSet)==0 );
45774   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45775
45776   pMem->u.i = doubleToInt64(pMem->r);
45777   if( pMem->r==(double)pMem->u.i ){
45778     pMem->flags |= MEM_Int;
45779   }
45780 }
45781
45782 /*
45783 ** Convert pMem to type integer.  Invalidate any prior representations.
45784 */
45785 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
45786   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45787   assert( (pMem->flags & MEM_RowSet)==0 );
45788   pMem->u.i = sqlite3VdbeIntValue(pMem);
45789   MemSetTypeFlag(pMem, MEM_Int);
45790   return SQLITE_OK;
45791 }
45792
45793 /*
45794 ** Convert pMem so that it is of type MEM_Real.
45795 ** Invalidate any prior representations.
45796 */
45797 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
45798   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45799   pMem->r = sqlite3VdbeRealValue(pMem);
45800   MemSetTypeFlag(pMem, MEM_Real);
45801   return SQLITE_OK;
45802 }
45803
45804 /*
45805 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
45806 ** Invalidate any prior representations.
45807 */
45808 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
45809   double r1, r2;
45810   i64 i;
45811   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
45812   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
45813   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45814   r1 = sqlite3VdbeRealValue(pMem);
45815   i = doubleToInt64(r1);
45816   r2 = (double)i;
45817   if( r1==r2 ){
45818     sqlite3VdbeMemIntegerify(pMem);
45819   }else{
45820     pMem->r = r1;
45821     MemSetTypeFlag(pMem, MEM_Real);
45822   }
45823   return SQLITE_OK;
45824 }
45825
45826 /*
45827 ** Delete any previous value and set the value stored in *pMem to NULL.
45828 */
45829 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
45830   if( pMem->flags & MEM_RowSet ){
45831     sqlite3RowSetClear(pMem->u.pRowSet);
45832   }
45833   MemSetTypeFlag(pMem, MEM_Null);
45834   pMem->type = SQLITE_NULL;
45835 }
45836
45837 /*
45838 ** Delete any previous value and set the value to be a BLOB of length
45839 ** n containing all zeros.
45840 */
45841 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
45842   sqlite3VdbeMemRelease(pMem);
45843   pMem->flags = MEM_Blob|MEM_Zero;
45844   pMem->type = SQLITE_BLOB;
45845   pMem->n = 0;
45846   if( n<0 ) n = 0;
45847   pMem->u.nZero = n;
45848   pMem->enc = SQLITE_UTF8;
45849 }
45850
45851 /*
45852 ** Delete any previous value and set the value stored in *pMem to val,
45853 ** manifest type INTEGER.
45854 */
45855 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
45856   sqlite3VdbeMemRelease(pMem);
45857   pMem->u.i = val;
45858   pMem->flags = MEM_Int;
45859   pMem->type = SQLITE_INTEGER;
45860 }
45861
45862 /*
45863 ** Delete any previous value and set the value stored in *pMem to val,
45864 ** manifest type REAL.
45865 */
45866 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
45867   if( sqlite3IsNaN(val) ){
45868     sqlite3VdbeMemSetNull(pMem);
45869   }else{
45870     sqlite3VdbeMemRelease(pMem);
45871     pMem->r = val;
45872     pMem->flags = MEM_Real;
45873     pMem->type = SQLITE_FLOAT;
45874   }
45875 }
45876
45877 /*
45878 ** Delete any previous value and set the value of pMem to be an
45879 ** empty boolean index.
45880 */
45881 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
45882   sqlite3 *db = pMem->db;
45883   assert( db!=0 );
45884   if( pMem->flags & MEM_RowSet ){
45885     sqlite3RowSetClear(pMem->u.pRowSet);
45886   }else{
45887     sqlite3VdbeMemRelease(pMem);
45888     pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
45889   }
45890   if( db->mallocFailed ){
45891     pMem->flags = MEM_Null;
45892   }else{
45893     assert( pMem->zMalloc );
45894     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
45895                                        sqlite3DbMallocSize(db, pMem->zMalloc));
45896     assert( pMem->u.pRowSet!=0 );
45897     pMem->flags = MEM_RowSet;
45898   }
45899 }
45900
45901 /*
45902 ** Return true if the Mem object contains a TEXT or BLOB that is
45903 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
45904 */
45905 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
45906   assert( p->db!=0 );
45907   if( p->flags & (MEM_Str|MEM_Blob) ){
45908     int n = p->n;
45909     if( p->flags & MEM_Zero ){
45910       n += p->u.nZero;
45911     }
45912     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
45913   }
45914   return 0; 
45915 }
45916
45917 /*
45918 ** Size of struct Mem not including the Mem.zMalloc member.
45919 */
45920 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
45921
45922 /*
45923 ** Make an shallow copy of pFrom into pTo.  Prior contents of
45924 ** pTo are freed.  The pFrom->z field is not duplicated.  If
45925 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
45926 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
45927 */
45928 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
45929   assert( (pFrom->flags & MEM_RowSet)==0 );
45930   sqlite3VdbeMemReleaseExternal(pTo);
45931   memcpy(pTo, pFrom, MEMCELLSIZE);
45932   pTo->xDel = 0;
45933   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
45934     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
45935     assert( srcType==MEM_Ephem || srcType==MEM_Static );
45936     pTo->flags |= srcType;
45937   }
45938 }
45939
45940 /*
45941 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
45942 ** freed before the copy is made.
45943 */
45944 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
45945   int rc = SQLITE_OK;
45946
45947   assert( (pFrom->flags & MEM_RowSet)==0 );
45948   sqlite3VdbeMemReleaseExternal(pTo);
45949   memcpy(pTo, pFrom, MEMCELLSIZE);
45950   pTo->flags &= ~MEM_Dyn;
45951
45952   if( pTo->flags&(MEM_Str|MEM_Blob) ){
45953     if( 0==(pFrom->flags&MEM_Static) ){
45954       pTo->flags |= MEM_Ephem;
45955       rc = sqlite3VdbeMemMakeWriteable(pTo);
45956     }
45957   }
45958
45959   return rc;
45960 }
45961
45962 /*
45963 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
45964 ** freed. If pFrom contains ephemeral data, a copy is made.
45965 **
45966 ** pFrom contains an SQL NULL when this routine returns.
45967 */
45968 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
45969   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
45970   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
45971   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
45972
45973   sqlite3VdbeMemRelease(pTo);
45974   memcpy(pTo, pFrom, sizeof(Mem));
45975   pFrom->flags = MEM_Null;
45976   pFrom->xDel = 0;
45977   pFrom->zMalloc = 0;
45978 }
45979
45980 /*
45981 ** Change the value of a Mem to be a string or a BLOB.
45982 **
45983 ** The memory management strategy depends on the value of the xDel
45984 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
45985 ** string is copied into a (possibly existing) buffer managed by the 
45986 ** Mem structure. Otherwise, any existing buffer is freed and the
45987 ** pointer copied.
45988 */
45989 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
45990   Mem *pMem,          /* Memory cell to set to string value */
45991   const char *z,      /* String pointer */
45992   int n,              /* Bytes in string, or negative */
45993   u8 enc,             /* Encoding of z.  0 for BLOBs */
45994   void (*xDel)(void*) /* Destructor function */
45995 ){
45996   int nByte = n;      /* New value for pMem->n */
45997   int iLimit;         /* Maximum allowed string or blob size */
45998   u16 flags = 0;      /* New value for pMem->flags */
45999
46000   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46001   assert( (pMem->flags & MEM_RowSet)==0 );
46002
46003   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46004   if( !z ){
46005     sqlite3VdbeMemSetNull(pMem);
46006     return SQLITE_OK;
46007   }
46008
46009   if( pMem->db ){
46010     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46011   }else{
46012     iLimit = SQLITE_MAX_LENGTH;
46013   }
46014   flags = (enc==0?MEM_Blob:MEM_Str);
46015   if( nByte<0 ){
46016     assert( enc!=0 );
46017     if( enc==SQLITE_UTF8 ){
46018       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
46019     }else{
46020       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
46021     }
46022     flags |= MEM_Term;
46023   }
46024
46025   /* The following block sets the new values of Mem.z and Mem.xDel. It
46026   ** also sets a flag in local variable "flags" to indicate the memory
46027   ** management (one of MEM_Dyn or MEM_Static).
46028   */
46029   if( xDel==SQLITE_TRANSIENT ){
46030     int nAlloc = nByte;
46031     if( flags&MEM_Term ){
46032       nAlloc += (enc==SQLITE_UTF8?1:2);
46033     }
46034     if( nByte>iLimit ){
46035       return SQLITE_TOOBIG;
46036     }
46037     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
46038       return SQLITE_NOMEM;
46039     }
46040     memcpy(pMem->z, z, nAlloc);
46041   }else if( xDel==SQLITE_DYNAMIC ){
46042     sqlite3VdbeMemRelease(pMem);
46043     pMem->zMalloc = pMem->z = (char *)z;
46044     pMem->xDel = 0;
46045   }else{
46046     sqlite3VdbeMemRelease(pMem);
46047     pMem->z = (char *)z;
46048     pMem->xDel = xDel;
46049     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
46050   }
46051   if( nByte>iLimit ){
46052     return SQLITE_TOOBIG;
46053   }
46054
46055   pMem->n = nByte;
46056   pMem->flags = flags;
46057   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
46058   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
46059
46060 #ifndef SQLITE_OMIT_UTF16
46061   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
46062     return SQLITE_NOMEM;
46063   }
46064 #endif
46065
46066   return SQLITE_OK;
46067 }
46068
46069 /*
46070 ** Compare the values contained by the two memory cells, returning
46071 ** negative, zero or positive if pMem1 is less than, equal to, or greater
46072 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
46073 ** and reals) sorted numerically, followed by text ordered by the collating
46074 ** sequence pColl and finally blob's ordered by memcmp().
46075 **
46076 ** Two NULL values are considered equal by this function.
46077 */
46078 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
46079   int rc;
46080   int f1, f2;
46081   int combined_flags;
46082
46083   /* Interchange pMem1 and pMem2 if the collating sequence specifies
46084   ** DESC order.
46085   */
46086   f1 = pMem1->flags;
46087   f2 = pMem2->flags;
46088   combined_flags = f1|f2;
46089   assert( (combined_flags & MEM_RowSet)==0 );
46090  
46091   /* If one value is NULL, it is less than the other. If both values
46092   ** are NULL, return 0.
46093   */
46094   if( combined_flags&MEM_Null ){
46095     return (f2&MEM_Null) - (f1&MEM_Null);
46096   }
46097
46098   /* If one value is a number and the other is not, the number is less.
46099   ** If both are numbers, compare as reals if one is a real, or as integers
46100   ** if both values are integers.
46101   */
46102   if( combined_flags&(MEM_Int|MEM_Real) ){
46103     if( !(f1&(MEM_Int|MEM_Real)) ){
46104       return 1;
46105     }
46106     if( !(f2&(MEM_Int|MEM_Real)) ){
46107       return -1;
46108     }
46109     if( (f1 & f2 & MEM_Int)==0 ){
46110       double r1, r2;
46111       if( (f1&MEM_Real)==0 ){
46112         r1 = (double)pMem1->u.i;
46113       }else{
46114         r1 = pMem1->r;
46115       }
46116       if( (f2&MEM_Real)==0 ){
46117         r2 = (double)pMem2->u.i;
46118       }else{
46119         r2 = pMem2->r;
46120       }
46121       if( r1<r2 ) return -1;
46122       if( r1>r2 ) return 1;
46123       return 0;
46124     }else{
46125       assert( f1&MEM_Int );
46126       assert( f2&MEM_Int );
46127       if( pMem1->u.i < pMem2->u.i ) return -1;
46128       if( pMem1->u.i > pMem2->u.i ) return 1;
46129       return 0;
46130     }
46131   }
46132
46133   /* If one value is a string and the other is a blob, the string is less.
46134   ** If both are strings, compare using the collating functions.
46135   */
46136   if( combined_flags&MEM_Str ){
46137     if( (f1 & MEM_Str)==0 ){
46138       return 1;
46139     }
46140     if( (f2 & MEM_Str)==0 ){
46141       return -1;
46142     }
46143
46144     assert( pMem1->enc==pMem2->enc );
46145     assert( pMem1->enc==SQLITE_UTF8 || 
46146             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
46147
46148     /* The collation sequence must be defined at this point, even if
46149     ** the user deletes the collation sequence after the vdbe program is
46150     ** compiled (this was not always the case).
46151     */
46152     assert( !pColl || pColl->xCmp );
46153
46154     if( pColl ){
46155       if( pMem1->enc==pColl->enc ){
46156         /* The strings are already in the correct encoding.  Call the
46157         ** comparison function directly */
46158         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
46159       }else{
46160         const void *v1, *v2;
46161         int n1, n2;
46162         Mem c1;
46163         Mem c2;
46164         memset(&c1, 0, sizeof(c1));
46165         memset(&c2, 0, sizeof(c2));
46166         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
46167         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
46168         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
46169         n1 = v1==0 ? 0 : c1.n;
46170         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
46171         n2 = v2==0 ? 0 : c2.n;
46172         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
46173         sqlite3VdbeMemRelease(&c1);
46174         sqlite3VdbeMemRelease(&c2);
46175         return rc;
46176       }
46177     }
46178     /* If a NULL pointer was passed as the collate function, fall through
46179     ** to the blob case and use memcmp().  */
46180   }
46181  
46182   /* Both values must be blobs.  Compare using memcmp().  */
46183   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
46184   if( rc==0 ){
46185     rc = pMem1->n - pMem2->n;
46186   }
46187   return rc;
46188 }
46189
46190 /*
46191 ** Move data out of a btree key or data field and into a Mem structure.
46192 ** The data or key is taken from the entry that pCur is currently pointing
46193 ** to.  offset and amt determine what portion of the data or key to retrieve.
46194 ** key is true to get the key or false to get data.  The result is written
46195 ** into the pMem element.
46196 **
46197 ** The pMem structure is assumed to be uninitialized.  Any prior content
46198 ** is overwritten without being freed.
46199 **
46200 ** If this routine fails for any reason (malloc returns NULL or unable
46201 ** to read from the disk) then the pMem is left in an inconsistent state.
46202 */
46203 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
46204   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
46205   int offset,       /* Offset from the start of data to return bytes from. */
46206   int amt,          /* Number of bytes to return. */
46207   int key,          /* If true, retrieve from the btree key, not data. */
46208   Mem *pMem         /* OUT: Return data in this Mem structure. */
46209 ){
46210   char *zData;       /* Data from the btree layer */
46211   int available = 0; /* Number of bytes available on the local btree page */
46212   sqlite3 *db;       /* Database connection */
46213   int rc = SQLITE_OK;
46214
46215   db = sqlite3BtreeCursorDb(pCur);
46216   assert( sqlite3_mutex_held(db->mutex) );
46217   assert( (pMem->flags & MEM_RowSet)==0 );
46218   if( key ){
46219     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
46220   }else{
46221     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
46222   }
46223   assert( zData!=0 );
46224
46225   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
46226     sqlite3VdbeMemRelease(pMem);
46227     pMem->z = &zData[offset];
46228     pMem->flags = MEM_Blob|MEM_Ephem;
46229   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
46230     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
46231     pMem->enc = 0;
46232     pMem->type = SQLITE_BLOB;
46233     if( key ){
46234       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
46235     }else{
46236       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
46237     }
46238     pMem->z[amt] = 0;
46239     pMem->z[amt+1] = 0;
46240     if( rc!=SQLITE_OK ){
46241       sqlite3VdbeMemRelease(pMem);
46242     }
46243   }
46244   pMem->n = amt;
46245
46246   return rc;
46247 }
46248
46249 /* This function is only available internally, it is not part of the
46250 ** external API. It works in a similar way to sqlite3_value_text(),
46251 ** except the data returned is in the encoding specified by the second
46252 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
46253 ** SQLITE_UTF8.
46254 **
46255 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
46256 ** If that is the case, then the result must be aligned on an even byte
46257 ** boundary.
46258 */
46259 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
46260   if( !pVal ) return 0;
46261
46262   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
46263   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
46264   assert( (pVal->flags & MEM_RowSet)==0 );
46265
46266   if( pVal->flags&MEM_Null ){
46267     return 0;
46268   }
46269   assert( (MEM_Blob>>3) == MEM_Str );
46270   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
46271   expandBlob(pVal);
46272   if( pVal->flags&MEM_Str ){
46273     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
46274     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
46275       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
46276       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
46277         return 0;
46278       }
46279     }
46280     sqlite3VdbeMemNulTerminate(pVal);
46281   }else{
46282     assert( (pVal->flags&MEM_Blob)==0 );
46283     sqlite3VdbeMemStringify(pVal, enc);
46284     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
46285   }
46286   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
46287               || pVal->db->mallocFailed );
46288   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
46289     return pVal->z;
46290   }else{
46291     return 0;
46292   }
46293 }
46294
46295 /*
46296 ** Create a new sqlite3_value object.
46297 */
46298 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
46299   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
46300   if( p ){
46301     p->flags = MEM_Null;
46302     p->type = SQLITE_NULL;
46303     p->db = db;
46304   }
46305   return p;
46306 }
46307
46308 /*
46309 ** Create a new sqlite3_value object, containing the value of pExpr.
46310 **
46311 ** This only works for very simple expressions that consist of one constant
46312 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
46313 ** be converted directly into a value, then the value is allocated and
46314 ** a pointer written to *ppVal. The caller is responsible for deallocating
46315 ** the value by passing it to sqlite3ValueFree() later on. If the expression
46316 ** cannot be converted to a value, then *ppVal is set to NULL.
46317 */
46318 SQLITE_PRIVATE int sqlite3ValueFromExpr(
46319   sqlite3 *db,              /* The database connection */
46320   Expr *pExpr,              /* The expression to evaluate */
46321   u8 enc,                   /* Encoding to use */
46322   u8 affinity,              /* Affinity to use */
46323   sqlite3_value **ppVal     /* Write the new value here */
46324 ){
46325   int op;
46326   char *zVal = 0;
46327   sqlite3_value *pVal = 0;
46328
46329   if( !pExpr ){
46330     *ppVal = 0;
46331     return SQLITE_OK;
46332   }
46333   op = pExpr->op;
46334
46335   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
46336     zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
46337     pVal = sqlite3ValueNew(db);
46338     if( !zVal || !pVal ) goto no_mem;
46339     sqlite3Dequote(zVal);
46340     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
46341     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
46342       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
46343     }else{
46344       sqlite3ValueApplyAffinity(pVal, affinity, enc);
46345     }
46346   }else if( op==TK_UMINUS ) {
46347     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
46348       pVal->u.i = -1 * pVal->u.i;
46349       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
46350       pVal->r = (double)-1 * pVal->r;
46351     }
46352   }
46353 #ifndef SQLITE_OMIT_BLOB_LITERAL
46354   else if( op==TK_BLOB ){
46355     int nVal;
46356     assert( pExpr->token.n>=3 );
46357     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
46358     assert( pExpr->token.z[1]=='\'' );
46359     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
46360     pVal = sqlite3ValueNew(db);
46361     if( !pVal ) goto no_mem;
46362     nVal = pExpr->token.n - 3;
46363     zVal = (char*)pExpr->token.z + 2;
46364     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
46365                          0, SQLITE_DYNAMIC);
46366   }
46367 #endif
46368
46369   *ppVal = pVal;
46370   return SQLITE_OK;
46371
46372 no_mem:
46373   db->mallocFailed = 1;
46374   sqlite3DbFree(db, zVal);
46375   sqlite3ValueFree(pVal);
46376   *ppVal = 0;
46377   return SQLITE_NOMEM;
46378 }
46379
46380 /*
46381 ** Change the string value of an sqlite3_value object
46382 */
46383 SQLITE_PRIVATE void sqlite3ValueSetStr(
46384   sqlite3_value *v,     /* Value to be set */
46385   int n,                /* Length of string z */
46386   const void *z,        /* Text of the new string */
46387   u8 enc,               /* Encoding to use */
46388   void (*xDel)(void*)   /* Destructor for the string */
46389 ){
46390   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
46391 }
46392
46393 /*
46394 ** Free an sqlite3_value object
46395 */
46396 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
46397   if( !v ) return;
46398   sqlite3VdbeMemRelease((Mem *)v);
46399   sqlite3DbFree(((Mem*)v)->db, v);
46400 }
46401
46402 /*
46403 ** Return the number of bytes in the sqlite3_value object assuming
46404 ** that it uses the encoding "enc"
46405 */
46406 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
46407   Mem *p = (Mem*)pVal;
46408   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
46409     if( p->flags & MEM_Zero ){
46410       return p->n + p->u.nZero;
46411     }else{
46412       return p->n;
46413     }
46414   }
46415   return 0;
46416 }
46417
46418 /************** End of vdbemem.c *********************************************/
46419 /************** Begin file vdbeaux.c *****************************************/
46420 /*
46421 ** 2003 September 6
46422 **
46423 ** The author disclaims copyright to this source code.  In place of
46424 ** a legal notice, here is a blessing:
46425 **
46426 **    May you do good and not evil.
46427 **    May you find forgiveness for yourself and forgive others.
46428 **    May you share freely, never taking more than you give.
46429 **
46430 *************************************************************************
46431 ** This file contains code used for creating, destroying, and populating
46432 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
46433 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
46434 ** But that file was getting too big so this subroutines were split out.
46435 **
46436 ** $Id: vdbeaux.c,v 1.435 2009/02/03 16:51:25 danielk1977 Exp $
46437 */
46438
46439
46440
46441 /*
46442 ** When debugging the code generator in a symbolic debugger, one can
46443 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
46444 ** as they are added to the instruction stream.
46445 */
46446 #ifdef SQLITE_DEBUG
46447 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
46448 #endif
46449
46450
46451 /*
46452 ** Create a new virtual database engine.
46453 */
46454 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
46455   Vdbe *p;
46456   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
46457   if( p==0 ) return 0;
46458   p->db = db;
46459   if( db->pVdbe ){
46460     db->pVdbe->pPrev = p;
46461   }
46462   p->pNext = db->pVdbe;
46463   p->pPrev = 0;
46464   db->pVdbe = p;
46465   p->magic = VDBE_MAGIC_INIT;
46466   return p;
46467 }
46468
46469 /*
46470 ** Remember the SQL string for a prepared statement.
46471 */
46472 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
46473   if( p==0 ) return;
46474   assert( p->zSql==0 );
46475   p->zSql = sqlite3DbStrNDup(p->db, z, n);
46476 }
46477
46478 /*
46479 ** Return the SQL associated with a prepared statement
46480 */
46481 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
46482   return ((Vdbe *)pStmt)->zSql;
46483 }
46484
46485 /*
46486 ** Swap all content between two VDBE structures.
46487 */
46488 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
46489   Vdbe tmp, *pTmp;
46490   char *zTmp;
46491   int nTmp;
46492   tmp = *pA;
46493   *pA = *pB;
46494   *pB = tmp;
46495   pTmp = pA->pNext;
46496   pA->pNext = pB->pNext;
46497   pB->pNext = pTmp;
46498   pTmp = pA->pPrev;
46499   pA->pPrev = pB->pPrev;
46500   pB->pPrev = pTmp;
46501   zTmp = pA->zSql;
46502   pA->zSql = pB->zSql;
46503   pB->zSql = zTmp;
46504   nTmp = pA->nSql;
46505   pA->nSql = pB->nSql;
46506   pB->nSql = nTmp;
46507 }
46508
46509 #ifdef SQLITE_DEBUG
46510 /*
46511 ** Turn tracing on or off
46512 */
46513 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
46514   p->trace = trace;
46515 }
46516 #endif
46517
46518 /*
46519 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
46520 ** it was.
46521 **
46522 ** If an out-of-memory error occurs while resizing the array, return
46523 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
46524 ** unchanged (this is so that any opcodes already allocated can be 
46525 ** correctly deallocated along with the rest of the Vdbe).
46526 */
46527 static int growOpArray(Vdbe *p){
46528   VdbeOp *pNew;
46529   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
46530   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
46531   if( pNew ){
46532     p->nOpAlloc = nNew;
46533     p->aOp = pNew;
46534   }
46535   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
46536 }
46537
46538 /*
46539 ** Add a new instruction to the list of instructions current in the
46540 ** VDBE.  Return the address of the new instruction.
46541 **
46542 ** Parameters:
46543 **
46544 **    p               Pointer to the VDBE
46545 **
46546 **    op              The opcode for this instruction
46547 **
46548 **    p1, p2, p3      Operands
46549 **
46550 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
46551 ** the sqlite3VdbeChangeP4() function to change the value of the P4
46552 ** operand.
46553 */
46554 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
46555   int i;
46556   VdbeOp *pOp;
46557
46558   i = p->nOp;
46559   assert( p->magic==VDBE_MAGIC_INIT );
46560   assert( op>0 && op<0xff );
46561   if( p->nOpAlloc<=i ){
46562     if( growOpArray(p) ){
46563       return 0;
46564     }
46565   }
46566   p->nOp++;
46567   pOp = &p->aOp[i];
46568   pOp->opcode = (u8)op;
46569   pOp->p5 = 0;
46570   pOp->p1 = p1;
46571   pOp->p2 = p2;
46572   pOp->p3 = p3;
46573   pOp->p4.p = 0;
46574   pOp->p4type = P4_NOTUSED;
46575   p->expired = 0;
46576 #ifdef SQLITE_DEBUG
46577   pOp->zComment = 0;
46578   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
46579 #endif
46580 #ifdef VDBE_PROFILE
46581   pOp->cycles = 0;
46582   pOp->cnt = 0;
46583 #endif
46584   return i;
46585 }
46586 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
46587   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
46588 }
46589 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
46590   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
46591 }
46592 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
46593   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
46594 }
46595
46596
46597 /*
46598 ** Add an opcode that includes the p4 value as a pointer.
46599 */
46600 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
46601   Vdbe *p,            /* Add the opcode to this VM */
46602   int op,             /* The new opcode */
46603   int p1,             /* The P1 operand */
46604   int p2,             /* The P2 operand */
46605   int p3,             /* The P3 operand */
46606   const char *zP4,    /* The P4 operand */
46607   int p4type          /* P4 operand type */
46608 ){
46609   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
46610   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
46611   return addr;
46612 }
46613
46614 /*
46615 ** Create a new symbolic label for an instruction that has yet to be
46616 ** coded.  The symbolic label is really just a negative number.  The
46617 ** label can be used as the P2 value of an operation.  Later, when
46618 ** the label is resolved to a specific address, the VDBE will scan
46619 ** through its operation list and change all values of P2 which match
46620 ** the label into the resolved address.
46621 **
46622 ** The VDBE knows that a P2 value is a label because labels are
46623 ** always negative and P2 values are suppose to be non-negative.
46624 ** Hence, a negative P2 value is a label that has yet to be resolved.
46625 **
46626 ** Zero is returned if a malloc() fails.
46627 */
46628 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
46629   int i;
46630   i = p->nLabel++;
46631   assert( p->magic==VDBE_MAGIC_INIT );
46632   if( i>=p->nLabelAlloc ){
46633     int n = p->nLabelAlloc*2 + 5;
46634     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
46635                                        n*sizeof(p->aLabel[0]));
46636     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
46637   }
46638   if( p->aLabel ){
46639     p->aLabel[i] = -1;
46640   }
46641   return -1-i;
46642 }
46643
46644 /*
46645 ** Resolve label "x" to be the address of the next instruction to
46646 ** be inserted.  The parameter "x" must have been obtained from
46647 ** a prior call to sqlite3VdbeMakeLabel().
46648 */
46649 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
46650   int j = -1-x;
46651   assert( p->magic==VDBE_MAGIC_INIT );
46652   assert( j>=0 && j<p->nLabel );
46653   if( p->aLabel ){
46654     p->aLabel[j] = p->nOp;
46655   }
46656 }
46657
46658 /*
46659 ** Loop through the program looking for P2 values that are negative
46660 ** on jump instructions.  Each such value is a label.  Resolve the
46661 ** label by setting the P2 value to its correct non-zero value.
46662 **
46663 ** This routine is called once after all opcodes have been inserted.
46664 **
46665 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
46666 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
46667 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
46668 **
46669 ** This routine also does the following optimization:  It scans for
46670 ** instructions that might cause a statement rollback.  Such instructions
46671 ** are:
46672 **
46673 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
46674 **   *  OP_Destroy
46675 **   *  OP_VUpdate
46676 **   *  OP_VRename
46677 **
46678 ** If no such instruction is found, then every Statement instruction 
46679 ** is changed to a Noop.  In this way, we avoid creating the statement 
46680 ** journal file unnecessarily.
46681 */
46682 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
46683   int i;
46684   int nMaxArgs = 0;
46685   Op *pOp;
46686   int *aLabel = p->aLabel;
46687   int doesStatementRollback = 0;
46688   int hasStatementBegin = 0;
46689   p->readOnly = 1;
46690   p->usesStmtJournal = 0;
46691   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
46692     u8 opcode = pOp->opcode;
46693
46694     if( opcode==OP_Function || opcode==OP_AggStep ){
46695       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
46696 #ifndef SQLITE_OMIT_VIRTUALTABLE
46697     }else if( opcode==OP_VUpdate ){
46698       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
46699 #endif
46700     }
46701     if( opcode==OP_Halt ){
46702       if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
46703         doesStatementRollback = 1;
46704       }
46705     }else if( opcode==OP_Statement ){
46706       hasStatementBegin = 1;
46707       p->usesStmtJournal = 1;
46708     }else if( opcode==OP_Destroy ){
46709       doesStatementRollback = 1;
46710     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
46711       p->readOnly = 0;
46712 #ifndef SQLITE_OMIT_VIRTUALTABLE
46713     }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
46714       doesStatementRollback = 1;
46715     }else if( opcode==OP_VFilter ){
46716       int n;
46717       assert( p->nOp - i >= 3 );
46718       assert( pOp[-1].opcode==OP_Integer );
46719       n = pOp[-1].p1;
46720       if( n>nMaxArgs ) nMaxArgs = n;
46721 #endif
46722     }
46723
46724     if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){
46725       assert( -1-pOp->p2<p->nLabel );
46726       pOp->p2 = aLabel[-1-pOp->p2];
46727     }
46728   }
46729   sqlite3DbFree(p->db, p->aLabel);
46730   p->aLabel = 0;
46731
46732   *pMaxFuncArgs = nMaxArgs;
46733
46734   /* If we never rollback a statement transaction, then statement
46735   ** transactions are not needed.  So change every OP_Statement
46736   ** opcode into an OP_Noop.  This avoid a call to sqlite3OsOpenExclusive()
46737   ** which can be expensive on some platforms.
46738   */
46739   if( hasStatementBegin && !doesStatementRollback ){
46740     p->usesStmtJournal = 0;
46741     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
46742       if( pOp->opcode==OP_Statement ){
46743         pOp->opcode = OP_Noop;
46744       }
46745     }
46746   }
46747 }
46748
46749 /*
46750 ** Return the address of the next instruction to be inserted.
46751 */
46752 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
46753   assert( p->magic==VDBE_MAGIC_INIT );
46754   return p->nOp;
46755 }
46756
46757 /*
46758 ** Add a whole list of operations to the operation stack.  Return the
46759 ** address of the first operation added.
46760 */
46761 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
46762   int addr;
46763   assert( p->magic==VDBE_MAGIC_INIT );
46764   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
46765     return 0;
46766   }
46767   addr = p->nOp;
46768   if( nOp>0 ){
46769     int i;
46770     VdbeOpList const *pIn = aOp;
46771     for(i=0; i<nOp; i++, pIn++){
46772       int p2 = pIn->p2;
46773       VdbeOp *pOut = &p->aOp[i+addr];
46774       pOut->opcode = pIn->opcode;
46775       pOut->p1 = pIn->p1;
46776       if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){
46777         pOut->p2 = addr + ADDR(p2);
46778       }else{
46779         pOut->p2 = p2;
46780       }
46781       pOut->p3 = pIn->p3;
46782       pOut->p4type = P4_NOTUSED;
46783       pOut->p4.p = 0;
46784       pOut->p5 = 0;
46785 #ifdef SQLITE_DEBUG
46786       pOut->zComment = 0;
46787       if( sqlite3VdbeAddopTrace ){
46788         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
46789       }
46790 #endif
46791     }
46792     p->nOp += nOp;
46793   }
46794   return addr;
46795 }
46796
46797 /*
46798 ** Change the value of the P1 operand for a specific instruction.
46799 ** This routine is useful when a large program is loaded from a
46800 ** static array using sqlite3VdbeAddOpList but we want to make a
46801 ** few minor changes to the program.
46802 */
46803 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
46804   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
46805   if( p && addr>=0 && p->nOp>addr && p->aOp ){
46806     p->aOp[addr].p1 = val;
46807   }
46808 }
46809
46810 /*
46811 ** Change the value of the P2 operand for a specific instruction.
46812 ** This routine is useful for setting a jump destination.
46813 */
46814 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
46815   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
46816   if( p && addr>=0 && p->nOp>addr && p->aOp ){
46817     p->aOp[addr].p2 = val;
46818   }
46819 }
46820
46821 /*
46822 ** Change the value of the P3 operand for a specific instruction.
46823 */
46824 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
46825   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
46826   if( p && addr>=0 && p->nOp>addr && p->aOp ){
46827     p->aOp[addr].p3 = val;
46828   }
46829 }
46830
46831 /*
46832 ** Change the value of the P5 operand for the most recently
46833 ** added operation.
46834 */
46835 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
46836   assert( p==0 || p->magic==VDBE_MAGIC_INIT );
46837   if( p && p->aOp ){
46838     assert( p->nOp>0 );
46839     p->aOp[p->nOp-1].p5 = val;
46840   }
46841 }
46842
46843 /*
46844 ** Change the P2 operand of instruction addr so that it points to
46845 ** the address of the next instruction to be coded.
46846 */
46847 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
46848   sqlite3VdbeChangeP2(p, addr, p->nOp);
46849 }
46850
46851
46852 /*
46853 ** If the input FuncDef structure is ephemeral, then free it.  If
46854 ** the FuncDef is not ephermal, then do nothing.
46855 */
46856 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
46857   if( pDef && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
46858     sqlite3DbFree(db, pDef);
46859   }
46860 }
46861
46862 /*
46863 ** Delete a P4 value if necessary.
46864 */
46865 static void freeP4(sqlite3 *db, int p4type, void *p4){
46866   if( p4 ){
46867     switch( p4type ){
46868       case P4_REAL:
46869       case P4_INT64:
46870       case P4_MPRINTF:
46871       case P4_DYNAMIC:
46872       case P4_KEYINFO:
46873       case P4_INTARRAY:
46874       case P4_KEYINFO_HANDOFF: {
46875         sqlite3DbFree(db, p4);
46876         break;
46877       }
46878       case P4_VDBEFUNC: {
46879         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
46880         freeEphemeralFunction(db, pVdbeFunc->pFunc);
46881         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
46882         sqlite3DbFree(db, pVdbeFunc);
46883         break;
46884       }
46885       case P4_FUNCDEF: {
46886         freeEphemeralFunction(db, (FuncDef*)p4);
46887         break;
46888       }
46889       case P4_MEM: {
46890         sqlite3ValueFree((sqlite3_value*)p4);
46891         break;
46892       }
46893     }
46894   }
46895 }
46896
46897
46898 /*
46899 ** Change N opcodes starting at addr to No-ops.
46900 */
46901 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
46902   if( p && p->aOp ){
46903     VdbeOp *pOp = &p->aOp[addr];
46904     sqlite3 *db = p->db;
46905     while( N-- ){
46906       freeP4(db, pOp->p4type, pOp->p4.p);
46907       memset(pOp, 0, sizeof(pOp[0]));
46908       pOp->opcode = OP_Noop;
46909       pOp++;
46910     }
46911   }
46912 }
46913
46914 /*
46915 ** Change the value of the P4 operand for a specific instruction.
46916 ** This routine is useful when a large program is loaded from a
46917 ** static array using sqlite3VdbeAddOpList but we want to make a
46918 ** few minor changes to the program.
46919 **
46920 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
46921 ** the string is made into memory obtained from sqlite3_malloc().
46922 ** A value of n==0 means copy bytes of zP4 up to and including the
46923 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
46924 **
46925 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
46926 ** A copy is made of the KeyInfo structure into memory obtained from
46927 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
46928 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
46929 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
46930 ** caller should not free the allocation, it will be freed when the Vdbe is
46931 ** finalized.
46932 ** 
46933 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
46934 ** to a string or structure that is guaranteed to exist for the lifetime of
46935 ** the Vdbe. In these cases we can just copy the pointer.
46936 **
46937 ** If addr<0 then change P4 on the most recently inserted instruction.
46938 */
46939 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
46940   Op *pOp;
46941   sqlite3 *db;
46942   assert( p!=0 );
46943   db = p->db;
46944   assert( p->magic==VDBE_MAGIC_INIT );
46945   if( p->aOp==0 || db->mallocFailed ){
46946     if (n != P4_KEYINFO) {
46947       freeP4(db, n, (void*)*(char**)&zP4);
46948     }
46949     return;
46950   }
46951   assert( addr<p->nOp );
46952   if( addr<0 ){
46953     addr = p->nOp - 1;
46954     if( addr<0 ) return;
46955   }
46956   pOp = &p->aOp[addr];
46957   freeP4(db, pOp->p4type, pOp->p4.p);
46958   pOp->p4.p = 0;
46959   if( n==P4_INT32 ){
46960     /* Note: this cast is safe, because the origin data point was an int
46961     ** that was cast to a (const char *). */
46962     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
46963     pOp->p4type = P4_INT32;
46964   }else if( zP4==0 ){
46965     pOp->p4.p = 0;
46966     pOp->p4type = P4_NOTUSED;
46967   }else if( n==P4_KEYINFO ){
46968     KeyInfo *pKeyInfo;
46969     int nField, nByte;
46970
46971     nField = ((KeyInfo*)zP4)->nField;
46972     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
46973     pKeyInfo = sqlite3Malloc( nByte );
46974     pOp->p4.pKeyInfo = pKeyInfo;
46975     if( pKeyInfo ){
46976       u8 *aSortOrder;
46977       memcpy(pKeyInfo, zP4, nByte);
46978       aSortOrder = pKeyInfo->aSortOrder;
46979       if( aSortOrder ){
46980         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
46981         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
46982       }
46983       pOp->p4type = P4_KEYINFO;
46984     }else{
46985       p->db->mallocFailed = 1;
46986       pOp->p4type = P4_NOTUSED;
46987     }
46988   }else if( n==P4_KEYINFO_HANDOFF ){
46989     pOp->p4.p = (void*)zP4;
46990     pOp->p4type = P4_KEYINFO;
46991   }else if( n<0 ){
46992     pOp->p4.p = (void*)zP4;
46993     pOp->p4type = (signed char)n;
46994   }else{
46995     if( n==0 ) n = sqlite3Strlen30(zP4);
46996     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
46997     pOp->p4type = P4_DYNAMIC;
46998   }
46999 }
47000
47001 #ifndef NDEBUG
47002 /*
47003 ** Change the comment on the the most recently coded instruction.  Or
47004 ** insert a No-op and add the comment to that new instruction.  This
47005 ** makes the code easier to read during debugging.  None of this happens
47006 ** in a production build.
47007 */
47008 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
47009   va_list ap;
47010   assert( p->nOp>0 || p->aOp==0 );
47011   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47012   if( p->nOp ){
47013     char **pz = &p->aOp[p->nOp-1].zComment;
47014     va_start(ap, zFormat);
47015     sqlite3DbFree(p->db, *pz);
47016     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47017     va_end(ap);
47018   }
47019 }
47020 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
47021   va_list ap;
47022   sqlite3VdbeAddOp0(p, OP_Noop);
47023   assert( p->nOp>0 || p->aOp==0 );
47024   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47025   if( p->nOp ){
47026     char **pz = &p->aOp[p->nOp-1].zComment;
47027     va_start(ap, zFormat);
47028     sqlite3DbFree(p->db, *pz);
47029     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47030     va_end(ap);
47031   }
47032 }
47033 #endif  /* NDEBUG */
47034
47035 /*
47036 ** Return the opcode for a given address.
47037 */
47038 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
47039   assert( p->magic==VDBE_MAGIC_INIT );
47040   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
47041   return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
47042 }
47043
47044 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
47045      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
47046 /*
47047 ** Compute a string that describes the P4 parameter for an opcode.
47048 ** Use zTemp for any required temporary buffer space.
47049 */
47050 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
47051   char *zP4 = zTemp;
47052   assert( nTemp>=20 );
47053   switch( pOp->p4type ){
47054     case P4_KEYINFO_STATIC:
47055     case P4_KEYINFO: {
47056       int i, j;
47057       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
47058       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
47059       i = sqlite3Strlen30(zTemp);
47060       for(j=0; j<pKeyInfo->nField; j++){
47061         CollSeq *pColl = pKeyInfo->aColl[j];
47062         if( pColl ){
47063           int n = sqlite3Strlen30(pColl->zName);
47064           if( i+n>nTemp-6 ){
47065             memcpy(&zTemp[i],",...",4);
47066             break;
47067           }
47068           zTemp[i++] = ',';
47069           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
47070             zTemp[i++] = '-';
47071           }
47072           memcpy(&zTemp[i], pColl->zName,n+1);
47073           i += n;
47074         }else if( i+4<nTemp-6 ){
47075           memcpy(&zTemp[i],",nil",4);
47076           i += 4;
47077         }
47078       }
47079       zTemp[i++] = ')';
47080       zTemp[i] = 0;
47081       assert( i<nTemp );
47082       break;
47083     }
47084     case P4_COLLSEQ: {
47085       CollSeq *pColl = pOp->p4.pColl;
47086       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
47087       break;
47088     }
47089     case P4_FUNCDEF: {
47090       FuncDef *pDef = pOp->p4.pFunc;
47091       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
47092       break;
47093     }
47094     case P4_INT64: {
47095       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
47096       break;
47097     }
47098     case P4_INT32: {
47099       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
47100       break;
47101     }
47102     case P4_REAL: {
47103       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
47104       break;
47105     }
47106     case P4_MEM: {
47107       Mem *pMem = pOp->p4.pMem;
47108       assert( (pMem->flags & MEM_Null)==0 );
47109       if( pMem->flags & MEM_Str ){
47110         zP4 = pMem->z;
47111       }else if( pMem->flags & MEM_Int ){
47112         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
47113       }else if( pMem->flags & MEM_Real ){
47114         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
47115       }
47116       break;
47117     }
47118 #ifndef SQLITE_OMIT_VIRTUALTABLE
47119     case P4_VTAB: {
47120       sqlite3_vtab *pVtab = pOp->p4.pVtab;
47121       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
47122       break;
47123     }
47124 #endif
47125     case P4_INTARRAY: {
47126       sqlite3_snprintf(nTemp, zTemp, "intarray");
47127       break;
47128     }
47129     default: {
47130       zP4 = pOp->p4.z;
47131       if( zP4==0 ){
47132         zP4 = zTemp;
47133         zTemp[0] = 0;
47134       }
47135     }
47136   }
47137   assert( zP4!=0 );
47138   return zP4;
47139 }
47140 #endif
47141
47142 /*
47143 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
47144 **
47145 */
47146 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
47147   int mask;
47148   assert( i>=0 && i<p->db->nDb );
47149   assert( i<(int)sizeof(p->btreeMask)*8 );
47150   mask = 1<<i;
47151   if( (p->btreeMask & mask)==0 ){
47152     p->btreeMask |= mask;
47153     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
47154   }
47155 }
47156
47157
47158 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
47159 /*
47160 ** Print a single opcode.  This routine is used for debugging only.
47161 */
47162 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
47163   char *zP4;
47164   char zPtr[50];
47165   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
47166   if( pOut==0 ) pOut = stdout;
47167   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
47168   fprintf(pOut, zFormat1, pc, 
47169       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
47170 #ifdef SQLITE_DEBUG
47171       pOp->zComment ? pOp->zComment : ""
47172 #else
47173       ""
47174 #endif
47175   );
47176   fflush(pOut);
47177 }
47178 #endif
47179
47180 /*
47181 ** Release an array of N Mem elements
47182 */
47183 static void releaseMemArray(Mem *p, int N){
47184   if( p && N ){
47185     Mem *pEnd;
47186     sqlite3 *db = p->db;
47187     u8 malloc_failed = db->mallocFailed;
47188     for(pEnd=&p[N]; p<pEnd; p++){
47189       assert( (&p[1])==pEnd || p[0].db==p[1].db );
47190
47191       /* This block is really an inlined version of sqlite3VdbeMemRelease()
47192       ** that takes advantage of the fact that the memory cell value is 
47193       ** being set to NULL after releasing any dynamic resources.
47194       **
47195       ** The justification for duplicating code is that according to 
47196       ** callgrind, this causes a certain test case to hit the CPU 4.7 
47197       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
47198       ** sqlite3MemRelease() were called from here. With -O2, this jumps
47199       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
47200       ** with no indexes using a single prepared INSERT statement, bind() 
47201       ** and reset(). Inserts are grouped into a transaction.
47202       */
47203       if( p->flags&(MEM_Agg|MEM_Dyn) ){
47204         sqlite3VdbeMemRelease(p);
47205       }else if( p->zMalloc ){
47206         sqlite3DbFree(db, p->zMalloc);
47207         p->zMalloc = 0;
47208       }
47209
47210       p->flags = MEM_Null;
47211     }
47212     db->mallocFailed = malloc_failed;
47213   }
47214 }
47215
47216 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
47217 SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p){
47218   int ii;
47219   int nFree = 0;
47220   assert( sqlite3_mutex_held(p->db->mutex) );
47221   for(ii=1; ii<=p->nMem; ii++){
47222     Mem *pMem = &p->aMem[ii];
47223     if( pMem->flags & MEM_RowSet ){
47224       sqlite3RowSetClear(pMem->u.pRowSet);
47225     }
47226     if( pMem->z && pMem->flags&MEM_Dyn ){
47227       assert( !pMem->xDel );
47228       nFree += sqlite3DbMallocSize(pMem->db, pMem->z);
47229       sqlite3VdbeMemRelease(pMem);
47230     }
47231   }
47232   return nFree;
47233 }
47234 #endif
47235
47236 #ifndef SQLITE_OMIT_EXPLAIN
47237 /*
47238 ** Give a listing of the program in the virtual machine.
47239 **
47240 ** The interface is the same as sqlite3VdbeExec().  But instead of
47241 ** running the code, it invokes the callback once for each instruction.
47242 ** This feature is used to implement "EXPLAIN".
47243 **
47244 ** When p->explain==1, each instruction is listed.  When
47245 ** p->explain==2, only OP_Explain instructions are listed and these
47246 ** are shown in a different format.  p->explain==2 is used to implement
47247 ** EXPLAIN QUERY PLAN.
47248 */
47249 SQLITE_PRIVATE int sqlite3VdbeList(
47250   Vdbe *p                   /* The VDBE */
47251 ){
47252   sqlite3 *db = p->db;
47253   int i;
47254   int rc = SQLITE_OK;
47255   Mem *pMem = p->pResultSet = &p->aMem[1];
47256
47257   assert( p->explain );
47258   if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
47259   assert( db->magic==SQLITE_MAGIC_BUSY );
47260   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
47261
47262   /* Even though this opcode does not use dynamic strings for
47263   ** the result, result columns may become dynamic if the user calls
47264   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
47265   */
47266   releaseMemArray(pMem, p->nMem);
47267
47268   if( p->rc==SQLITE_NOMEM ){
47269     /* This happens if a malloc() inside a call to sqlite3_column_text() or
47270     ** sqlite3_column_text16() failed.  */
47271     db->mallocFailed = 1;
47272     return SQLITE_ERROR;
47273   }
47274
47275   do{
47276     i = p->pc++;
47277   }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
47278   if( i>=p->nOp ){
47279     p->rc = SQLITE_OK;
47280     rc = SQLITE_DONE;
47281   }else if( db->u1.isInterrupted ){
47282     p->rc = SQLITE_INTERRUPT;
47283     rc = SQLITE_ERROR;
47284     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
47285   }else{
47286     char *z;
47287     Op *pOp = &p->aOp[i];
47288     if( p->explain==1 ){
47289       pMem->flags = MEM_Int;
47290       pMem->type = SQLITE_INTEGER;
47291       pMem->u.i = i;                                /* Program counter */
47292       pMem++;
47293   
47294       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
47295       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
47296       assert( pMem->z!=0 );
47297       pMem->n = sqlite3Strlen30(pMem->z);
47298       pMem->type = SQLITE_TEXT;
47299       pMem->enc = SQLITE_UTF8;
47300       pMem++;
47301     }
47302
47303     pMem->flags = MEM_Int;
47304     pMem->u.i = pOp->p1;                          /* P1 */
47305     pMem->type = SQLITE_INTEGER;
47306     pMem++;
47307
47308     pMem->flags = MEM_Int;
47309     pMem->u.i = pOp->p2;                          /* P2 */
47310     pMem->type = SQLITE_INTEGER;
47311     pMem++;
47312
47313     if( p->explain==1 ){
47314       pMem->flags = MEM_Int;
47315       pMem->u.i = pOp->p3;                          /* P3 */
47316       pMem->type = SQLITE_INTEGER;
47317       pMem++;
47318     }
47319
47320     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
47321       p->db->mallocFailed = 1;
47322       return SQLITE_NOMEM;
47323     }
47324     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
47325     z = displayP4(pOp, pMem->z, 32);
47326     if( z!=pMem->z ){
47327       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
47328     }else{
47329       assert( pMem->z!=0 );
47330       pMem->n = sqlite3Strlen30(pMem->z);
47331       pMem->enc = SQLITE_UTF8;
47332     }
47333     pMem->type = SQLITE_TEXT;
47334     pMem++;
47335
47336     if( p->explain==1 ){
47337       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
47338         p->db->mallocFailed = 1;
47339         return SQLITE_NOMEM;
47340       }
47341       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
47342       pMem->n = 2;
47343       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
47344       pMem->type = SQLITE_TEXT;
47345       pMem->enc = SQLITE_UTF8;
47346       pMem++;
47347   
47348 #ifdef SQLITE_DEBUG
47349       if( pOp->zComment ){
47350         pMem->flags = MEM_Str|MEM_Term;
47351         pMem->z = pOp->zComment;
47352         pMem->n = sqlite3Strlen30(pMem->z);
47353         pMem->enc = SQLITE_UTF8;
47354         pMem->type = SQLITE_TEXT;
47355       }else
47356 #endif
47357       {
47358         pMem->flags = MEM_Null;                       /* Comment */
47359         pMem->type = SQLITE_NULL;
47360       }
47361     }
47362
47363     p->nResColumn = 8 - 5*(p->explain-1);
47364     p->rc = SQLITE_OK;
47365     rc = SQLITE_ROW;
47366   }
47367   return rc;
47368 }
47369 #endif /* SQLITE_OMIT_EXPLAIN */
47370
47371 #ifdef SQLITE_DEBUG
47372 /*
47373 ** Print the SQL that was used to generate a VDBE program.
47374 */
47375 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
47376   int nOp = p->nOp;
47377   VdbeOp *pOp;
47378   if( nOp<1 ) return;
47379   pOp = &p->aOp[0];
47380   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
47381     const char *z = pOp->p4.z;
47382     while( sqlite3Isspace(*z) ) z++;
47383     printf("SQL: [%s]\n", z);
47384   }
47385 }
47386 #endif
47387
47388 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
47389 /*
47390 ** Print an IOTRACE message showing SQL content.
47391 */
47392 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
47393   int nOp = p->nOp;
47394   VdbeOp *pOp;
47395   if( sqlite3IoTrace==0 ) return;
47396   if( nOp<1 ) return;
47397   pOp = &p->aOp[0];
47398   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
47399     int i, j;
47400     char z[1000];
47401     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
47402     for(i=0; sqlite3Isspace(z[i]); i++){}
47403     for(j=0; z[i]; i++){
47404       if( sqlite3Isspace(z[i]) ){
47405         if( z[i-1]!=' ' ){
47406           z[j++] = ' ';
47407         }
47408       }else{
47409         z[j++] = z[i];
47410       }
47411     }
47412     z[j] = 0;
47413     sqlite3IoTrace("SQL %s\n", z);
47414   }
47415 }
47416 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
47417
47418
47419 /*
47420 ** Prepare a virtual machine for execution.  This involves things such
47421 ** as allocating stack space and initializing the program counter.
47422 ** After the VDBE has be prepped, it can be executed by one or more
47423 ** calls to sqlite3VdbeExec().  
47424 **
47425 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
47426 ** VDBE_MAGIC_RUN.
47427 */
47428 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
47429   Vdbe *p,                       /* The VDBE */
47430   int nVar,                      /* Number of '?' see in the SQL statement */
47431   int nMem,                      /* Number of memory cells to allocate */
47432   int nCursor,                   /* Number of cursors to allocate */
47433   int isExplain                  /* True if the EXPLAIN keywords is present */
47434 ){
47435   int n;
47436   sqlite3 *db = p->db;
47437
47438   assert( p!=0 );
47439   assert( p->magic==VDBE_MAGIC_INIT );
47440
47441   /* There should be at least one opcode.
47442   */
47443   assert( p->nOp>0 );
47444
47445   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
47446   p->magic = VDBE_MAGIC_RUN;
47447
47448   /* For each cursor required, also allocate a memory cell. Memory
47449   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
47450   ** the vdbe program. Instead they are used to allocate space for
47451   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
47452   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
47453   ** stores the blob of memory associated with cursor 1, etc.
47454   **
47455   ** See also: allocateCursor().
47456   */
47457   nMem += nCursor;
47458
47459   /*
47460   ** Allocation space for registers.
47461   */
47462   if( p->aMem==0 ){
47463     int nArg;       /* Maximum number of args passed to a user function. */
47464     resolveP2Values(p, &nArg);
47465     assert( nVar>=0 );
47466     if( isExplain && nMem<10 ){
47467       nMem = 10;
47468     }
47469     p->aMem = sqlite3DbMallocZero(db,
47470         nMem*sizeof(Mem)               /* aMem */
47471       + nVar*sizeof(Mem)               /* aVar */
47472       + nArg*sizeof(Mem*)              /* apArg */
47473       + nVar*sizeof(char*)             /* azVar */
47474       + nCursor*sizeof(VdbeCursor*)+1  /* apCsr */
47475     );
47476     if( !db->mallocFailed ){
47477       p->aMem--;             /* aMem[] goes from 1..nMem */
47478       p->nMem = nMem;        /*       not from 0..nMem-1 */
47479       p->aVar = &p->aMem[nMem+1];
47480       p->nVar = nVar;
47481       p->okVar = 0;
47482       p->apArg = (Mem**)&p->aVar[nVar];
47483       p->azVar = (char**)&p->apArg[nArg];
47484       p->apCsr = (VdbeCursor**)&p->azVar[nVar];
47485       p->nCursor = nCursor;
47486       for(n=0; n<nVar; n++){
47487         p->aVar[n].flags = MEM_Null;
47488         p->aVar[n].db = db;
47489       }
47490       for(n=1; n<=nMem; n++){
47491         p->aMem[n].flags = MEM_Null;
47492         p->aMem[n].db = db;
47493       }
47494     }
47495   }
47496 #ifdef SQLITE_DEBUG
47497   for(n=1; n<p->nMem; n++){
47498     assert( p->aMem[n].db==db );
47499   }
47500 #endif
47501
47502   p->pc = -1;
47503   p->rc = SQLITE_OK;
47504   p->uniqueCnt = 0;
47505   p->errorAction = OE_Abort;
47506   p->explain |= isExplain;
47507   p->magic = VDBE_MAGIC_RUN;
47508   p->nChange = 0;
47509   p->cacheCtr = 1;
47510   p->minWriteFileFormat = 255;
47511   p->openedStatement = 0;
47512 #ifdef VDBE_PROFILE
47513   {
47514     int i;
47515     for(i=0; i<p->nOp; i++){
47516       p->aOp[i].cnt = 0;
47517       p->aOp[i].cycles = 0;
47518     }
47519   }
47520 #endif
47521 }
47522
47523 /*
47524 ** Close a VDBE cursor and release all the resources that cursor 
47525 ** happens to hold.
47526 */
47527 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
47528   if( pCx==0 ){
47529     return;
47530   }
47531   if( pCx->pBt ){
47532     sqlite3BtreeClose(pCx->pBt);
47533     /* The pCx->pCursor will be close automatically, if it exists, by
47534     ** the call above. */
47535   }else if( pCx->pCursor ){
47536     sqlite3BtreeCloseCursor(pCx->pCursor);
47537   }
47538 #ifndef SQLITE_OMIT_VIRTUALTABLE
47539   if( pCx->pVtabCursor ){
47540     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
47541     const sqlite3_module *pModule = pCx->pModule;
47542     p->inVtabMethod = 1;
47543     (void)sqlite3SafetyOff(p->db);
47544     pModule->xClose(pVtabCursor);
47545     (void)sqlite3SafetyOn(p->db);
47546     p->inVtabMethod = 0;
47547   }
47548 #endif
47549   if( !pCx->ephemPseudoTable ){
47550     sqlite3DbFree(p->db, pCx->pData);
47551   }
47552 }
47553
47554 /*
47555 ** Close all cursors except for VTab cursors that are currently
47556 ** in use.
47557 */
47558 static void closeAllCursorsExceptActiveVtabs(Vdbe *p){
47559   int i;
47560   if( p->apCsr==0 ) return;
47561   for(i=0; i<p->nCursor; i++){
47562     VdbeCursor *pC = p->apCsr[i];
47563     if( pC && (!p->inVtabMethod || !pC->pVtabCursor) ){
47564       sqlite3VdbeFreeCursor(p, pC);
47565       p->apCsr[i] = 0;
47566     }
47567   }
47568 }
47569
47570 /*
47571 ** Clean up the VM after execution.
47572 **
47573 ** This routine will automatically close any cursors, lists, and/or
47574 ** sorters that were left open.  It also deletes the values of
47575 ** variables in the aVar[] array.
47576 */
47577 static void Cleanup(Vdbe *p){
47578   int i;
47579   sqlite3 *db = p->db;
47580   Mem *pMem;
47581   closeAllCursorsExceptActiveVtabs(p);
47582   for(pMem=&p->aMem[1], i=1; i<=p->nMem; i++, pMem++){
47583     if( pMem->flags & MEM_RowSet ){
47584       sqlite3RowSetClear(pMem->u.pRowSet);
47585     }
47586     MemSetTypeFlag(pMem, MEM_Null);
47587   }
47588   releaseMemArray(&p->aMem[1], p->nMem);
47589   if( p->contextStack ){
47590     sqlite3DbFree(db, p->contextStack);
47591   }
47592   p->contextStack = 0;
47593   p->contextStackDepth = 0;
47594   p->contextStackTop = 0;
47595   sqlite3DbFree(db, p->zErrMsg);
47596   p->zErrMsg = 0;
47597   p->pResultSet = 0;
47598 }
47599
47600 /*
47601 ** Set the number of result columns that will be returned by this SQL
47602 ** statement. This is now set at compile time, rather than during
47603 ** execution of the vdbe program so that sqlite3_column_count() can
47604 ** be called on an SQL statement before sqlite3_step().
47605 */
47606 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
47607   Mem *pColName;
47608   int n;
47609   sqlite3 *db = p->db;
47610
47611   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
47612   sqlite3DbFree(db, p->aColName);
47613   n = nResColumn*COLNAME_N;
47614   p->nResColumn = nResColumn;
47615   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
47616   if( p->aColName==0 ) return;
47617   while( n-- > 0 ){
47618     pColName->flags = MEM_Null;
47619     pColName->db = p->db;
47620     pColName++;
47621   }
47622 }
47623
47624 /*
47625 ** Set the name of the idx'th column to be returned by the SQL statement.
47626 ** zName must be a pointer to a nul terminated string.
47627 **
47628 ** This call must be made after a call to sqlite3VdbeSetNumCols().
47629 **
47630 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
47631 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
47632 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
47633 */
47634 SQLITE_PRIVATE int sqlite3VdbeSetColName(
47635   Vdbe *p,                         /* Vdbe being configured */
47636   int idx,                         /* Index of column zName applies to */
47637   int var,                         /* One of the COLNAME_* constants */
47638   const char *zName,               /* Pointer to buffer containing name */
47639   void (*xDel)(void*)              /* Memory management strategy for zName */
47640 ){
47641   int rc;
47642   Mem *pColName;
47643   assert( idx<p->nResColumn );
47644   assert( var<COLNAME_N );
47645   if( p->db->mallocFailed ){
47646     assert( !zName || xDel!=SQLITE_DYNAMIC );
47647     return SQLITE_NOMEM;
47648   }
47649   assert( p->aColName!=0 );
47650   pColName = &(p->aColName[idx+var*p->nResColumn]);
47651   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
47652   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
47653   return rc;
47654 }
47655
47656 /*
47657 ** A read or write transaction may or may not be active on database handle
47658 ** db. If a transaction is active, commit it. If there is a
47659 ** write-transaction spanning more than one database file, this routine
47660 ** takes care of the master journal trickery.
47661 */
47662 static int vdbeCommit(sqlite3 *db, Vdbe *p){
47663   int i;
47664   int nTrans = 0;  /* Number of databases with an active write-transaction */
47665   int rc = SQLITE_OK;
47666   int needXcommit = 0;
47667
47668   /* Before doing anything else, call the xSync() callback for any
47669   ** virtual module tables written in this transaction. This has to
47670   ** be done before determining whether a master journal file is 
47671   ** required, as an xSync() callback may add an attached database
47672   ** to the transaction.
47673   */
47674   rc = sqlite3VtabSync(db, &p->zErrMsg);
47675   if( rc!=SQLITE_OK ){
47676     return rc;
47677   }
47678
47679   /* This loop determines (a) if the commit hook should be invoked and
47680   ** (b) how many database files have open write transactions, not 
47681   ** including the temp database. (b) is important because if more than 
47682   ** one database file has an open write transaction, a master journal
47683   ** file is required for an atomic commit.
47684   */ 
47685   for(i=0; i<db->nDb; i++){ 
47686     Btree *pBt = db->aDb[i].pBt;
47687     if( sqlite3BtreeIsInTrans(pBt) ){
47688       needXcommit = 1;
47689       if( i!=1 ) nTrans++;
47690     }
47691   }
47692
47693   /* If there are any write-transactions at all, invoke the commit hook */
47694   if( needXcommit && db->xCommitCallback ){
47695     assert( (db->flags & SQLITE_CommitBusy)==0 );
47696     db->flags |= SQLITE_CommitBusy;
47697     (void)sqlite3SafetyOff(db);
47698     rc = db->xCommitCallback(db->pCommitArg);
47699     (void)sqlite3SafetyOn(db);
47700     db->flags &= ~SQLITE_CommitBusy;
47701     if( rc ){
47702       return SQLITE_CONSTRAINT;
47703     }
47704   }
47705
47706   /* The simple case - no more than one database file (not counting the
47707   ** TEMP database) has a transaction active.   There is no need for the
47708   ** master-journal.
47709   **
47710   ** If the return value of sqlite3BtreeGetFilename() is a zero length
47711   ** string, it means the main database is :memory: or a temp file.  In 
47712   ** that case we do not support atomic multi-file commits, so use the 
47713   ** simple case then too.
47714   */
47715   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
47716    || nTrans<=1
47717   ){
47718     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
47719       Btree *pBt = db->aDb[i].pBt;
47720       if( pBt ){
47721         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
47722       }
47723     }
47724
47725     /* Do the commit only if all databases successfully complete phase 1. 
47726     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
47727     ** IO error while deleting or truncating a journal file. It is unlikely,
47728     ** but could happen. In this case abandon processing and return the error.
47729     */
47730     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
47731       Btree *pBt = db->aDb[i].pBt;
47732       if( pBt ){
47733         rc = sqlite3BtreeCommitPhaseTwo(pBt);
47734       }
47735     }
47736     if( rc==SQLITE_OK ){
47737       sqlite3VtabCommit(db);
47738     }
47739   }
47740
47741   /* The complex case - There is a multi-file write-transaction active.
47742   ** This requires a master journal file to ensure the transaction is
47743   ** committed atomicly.
47744   */
47745 #ifndef SQLITE_OMIT_DISKIO
47746   else{
47747     sqlite3_vfs *pVfs = db->pVfs;
47748     int needSync = 0;
47749     char *zMaster = 0;   /* File-name for the master journal */
47750     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
47751     sqlite3_file *pMaster = 0;
47752     i64 offset = 0;
47753     int res;
47754
47755     /* Select a master journal file name */
47756     do {
47757       u32 iRandom;
47758       sqlite3DbFree(db, zMaster);
47759       sqlite3_randomness(sizeof(iRandom), &iRandom);
47760       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
47761       if( !zMaster ){
47762         return SQLITE_NOMEM;
47763       }
47764       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
47765     }while( rc==SQLITE_OK && res );
47766     if( rc==SQLITE_OK ){
47767       /* Open the master journal. */
47768       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
47769           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
47770           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
47771       );
47772     }
47773     if( rc!=SQLITE_OK ){
47774       sqlite3DbFree(db, zMaster);
47775       return rc;
47776     }
47777  
47778     /* Write the name of each database file in the transaction into the new
47779     ** master journal file. If an error occurs at this point close
47780     ** and delete the master journal file. All the individual journal files
47781     ** still have 'null' as the master journal pointer, so they will roll
47782     ** back independently if a failure occurs.
47783     */
47784     for(i=0; i<db->nDb; i++){
47785       Btree *pBt = db->aDb[i].pBt;
47786       if( i==1 ) continue;   /* Ignore the TEMP database */
47787       if( sqlite3BtreeIsInTrans(pBt) ){
47788         char const *zFile = sqlite3BtreeGetJournalname(pBt);
47789         if( zFile[0]==0 ) continue;  /* Ignore :memory: databases */
47790         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
47791           needSync = 1;
47792         }
47793         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
47794         offset += sqlite3Strlen30(zFile)+1;
47795         if( rc!=SQLITE_OK ){
47796           sqlite3OsCloseFree(pMaster);
47797           sqlite3OsDelete(pVfs, zMaster, 0);
47798           sqlite3DbFree(db, zMaster);
47799           return rc;
47800         }
47801       }
47802     }
47803
47804     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
47805     ** flag is set this is not required.
47806     */
47807     if( needSync 
47808      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
47809      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
47810     ){
47811       sqlite3OsCloseFree(pMaster);
47812       sqlite3OsDelete(pVfs, zMaster, 0);
47813       sqlite3DbFree(db, zMaster);
47814       return rc;
47815     }
47816
47817     /* Sync all the db files involved in the transaction. The same call
47818     ** sets the master journal pointer in each individual journal. If
47819     ** an error occurs here, do not delete the master journal file.
47820     **
47821     ** If the error occurs during the first call to
47822     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
47823     ** master journal file will be orphaned. But we cannot delete it,
47824     ** in case the master journal file name was written into the journal
47825     ** file before the failure occured.
47826     */
47827     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
47828       Btree *pBt = db->aDb[i].pBt;
47829       if( pBt ){
47830         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
47831       }
47832     }
47833     sqlite3OsCloseFree(pMaster);
47834     if( rc!=SQLITE_OK ){
47835       sqlite3DbFree(db, zMaster);
47836       return rc;
47837     }
47838
47839     /* Delete the master journal file. This commits the transaction. After
47840     ** doing this the directory is synced again before any individual
47841     ** transaction files are deleted.
47842     */
47843     rc = sqlite3OsDelete(pVfs, zMaster, 1);
47844     sqlite3DbFree(db, zMaster);
47845     zMaster = 0;
47846     if( rc ){
47847       return rc;
47848     }
47849
47850     /* All files and directories have already been synced, so the following
47851     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
47852     ** deleting or truncating journals. If something goes wrong while
47853     ** this is happening we don't really care. The integrity of the
47854     ** transaction is already guaranteed, but some stray 'cold' journals
47855     ** may be lying around. Returning an error code won't help matters.
47856     */
47857     disable_simulated_io_errors();
47858     sqlite3BeginBenignMalloc();
47859     for(i=0; i<db->nDb; i++){ 
47860       Btree *pBt = db->aDb[i].pBt;
47861       if( pBt ){
47862         sqlite3BtreeCommitPhaseTwo(pBt);
47863       }
47864     }
47865     sqlite3EndBenignMalloc();
47866     enable_simulated_io_errors();
47867
47868     sqlite3VtabCommit(db);
47869   }
47870 #endif
47871
47872   return rc;
47873 }
47874
47875 /* 
47876 ** This routine checks that the sqlite3.activeVdbeCnt count variable
47877 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
47878 ** currently active. An assertion fails if the two counts do not match.
47879 ** This is an internal self-check only - it is not an essential processing
47880 ** step.
47881 **
47882 ** This is a no-op if NDEBUG is defined.
47883 */
47884 #ifndef NDEBUG
47885 static void checkActiveVdbeCnt(sqlite3 *db){
47886   Vdbe *p;
47887   int cnt = 0;
47888   int nWrite = 0;
47889   p = db->pVdbe;
47890   while( p ){
47891     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
47892       cnt++;
47893       if( p->readOnly==0 ) nWrite++;
47894     }
47895     p = p->pNext;
47896   }
47897   assert( cnt==db->activeVdbeCnt );
47898   assert( nWrite==db->writeVdbeCnt );
47899 }
47900 #else
47901 #define checkActiveVdbeCnt(x)
47902 #endif
47903
47904 /*
47905 ** For every Btree that in database connection db which 
47906 ** has been modified, "trip" or invalidate each cursor in
47907 ** that Btree might have been modified so that the cursor
47908 ** can never be used again.  This happens when a rollback
47909 *** occurs.  We have to trip all the other cursors, even
47910 ** cursor from other VMs in different database connections,
47911 ** so that none of them try to use the data at which they
47912 ** were pointing and which now may have been changed due
47913 ** to the rollback.
47914 **
47915 ** Remember that a rollback can delete tables complete and
47916 ** reorder rootpages.  So it is not sufficient just to save
47917 ** the state of the cursor.  We have to invalidate the cursor
47918 ** so that it is never used again.
47919 */
47920 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
47921   int i;
47922   for(i=0; i<db->nDb; i++){
47923     Btree *p = db->aDb[i].pBt;
47924     if( p && sqlite3BtreeIsInTrans(p) ){
47925       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
47926     }
47927   }
47928 }
47929
47930 /*
47931 ** This routine is called the when a VDBE tries to halt.  If the VDBE
47932 ** has made changes and is in autocommit mode, then commit those
47933 ** changes.  If a rollback is needed, then do the rollback.
47934 **
47935 ** This routine is the only way to move the state of a VM from
47936 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
47937 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
47938 **
47939 ** Return an error code.  If the commit could not complete because of
47940 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
47941 ** means the close did not happen and needs to be repeated.
47942 */
47943 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
47944   sqlite3 *db = p->db;
47945   int i;
47946   int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
47947   int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */
47948
47949   /* This function contains the logic that determines if a statement or
47950   ** transaction will be committed or rolled back as a result of the
47951   ** execution of this virtual machine. 
47952   **
47953   ** If any of the following errors occur:
47954   **
47955   **     SQLITE_NOMEM
47956   **     SQLITE_IOERR
47957   **     SQLITE_FULL
47958   **     SQLITE_INTERRUPT
47959   **
47960   ** Then the internal cache might have been left in an inconsistent
47961   ** state.  We need to rollback the statement transaction, if there is
47962   ** one, or the complete transaction if there is no statement transaction.
47963   */
47964
47965   if( p->db->mallocFailed ){
47966     p->rc = SQLITE_NOMEM;
47967   }
47968   closeAllCursorsExceptActiveVtabs(p);
47969   if( p->magic!=VDBE_MAGIC_RUN ){
47970     return SQLITE_OK;
47971   }
47972   checkActiveVdbeCnt(db);
47973
47974   /* No commit or rollback needed if the program never started */
47975   if( p->pc>=0 ){
47976     int mrc;   /* Primary error code from p->rc */
47977
47978     /* Lock all btrees used by the statement */
47979     sqlite3BtreeMutexArrayEnter(&p->aMutex);
47980
47981     /* Check for one of the special errors */
47982     mrc = p->rc & 0xff;
47983     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
47984                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
47985     if( isSpecialError ){
47986       /* If the query was read-only, we need do no rollback at all. Otherwise,
47987       ** proceed with the special handling.
47988       */
47989       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
47990         if( p->rc==SQLITE_IOERR_BLOCKED && p->usesStmtJournal ){
47991           xFunc = sqlite3BtreeRollbackStmt;
47992           p->rc = SQLITE_BUSY;
47993         }else if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL)
47994                    && p->usesStmtJournal ){
47995           xFunc = sqlite3BtreeRollbackStmt;
47996         }else{
47997           /* We are forced to roll back the active transaction. Before doing
47998           ** so, abort any other statements this handle currently has active.
47999           */
48000           invalidateCursorsOnModifiedBtrees(db);
48001           sqlite3RollbackAll(db);
48002           sqlite3CloseSavepoints(db);
48003           db->autoCommit = 1;
48004         }
48005       }
48006     }
48007   
48008     /* If the auto-commit flag is set and this is the only active vdbe, then
48009     ** we do either a commit or rollback of the current transaction. 
48010     **
48011     ** Note: This block also runs if one of the special errors handled 
48012     ** above has occurred. 
48013     */
48014     if( !sqlite3VtabInSync(db) 
48015      && db->autoCommit 
48016      && db->writeVdbeCnt==(p->readOnly==0) 
48017      && (db->flags & SQLITE_CommitBusy)==0
48018     ){
48019       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
48020         /* The auto-commit flag is true, and the vdbe program was 
48021         ** successful or hit an 'OR FAIL' constraint. This means a commit 
48022         ** is required.
48023         */
48024         int rc = vdbeCommit(db, p);
48025         if( rc==SQLITE_BUSY ){
48026           sqlite3BtreeMutexArrayLeave(&p->aMutex);
48027           return SQLITE_BUSY;
48028         }else if( rc!=SQLITE_OK ){
48029           p->rc = rc;
48030           sqlite3RollbackAll(db);
48031         }else{
48032           sqlite3CommitInternalChanges(db);
48033         }
48034       }else{
48035         sqlite3RollbackAll(db);
48036       }
48037     }else if( !xFunc ){
48038       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
48039         if( p->openedStatement ){
48040           xFunc = sqlite3BtreeCommitStmt;
48041         } 
48042       }else if( p->errorAction==OE_Abort ){
48043         xFunc = sqlite3BtreeRollbackStmt;
48044       }else{
48045         invalidateCursorsOnModifiedBtrees(db);
48046         sqlite3RollbackAll(db);
48047         sqlite3CloseSavepoints(db);
48048         db->autoCommit = 1;
48049       }
48050     }
48051   
48052     /* If xFunc is not NULL, then it is one of sqlite3BtreeRollbackStmt or
48053     ** sqlite3BtreeCommitStmt. Call it once on each backend. If an error occurs
48054     ** and the return code is still SQLITE_OK, set the return code to the new
48055     ** error value.
48056     */
48057     assert(!xFunc ||
48058       xFunc==sqlite3BtreeCommitStmt ||
48059       xFunc==sqlite3BtreeRollbackStmt
48060     );
48061     for(i=0; xFunc && i<db->nDb; i++){ 
48062       int rc;
48063       Btree *pBt = db->aDb[i].pBt;
48064       if( pBt ){
48065         rc = xFunc(pBt);
48066         if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
48067           p->rc = rc;
48068           sqlite3DbFree(db, p->zErrMsg);
48069           p->zErrMsg = 0;
48070         }
48071       }
48072     }
48073   
48074     /* If this was an INSERT, UPDATE or DELETE and the statement was committed, 
48075     ** set the change counter. 
48076     */
48077     if( p->changeCntOn && p->pc>=0 ){
48078       if( !xFunc || xFunc==sqlite3BtreeCommitStmt ){
48079         sqlite3VdbeSetChanges(db, p->nChange);
48080       }else{
48081         sqlite3VdbeSetChanges(db, 0);
48082       }
48083       p->nChange = 0;
48084     }
48085   
48086     /* Rollback or commit any schema changes that occurred. */
48087     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
48088       sqlite3ResetInternalSchema(db, 0);
48089       db->flags = (db->flags | SQLITE_InternChanges);
48090     }
48091
48092     /* Release the locks */
48093     sqlite3BtreeMutexArrayLeave(&p->aMutex);
48094   }
48095
48096   /* We have successfully halted and closed the VM.  Record this fact. */
48097   if( p->pc>=0 ){
48098     db->activeVdbeCnt--;
48099     if( !p->readOnly ){
48100       db->writeVdbeCnt--;
48101     }
48102     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
48103   }
48104   p->magic = VDBE_MAGIC_HALT;
48105   checkActiveVdbeCnt(db);
48106   if( p->db->mallocFailed ){
48107     p->rc = SQLITE_NOMEM;
48108   }
48109
48110   return SQLITE_OK;
48111 }
48112
48113
48114 /*
48115 ** Each VDBE holds the result of the most recent sqlite3_step() call
48116 ** in p->rc.  This routine sets that result back to SQLITE_OK.
48117 */
48118 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
48119   p->rc = SQLITE_OK;
48120 }
48121
48122 /*
48123 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
48124 ** Write any error messages into *pzErrMsg.  Return the result code.
48125 **
48126 ** After this routine is run, the VDBE should be ready to be executed
48127 ** again.
48128 **
48129 ** To look at it another way, this routine resets the state of the
48130 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
48131 ** VDBE_MAGIC_INIT.
48132 */
48133 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
48134   sqlite3 *db;
48135   db = p->db;
48136
48137   /* If the VM did not run to completion or if it encountered an
48138   ** error, then it might not have been halted properly.  So halt
48139   ** it now.
48140   */
48141   (void)sqlite3SafetyOn(db);
48142   sqlite3VdbeHalt(p);
48143   (void)sqlite3SafetyOff(db);
48144
48145   /* If the VDBE has be run even partially, then transfer the error code
48146   ** and error message from the VDBE into the main database structure.  But
48147   ** if the VDBE has just been set to run but has not actually executed any
48148   ** instructions yet, leave the main database error information unchanged.
48149   */
48150   if( p->pc>=0 ){
48151     if( p->zErrMsg ){
48152       sqlite3BeginBenignMalloc();
48153       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
48154       sqlite3EndBenignMalloc();
48155       db->errCode = p->rc;
48156       sqlite3DbFree(db, p->zErrMsg);
48157       p->zErrMsg = 0;
48158     }else if( p->rc ){
48159       sqlite3Error(db, p->rc, 0);
48160     }else{
48161       sqlite3Error(db, SQLITE_OK, 0);
48162     }
48163   }else if( p->rc && p->expired ){
48164     /* The expired flag was set on the VDBE before the first call
48165     ** to sqlite3_step(). For consistency (since sqlite3_step() was
48166     ** called), set the database error in this case as well.
48167     */
48168     sqlite3Error(db, p->rc, 0);
48169     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
48170     sqlite3DbFree(db, p->zErrMsg);
48171     p->zErrMsg = 0;
48172   }
48173
48174   /* Reclaim all memory used by the VDBE
48175   */
48176   Cleanup(p);
48177
48178   /* Save profiling information from this VDBE run.
48179   */
48180 #ifdef VDBE_PROFILE
48181   {
48182     FILE *out = fopen("vdbe_profile.out", "a");
48183     if( out ){
48184       int i;
48185       fprintf(out, "---- ");
48186       for(i=0; i<p->nOp; i++){
48187         fprintf(out, "%02x", p->aOp[i].opcode);
48188       }
48189       fprintf(out, "\n");
48190       for(i=0; i<p->nOp; i++){
48191         fprintf(out, "%6d %10lld %8lld ",
48192            p->aOp[i].cnt,
48193            p->aOp[i].cycles,
48194            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
48195         );
48196         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
48197       }
48198       fclose(out);
48199     }
48200   }
48201 #endif
48202   p->magic = VDBE_MAGIC_INIT;
48203   return p->rc & db->errMask;
48204 }
48205  
48206 /*
48207 ** Clean up and delete a VDBE after execution.  Return an integer which is
48208 ** the result code.  Write any error message text into *pzErrMsg.
48209 */
48210 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
48211   int rc = SQLITE_OK;
48212   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
48213     rc = sqlite3VdbeReset(p);
48214     assert( (rc & p->db->errMask)==rc );
48215   }else if( p->magic!=VDBE_MAGIC_INIT ){
48216     return SQLITE_MISUSE;
48217   }
48218   sqlite3VdbeDelete(p);
48219   return rc;
48220 }
48221
48222 /*
48223 ** Call the destructor for each auxdata entry in pVdbeFunc for which
48224 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
48225 ** are always destroyed.  To destroy all auxdata entries, call this
48226 ** routine with mask==0.
48227 */
48228 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
48229   int i;
48230   for(i=0; i<pVdbeFunc->nAux; i++){
48231     struct AuxData *pAux = &pVdbeFunc->apAux[i];
48232     if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
48233       if( pAux->xDelete ){
48234         pAux->xDelete(pAux->pAux);
48235       }
48236       pAux->pAux = 0;
48237     }
48238   }
48239 }
48240
48241 /*
48242 ** Delete an entire VDBE.
48243 */
48244 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
48245   int i;
48246   sqlite3 *db;
48247
48248   if( p==0 ) return;
48249   db = p->db;
48250   if( p->pPrev ){
48251     p->pPrev->pNext = p->pNext;
48252   }else{
48253     assert( db->pVdbe==p );
48254     db->pVdbe = p->pNext;
48255   }
48256   if( p->pNext ){
48257     p->pNext->pPrev = p->pPrev;
48258   }
48259   if( p->aOp ){
48260     Op *pOp = p->aOp;
48261     for(i=0; i<p->nOp; i++, pOp++){
48262       freeP4(db, pOp->p4type, pOp->p4.p);
48263 #ifdef SQLITE_DEBUG
48264       sqlite3DbFree(db, pOp->zComment);
48265 #endif     
48266     }
48267     sqlite3DbFree(db, p->aOp);
48268   }
48269   releaseMemArray(p->aVar, p->nVar);
48270   sqlite3DbFree(db, p->aLabel);
48271   if( p->aMem ){
48272     sqlite3DbFree(db, &p->aMem[1]);
48273   }
48274   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48275   sqlite3DbFree(db, p->aColName);
48276   sqlite3DbFree(db, p->zSql);
48277   p->magic = VDBE_MAGIC_DEAD;
48278   sqlite3DbFree(db, p);
48279 }
48280
48281 /*
48282 ** If a MoveTo operation is pending on the given cursor, then do that
48283 ** MoveTo now.  Return an error code.  If no MoveTo is pending, this
48284 ** routine does nothing and returns SQLITE_OK.
48285 */
48286 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
48287   if( p->deferredMoveto ){
48288     int res, rc;
48289 #ifdef SQLITE_TEST
48290     extern int sqlite3_search_count;
48291 #endif
48292     assert( p->isTable );
48293     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
48294     if( rc ) return rc;
48295     p->lastRowid = keyToInt(p->movetoTarget);
48296     p->rowidIsValid = res==0 ?1:0;
48297     if( res<0 ){
48298       rc = sqlite3BtreeNext(p->pCursor, &res);
48299       if( rc ) return rc;
48300     }
48301 #ifdef SQLITE_TEST
48302     sqlite3_search_count++;
48303 #endif
48304     p->deferredMoveto = 0;
48305     p->cacheStatus = CACHE_STALE;
48306   }else if( p->pCursor ){
48307     int hasMoved;
48308     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
48309     if( rc ) return rc;
48310     if( hasMoved ){
48311       p->cacheStatus = CACHE_STALE;
48312       p->nullRow = 1;
48313     }
48314   }
48315   return SQLITE_OK;
48316 }
48317
48318 /*
48319 ** The following functions:
48320 **
48321 ** sqlite3VdbeSerialType()
48322 ** sqlite3VdbeSerialTypeLen()
48323 ** sqlite3VdbeSerialLen()
48324 ** sqlite3VdbeSerialPut()
48325 ** sqlite3VdbeSerialGet()
48326 **
48327 ** encapsulate the code that serializes values for storage in SQLite
48328 ** data and index records. Each serialized value consists of a
48329 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
48330 ** integer, stored as a varint.
48331 **
48332 ** In an SQLite index record, the serial type is stored directly before
48333 ** the blob of data that it corresponds to. In a table record, all serial
48334 ** types are stored at the start of the record, and the blobs of data at
48335 ** the end. Hence these functions allow the caller to handle the
48336 ** serial-type and data blob seperately.
48337 **
48338 ** The following table describes the various storage classes for data:
48339 **
48340 **   serial type        bytes of data      type
48341 **   --------------     ---------------    ---------------
48342 **      0                     0            NULL
48343 **      1                     1            signed integer
48344 **      2                     2            signed integer
48345 **      3                     3            signed integer
48346 **      4                     4            signed integer
48347 **      5                     6            signed integer
48348 **      6                     8            signed integer
48349 **      7                     8            IEEE float
48350 **      8                     0            Integer constant 0
48351 **      9                     0            Integer constant 1
48352 **     10,11                               reserved for expansion
48353 **    N>=12 and even       (N-12)/2        BLOB
48354 **    N>=13 and odd        (N-13)/2        text
48355 **
48356 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
48357 ** of SQLite will not understand those serial types.
48358 */
48359
48360 /*
48361 ** Return the serial-type for the value stored in pMem.
48362 */
48363 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
48364   int flags = pMem->flags;
48365   int n;
48366
48367   if( flags&MEM_Null ){
48368     return 0;
48369   }
48370   if( flags&MEM_Int ){
48371     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
48372 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
48373     i64 i = pMem->u.i;
48374     u64 u;
48375     if( file_format>=4 && (i&1)==i ){
48376       return 8+(u32)i;
48377     }
48378     u = i<0 ? -i : i;
48379     if( u<=127 ) return 1;
48380     if( u<=32767 ) return 2;
48381     if( u<=8388607 ) return 3;
48382     if( u<=2147483647 ) return 4;
48383     if( u<=MAX_6BYTE ) return 5;
48384     return 6;
48385   }
48386   if( flags&MEM_Real ){
48387     return 7;
48388   }
48389   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
48390   n = pMem->n;
48391   if( flags & MEM_Zero ){
48392     n += pMem->u.nZero;
48393   }
48394   assert( n>=0 );
48395   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
48396 }
48397
48398 /*
48399 ** Return the length of the data corresponding to the supplied serial-type.
48400 */
48401 SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
48402   if( serial_type>=12 ){
48403     return (serial_type-12)/2;
48404   }else{
48405     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
48406     return aSize[serial_type];
48407   }
48408 }
48409
48410 /*
48411 ** If we are on an architecture with mixed-endian floating 
48412 ** points (ex: ARM7) then swap the lower 4 bytes with the 
48413 ** upper 4 bytes.  Return the result.
48414 **
48415 ** For most architectures, this is a no-op.
48416 **
48417 ** (later):  It is reported to me that the mixed-endian problem
48418 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
48419 ** that early versions of GCC stored the two words of a 64-bit
48420 ** float in the wrong order.  And that error has been propagated
48421 ** ever since.  The blame is not necessarily with GCC, though.
48422 ** GCC might have just copying the problem from a prior compiler.
48423 ** I am also told that newer versions of GCC that follow a different
48424 ** ABI get the byte order right.
48425 **
48426 ** Developers using SQLite on an ARM7 should compile and run their
48427 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
48428 ** enabled, some asserts below will ensure that the byte order of
48429 ** floating point values is correct.
48430 **
48431 ** (2007-08-30)  Frank van Vugt has studied this problem closely
48432 ** and has send his findings to the SQLite developers.  Frank
48433 ** writes that some Linux kernels offer floating point hardware
48434 ** emulation that uses only 32-bit mantissas instead of a full 
48435 ** 48-bits as required by the IEEE standard.  (This is the
48436 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
48437 ** byte swapping becomes very complicated.  To avoid problems,
48438 ** the necessary byte swapping is carried out using a 64-bit integer
48439 ** rather than a 64-bit float.  Frank assures us that the code here
48440 ** works for him.  We, the developers, have no way to independently
48441 ** verify this, but Frank seems to know what he is talking about
48442 ** so we trust him.
48443 */
48444 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
48445 static u64 floatSwap(u64 in){
48446   union {
48447     u64 r;
48448     u32 i[2];
48449   } u;
48450   u32 t;
48451
48452   u.r = in;
48453   t = u.i[0];
48454   u.i[0] = u.i[1];
48455   u.i[1] = t;
48456   return u.r;
48457 }
48458 # define swapMixedEndianFloat(X)  X = floatSwap(X)
48459 #else
48460 # define swapMixedEndianFloat(X)
48461 #endif
48462
48463 /*
48464 ** Write the serialized data blob for the value stored in pMem into 
48465 ** buf. It is assumed that the caller has allocated sufficient space.
48466 ** Return the number of bytes written.
48467 **
48468 ** nBuf is the amount of space left in buf[].  nBuf must always be
48469 ** large enough to hold the entire field.  Except, if the field is
48470 ** a blob with a zero-filled tail, then buf[] might be just the right
48471 ** size to hold everything except for the zero-filled tail.  If buf[]
48472 ** is only big enough to hold the non-zero prefix, then only write that
48473 ** prefix into buf[].  But if buf[] is large enough to hold both the
48474 ** prefix and the tail then write the prefix and set the tail to all
48475 ** zeros.
48476 **
48477 ** Return the number of bytes actually written into buf[].  The number
48478 ** of bytes in the zero-filled tail is included in the return value only
48479 ** if those bytes were zeroed in buf[].
48480 */ 
48481 SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
48482   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
48483   int len;
48484
48485   /* Integer and Real */
48486   if( serial_type<=7 && serial_type>0 ){
48487     u64 v;
48488     int i;
48489     if( serial_type==7 ){
48490       assert( sizeof(v)==sizeof(pMem->r) );
48491       memcpy(&v, &pMem->r, sizeof(v));
48492       swapMixedEndianFloat(v);
48493     }else{
48494       v = pMem->u.i;
48495     }
48496     len = i = sqlite3VdbeSerialTypeLen(serial_type);
48497     assert( len<=nBuf );
48498     while( i-- ){
48499       buf[i] = (u8)(v&0xFF);
48500       v >>= 8;
48501     }
48502     return len;
48503   }
48504
48505   /* String or blob */
48506   if( serial_type>=12 ){
48507     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
48508              == sqlite3VdbeSerialTypeLen(serial_type) );
48509     assert( pMem->n<=nBuf );
48510     len = pMem->n;
48511     memcpy(buf, pMem->z, len);
48512     if( pMem->flags & MEM_Zero ){
48513       len += pMem->u.nZero;
48514       if( len>nBuf ){
48515         len = nBuf;
48516       }
48517       memset(&buf[pMem->n], 0, len-pMem->n);
48518     }
48519     return len;
48520   }
48521
48522   /* NULL or constants 0 or 1 */
48523   return 0;
48524 }
48525
48526 /*
48527 ** Deserialize the data blob pointed to by buf as serial type serial_type
48528 ** and store the result in pMem.  Return the number of bytes read.
48529 */ 
48530 SQLITE_PRIVATE int sqlite3VdbeSerialGet(
48531   const unsigned char *buf,     /* Buffer to deserialize from */
48532   u32 serial_type,              /* Serial type to deserialize */
48533   Mem *pMem                     /* Memory cell to write value into */
48534 ){
48535   switch( serial_type ){
48536     case 10:   /* Reserved for future use */
48537     case 11:   /* Reserved for future use */
48538     case 0: {  /* NULL */
48539       pMem->flags = MEM_Null;
48540       break;
48541     }
48542     case 1: { /* 1-byte signed integer */
48543       pMem->u.i = (signed char)buf[0];
48544       pMem->flags = MEM_Int;
48545       return 1;
48546     }
48547     case 2: { /* 2-byte signed integer */
48548       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
48549       pMem->flags = MEM_Int;
48550       return 2;
48551     }
48552     case 3: { /* 3-byte signed integer */
48553       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
48554       pMem->flags = MEM_Int;
48555       return 3;
48556     }
48557     case 4: { /* 4-byte signed integer */
48558       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
48559       pMem->flags = MEM_Int;
48560       return 4;
48561     }
48562     case 5: { /* 6-byte signed integer */
48563       u64 x = (((signed char)buf[0])<<8) | buf[1];
48564       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
48565       x = (x<<32) | y;
48566       pMem->u.i = *(i64*)&x;
48567       pMem->flags = MEM_Int;
48568       return 6;
48569     }
48570     case 6:   /* 8-byte signed integer */
48571     case 7: { /* IEEE floating point */
48572       u64 x;
48573       u32 y;
48574 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
48575       /* Verify that integers and floating point values use the same
48576       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
48577       ** defined that 64-bit floating point values really are mixed
48578       ** endian.
48579       */
48580       static const u64 t1 = ((u64)0x3ff00000)<<32;
48581       static const double r1 = 1.0;
48582       u64 t2 = t1;
48583       swapMixedEndianFloat(t2);
48584       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
48585 #endif
48586
48587       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
48588       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
48589       x = (x<<32) | y;
48590       if( serial_type==6 ){
48591         pMem->u.i = *(i64*)&x;
48592         pMem->flags = MEM_Int;
48593       }else{
48594         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
48595         swapMixedEndianFloat(x);
48596         memcpy(&pMem->r, &x, sizeof(x));
48597         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
48598       }
48599       return 8;
48600     }
48601     case 8:    /* Integer 0 */
48602     case 9: {  /* Integer 1 */
48603       pMem->u.i = serial_type-8;
48604       pMem->flags = MEM_Int;
48605       return 0;
48606     }
48607     default: {
48608       int len = (serial_type-12)/2;
48609       pMem->z = (char *)buf;
48610       pMem->n = len;
48611       pMem->xDel = 0;
48612       if( serial_type&0x01 ){
48613         pMem->flags = MEM_Str | MEM_Ephem;
48614       }else{
48615         pMem->flags = MEM_Blob | MEM_Ephem;
48616       }
48617       return len;
48618     }
48619   }
48620   return 0;
48621 }
48622
48623
48624 /*
48625 ** Given the nKey-byte encoding of a record in pKey[], parse the
48626 ** record into a UnpackedRecord structure.  Return a pointer to
48627 ** that structure.
48628 **
48629 ** The calling function might provide szSpace bytes of memory
48630 ** space at pSpace.  This space can be used to hold the returned
48631 ** VDbeParsedRecord structure if it is large enough.  If it is
48632 ** not big enough, space is obtained from sqlite3_malloc().
48633 **
48634 ** The returned structure should be closed by a call to
48635 ** sqlite3VdbeDeleteUnpackedRecord().
48636 */ 
48637 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
48638   KeyInfo *pKeyInfo,     /* Information about the record format */
48639   int nKey,              /* Size of the binary record */
48640   const void *pKey,      /* The binary record */
48641   UnpackedRecord *pSpace,/* Space available to hold resulting object */
48642   int szSpace            /* Size of pSpace[] in bytes */
48643 ){
48644   const unsigned char *aKey = (const unsigned char *)pKey;
48645   UnpackedRecord *p;
48646   int nByte, d;
48647   u32 idx;
48648   u16 u;                 /* Unsigned loop counter */
48649   u32 szHdr;
48650   Mem *pMem;
48651   
48652   assert( sizeof(Mem)>sizeof(*p) );
48653   nByte = sizeof(Mem)*(pKeyInfo->nField+2);
48654   if( nByte>szSpace ){
48655     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
48656     if( p==0 ) return 0;
48657     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
48658   }else{
48659     p = pSpace;
48660     p->flags = UNPACKED_NEED_DESTROY;
48661   }
48662   p->pKeyInfo = pKeyInfo;
48663   p->nField = pKeyInfo->nField + 1;
48664   p->aMem = pMem = &((Mem*)p)[1];
48665   idx = getVarint32(aKey, szHdr);
48666   d = szHdr;
48667   u = 0;
48668   while( idx<szHdr && u<p->nField ){
48669     u32 serial_type;
48670
48671     idx += getVarint32(&aKey[idx], serial_type);
48672     if( d>=nKey && sqlite3VdbeSerialTypeLen(serial_type)>0 ) break;
48673     pMem->enc = pKeyInfo->enc;
48674     pMem->db = pKeyInfo->db;
48675     pMem->flags = 0;
48676     pMem->zMalloc = 0;
48677     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
48678     pMem++;
48679     u++;
48680   }
48681   assert( u<=pKeyInfo->nField + 1 );
48682   p->nField = u;
48683   return (void*)p;
48684 }
48685
48686 /*
48687 ** This routine destroys a UnpackedRecord object
48688 */
48689 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
48690   if( p ){
48691     if( p->flags & UNPACKED_NEED_DESTROY ){
48692       int i;
48693       Mem *pMem;
48694       for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
48695         if( pMem->zMalloc ){
48696           sqlite3VdbeMemRelease(pMem);
48697         }
48698       }
48699     }
48700     if( p->flags & UNPACKED_NEED_FREE ){
48701       sqlite3DbFree(p->pKeyInfo->db, p);
48702     }
48703   }
48704 }
48705
48706 /*
48707 ** This function compares the two table rows or index records
48708 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
48709 ** or positive integer if key1 is less than, equal to or 
48710 ** greater than key2.  The {nKey1, pKey1} key must be a blob
48711 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
48712 ** key must be a parsed key such as obtained from
48713 ** sqlite3VdbeParseRecord.
48714 **
48715 ** Key1 and Key2 do not have to contain the same number of fields.
48716 ** The key with fewer fields is usually compares less than the 
48717 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
48718 ** and the common prefixes are equal, then key1 is less than key2.
48719 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
48720 ** equal, then the keys are considered to be equal and
48721 ** the parts beyond the common prefix are ignored.
48722 **
48723 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
48724 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
48725 ** an index key, and thus ends with a rowid value.  The last byte
48726 ** of the header will therefore be the serial type of the rowid:
48727 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
48728 ** The serial type of the final rowid will always be a single byte.
48729 ** By ignoring this last byte of the header, we force the comparison
48730 ** to ignore the rowid at the end of key1.
48731 */
48732 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
48733   int nKey1, const void *pKey1, /* Left key */
48734   UnpackedRecord *pPKey2        /* Right key */
48735 ){
48736   int d1;            /* Offset into aKey[] of next data element */
48737   u32 idx1;          /* Offset into aKey[] of next header element */
48738   u32 szHdr1;        /* Number of bytes in header */
48739   int i = 0;
48740   int nField;
48741   int rc = 0;
48742   const unsigned char *aKey1 = (const unsigned char *)pKey1;
48743   KeyInfo *pKeyInfo;
48744   Mem mem1;
48745
48746   pKeyInfo = pPKey2->pKeyInfo;
48747   mem1.enc = pKeyInfo->enc;
48748   mem1.db = pKeyInfo->db;
48749   mem1.flags = 0;
48750   mem1.zMalloc = 0;
48751   
48752   idx1 = getVarint32(aKey1, szHdr1);
48753   d1 = szHdr1;
48754   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
48755     szHdr1--;
48756   }
48757   nField = pKeyInfo->nField;
48758   while( idx1<szHdr1 && i<pPKey2->nField ){
48759     u32 serial_type1;
48760
48761     /* Read the serial types for the next element in each key. */
48762     idx1 += getVarint32( aKey1+idx1, serial_type1 );
48763     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
48764
48765     /* Extract the values to be compared.
48766     */
48767     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
48768
48769     /* Do the comparison
48770     */
48771     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
48772                            i<nField ? pKeyInfo->aColl[i] : 0);
48773     if( rc!=0 ){
48774       break;
48775     }
48776     i++;
48777   }
48778   if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
48779
48780   if( rc==0 ){
48781     /* rc==0 here means that one of the keys ran out of fields and
48782     ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
48783     ** flag is set, then break the tie by treating key2 as larger.
48784     ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
48785     ** are considered to be equal.  Otherwise, the longer key is the 
48786     ** larger.  As it happens, the pPKey2 will always be the longer
48787     ** if there is a difference.
48788     */
48789     if( pPKey2->flags & UNPACKED_INCRKEY ){
48790       rc = -1;
48791     }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
48792       /* Leave rc==0 */
48793     }else if( idx1<szHdr1 ){
48794       rc = 1;
48795     }
48796   }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField
48797                && pKeyInfo->aSortOrder[i] ){
48798     rc = -rc;
48799   }
48800
48801   return rc;
48802 }
48803  
48804
48805 /*
48806 ** pCur points at an index entry created using the OP_MakeRecord opcode.
48807 ** Read the rowid (the last field in the record) and store it in *rowid.
48808 ** Return SQLITE_OK if everything works, or an error code otherwise.
48809 **
48810 ** pCur might be pointing to text obtained from a corrupt database file.
48811 ** So the content cannot be trusted.  Do appropriate checks on the content.
48812 */
48813 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
48814   i64 nCellKey = 0;
48815   int rc;
48816   u32 szHdr;        /* Size of the header */
48817   u32 typeRowid;    /* Serial type of the rowid */
48818   u32 lenRowid;     /* Size of the rowid */
48819   Mem m, v;
48820
48821   /* Get the size of the index entry.  Only indices entries of less
48822   ** than 2GiB are support - anything large must be database corruption */
48823   sqlite3BtreeKeySize(pCur, &nCellKey);
48824   if( unlikely(nCellKey<=0 || nCellKey>0x7fffffff) ){
48825     return SQLITE_CORRUPT_BKPT;
48826   }
48827
48828   /* Read in the complete content of the index entry */
48829   m.flags = 0;
48830   m.db = 0;
48831   m.zMalloc = 0;
48832   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
48833   if( rc ){
48834     return rc;
48835   }
48836
48837   /* The index entry must begin with a header size */
48838   (void)getVarint32((u8*)m.z, szHdr);
48839   testcase( szHdr==2 );
48840   testcase( szHdr==m.n );
48841   if( unlikely(szHdr<2 || (int)szHdr>m.n) ){
48842     goto idx_rowid_corruption;
48843   }
48844
48845   /* The last field of the index should be an integer - the ROWID.
48846   ** Verify that the last entry really is an integer. */
48847   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
48848   testcase( typeRowid==1 );
48849   testcase( typeRowid==2 );
48850   testcase( typeRowid==3 );
48851   testcase( typeRowid==4 );
48852   testcase( typeRowid==5 );
48853   testcase( typeRowid==6 );
48854   testcase( typeRowid==8 );
48855   testcase( typeRowid==9 );
48856   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
48857     goto idx_rowid_corruption;
48858   }
48859   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
48860   testcase( m.n-lenRowid==szHdr );
48861   if( unlikely(m.n-lenRowid<szHdr) ){
48862     goto idx_rowid_corruption;
48863   }
48864
48865   /* Fetch the integer off the end of the index record */
48866   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
48867   *rowid = v.u.i;
48868   sqlite3VdbeMemRelease(&m);
48869   return SQLITE_OK;
48870
48871   /* Jump here if database corruption is detected after m has been
48872   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
48873 idx_rowid_corruption:
48874   testcase( m.zMalloc!=0 );
48875   sqlite3VdbeMemRelease(&m);
48876   return SQLITE_CORRUPT_BKPT;
48877 }
48878
48879 /*
48880 ** Compare the key of the index entry that cursor pC is point to against
48881 ** the key string in pKey (of length nKey).  Write into *pRes a number
48882 ** that is negative, zero, or positive if pC is less than, equal to,
48883 ** or greater than pKey.  Return SQLITE_OK on success.
48884 **
48885 ** pKey is either created without a rowid or is truncated so that it
48886 ** omits the rowid at the end.  The rowid at the end of the index entry
48887 ** is ignored as well.  Hence, this routine only compares the prefixes 
48888 ** of the keys prior to the final rowid, not the entire key.
48889 **
48890 ** pUnpacked may be an unpacked version of pKey,nKey.  If pUnpacked is
48891 ** supplied it is used in place of pKey,nKey.
48892 */
48893 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
48894   VdbeCursor *pC,             /* The cursor to compare against */
48895   UnpackedRecord *pUnpacked,  /* Unpacked version of pKey and nKey */
48896   int *res                    /* Write the comparison result here */
48897 ){
48898   i64 nCellKey = 0;
48899   int rc;
48900   BtCursor *pCur = pC->pCursor;
48901   Mem m;
48902
48903   sqlite3BtreeKeySize(pCur, &nCellKey);
48904   if( nCellKey<=0 || nCellKey>0x7fffffff ){
48905     *res = 0;
48906     return SQLITE_OK;
48907   }
48908   m.db = 0;
48909   m.flags = 0;
48910   m.zMalloc = 0;
48911   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
48912   if( rc ){
48913     return rc;
48914   }
48915   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
48916   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
48917   sqlite3VdbeMemRelease(&m);
48918   return SQLITE_OK;
48919 }
48920
48921 /*
48922 ** This routine sets the value to be returned by subsequent calls to
48923 ** sqlite3_changes() on the database handle 'db'. 
48924 */
48925 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
48926   assert( sqlite3_mutex_held(db->mutex) );
48927   db->nChange = nChange;
48928   db->nTotalChange += nChange;
48929 }
48930
48931 /*
48932 ** Set a flag in the vdbe to update the change counter when it is finalised
48933 ** or reset.
48934 */
48935 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
48936   v->changeCntOn = 1;
48937 }
48938
48939 /*
48940 ** Mark every prepared statement associated with a database connection
48941 ** as expired.
48942 **
48943 ** An expired statement means that recompilation of the statement is
48944 ** recommend.  Statements expire when things happen that make their
48945 ** programs obsolete.  Removing user-defined functions or collating
48946 ** sequences, or changing an authorization function are the types of
48947 ** things that make prepared statements obsolete.
48948 */
48949 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
48950   Vdbe *p;
48951   for(p = db->pVdbe; p; p=p->pNext){
48952     p->expired = 1;
48953   }
48954 }
48955
48956 /*
48957 ** Return the database associated with the Vdbe.
48958 */
48959 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
48960   return v->db;
48961 }
48962
48963 /************** End of vdbeaux.c *********************************************/
48964 /************** Begin file vdbeapi.c *****************************************/
48965 /*
48966 ** 2004 May 26
48967 **
48968 ** The author disclaims copyright to this source code.  In place of
48969 ** a legal notice, here is a blessing:
48970 **
48971 **    May you do good and not evil.
48972 **    May you find forgiveness for yourself and forgive others.
48973 **    May you share freely, never taking more than you give.
48974 **
48975 *************************************************************************
48976 **
48977 ** This file contains code use to implement APIs that are part of the
48978 ** VDBE.
48979 **
48980 ** $Id: vdbeapi.c,v 1.151 2009/02/04 03:59:25 shane Exp $
48981 */
48982
48983 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
48984 /*
48985 ** The following structure contains pointers to the end points of a
48986 ** doubly-linked list of all compiled SQL statements that may be holding
48987 ** buffers eligible for release when the sqlite3_release_memory() interface is
48988 ** invoked. Access to this list is protected by the SQLITE_MUTEX_STATIC_LRU2
48989 ** mutex.
48990 **
48991 ** Statements are added to the end of this list when sqlite3_reset() is
48992 ** called. They are removed either when sqlite3_step() or sqlite3_finalize()
48993 ** is called. When statements are added to this list, the associated 
48994 ** register array (p->aMem[1..p->nMem]) may contain dynamic buffers that
48995 ** can be freed using sqlite3VdbeReleaseMemory().
48996 **
48997 ** When statements are added or removed from this list, the mutex
48998 ** associated with the Vdbe being added or removed (Vdbe.db->mutex) is
48999 ** already held. The LRU2 mutex is then obtained, blocking if necessary,
49000 ** the linked-list pointers manipulated and the LRU2 mutex relinquished.
49001 */
49002 struct StatementLruList {
49003   Vdbe *pFirst;
49004   Vdbe *pLast;
49005 };
49006 static struct StatementLruList sqlite3LruStatements;
49007
49008 /*
49009 ** Check that the list looks to be internally consistent. This is used
49010 ** as part of an assert() statement as follows:
49011 **
49012 **   assert( stmtLruCheck() );
49013 */
49014 #ifndef NDEBUG
49015 static int stmtLruCheck(){
49016   Vdbe *p;
49017   for(p=sqlite3LruStatements.pFirst; p; p=p->pLruNext){
49018     assert(p->pLruNext || p==sqlite3LruStatements.pLast);
49019     assert(!p->pLruNext || p->pLruNext->pLruPrev==p);
49020     assert(p->pLruPrev || p==sqlite3LruStatements.pFirst);
49021     assert(!p->pLruPrev || p->pLruPrev->pLruNext==p);
49022   }
49023   return 1;
49024 }
49025 #endif
49026
49027 /*
49028 ** Add vdbe p to the end of the statement lru list. It is assumed that
49029 ** p is not already part of the list when this is called. The lru list
49030 ** is protected by the SQLITE_MUTEX_STATIC_LRU mutex.
49031 */
49032 static void stmtLruAdd(Vdbe *p){
49033   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49034
49035   if( p->pLruPrev || p->pLruNext || sqlite3LruStatements.pFirst==p ){
49036     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49037     return;
49038   }
49039
49040   assert( stmtLruCheck() );
49041
49042   if( !sqlite3LruStatements.pFirst ){
49043     assert( !sqlite3LruStatements.pLast );
49044     sqlite3LruStatements.pFirst = p;
49045     sqlite3LruStatements.pLast = p;
49046   }else{
49047     assert( !sqlite3LruStatements.pLast->pLruNext );
49048     p->pLruPrev = sqlite3LruStatements.pLast;
49049     sqlite3LruStatements.pLast->pLruNext = p;
49050     sqlite3LruStatements.pLast = p;
49051   }
49052
49053   assert( stmtLruCheck() );
49054
49055   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49056 }
49057
49058 /*
49059 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is already held, remove
49060 ** statement p from the least-recently-used statement list. If the 
49061 ** statement is not currently part of the list, this call is a no-op.
49062 */
49063 static void stmtLruRemoveNomutex(Vdbe *p){
49064   if( p->pLruPrev || p->pLruNext || p==sqlite3LruStatements.pFirst ){
49065     assert( stmtLruCheck() );
49066     if( p->pLruNext ){
49067       p->pLruNext->pLruPrev = p->pLruPrev;
49068     }else{
49069       sqlite3LruStatements.pLast = p->pLruPrev;
49070     }
49071     if( p->pLruPrev ){
49072       p->pLruPrev->pLruNext = p->pLruNext;
49073     }else{
49074       sqlite3LruStatements.pFirst = p->pLruNext;
49075     }
49076     p->pLruNext = 0;
49077     p->pLruPrev = 0;
49078     assert( stmtLruCheck() );
49079   }
49080 }
49081
49082 /*
49083 ** Assuming the SQLITE_MUTEX_STATIC_LRU2 mutext is not held, remove
49084 ** statement p from the least-recently-used statement list. If the 
49085 ** statement is not currently part of the list, this call is a no-op.
49086 */
49087 static void stmtLruRemove(Vdbe *p){
49088   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49089   stmtLruRemoveNomutex(p);
49090   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49091 }
49092
49093 /*
49094 ** Try to release n bytes of memory by freeing buffers associated 
49095 ** with the memory registers of currently unused vdbes.
49096 */
49097 SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int n){
49098   Vdbe *p;
49099   Vdbe *pNext;
49100   int nFree = 0;
49101
49102   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49103   for(p=sqlite3LruStatements.pFirst; p && nFree<n; p=pNext){
49104     pNext = p->pLruNext;
49105
49106     /* For each statement handle in the lru list, attempt to obtain the
49107     ** associated database mutex. If it cannot be obtained, continue
49108     ** to the next statement handle. It is not possible to block on
49109     ** the database mutex - that could cause deadlock.
49110     */
49111     if( SQLITE_OK==sqlite3_mutex_try(p->db->mutex) ){
49112       nFree += sqlite3VdbeReleaseBuffers(p);
49113       stmtLruRemoveNomutex(p);
49114       sqlite3_mutex_leave(p->db->mutex);
49115     }
49116   }
49117   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU2));
49118
49119   return nFree;
49120 }
49121
49122 /*
49123 ** Call sqlite3Reprepare() on the statement. Remove it from the
49124 ** lru list before doing so, as Reprepare() will free all the
49125 ** memory register buffers anyway.
49126 */
49127 int vdbeReprepare(Vdbe *p){
49128   stmtLruRemove(p);
49129   return sqlite3Reprepare(p);
49130 }
49131
49132 #else       /* !SQLITE_ENABLE_MEMORY_MANAGEMENT */
49133   #define stmtLruRemove(x)
49134   #define stmtLruAdd(x)
49135   #define vdbeReprepare(x) sqlite3Reprepare(x)
49136 #endif
49137
49138
49139 #ifndef SQLITE_OMIT_DEPRECATED
49140 /*
49141 ** Return TRUE (non-zero) of the statement supplied as an argument needs
49142 ** to be recompiled.  A statement needs to be recompiled whenever the
49143 ** execution environment changes in a way that would alter the program
49144 ** that sqlite3_prepare() generates.  For example, if new functions or
49145 ** collating sequences are registered or if an authorizer function is
49146 ** added or changed.
49147 */
49148 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
49149   Vdbe *p = (Vdbe*)pStmt;
49150   return p==0 || p->expired;
49151 }
49152 #endif
49153
49154 /*
49155 ** The following routine destroys a virtual machine that is created by
49156 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
49157 ** success/failure code that describes the result of executing the virtual
49158 ** machine.
49159 **
49160 ** This routine sets the error code and string returned by
49161 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
49162 */
49163 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
49164   int rc;
49165   if( pStmt==0 ){
49166     rc = SQLITE_OK;
49167   }else{
49168     Vdbe *v = (Vdbe*)pStmt;
49169 #if SQLITE_THREADSAFE
49170     sqlite3_mutex *mutex = v->db->mutex;
49171 #endif
49172     sqlite3_mutex_enter(mutex);
49173     stmtLruRemove(v);
49174     rc = sqlite3VdbeFinalize(v);
49175     sqlite3_mutex_leave(mutex);
49176   }
49177   return rc;
49178 }
49179
49180 /*
49181 ** Terminate the current execution of an SQL statement and reset it
49182 ** back to its starting state so that it can be reused. A success code from
49183 ** the prior execution is returned.
49184 **
49185 ** This routine sets the error code and string returned by
49186 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
49187 */
49188 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
49189   int rc;
49190   if( pStmt==0 ){
49191     rc = SQLITE_OK;
49192   }else{
49193     Vdbe *v = (Vdbe*)pStmt;
49194     sqlite3_mutex_enter(v->db->mutex);
49195     rc = sqlite3VdbeReset(v);
49196     stmtLruAdd(v);
49197     sqlite3VdbeMakeReady(v, -1, 0, 0, 0);
49198     assert( (rc & (v->db->errMask))==rc );
49199     sqlite3_mutex_leave(v->db->mutex);
49200   }
49201   return rc;
49202 }
49203
49204 /*
49205 ** Set all the parameters in the compiled SQL statement to NULL.
49206 */
49207 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
49208   int i;
49209   int rc = SQLITE_OK;
49210   Vdbe *p = (Vdbe*)pStmt;
49211 #if SQLITE_THREADSAFE
49212   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
49213 #endif
49214   sqlite3_mutex_enter(mutex);
49215   for(i=0; i<p->nVar; i++){
49216     sqlite3VdbeMemRelease(&p->aVar[i]);
49217     p->aVar[i].flags = MEM_Null;
49218   }
49219   sqlite3_mutex_leave(mutex);
49220   return rc;
49221 }
49222
49223
49224 /**************************** sqlite3_value_  *******************************
49225 ** The following routines extract information from a Mem or sqlite3_value
49226 ** structure.
49227 */
49228 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
49229   Mem *p = (Mem*)pVal;
49230   if( p->flags & (MEM_Blob|MEM_Str) ){
49231     sqlite3VdbeMemExpandBlob(p);
49232     p->flags &= ~MEM_Str;
49233     p->flags |= MEM_Blob;
49234     return p->z;
49235   }else{
49236     return sqlite3_value_text(pVal);
49237   }
49238 }
49239 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
49240   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
49241 }
49242 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
49243   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
49244 }
49245 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
49246   return sqlite3VdbeRealValue((Mem*)pVal);
49247 }
49248 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
49249   return (int)sqlite3VdbeIntValue((Mem*)pVal);
49250 }
49251 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
49252   return sqlite3VdbeIntValue((Mem*)pVal);
49253 }
49254 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
49255   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
49256 }
49257 #ifndef SQLITE_OMIT_UTF16
49258 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
49259   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
49260 }
49261 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
49262   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
49263 }
49264 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
49265   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
49266 }
49267 #endif /* SQLITE_OMIT_UTF16 */
49268 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
49269   return pVal->type;
49270 }
49271
49272 /**************************** sqlite3_result_  *******************************
49273 ** The following routines are used by user-defined functions to specify
49274 ** the function result.
49275 */
49276 SQLITE_API void sqlite3_result_blob(
49277   sqlite3_context *pCtx, 
49278   const void *z, 
49279   int n, 
49280   void (*xDel)(void *)
49281 ){
49282   assert( n>=0 );
49283   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49284   sqlite3VdbeMemSetStr(&pCtx->s, z, n, 0, xDel);
49285 }
49286 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
49287   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49288   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
49289 }
49290 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
49291   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49292   pCtx->isError = SQLITE_ERROR;
49293   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
49294 }
49295 #ifndef SQLITE_OMIT_UTF16
49296 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
49297   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49298   pCtx->isError = SQLITE_ERROR;
49299   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
49300 }
49301 #endif
49302 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
49303   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49304   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
49305 }
49306 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
49307   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49308   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
49309 }
49310 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
49311   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49312   sqlite3VdbeMemSetNull(&pCtx->s);
49313 }
49314 SQLITE_API void sqlite3_result_text(
49315   sqlite3_context *pCtx, 
49316   const char *z, 
49317   int n,
49318   void (*xDel)(void *)
49319 ){
49320   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49321   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, xDel);
49322 }
49323 #ifndef SQLITE_OMIT_UTF16
49324 SQLITE_API void sqlite3_result_text16(
49325   sqlite3_context *pCtx, 
49326   const void *z, 
49327   int n, 
49328   void (*xDel)(void *)
49329 ){
49330   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49331   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, xDel);
49332 }
49333 SQLITE_API void sqlite3_result_text16be(
49334   sqlite3_context *pCtx, 
49335   const void *z, 
49336   int n, 
49337   void (*xDel)(void *)
49338 ){
49339   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49340   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16BE, xDel);
49341 }
49342 SQLITE_API void sqlite3_result_text16le(
49343   sqlite3_context *pCtx, 
49344   const void *z, 
49345   int n, 
49346   void (*xDel)(void *)
49347 ){
49348   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49349   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16LE, xDel);
49350 }
49351 #endif /* SQLITE_OMIT_UTF16 */
49352 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
49353   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49354   sqlite3VdbeMemCopy(&pCtx->s, pValue);
49355 }
49356 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
49357   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49358   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
49359 }
49360 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
49361   pCtx->isError = errCode;
49362 }
49363
49364 /* Force an SQLITE_TOOBIG error. */
49365 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
49366   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49367   pCtx->isError = SQLITE_TOOBIG;
49368   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
49369                        SQLITE_UTF8, SQLITE_STATIC);
49370 }
49371
49372 /* An SQLITE_NOMEM error. */
49373 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
49374   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49375   sqlite3VdbeMemSetNull(&pCtx->s);
49376   pCtx->isError = SQLITE_NOMEM;
49377   pCtx->s.db->mallocFailed = 1;
49378 }
49379
49380 /*
49381 ** Execute the statement pStmt, either until a row of data is ready, the
49382 ** statement is completely executed or an error occurs.
49383 **
49384 ** This routine implements the bulk of the logic behind the sqlite_step()
49385 ** API.  The only thing omitted is the automatic recompile if a 
49386 ** schema change has occurred.  That detail is handled by the
49387 ** outer sqlite3_step() wrapper procedure.
49388 */
49389 static int sqlite3Step(Vdbe *p){
49390   sqlite3 *db;
49391   int rc;
49392
49393   assert(p);
49394   if( p->magic!=VDBE_MAGIC_RUN ){
49395     return SQLITE_MISUSE;
49396   }
49397
49398   /* Assert that malloc() has not failed */
49399   db = p->db;
49400   if( db->mallocFailed ){
49401     return SQLITE_NOMEM;
49402   }
49403
49404   if( p->pc<=0 && p->expired ){
49405     if( p->rc==SQLITE_OK ){
49406       p->rc = SQLITE_SCHEMA;
49407     }
49408     rc = SQLITE_ERROR;
49409     goto end_of_step;
49410   }
49411   if( sqlite3SafetyOn(db) ){
49412     p->rc = SQLITE_MISUSE;
49413     return SQLITE_MISUSE;
49414   }
49415   if( p->pc<0 ){
49416     /* If there are no other statements currently running, then
49417     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
49418     ** from interrupting a statement that has not yet started.
49419     */
49420     if( db->activeVdbeCnt==0 ){
49421       db->u1.isInterrupted = 0;
49422     }
49423
49424 #ifndef SQLITE_OMIT_TRACE
49425     if( db->xProfile && !db->init.busy ){
49426       double rNow;
49427       sqlite3OsCurrentTime(db->pVfs, &rNow);
49428       p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
49429     }
49430 #endif
49431
49432     db->activeVdbeCnt++;
49433     if( p->readOnly==0 ) db->writeVdbeCnt++;
49434     p->pc = 0;
49435     stmtLruRemove(p);
49436   }
49437 #ifndef SQLITE_OMIT_EXPLAIN
49438   if( p->explain ){
49439     rc = sqlite3VdbeList(p);
49440   }else
49441 #endif /* SQLITE_OMIT_EXPLAIN */
49442   {
49443     rc = sqlite3VdbeExec(p);
49444   }
49445
49446   if( sqlite3SafetyOff(db) ){
49447     rc = SQLITE_MISUSE;
49448   }
49449
49450 #ifndef SQLITE_OMIT_TRACE
49451   /* Invoke the profile callback if there is one
49452   */
49453   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0
49454            && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){
49455     double rNow;
49456     u64 elapseTime;
49457
49458     sqlite3OsCurrentTime(db->pVfs, &rNow);
49459     elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
49460     elapseTime -= p->startTime;
49461     db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime);
49462   }
49463 #endif
49464
49465   db->errCode = rc;
49466   /*sqlite3Error(p->db, rc, 0);*/
49467   p->rc = sqlite3ApiExit(p->db, p->rc);
49468 end_of_step:
49469   assert( (rc&0xff)==rc );
49470   if( p->zSql && (rc&0xff)<SQLITE_ROW ){
49471     /* This behavior occurs if sqlite3_prepare_v2() was used to build
49472     ** the prepared statement.  Return error codes directly */
49473     p->db->errCode = p->rc;
49474     /* sqlite3Error(p->db, p->rc, 0); */
49475     return p->rc;
49476   }else{
49477     /* This is for legacy sqlite3_prepare() builds and when the code
49478     ** is SQLITE_ROW or SQLITE_DONE */
49479     return rc;
49480   }
49481 }
49482
49483 /*
49484 ** This is the top-level implementation of sqlite3_step().  Call
49485 ** sqlite3Step() to do most of the work.  If a schema error occurs,
49486 ** call sqlite3Reprepare() and try again.
49487 */
49488 #ifdef SQLITE_OMIT_PARSER
49489 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
49490   int rc = SQLITE_MISUSE;
49491   if( pStmt ){
49492     Vdbe *v;
49493     v = (Vdbe*)pStmt;
49494     sqlite3_mutex_enter(v->db->mutex);
49495     rc = sqlite3Step(v);
49496     sqlite3_mutex_leave(v->db->mutex);
49497   }
49498   return rc;
49499 }
49500 #else
49501 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
49502   int rc = SQLITE_MISUSE;
49503   if( pStmt ){
49504     int cnt = 0;
49505     Vdbe *v = (Vdbe*)pStmt;
49506     sqlite3 *db = v->db;
49507     sqlite3_mutex_enter(db->mutex);
49508     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
49509            && cnt++ < 5
49510            && vdbeReprepare(v) ){
49511       sqlite3_reset(pStmt);
49512       v->expired = 0;
49513     }
49514     if( rc==SQLITE_SCHEMA && v->zSql && db->pErr ){
49515       /* This case occurs after failing to recompile an sql statement. 
49516       ** The error message from the SQL compiler has already been loaded 
49517       ** into the database handle. This block copies the error message 
49518       ** from the database handle into the statement and sets the statement
49519       ** program counter to 0 to ensure that when the statement is 
49520       ** finalized or reset the parser error message is available via
49521       ** sqlite3_errmsg() and sqlite3_errcode().
49522       */
49523       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
49524       sqlite3DbFree(db, v->zErrMsg);
49525       if( !db->mallocFailed ){
49526         v->zErrMsg = sqlite3DbStrDup(db, zErr);
49527       } else {
49528         v->zErrMsg = 0;
49529         v->rc = SQLITE_NOMEM;
49530       }
49531     }
49532     rc = sqlite3ApiExit(db, rc);
49533     sqlite3_mutex_leave(db->mutex);
49534   }
49535   return rc;
49536 }
49537 #endif
49538
49539 /*
49540 ** Extract the user data from a sqlite3_context structure and return a
49541 ** pointer to it.
49542 */
49543 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
49544   assert( p && p->pFunc );
49545   return p->pFunc->pUserData;
49546 }
49547
49548 /*
49549 ** Extract the user data from a sqlite3_context structure and return a
49550 ** pointer to it.
49551 */
49552 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
49553   assert( p && p->pFunc );
49554   return p->s.db;
49555 }
49556
49557 /*
49558 ** The following is the implementation of an SQL function that always
49559 ** fails with an error message stating that the function is used in the
49560 ** wrong context.  The sqlite3_overload_function() API might construct
49561 ** SQL function that use this routine so that the functions will exist
49562 ** for name resolution but are actually overloaded by the xFindFunction
49563 ** method of virtual tables.
49564 */
49565 SQLITE_PRIVATE void sqlite3InvalidFunction(
49566   sqlite3_context *context,  /* The function calling context */
49567   int NotUsed,               /* Number of arguments to the function */
49568   sqlite3_value **NotUsed2   /* Value of each argument */
49569 ){
49570   const char *zName = context->pFunc->zName;
49571   char *zErr;
49572   UNUSED_PARAMETER2(NotUsed, NotUsed2);
49573   zErr = sqlite3MPrintf(0,
49574       "unable to use function %s in the requested context", zName);
49575   sqlite3_result_error(context, zErr, -1);
49576   sqlite3_free(zErr);
49577 }
49578
49579 /*
49580 ** Allocate or return the aggregate context for a user function.  A new
49581 ** context is allocated on the first call.  Subsequent calls return the
49582 ** same context that was returned on prior calls.
49583 */
49584 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
49585   Mem *pMem;
49586   assert( p && p->pFunc && p->pFunc->xStep );
49587   assert( sqlite3_mutex_held(p->s.db->mutex) );
49588   pMem = p->pMem;
49589   if( (pMem->flags & MEM_Agg)==0 ){
49590     if( nByte==0 ){
49591       sqlite3VdbeMemReleaseExternal(pMem);
49592       pMem->flags = MEM_Null;
49593       pMem->z = 0;
49594     }else{
49595       sqlite3VdbeMemGrow(pMem, nByte, 0);
49596       pMem->flags = MEM_Agg;
49597       pMem->u.pDef = p->pFunc;
49598       if( pMem->z ){
49599         memset(pMem->z, 0, nByte);
49600       }
49601     }
49602   }
49603   return (void*)pMem->z;
49604 }
49605
49606 /*
49607 ** Return the auxilary data pointer, if any, for the iArg'th argument to
49608 ** the user-function defined by pCtx.
49609 */
49610 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
49611   VdbeFunc *pVdbeFunc;
49612
49613   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49614   pVdbeFunc = pCtx->pVdbeFunc;
49615   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
49616     return 0;
49617   }
49618   return pVdbeFunc->apAux[iArg].pAux;
49619 }
49620
49621 /*
49622 ** Set the auxilary data pointer and delete function, for the iArg'th
49623 ** argument to the user-function defined by pCtx. Any previous value is
49624 ** deleted by calling the delete function specified when it was set.
49625 */
49626 SQLITE_API void sqlite3_set_auxdata(
49627   sqlite3_context *pCtx, 
49628   int iArg, 
49629   void *pAux, 
49630   void (*xDelete)(void*)
49631 ){
49632   struct AuxData *pAuxData;
49633   VdbeFunc *pVdbeFunc;
49634   if( iArg<0 ) goto failed;
49635
49636   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
49637   pVdbeFunc = pCtx->pVdbeFunc;
49638   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
49639     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
49640     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
49641     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
49642     if( !pVdbeFunc ){
49643       goto failed;
49644     }
49645     pCtx->pVdbeFunc = pVdbeFunc;
49646     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
49647     pVdbeFunc->nAux = iArg+1;
49648     pVdbeFunc->pFunc = pCtx->pFunc;
49649   }
49650
49651   pAuxData = &pVdbeFunc->apAux[iArg];
49652   if( pAuxData->pAux && pAuxData->xDelete ){
49653     pAuxData->xDelete(pAuxData->pAux);
49654   }
49655   pAuxData->pAux = pAux;
49656   pAuxData->xDelete = xDelete;
49657   return;
49658
49659 failed:
49660   if( xDelete ){
49661     xDelete(pAux);
49662   }
49663 }
49664
49665 #ifndef SQLITE_OMIT_DEPRECATED
49666 /*
49667 ** Return the number of times the Step function of a aggregate has been 
49668 ** called.
49669 **
49670 ** This function is deprecated.  Do not use it for new code.  It is
49671 ** provide only to avoid breaking legacy code.  New aggregate function
49672 ** implementations should keep their own counts within their aggregate
49673 ** context.
49674 */
49675 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
49676   assert( p && p->pFunc && p->pFunc->xStep );
49677   return p->pMem->n;
49678 }
49679 #endif
49680
49681 /*
49682 ** Return the number of columns in the result set for the statement pStmt.
49683 */
49684 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
49685   Vdbe *pVm = (Vdbe *)pStmt;
49686   return pVm ? pVm->nResColumn : 0;
49687 }
49688
49689 /*
49690 ** Return the number of values available from the current row of the
49691 ** currently executing statement pStmt.
49692 */
49693 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
49694   Vdbe *pVm = (Vdbe *)pStmt;
49695   if( pVm==0 || pVm->pResultSet==0 ) return 0;
49696   return pVm->nResColumn;
49697 }
49698
49699
49700 /*
49701 ** Check to see if column iCol of the given statement is valid.  If
49702 ** it is, return a pointer to the Mem for the value of that column.
49703 ** If iCol is not valid, return a pointer to a Mem which has a value
49704 ** of NULL.
49705 */
49706 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
49707   Vdbe *pVm;
49708   int vals;
49709   Mem *pOut;
49710
49711   pVm = (Vdbe *)pStmt;
49712   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
49713     sqlite3_mutex_enter(pVm->db->mutex);
49714     vals = sqlite3_data_count(pStmt);
49715     pOut = &pVm->pResultSet[i];
49716   }else{
49717     /* ((double)0) In case of SQLITE_OMIT_FLOATING_POINT... */
49718     static const Mem nullMem = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
49719     if( pVm->db ){
49720       sqlite3_mutex_enter(pVm->db->mutex);
49721       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
49722     }
49723     pOut = (Mem*)&nullMem;
49724   }
49725   return pOut;
49726 }
49727
49728 /*
49729 ** This function is called after invoking an sqlite3_value_XXX function on a 
49730 ** column value (i.e. a value returned by evaluating an SQL expression in the
49731 ** select list of a SELECT statement) that may cause a malloc() failure. If 
49732 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
49733 ** code of statement pStmt set to SQLITE_NOMEM.
49734 **
49735 ** Specifically, this is called from within:
49736 **
49737 **     sqlite3_column_int()
49738 **     sqlite3_column_int64()
49739 **     sqlite3_column_text()
49740 **     sqlite3_column_text16()
49741 **     sqlite3_column_real()
49742 **     sqlite3_column_bytes()
49743 **     sqlite3_column_bytes16()
49744 **
49745 ** But not for sqlite3_column_blob(), which never calls malloc().
49746 */
49747 static void columnMallocFailure(sqlite3_stmt *pStmt)
49748 {
49749   /* If malloc() failed during an encoding conversion within an
49750   ** sqlite3_column_XXX API, then set the return code of the statement to
49751   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
49752   ** and _finalize() will return NOMEM.
49753   */
49754   Vdbe *p = (Vdbe *)pStmt;
49755   if( p ){
49756     p->rc = sqlite3ApiExit(p->db, p->rc);
49757     sqlite3_mutex_leave(p->db->mutex);
49758   }
49759 }
49760
49761 /**************************** sqlite3_column_  *******************************
49762 ** The following routines are used to access elements of the current row
49763 ** in the result set.
49764 */
49765 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
49766   const void *val;
49767   val = sqlite3_value_blob( columnMem(pStmt,i) );
49768   /* Even though there is no encoding conversion, value_blob() might
49769   ** need to call malloc() to expand the result of a zeroblob() 
49770   ** expression. 
49771   */
49772   columnMallocFailure(pStmt);
49773   return val;
49774 }
49775 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
49776   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
49777   columnMallocFailure(pStmt);
49778   return val;
49779 }
49780 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
49781   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
49782   columnMallocFailure(pStmt);
49783   return val;
49784 }
49785 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
49786   double val = sqlite3_value_double( columnMem(pStmt,i) );
49787   columnMallocFailure(pStmt);
49788   return val;
49789 }
49790 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
49791   int val = sqlite3_value_int( columnMem(pStmt,i) );
49792   columnMallocFailure(pStmt);
49793   return val;
49794 }
49795 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
49796   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
49797   columnMallocFailure(pStmt);
49798   return val;
49799 }
49800 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
49801   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
49802   columnMallocFailure(pStmt);
49803   return val;
49804 }
49805 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
49806   Mem *pOut = columnMem(pStmt, i);
49807   if( pOut->flags&MEM_Static ){
49808     pOut->flags &= ~MEM_Static;
49809     pOut->flags |= MEM_Ephem;
49810   }
49811   columnMallocFailure(pStmt);
49812   return (sqlite3_value *)pOut;
49813 }
49814 #ifndef SQLITE_OMIT_UTF16
49815 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
49816   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
49817   columnMallocFailure(pStmt);
49818   return val;
49819 }
49820 #endif /* SQLITE_OMIT_UTF16 */
49821 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
49822   int iType = sqlite3_value_type( columnMem(pStmt,i) );
49823   columnMallocFailure(pStmt);
49824   return iType;
49825 }
49826
49827 /* The following function is experimental and subject to change or
49828 ** removal */
49829 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
49830 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
49831 **}
49832 */
49833
49834 /*
49835 ** Convert the N-th element of pStmt->pColName[] into a string using
49836 ** xFunc() then return that string.  If N is out of range, return 0.
49837 **
49838 ** There are up to 5 names for each column.  useType determines which
49839 ** name is returned.  Here are the names:
49840 **
49841 **    0      The column name as it should be displayed for output
49842 **    1      The datatype name for the column
49843 **    2      The name of the database that the column derives from
49844 **    3      The name of the table that the column derives from
49845 **    4      The name of the table column that the result column derives from
49846 **
49847 ** If the result is not a simple column reference (if it is an expression
49848 ** or a constant) then useTypes 2, 3, and 4 return NULL.
49849 */
49850 static const void *columnName(
49851   sqlite3_stmt *pStmt,
49852   int N,
49853   const void *(*xFunc)(Mem*),
49854   int useType
49855 ){
49856   const void *ret = 0;
49857   Vdbe *p = (Vdbe *)pStmt;
49858   int n;
49859   
49860
49861   if( p!=0 ){
49862     n = sqlite3_column_count(pStmt);
49863     if( N<n && N>=0 ){
49864       N += useType*n;
49865       sqlite3_mutex_enter(p->db->mutex);
49866       ret = xFunc(&p->aColName[N]);
49867
49868       /* A malloc may have failed inside of the xFunc() call. If this
49869       ** is the case, clear the mallocFailed flag and return NULL.
49870       */
49871       if( p->db && p->db->mallocFailed ){
49872         p->db->mallocFailed = 0;
49873         ret = 0;
49874       }
49875       sqlite3_mutex_leave(p->db->mutex);
49876     }
49877   }
49878   return ret;
49879 }
49880
49881 /*
49882 ** Return the name of the Nth column of the result set returned by SQL
49883 ** statement pStmt.
49884 */
49885 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
49886   return columnName(
49887       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
49888 }
49889 #ifndef SQLITE_OMIT_UTF16
49890 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
49891   return columnName(
49892       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
49893 }
49894 #endif
49895
49896 /*
49897 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
49898 ** not define OMIT_DECLTYPE.
49899 */
49900 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
49901 # error "Must not define both SQLITE_OMIT_DECLTYPE \
49902          and SQLITE_ENABLE_COLUMN_METADATA"
49903 #endif
49904
49905 #ifndef SQLITE_OMIT_DECLTYPE
49906 /*
49907 ** Return the column declaration type (if applicable) of the 'i'th column
49908 ** of the result set of SQL statement pStmt.
49909 */
49910 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
49911   return columnName(
49912       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
49913 }
49914 #ifndef SQLITE_OMIT_UTF16
49915 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
49916   return columnName(
49917       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
49918 }
49919 #endif /* SQLITE_OMIT_UTF16 */
49920 #endif /* SQLITE_OMIT_DECLTYPE */
49921
49922 #ifdef SQLITE_ENABLE_COLUMN_METADATA
49923 /*
49924 ** Return the name of the database from which a result column derives.
49925 ** NULL is returned if the result column is an expression or constant or
49926 ** anything else which is not an unabiguous reference to a database column.
49927 */
49928 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
49929   return columnName(
49930       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
49931 }
49932 #ifndef SQLITE_OMIT_UTF16
49933 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
49934   return columnName(
49935       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
49936 }
49937 #endif /* SQLITE_OMIT_UTF16 */
49938
49939 /*
49940 ** Return the name of the table from which a result column derives.
49941 ** NULL is returned if the result column is an expression or constant or
49942 ** anything else which is not an unabiguous reference to a database column.
49943 */
49944 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
49945   return columnName(
49946       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
49947 }
49948 #ifndef SQLITE_OMIT_UTF16
49949 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
49950   return columnName(
49951       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
49952 }
49953 #endif /* SQLITE_OMIT_UTF16 */
49954
49955 /*
49956 ** Return the name of the table column from which a result column derives.
49957 ** NULL is returned if the result column is an expression or constant or
49958 ** anything else which is not an unabiguous reference to a database column.
49959 */
49960 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
49961   return columnName(
49962       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
49963 }
49964 #ifndef SQLITE_OMIT_UTF16
49965 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
49966   return columnName(
49967       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
49968 }
49969 #endif /* SQLITE_OMIT_UTF16 */
49970 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
49971
49972
49973 /******************************* sqlite3_bind_  ***************************
49974 ** 
49975 ** Routines used to attach values to wildcards in a compiled SQL statement.
49976 */
49977 /*
49978 ** Unbind the value bound to variable i in virtual machine p. This is the 
49979 ** the same as binding a NULL value to the column. If the "i" parameter is
49980 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
49981 **
49982 ** A successful evaluation of this routine acquires the mutex on p.
49983 ** the mutex is released if any kind of error occurs.
49984 **
49985 ** The error code stored in database p->db is overwritten with the return
49986 ** value in any case.
49987 */
49988 static int vdbeUnbind(Vdbe *p, int i){
49989   Mem *pVar;
49990   if( p==0 ) return SQLITE_MISUSE;
49991   sqlite3_mutex_enter(p->db->mutex);
49992   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
49993     sqlite3Error(p->db, SQLITE_MISUSE, 0);
49994     sqlite3_mutex_leave(p->db->mutex);
49995     return SQLITE_MISUSE;
49996   }
49997   if( i<1 || i>p->nVar ){
49998     sqlite3Error(p->db, SQLITE_RANGE, 0);
49999     sqlite3_mutex_leave(p->db->mutex);
50000     return SQLITE_RANGE;
50001   }
50002   i--;
50003   pVar = &p->aVar[i];
50004   sqlite3VdbeMemRelease(pVar);
50005   pVar->flags = MEM_Null;
50006   sqlite3Error(p->db, SQLITE_OK, 0);
50007   return SQLITE_OK;
50008 }
50009
50010 /*
50011 ** Bind a text or BLOB value.
50012 */
50013 static int bindText(
50014   sqlite3_stmt *pStmt,   /* The statement to bind against */
50015   int i,                 /* Index of the parameter to bind */
50016   const void *zData,     /* Pointer to the data to be bound */
50017   int nData,             /* Number of bytes of data to be bound */
50018   void (*xDel)(void*),   /* Destructor for the data */
50019   u8 encoding            /* Encoding for the data */
50020 ){
50021   Vdbe *p = (Vdbe *)pStmt;
50022   Mem *pVar;
50023   int rc;
50024
50025   rc = vdbeUnbind(p, i);
50026   if( rc==SQLITE_OK ){
50027     if( zData!=0 ){
50028       pVar = &p->aVar[i-1];
50029       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
50030       if( rc==SQLITE_OK && encoding!=0 ){
50031         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
50032       }
50033       sqlite3Error(p->db, rc, 0);
50034       rc = sqlite3ApiExit(p->db, rc);
50035     }
50036     sqlite3_mutex_leave(p->db->mutex);
50037   }
50038   return rc;
50039 }
50040
50041
50042 /*
50043 ** Bind a blob value to an SQL statement variable.
50044 */
50045 SQLITE_API int sqlite3_bind_blob(
50046   sqlite3_stmt *pStmt, 
50047   int i, 
50048   const void *zData, 
50049   int nData, 
50050   void (*xDel)(void*)
50051 ){
50052   return bindText(pStmt, i, zData, nData, xDel, 0);
50053 }
50054 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
50055   int rc;
50056   Vdbe *p = (Vdbe *)pStmt;
50057   rc = vdbeUnbind(p, i);
50058   if( rc==SQLITE_OK ){
50059     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
50060     sqlite3_mutex_leave(p->db->mutex);
50061   }
50062   return rc;
50063 }
50064 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
50065   return sqlite3_bind_int64(p, i, (i64)iValue);
50066 }
50067 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
50068   int rc;
50069   Vdbe *p = (Vdbe *)pStmt;
50070   rc = vdbeUnbind(p, i);
50071   if( rc==SQLITE_OK ){
50072     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
50073     sqlite3_mutex_leave(p->db->mutex);
50074   }
50075   return rc;
50076 }
50077 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
50078   int rc;
50079   Vdbe *p = (Vdbe*)pStmt;
50080   rc = vdbeUnbind(p, i);
50081   if( rc==SQLITE_OK ){
50082     sqlite3_mutex_leave(p->db->mutex);
50083   }
50084   return rc;
50085 }
50086 SQLITE_API int sqlite3_bind_text( 
50087   sqlite3_stmt *pStmt, 
50088   int i, 
50089   const char *zData, 
50090   int nData, 
50091   void (*xDel)(void*)
50092 ){
50093   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
50094 }
50095 #ifndef SQLITE_OMIT_UTF16
50096 SQLITE_API int sqlite3_bind_text16(
50097   sqlite3_stmt *pStmt, 
50098   int i, 
50099   const void *zData, 
50100   int nData, 
50101   void (*xDel)(void*)
50102 ){
50103   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
50104 }
50105 #endif /* SQLITE_OMIT_UTF16 */
50106 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
50107   int rc;
50108   Vdbe *p = (Vdbe *)pStmt;
50109   rc = vdbeUnbind(p, i);
50110   if( rc==SQLITE_OK ){
50111     rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
50112     if( rc==SQLITE_OK ){
50113       rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
50114     }
50115     sqlite3_mutex_leave(p->db->mutex);
50116   }
50117   rc = sqlite3ApiExit(p->db, rc);
50118   return rc;
50119 }
50120 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
50121   int rc;
50122   Vdbe *p = (Vdbe *)pStmt;
50123   rc = vdbeUnbind(p, i);
50124   if( rc==SQLITE_OK ){
50125     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
50126     sqlite3_mutex_leave(p->db->mutex);
50127   }
50128   return rc;
50129 }
50130
50131 /*
50132 ** Return the number of wildcards that can be potentially bound to.
50133 ** This routine is added to support DBD::SQLite.  
50134 */
50135 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
50136   Vdbe *p = (Vdbe*)pStmt;
50137   return p ? p->nVar : 0;
50138 }
50139
50140 /*
50141 ** Create a mapping from variable numbers to variable names
50142 ** in the Vdbe.azVar[] array, if such a mapping does not already
50143 ** exist.
50144 */
50145 static void createVarMap(Vdbe *p){
50146   if( !p->okVar ){
50147     sqlite3_mutex_enter(p->db->mutex);
50148     if( !p->okVar ){
50149       int j;
50150       Op *pOp;
50151       for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
50152         if( pOp->opcode==OP_Variable ){
50153           assert( pOp->p1>0 && pOp->p1<=p->nVar );
50154           p->azVar[pOp->p1-1] = pOp->p4.z;
50155         }
50156       }
50157       p->okVar = 1;
50158     }
50159     sqlite3_mutex_leave(p->db->mutex);
50160   }
50161 }
50162
50163 /*
50164 ** Return the name of a wildcard parameter.  Return NULL if the index
50165 ** is out of range or if the wildcard is unnamed.
50166 **
50167 ** The result is always UTF-8.
50168 */
50169 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
50170   Vdbe *p = (Vdbe*)pStmt;
50171   if( p==0 || i<1 || i>p->nVar ){
50172     return 0;
50173   }
50174   createVarMap(p);
50175   return p->azVar[i-1];
50176 }
50177
50178 /*
50179 ** Given a wildcard parameter name, return the index of the variable
50180 ** with that name.  If there is no variable with the given name,
50181 ** return 0.
50182 */
50183 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
50184   Vdbe *p = (Vdbe*)pStmt;
50185   int i;
50186   if( p==0 ){
50187     return 0;
50188   }
50189   createVarMap(p); 
50190   if( zName ){
50191     for(i=0; i<p->nVar; i++){
50192       const char *z = p->azVar[i];
50193       if( z && strcmp(z,zName)==0 ){
50194         return i+1;
50195       }
50196     }
50197   }
50198   return 0;
50199 }
50200
50201 /*
50202 ** Transfer all bindings from the first statement over to the second.
50203 ** If the two statements contain a different number of bindings, then
50204 ** an SQLITE_ERROR is returned.
50205 */
50206 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
50207   Vdbe *pFrom = (Vdbe*)pFromStmt;
50208   Vdbe *pTo = (Vdbe*)pToStmt;
50209   int i, rc = SQLITE_OK;
50210   if( (pFrom->magic!=VDBE_MAGIC_RUN && pFrom->magic!=VDBE_MAGIC_HALT)
50211     || (pTo->magic!=VDBE_MAGIC_RUN && pTo->magic!=VDBE_MAGIC_HALT)
50212     || pTo->db!=pFrom->db ){
50213     return SQLITE_MISUSE;
50214   }
50215   if( pFrom->nVar!=pTo->nVar ){
50216     return SQLITE_ERROR;
50217   }
50218   sqlite3_mutex_enter(pTo->db->mutex);
50219   for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){
50220     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
50221   }
50222   sqlite3_mutex_leave(pTo->db->mutex);
50223   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
50224   return rc;
50225 }
50226
50227 #ifndef SQLITE_OMIT_DEPRECATED
50228 /*
50229 ** Deprecated external interface.  Internal/core SQLite code
50230 ** should call sqlite3TransferBindings.
50231 */
50232 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
50233   return sqlite3TransferBindings(pFromStmt, pToStmt);
50234 }
50235 #endif
50236
50237 /*
50238 ** Return the sqlite3* database handle to which the prepared statement given
50239 ** in the argument belongs.  This is the same database handle that was
50240 ** the first argument to the sqlite3_prepare() that was used to create
50241 ** the statement in the first place.
50242 */
50243 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
50244   return pStmt ? ((Vdbe*)pStmt)->db : 0;
50245 }
50246
50247 /*
50248 ** Return a pointer to the next prepared statement after pStmt associated
50249 ** with database connection pDb.  If pStmt is NULL, return the first
50250 ** prepared statement for the database connection.  Return NULL if there
50251 ** are no more.
50252 */
50253 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
50254   sqlite3_stmt *pNext;
50255   sqlite3_mutex_enter(pDb->mutex);
50256   if( pStmt==0 ){
50257     pNext = (sqlite3_stmt*)pDb->pVdbe;
50258   }else{
50259     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
50260   }
50261   sqlite3_mutex_leave(pDb->mutex);
50262   return pNext;
50263 }
50264
50265 /*
50266 ** Return the value of a status counter for a prepared statement
50267 */
50268 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
50269   Vdbe *pVdbe = (Vdbe*)pStmt;
50270   int v = pVdbe->aCounter[op-1];
50271   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
50272   return v;
50273 }
50274
50275 /************** End of vdbeapi.c *********************************************/
50276 /************** Begin file vdbe.c ********************************************/
50277 /*
50278 ** 2001 September 15
50279 **
50280 ** The author disclaims copyright to this source code.  In place of
50281 ** a legal notice, here is a blessing:
50282 **
50283 **    May you do good and not evil.
50284 **    May you find forgiveness for yourself and forgive others.
50285 **    May you share freely, never taking more than you give.
50286 **
50287 *************************************************************************
50288 ** The code in this file implements execution method of the 
50289 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
50290 ** handles housekeeping details such as creating and deleting
50291 ** VDBE instances.  This file is solely interested in executing
50292 ** the VDBE program.
50293 **
50294 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
50295 ** to a VDBE.
50296 **
50297 ** The SQL parser generates a program which is then executed by
50298 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
50299 ** similar in form to assembly language.  The program consists of
50300 ** a linear sequence of operations.  Each operation has an opcode 
50301 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
50302 ** is a null-terminated string.  Operand P5 is an unsigned character.
50303 ** Few opcodes use all 5 operands.
50304 **
50305 ** Computation results are stored on a set of registers numbered beginning
50306 ** with 1 and going up to Vdbe.nMem.  Each register can store
50307 ** either an integer, a null-terminated string, a floating point
50308 ** number, or the SQL "NULL" value.  An implicit conversion from one
50309 ** type to the other occurs as necessary.
50310 ** 
50311 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
50312 ** function which does the work of interpreting a VDBE program.
50313 ** But other routines are also provided to help in building up
50314 ** a program instruction by instruction.
50315 **
50316 ** Various scripts scan this source file in order to generate HTML
50317 ** documentation, headers files, or other derived files.  The formatting
50318 ** of the code in this file is, therefore, important.  See other comments
50319 ** in this file for details.  If in doubt, do not deviate from existing
50320 ** commenting and indentation practices when changing or adding code.
50321 **
50322 ** $Id: vdbe.c,v 1.817 2009/02/16 17:55:47 shane Exp $
50323 */
50324
50325 /*
50326 ** The following global variable is incremented every time a cursor
50327 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
50328 ** procedures use this information to make sure that indices are
50329 ** working correctly.  This variable has no function other than to
50330 ** help verify the correct operation of the library.
50331 */
50332 #ifdef SQLITE_TEST
50333 SQLITE_API int sqlite3_search_count = 0;
50334 #endif
50335
50336 /*
50337 ** When this global variable is positive, it gets decremented once before
50338 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
50339 ** field of the sqlite3 structure is set in order to simulate and interrupt.
50340 **
50341 ** This facility is used for testing purposes only.  It does not function
50342 ** in an ordinary build.
50343 */
50344 #ifdef SQLITE_TEST
50345 SQLITE_API int sqlite3_interrupt_count = 0;
50346 #endif
50347
50348 /*
50349 ** The next global variable is incremented each type the OP_Sort opcode
50350 ** is executed.  The test procedures use this information to make sure that
50351 ** sorting is occurring or not occurring at appropriate times.   This variable
50352 ** has no function other than to help verify the correct operation of the
50353 ** library.
50354 */
50355 #ifdef SQLITE_TEST
50356 SQLITE_API int sqlite3_sort_count = 0;
50357 #endif
50358
50359 /*
50360 ** The next global variable records the size of the largest MEM_Blob
50361 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
50362 ** use this information to make sure that the zero-blob functionality
50363 ** is working correctly.   This variable has no function other than to
50364 ** help verify the correct operation of the library.
50365 */
50366 #ifdef SQLITE_TEST
50367 SQLITE_API int sqlite3_max_blobsize = 0;
50368 static void updateMaxBlobsize(Mem *p){
50369   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
50370     sqlite3_max_blobsize = p->n;
50371   }
50372 }
50373 #endif
50374
50375 /*
50376 ** Test a register to see if it exceeds the current maximum blob size.
50377 ** If it does, record the new maximum blob size.
50378 */
50379 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
50380 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
50381 #else
50382 # define UPDATE_MAX_BLOBSIZE(P)
50383 #endif
50384
50385 /*
50386 ** Convert the given register into a string if it isn't one
50387 ** already. Return non-zero if a malloc() fails.
50388 */
50389 #define Stringify(P, enc) \
50390    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
50391      { goto no_mem; }
50392
50393 /*
50394 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
50395 ** a pointer to a dynamically allocated string where some other entity
50396 ** is responsible for deallocating that string.  Because the register
50397 ** does not control the string, it might be deleted without the register
50398 ** knowing it.
50399 **
50400 ** This routine converts an ephemeral string into a dynamically allocated
50401 ** string that the register itself controls.  In other words, it
50402 ** converts an MEM_Ephem string into an MEM_Dyn string.
50403 */
50404 #define Deephemeralize(P) \
50405    if( ((P)->flags&MEM_Ephem)!=0 \
50406        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
50407
50408 /*
50409 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
50410 ** P if required.
50411 */
50412 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
50413
50414 /*
50415 ** Argument pMem points at a register that will be passed to a
50416 ** user-defined function or returned to the user as the result of a query.
50417 ** The second argument, 'db_enc' is the text encoding used by the vdbe for
50418 ** register variables.  This routine sets the pMem->enc and pMem->type
50419 ** variables used by the sqlite3_value_*() routines.
50420 */
50421 #define storeTypeInfo(A,B) _storeTypeInfo(A)
50422 static void _storeTypeInfo(Mem *pMem){
50423   int flags = pMem->flags;
50424   if( flags & MEM_Null ){
50425     pMem->type = SQLITE_NULL;
50426   }
50427   else if( flags & MEM_Int ){
50428     pMem->type = SQLITE_INTEGER;
50429   }
50430   else if( flags & MEM_Real ){
50431     pMem->type = SQLITE_FLOAT;
50432   }
50433   else if( flags & MEM_Str ){
50434     pMem->type = SQLITE_TEXT;
50435   }else{
50436     pMem->type = SQLITE_BLOB;
50437   }
50438 }
50439
50440 /*
50441 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
50442 ** created by mkopcodeh.awk during compilation.  Data is obtained
50443 ** from the comments following the "case OP_xxxx:" statements in
50444 ** this file.  
50445 */
50446 static const unsigned char opcodeProperty[] = OPFLG_INITIALIZER;
50447
50448 /*
50449 ** Return true if an opcode has any of the OPFLG_xxx properties
50450 ** specified by mask.
50451 */
50452 SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){
50453   assert( opcode>0 && opcode<(int)sizeof(opcodeProperty) );
50454   return (opcodeProperty[opcode]&mask)!=0;
50455 }
50456
50457 /*
50458 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
50459 ** if we run out of memory.
50460 */
50461 static VdbeCursor *allocateCursor(
50462   Vdbe *p,              /* The virtual machine */
50463   int iCur,             /* Index of the new VdbeCursor */
50464   Op *pOp,              /* */
50465   int iDb,              /* When database the cursor belongs to, or -1 */
50466   int isBtreeCursor     /* */
50467 ){
50468   /* Find the memory cell that will be used to store the blob of memory
50469   ** required for this VdbeCursor structure. It is convenient to use a 
50470   ** vdbe memory cell to manage the memory allocation required for a
50471   ** VdbeCursor structure for the following reasons:
50472   **
50473   **   * Sometimes cursor numbers are used for a couple of different
50474   **     purposes in a vdbe program. The different uses might require
50475   **     different sized allocations. Memory cells provide growable
50476   **     allocations.
50477   **
50478   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
50479   **     be freed lazily via the sqlite3_release_memory() API. This
50480   **     minimizes the number of malloc calls made by the system.
50481   **
50482   ** Memory cells for cursors are allocated at the top of the address
50483   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
50484   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
50485   */
50486   Mem *pMem = &p->aMem[p->nMem-iCur];
50487
50488   int nByte;
50489   VdbeCursor *pCx = 0;
50490   /* If the opcode of pOp is OP_SetNumColumns, then pOp->p2 contains
50491   ** the number of fields in the records contained in the table or
50492   ** index being opened. Use this to reserve space for the 
50493   ** VdbeCursor.aType[] array.
50494   */
50495   int nField = 0;
50496   if( pOp->opcode==OP_SetNumColumns || pOp->opcode==OP_OpenEphemeral ){
50497     nField = pOp->p2;
50498   }
50499   nByte = 
50500       sizeof(VdbeCursor) + 
50501       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
50502       2*nField*sizeof(u32);
50503
50504   assert( iCur<p->nCursor );
50505   if( p->apCsr[iCur] ){
50506     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
50507     p->apCsr[iCur] = 0;
50508   }
50509   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
50510     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
50511     memset(pMem->z, 0, nByte);
50512     pCx->iDb = iDb;
50513     pCx->nField = nField;
50514     if( nField ){
50515       pCx->aType = (u32 *)&pMem->z[sizeof(VdbeCursor)];
50516     }
50517     if( isBtreeCursor ){
50518       pCx->pCursor = (BtCursor*)
50519           &pMem->z[sizeof(VdbeCursor)+2*nField*sizeof(u32)];
50520     }
50521   }
50522   return pCx;
50523 }
50524
50525 /*
50526 ** Try to convert a value into a numeric representation if we can
50527 ** do so without loss of information.  In other words, if the string
50528 ** looks like a number, convert it into a number.  If it does not
50529 ** look like a number, leave it alone.
50530 */
50531 static void applyNumericAffinity(Mem *pRec){
50532   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
50533     int realnum;
50534     sqlite3VdbeMemNulTerminate(pRec);
50535     if( (pRec->flags&MEM_Str)
50536          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
50537       i64 value;
50538       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
50539       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
50540         pRec->u.i = value;
50541         MemSetTypeFlag(pRec, MEM_Int);
50542       }else{
50543         sqlite3VdbeMemRealify(pRec);
50544       }
50545     }
50546   }
50547 }
50548
50549 /*
50550 ** Processing is determine by the affinity parameter:
50551 **
50552 ** SQLITE_AFF_INTEGER:
50553 ** SQLITE_AFF_REAL:
50554 ** SQLITE_AFF_NUMERIC:
50555 **    Try to convert pRec to an integer representation or a 
50556 **    floating-point representation if an integer representation
50557 **    is not possible.  Note that the integer representation is
50558 **    always preferred, even if the affinity is REAL, because
50559 **    an integer representation is more space efficient on disk.
50560 **
50561 ** SQLITE_AFF_TEXT:
50562 **    Convert pRec to a text representation.
50563 **
50564 ** SQLITE_AFF_NONE:
50565 **    No-op.  pRec is unchanged.
50566 */
50567 static void applyAffinity(
50568   Mem *pRec,          /* The value to apply affinity to */
50569   char affinity,      /* The affinity to be applied */
50570   u8 enc              /* Use this text encoding */
50571 ){
50572   if( affinity==SQLITE_AFF_TEXT ){
50573     /* Only attempt the conversion to TEXT if there is an integer or real
50574     ** representation (blob and NULL do not get converted) but no string
50575     ** representation.
50576     */
50577     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
50578       sqlite3VdbeMemStringify(pRec, enc);
50579     }
50580     pRec->flags &= ~(MEM_Real|MEM_Int);
50581   }else if( affinity!=SQLITE_AFF_NONE ){
50582     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
50583              || affinity==SQLITE_AFF_NUMERIC );
50584     applyNumericAffinity(pRec);
50585     if( pRec->flags & MEM_Real ){
50586       sqlite3VdbeIntegerAffinity(pRec);
50587     }
50588   }
50589 }
50590
50591 /*
50592 ** Try to convert the type of a function argument or a result column
50593 ** into a numeric representation.  Use either INTEGER or REAL whichever
50594 ** is appropriate.  But only do the conversion if it is possible without
50595 ** loss of information and return the revised type of the argument.
50596 **
50597 ** This is an EXPERIMENTAL api and is subject to change or removal.
50598 */
50599 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
50600   Mem *pMem = (Mem*)pVal;
50601   applyNumericAffinity(pMem);
50602   storeTypeInfo(pMem, 0);
50603   return pMem->type;
50604 }
50605
50606 /*
50607 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
50608 ** not the internal Mem* type.
50609 */
50610 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
50611   sqlite3_value *pVal, 
50612   u8 affinity, 
50613   u8 enc
50614 ){
50615   applyAffinity((Mem *)pVal, affinity, enc);
50616 }
50617
50618 #ifdef SQLITE_DEBUG
50619 /*
50620 ** Write a nice string representation of the contents of cell pMem
50621 ** into buffer zBuf, length nBuf.
50622 */
50623 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
50624   char *zCsr = zBuf;
50625   int f = pMem->flags;
50626
50627   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
50628
50629   if( f&MEM_Blob ){
50630     int i;
50631     char c;
50632     if( f & MEM_Dyn ){
50633       c = 'z';
50634       assert( (f & (MEM_Static|MEM_Ephem))==0 );
50635     }else if( f & MEM_Static ){
50636       c = 't';
50637       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
50638     }else if( f & MEM_Ephem ){
50639       c = 'e';
50640       assert( (f & (MEM_Static|MEM_Dyn))==0 );
50641     }else{
50642       c = 's';
50643     }
50644
50645     sqlite3_snprintf(100, zCsr, "%c", c);
50646     zCsr += sqlite3Strlen30(zCsr);
50647     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
50648     zCsr += sqlite3Strlen30(zCsr);
50649     for(i=0; i<16 && i<pMem->n; i++){
50650       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
50651       zCsr += sqlite3Strlen30(zCsr);
50652     }
50653     for(i=0; i<16 && i<pMem->n; i++){
50654       char z = pMem->z[i];
50655       if( z<32 || z>126 ) *zCsr++ = '.';
50656       else *zCsr++ = z;
50657     }
50658
50659     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
50660     zCsr += sqlite3Strlen30(zCsr);
50661     if( f & MEM_Zero ){
50662       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
50663       zCsr += sqlite3Strlen30(zCsr);
50664     }
50665     *zCsr = '\0';
50666   }else if( f & MEM_Str ){
50667     int j, k;
50668     zBuf[0] = ' ';
50669     if( f & MEM_Dyn ){
50670       zBuf[1] = 'z';
50671       assert( (f & (MEM_Static|MEM_Ephem))==0 );
50672     }else if( f & MEM_Static ){
50673       zBuf[1] = 't';
50674       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
50675     }else if( f & MEM_Ephem ){
50676       zBuf[1] = 'e';
50677       assert( (f & (MEM_Static|MEM_Dyn))==0 );
50678     }else{
50679       zBuf[1] = 's';
50680     }
50681     k = 2;
50682     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
50683     k += sqlite3Strlen30(&zBuf[k]);
50684     zBuf[k++] = '[';
50685     for(j=0; j<15 && j<pMem->n; j++){
50686       u8 c = pMem->z[j];
50687       if( c>=0x20 && c<0x7f ){
50688         zBuf[k++] = c;
50689       }else{
50690         zBuf[k++] = '.';
50691       }
50692     }
50693     zBuf[k++] = ']';
50694     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
50695     k += sqlite3Strlen30(&zBuf[k]);
50696     zBuf[k++] = 0;
50697   }
50698 }
50699 #endif
50700
50701 #ifdef SQLITE_DEBUG
50702 /*
50703 ** Print the value of a register for tracing purposes:
50704 */
50705 static void memTracePrint(FILE *out, Mem *p){
50706   if( p->flags & MEM_Null ){
50707     fprintf(out, " NULL");
50708   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
50709     fprintf(out, " si:%lld", p->u.i);
50710   }else if( p->flags & MEM_Int ){
50711     fprintf(out, " i:%lld", p->u.i);
50712   }else if( p->flags & MEM_Real ){
50713     fprintf(out, " r:%g", p->r);
50714   }else{
50715     char zBuf[200];
50716     sqlite3VdbeMemPrettyPrint(p, zBuf);
50717     fprintf(out, " ");
50718     fprintf(out, "%s", zBuf);
50719   }
50720 }
50721 static void registerTrace(FILE *out, int iReg, Mem *p){
50722   fprintf(out, "REG[%d] = ", iReg);
50723   memTracePrint(out, p);
50724   fprintf(out, "\n");
50725 }
50726 #endif
50727
50728 #ifdef SQLITE_DEBUG
50729 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
50730 #else
50731 #  define REGISTER_TRACE(R,M)
50732 #endif
50733
50734
50735 #ifdef VDBE_PROFILE
50736
50737 /* 
50738 ** hwtime.h contains inline assembler code for implementing 
50739 ** high-performance timing routines.
50740 */
50741 /************** Include hwtime.h in the middle of vdbe.c *********************/
50742 /************** Begin file hwtime.h ******************************************/
50743 /*
50744 ** 2008 May 27
50745 **
50746 ** The author disclaims copyright to this source code.  In place of
50747 ** a legal notice, here is a blessing:
50748 **
50749 **    May you do good and not evil.
50750 **    May you find forgiveness for yourself and forgive others.
50751 **    May you share freely, never taking more than you give.
50752 **
50753 ******************************************************************************
50754 **
50755 ** This file contains inline asm code for retrieving "high-performance"
50756 ** counters for x86 class CPUs.
50757 **
50758 ** $Id: hwtime.h,v 1.3 2008/08/01 14:33:15 shane Exp $
50759 */
50760 #ifndef _HWTIME_H_
50761 #define _HWTIME_H_
50762
50763 /*
50764 ** The following routine only works on pentium-class (or newer) processors.
50765 ** It uses the RDTSC opcode to read the cycle count value out of the
50766 ** processor and returns that value.  This can be used for high-res
50767 ** profiling.
50768 */
50769 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
50770       (defined(i386) || defined(__i386__) || defined(_M_IX86))
50771
50772   #if defined(__GNUC__)
50773
50774   __inline__ sqlite_uint64 sqlite3Hwtime(void){
50775      unsigned int lo, hi;
50776      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
50777      return (sqlite_uint64)hi << 32 | lo;
50778   }
50779
50780   #elif defined(_MSC_VER)
50781
50782   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
50783      __asm {
50784         rdtsc
50785         ret       ; return value at EDX:EAX
50786      }
50787   }
50788
50789   #endif
50790
50791 #elif (defined(__GNUC__) && defined(__x86_64__))
50792
50793   __inline__ sqlite_uint64 sqlite3Hwtime(void){
50794       unsigned long val;
50795       __asm__ __volatile__ ("rdtsc" : "=A" (val));
50796       return val;
50797   }
50798  
50799 #elif (defined(__GNUC__) && defined(__ppc__))
50800
50801   __inline__ sqlite_uint64 sqlite3Hwtime(void){
50802       unsigned long long retval;
50803       unsigned long junk;
50804       __asm__ __volatile__ ("\n\
50805           1:      mftbu   %1\n\
50806                   mftb    %L0\n\
50807                   mftbu   %0\n\
50808                   cmpw    %0,%1\n\
50809                   bne     1b"
50810                   : "=r" (retval), "=r" (junk));
50811       return retval;
50812   }
50813
50814 #else
50815
50816   #error Need implementation of sqlite3Hwtime() for your platform.
50817
50818   /*
50819   ** To compile without implementing sqlite3Hwtime() for your platform,
50820   ** you can remove the above #error and use the following
50821   ** stub function.  You will lose timing support for many
50822   ** of the debugging and testing utilities, but it should at
50823   ** least compile and run.
50824   */
50825 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
50826
50827 #endif
50828
50829 #endif /* !defined(_HWTIME_H_) */
50830
50831 /************** End of hwtime.h **********************************************/
50832 /************** Continuing where we left off in vdbe.c ***********************/
50833
50834 #endif
50835
50836 /*
50837 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
50838 ** sqlite3_interrupt() routine has been called.  If it has been, then
50839 ** processing of the VDBE program is interrupted.
50840 **
50841 ** This macro added to every instruction that does a jump in order to
50842 ** implement a loop.  This test used to be on every single instruction,
50843 ** but that meant we more testing that we needed.  By only testing the
50844 ** flag on jump instructions, we get a (small) speed improvement.
50845 */
50846 #define CHECK_FOR_INTERRUPT \
50847    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
50848
50849 #ifdef SQLITE_DEBUG
50850 static int fileExists(sqlite3 *db, const char *zFile){
50851   int res = 0;
50852   int rc = SQLITE_OK;
50853 #ifdef SQLITE_TEST
50854   /* If we are currently testing IO errors, then do not call OsAccess() to
50855   ** test for the presence of zFile. This is because any IO error that
50856   ** occurs here will not be reported, causing the test to fail.
50857   */
50858   extern int sqlite3_io_error_pending;
50859   if( sqlite3_io_error_pending<=0 )
50860 #endif
50861     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
50862   return (res && rc==SQLITE_OK);
50863 }
50864 #endif
50865
50866 #ifndef NDEBUG
50867 /*
50868 ** This function is only called from within an assert() expression. It
50869 ** checks that the sqlite3.nTransaction variable is correctly set to
50870 ** the number of non-transaction savepoints currently in the 
50871 ** linked list starting at sqlite3.pSavepoint.
50872 ** 
50873 ** Usage:
50874 **
50875 **     assert( checkSavepointCount(db) );
50876 */
50877 static int checkSavepointCount(sqlite3 *db){
50878   int n = 0;
50879   Savepoint *p;
50880   for(p=db->pSavepoint; p; p=p->pNext) n++;
50881   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
50882   return 1;
50883 }
50884 #endif
50885
50886 /*
50887 ** Execute as much of a VDBE program as we can then return.
50888 **
50889 ** sqlite3VdbeMakeReady() must be called before this routine in order to
50890 ** close the program with a final OP_Halt and to set up the callbacks
50891 ** and the error message pointer.
50892 **
50893 ** Whenever a row or result data is available, this routine will either
50894 ** invoke the result callback (if there is one) or return with
50895 ** SQLITE_ROW.
50896 **
50897 ** If an attempt is made to open a locked database, then this routine
50898 ** will either invoke the busy callback (if there is one) or it will
50899 ** return SQLITE_BUSY.
50900 **
50901 ** If an error occurs, an error message is written to memory obtained
50902 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
50903 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
50904 **
50905 ** If the callback ever returns non-zero, then the program exits
50906 ** immediately.  There will be no error message but the p->rc field is
50907 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
50908 **
50909 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
50910 ** routine to return SQLITE_ERROR.
50911 **
50912 ** Other fatal errors return SQLITE_ERROR.
50913 **
50914 ** After this routine has finished, sqlite3VdbeFinalize() should be
50915 ** used to clean up the mess that was left behind.
50916 */
50917 SQLITE_PRIVATE int sqlite3VdbeExec(
50918   Vdbe *p                    /* The VDBE */
50919 ){
50920   int pc;                    /* The program counter */
50921   Op *pOp;                   /* Current operation */
50922   int rc = SQLITE_OK;        /* Value to return */
50923   sqlite3 *db = p->db;       /* The database */
50924   u8 encoding = ENC(db);     /* The database encoding */
50925   Mem *pIn1 = 0;             /* 1st input operand */
50926   Mem *pIn2 = 0;             /* 2nd input operand */
50927   Mem *pIn3 = 0;             /* 3rd input operand */
50928   Mem *pOut = 0;             /* Output operand */
50929   u8 opProperty;
50930   int iCompare = 0;          /* Result of last OP_Compare operation */
50931   int *aPermute = 0;         /* Permuation of columns for OP_Compare */
50932 #ifdef VDBE_PROFILE
50933   u64 start;                 /* CPU clock count at start of opcode */
50934   int origPc;                /* Program counter at start of opcode */
50935 #endif
50936 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
50937   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
50938 #endif
50939   UnpackedRecord aTempRec[16]; /* Space to hold a transient UnpackedRecord */
50940
50941   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
50942   assert( db->magic==SQLITE_MAGIC_BUSY );
50943   sqlite3BtreeMutexArrayEnter(&p->aMutex);
50944   if( p->rc==SQLITE_NOMEM ){
50945     /* This happens if a malloc() inside a call to sqlite3_column_text() or
50946     ** sqlite3_column_text16() failed.  */
50947     goto no_mem;
50948   }
50949   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
50950   p->rc = SQLITE_OK;
50951   assert( p->explain==0 );
50952   p->pResultSet = 0;
50953   db->busyHandler.nBusy = 0;
50954   CHECK_FOR_INTERRUPT;
50955   sqlite3VdbeIOTraceSql(p);
50956 #ifdef SQLITE_DEBUG
50957   sqlite3BeginBenignMalloc();
50958   if( p->pc==0 
50959    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
50960   ){
50961     int i;
50962     printf("VDBE Program Listing:\n");
50963     sqlite3VdbePrintSql(p);
50964     for(i=0; i<p->nOp; i++){
50965       sqlite3VdbePrintOp(stdout, i, &p->aOp[i]);
50966     }
50967   }
50968   if( fileExists(db, "vdbe_trace") ){
50969     p->trace = stdout;
50970   }
50971   sqlite3EndBenignMalloc();
50972 #endif
50973   for(pc=p->pc; rc==SQLITE_OK; pc++){
50974     assert( pc>=0 && pc<p->nOp );
50975     if( db->mallocFailed ) goto no_mem;
50976 #ifdef VDBE_PROFILE
50977     origPc = pc;
50978     start = sqlite3Hwtime();
50979 #endif
50980     pOp = &p->aOp[pc];
50981
50982     /* Only allow tracing if SQLITE_DEBUG is defined.
50983     */
50984 #ifdef SQLITE_DEBUG
50985     if( p->trace ){
50986       if( pc==0 ){
50987         printf("VDBE Execution Trace:\n");
50988         sqlite3VdbePrintSql(p);
50989       }
50990       sqlite3VdbePrintOp(p->trace, pc, pOp);
50991     }
50992     if( p->trace==0 && pc==0 ){
50993       sqlite3BeginBenignMalloc();
50994       if( fileExists(db, "vdbe_sqltrace") ){
50995         sqlite3VdbePrintSql(p);
50996       }
50997       sqlite3EndBenignMalloc();
50998     }
50999 #endif
51000       
51001
51002     /* Check to see if we need to simulate an interrupt.  This only happens
51003     ** if we have a special test build.
51004     */
51005 #ifdef SQLITE_TEST
51006     if( sqlite3_interrupt_count>0 ){
51007       sqlite3_interrupt_count--;
51008       if( sqlite3_interrupt_count==0 ){
51009         sqlite3_interrupt(db);
51010       }
51011     }
51012 #endif
51013
51014 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
51015     /* Call the progress callback if it is configured and the required number
51016     ** of VDBE ops have been executed (either since this invocation of
51017     ** sqlite3VdbeExec() or since last time the progress callback was called).
51018     ** If the progress callback returns non-zero, exit the virtual machine with
51019     ** a return code SQLITE_ABORT.
51020     */
51021     if( db->xProgress ){
51022       if( db->nProgressOps==nProgressOps ){
51023         int prc;
51024         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51025         prc =db->xProgress(db->pProgressArg);
51026         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
51027         if( prc!=0 ){
51028           rc = SQLITE_INTERRUPT;
51029           goto vdbe_error_halt;
51030         }
51031         nProgressOps = 0;
51032       }
51033       nProgressOps++;
51034     }
51035 #endif
51036
51037     /* Do common setup processing for any opcode that is marked
51038     ** with the "out2-prerelease" tag.  Such opcodes have a single
51039     ** output which is specified by the P2 parameter.  The P2 register
51040     ** is initialized to a NULL.
51041     */
51042     opProperty = opcodeProperty[pOp->opcode];
51043     if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){
51044       assert( pOp->p2>0 );
51045       assert( pOp->p2<=p->nMem );
51046       pOut = &p->aMem[pOp->p2];
51047       sqlite3VdbeMemReleaseExternal(pOut);
51048       pOut->flags = MEM_Null;
51049     }else
51050  
51051     /* Do common setup for opcodes marked with one of the following
51052     ** combinations of properties.
51053     **
51054     **           in1
51055     **           in1 in2
51056     **           in1 in2 out3
51057     **           in1 in3
51058     **
51059     ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate
51060     ** registers for inputs.  Variable pOut points to the output register.
51061     */
51062     if( (opProperty & OPFLG_IN1)!=0 ){
51063       assert( pOp->p1>0 );
51064       assert( pOp->p1<=p->nMem );
51065       pIn1 = &p->aMem[pOp->p1];
51066       REGISTER_TRACE(pOp->p1, pIn1);
51067       if( (opProperty & OPFLG_IN2)!=0 ){
51068         assert( pOp->p2>0 );
51069         assert( pOp->p2<=p->nMem );
51070         pIn2 = &p->aMem[pOp->p2];
51071         REGISTER_TRACE(pOp->p2, pIn2);
51072         if( (opProperty & OPFLG_OUT3)!=0 ){
51073           assert( pOp->p3>0 );
51074           assert( pOp->p3<=p->nMem );
51075           pOut = &p->aMem[pOp->p3];
51076         }
51077       }else if( (opProperty & OPFLG_IN3)!=0 ){
51078         assert( pOp->p3>0 );
51079         assert( pOp->p3<=p->nMem );
51080         pIn3 = &p->aMem[pOp->p3];
51081         REGISTER_TRACE(pOp->p3, pIn3);
51082       }
51083     }else if( (opProperty & OPFLG_IN2)!=0 ){
51084       assert( pOp->p2>0 );
51085       assert( pOp->p2<=p->nMem );
51086       pIn2 = &p->aMem[pOp->p2];
51087       REGISTER_TRACE(pOp->p2, pIn2);
51088     }else if( (opProperty & OPFLG_IN3)!=0 ){
51089       assert( pOp->p3>0 );
51090       assert( pOp->p3<=p->nMem );
51091       pIn3 = &p->aMem[pOp->p3];
51092       REGISTER_TRACE(pOp->p3, pIn3);
51093     }
51094
51095     switch( pOp->opcode ){
51096
51097 /*****************************************************************************
51098 ** What follows is a massive switch statement where each case implements a
51099 ** separate instruction in the virtual machine.  If we follow the usual
51100 ** indentation conventions, each case should be indented by 6 spaces.  But
51101 ** that is a lot of wasted space on the left margin.  So the code within
51102 ** the switch statement will break with convention and be flush-left. Another
51103 ** big comment (similar to this one) will mark the point in the code where
51104 ** we transition back to normal indentation.
51105 **
51106 ** The formatting of each case is important.  The makefile for SQLite
51107 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
51108 ** file looking for lines that begin with "case OP_".  The opcodes.h files
51109 ** will be filled with #defines that give unique integer values to each
51110 ** opcode and the opcodes.c file is filled with an array of strings where
51111 ** each string is the symbolic name for the corresponding opcode.  If the
51112 ** case statement is followed by a comment of the form "/# same as ... #/"
51113 ** that comment is used to determine the particular value of the opcode.
51114 **
51115 ** Other keywords in the comment that follows each case are used to
51116 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
51117 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
51118 ** the mkopcodeh.awk script for additional information.
51119 **
51120 ** Documentation about VDBE opcodes is generated by scanning this file
51121 ** for lines of that contain "Opcode:".  That line and all subsequent
51122 ** comment lines are used in the generation of the opcode.html documentation
51123 ** file.
51124 **
51125 ** SUMMARY:
51126 **
51127 **     Formatting is important to scripts that scan this file.
51128 **     Do not deviate from the formatting style currently in use.
51129 **
51130 *****************************************************************************/
51131
51132 /* Opcode:  Goto * P2 * * *
51133 **
51134 ** An unconditional jump to address P2.
51135 ** The next instruction executed will be 
51136 ** the one at index P2 from the beginning of
51137 ** the program.
51138 */
51139 case OP_Goto: {             /* jump */
51140   CHECK_FOR_INTERRUPT;
51141   pc = pOp->p2 - 1;
51142   break;
51143 }
51144
51145 /* Opcode:  Gosub P1 P2 * * *
51146 **
51147 ** Write the current address onto register P1
51148 ** and then jump to address P2.
51149 */
51150 case OP_Gosub: {            /* jump */
51151   assert( pOp->p1>0 );
51152   assert( pOp->p1<=p->nMem );
51153   pIn1 = &p->aMem[pOp->p1];
51154   assert( (pIn1->flags & MEM_Dyn)==0 );
51155   pIn1->flags = MEM_Int;
51156   pIn1->u.i = pc;
51157   REGISTER_TRACE(pOp->p1, pIn1);
51158   pc = pOp->p2 - 1;
51159   break;
51160 }
51161
51162 /* Opcode:  Return P1 * * * *
51163 **
51164 ** Jump to the next instruction after the address in register P1.
51165 */
51166 case OP_Return: {           /* in1 */
51167   assert( pIn1->flags & MEM_Int );
51168   pc = (int)pIn1->u.i;
51169   break;
51170 }
51171
51172 /* Opcode:  Yield P1 * * * *
51173 **
51174 ** Swap the program counter with the value in register P1.
51175 */
51176 case OP_Yield: {            /* in1 */
51177   int pcDest;
51178   assert( (pIn1->flags & MEM_Dyn)==0 );
51179   pIn1->flags = MEM_Int;
51180   pcDest = (int)pIn1->u.i;
51181   pIn1->u.i = pc;
51182   REGISTER_TRACE(pOp->p1, pIn1);
51183   pc = pcDest;
51184   break;
51185 }
51186
51187
51188 /* Opcode:  Halt P1 P2 * P4 *
51189 **
51190 ** Exit immediately.  All open cursors, etc are closed
51191 ** automatically.
51192 **
51193 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
51194 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
51195 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
51196 ** whether or not to rollback the current transaction.  Do not rollback
51197 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
51198 ** then back out all changes that have occurred during this execution of the
51199 ** VDBE, but do not rollback the transaction. 
51200 **
51201 ** If P4 is not null then it is an error message string.
51202 **
51203 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
51204 ** every program.  So a jump past the last instruction of the program
51205 ** is the same as executing Halt.
51206 */
51207 case OP_Halt: {
51208   p->rc = pOp->p1;
51209   p->pc = pc;
51210   p->errorAction = pOp->p2;
51211   if( pOp->p4.z ){
51212     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
51213   }
51214   rc = sqlite3VdbeHalt(p);
51215   assert( rc==SQLITE_BUSY || rc==SQLITE_OK );
51216   if( rc==SQLITE_BUSY ){
51217     p->rc = rc = SQLITE_BUSY;
51218   }else{
51219     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
51220   }
51221   goto vdbe_return;
51222 }
51223
51224 /* Opcode: Integer P1 P2 * * *
51225 **
51226 ** The 32-bit integer value P1 is written into register P2.
51227 */
51228 case OP_Integer: {         /* out2-prerelease */
51229   pOut->flags = MEM_Int;
51230   pOut->u.i = pOp->p1;
51231   break;
51232 }
51233
51234 /* Opcode: Int64 * P2 * P4 *
51235 **
51236 ** P4 is a pointer to a 64-bit integer value.
51237 ** Write that value into register P2.
51238 */
51239 case OP_Int64: {           /* out2-prerelease */
51240   assert( pOp->p4.pI64!=0 );
51241   pOut->flags = MEM_Int;
51242   pOut->u.i = *pOp->p4.pI64;
51243   break;
51244 }
51245
51246 /* Opcode: Real * P2 * P4 *
51247 **
51248 ** P4 is a pointer to a 64-bit floating point value.
51249 ** Write that value into register P2.
51250 */
51251 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
51252   pOut->flags = MEM_Real;
51253   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
51254   pOut->r = *pOp->p4.pReal;
51255   break;
51256 }
51257
51258 /* Opcode: String8 * P2 * P4 *
51259 **
51260 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
51261 ** into an OP_String before it is executed for the first time.
51262 */
51263 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
51264   assert( pOp->p4.z!=0 );
51265   pOp->opcode = OP_String;
51266   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
51267
51268 #ifndef SQLITE_OMIT_UTF16
51269   if( encoding!=SQLITE_UTF8 ){
51270     sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
51271     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
51272     if( SQLITE_OK!=sqlite3VdbeMemMakeWriteable(pOut) ) goto no_mem;
51273     pOut->zMalloc = 0;
51274     pOut->flags |= MEM_Static;
51275     pOut->flags &= ~MEM_Dyn;
51276     if( pOp->p4type==P4_DYNAMIC ){
51277       sqlite3DbFree(db, pOp->p4.z);
51278     }
51279     pOp->p4type = P4_DYNAMIC;
51280     pOp->p4.z = pOut->z;
51281     pOp->p1 = pOut->n;
51282     if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
51283       goto too_big;
51284     }
51285     UPDATE_MAX_BLOBSIZE(pOut);
51286     break;
51287   }
51288 #endif
51289   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
51290     goto too_big;
51291   }
51292   /* Fall through to the next case, OP_String */
51293 }
51294   
51295 /* Opcode: String P1 P2 * P4 *
51296 **
51297 ** The string value P4 of length P1 (bytes) is stored in register P2.
51298 */
51299 case OP_String: {          /* out2-prerelease */
51300   assert( pOp->p4.z!=0 );
51301   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
51302   pOut->z = pOp->p4.z;
51303   pOut->n = pOp->p1;
51304   pOut->enc = encoding;
51305   UPDATE_MAX_BLOBSIZE(pOut);
51306   break;
51307 }
51308
51309 /* Opcode: Null * P2 * * *
51310 **
51311 ** Write a NULL into register P2.
51312 */
51313 case OP_Null: {           /* out2-prerelease */
51314   break;
51315 }
51316
51317
51318 /* Opcode: Blob P1 P2 * P4
51319 **
51320 ** P4 points to a blob of data P1 bytes long.  Store this
51321 ** blob in register P2. This instruction is not coded directly
51322 ** by the compiler. Instead, the compiler layer specifies
51323 ** an OP_HexBlob opcode, with the hex string representation of
51324 ** the blob as P4. This opcode is transformed to an OP_Blob
51325 ** the first time it is executed.
51326 */
51327 case OP_Blob: {                /* out2-prerelease */
51328   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
51329   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
51330   pOut->enc = encoding;
51331   UPDATE_MAX_BLOBSIZE(pOut);
51332   break;
51333 }
51334
51335 /* Opcode: Variable P1 P2 * * *
51336 **
51337 ** The value of variable P1 is written into register P2. A variable is
51338 ** an unknown in the original SQL string as handed to sqlite3_compile().
51339 ** Any occurrence of the '?' character in the original SQL is considered
51340 ** a variable.  Variables in the SQL string are number from left to
51341 ** right beginning with 1.  The values of variables are set using the
51342 ** sqlite3_bind() API.
51343 */
51344 case OP_Variable: {           /* out2-prerelease */
51345   int j = pOp->p1 - 1;
51346   Mem *pVar;
51347   assert( j>=0 && j<p->nVar );
51348
51349   pVar = &p->aVar[j];
51350   if( sqlite3VdbeMemTooBig(pVar) ){
51351     goto too_big;
51352   }
51353   sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static);
51354   UPDATE_MAX_BLOBSIZE(pOut);
51355   break;
51356 }
51357
51358 /* Opcode: Move P1 P2 P3 * *
51359 **
51360 ** Move the values in register P1..P1+P3-1 over into
51361 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
51362 ** left holding a NULL.  It is an error for register ranges
51363 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
51364 */
51365 case OP_Move: {
51366   char *zMalloc;
51367   int n = pOp->p3;
51368   int p1 = pOp->p1;
51369   int p2 = pOp->p2;
51370   assert( n>0 );
51371   assert( p1>0 );
51372   assert( p1+n<p->nMem );
51373   pIn1 = &p->aMem[p1];
51374   assert( p2>0 );
51375   assert( p2+n<p->nMem );
51376   pOut = &p->aMem[p2];
51377   assert( p1+n<=p2 || p2+n<=p1 );
51378   while( n-- ){
51379     zMalloc = pOut->zMalloc;
51380     pOut->zMalloc = 0;
51381     sqlite3VdbeMemMove(pOut, pIn1);
51382     pIn1->zMalloc = zMalloc;
51383     REGISTER_TRACE(p2++, pOut);
51384     pIn1++;
51385     pOut++;
51386   }
51387   break;
51388 }
51389
51390 /* Opcode: Copy P1 P2 * * *
51391 **
51392 ** Make a copy of register P1 into register P2.
51393 **
51394 ** This instruction makes a deep copy of the value.  A duplicate
51395 ** is made of any string or blob constant.  See also OP_SCopy.
51396 */
51397 case OP_Copy: {             /* in1 */
51398   assert( pOp->p2>0 );
51399   assert( pOp->p2<=p->nMem );
51400   pOut = &p->aMem[pOp->p2];
51401   assert( pOut!=pIn1 );
51402   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
51403   Deephemeralize(pOut);
51404   REGISTER_TRACE(pOp->p2, pOut);
51405   break;
51406 }
51407
51408 /* Opcode: SCopy P1 P2 * * *
51409 **
51410 ** Make a shallow copy of register P1 into register P2.
51411 **
51412 ** This instruction makes a shallow copy of the value.  If the value
51413 ** is a string or blob, then the copy is only a pointer to the
51414 ** original and hence if the original changes so will the copy.
51415 ** Worse, if the original is deallocated, the copy becomes invalid.
51416 ** Thus the program must guarantee that the original will not change
51417 ** during the lifetime of the copy.  Use OP_Copy to make a complete
51418 ** copy.
51419 */
51420 case OP_SCopy: {            /* in1 */
51421   REGISTER_TRACE(pOp->p1, pIn1);
51422   assert( pOp->p2>0 );
51423   assert( pOp->p2<=p->nMem );
51424   pOut = &p->aMem[pOp->p2];
51425   assert( pOut!=pIn1 );
51426   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
51427   REGISTER_TRACE(pOp->p2, pOut);
51428   break;
51429 }
51430
51431 /* Opcode: ResultRow P1 P2 * * *
51432 **
51433 ** The registers P1 through P1+P2-1 contain a single row of
51434 ** results. This opcode causes the sqlite3_step() call to terminate
51435 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
51436 ** structure to provide access to the top P1 values as the result
51437 ** row.
51438 */
51439 case OP_ResultRow: {
51440   Mem *pMem;
51441   int i;
51442   assert( p->nResColumn==pOp->p2 );
51443   assert( pOp->p1>0 );
51444   assert( pOp->p1+pOp->p2<=p->nMem );
51445
51446   /* Invalidate all ephemeral cursor row caches */
51447   p->cacheCtr = (p->cacheCtr + 2)|1;
51448
51449   /* Make sure the results of the current row are \000 terminated
51450   ** and have an assigned type.  The results are de-ephemeralized as
51451   ** as side effect.
51452   */
51453   pMem = p->pResultSet = &p->aMem[pOp->p1];
51454   for(i=0; i<pOp->p2; i++){
51455     sqlite3VdbeMemNulTerminate(&pMem[i]);
51456     storeTypeInfo(&pMem[i], encoding);
51457     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
51458   }
51459   if( db->mallocFailed ) goto no_mem;
51460
51461   /* Return SQLITE_ROW
51462   */
51463   p->nCallback++;
51464   p->pc = pc + 1;
51465   rc = SQLITE_ROW;
51466   goto vdbe_return;
51467 }
51468
51469 /* Opcode: Concat P1 P2 P3 * *
51470 **
51471 ** Add the text in register P1 onto the end of the text in
51472 ** register P2 and store the result in register P3.
51473 ** If either the P1 or P2 text are NULL then store NULL in P3.
51474 **
51475 **   P3 = P2 || P1
51476 **
51477 ** It is illegal for P1 and P3 to be the same register. Sometimes,
51478 ** if P3 is the same register as P2, the implementation is able
51479 ** to avoid a memcpy().
51480 */
51481 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
51482   i64 nByte;
51483
51484   assert( pIn1!=pOut );
51485   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
51486     sqlite3VdbeMemSetNull(pOut);
51487     break;
51488   }
51489   ExpandBlob(pIn1);
51490   Stringify(pIn1, encoding);
51491   ExpandBlob(pIn2);
51492   Stringify(pIn2, encoding);
51493   nByte = pIn1->n + pIn2->n;
51494   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
51495     goto too_big;
51496   }
51497   MemSetTypeFlag(pOut, MEM_Str);
51498   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
51499     goto no_mem;
51500   }
51501   if( pOut!=pIn2 ){
51502     memcpy(pOut->z, pIn2->z, pIn2->n);
51503   }
51504   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
51505   pOut->z[nByte] = 0;
51506   pOut->z[nByte+1] = 0;
51507   pOut->flags |= MEM_Term;
51508   pOut->n = (int)nByte;
51509   pOut->enc = encoding;
51510   UPDATE_MAX_BLOBSIZE(pOut);
51511   break;
51512 }
51513
51514 /* Opcode: Add P1 P2 P3 * *
51515 **
51516 ** Add the value in register P1 to the value in register P2
51517 ** and store the result in register P3.
51518 ** If either input is NULL, the result is NULL.
51519 */
51520 /* Opcode: Multiply P1 P2 P3 * *
51521 **
51522 **
51523 ** Multiply the value in register P1 by the value in register P2
51524 ** and store the result in register P3.
51525 ** If either input is NULL, the result is NULL.
51526 */
51527 /* Opcode: Subtract P1 P2 P3 * *
51528 **
51529 ** Subtract the value in register P1 from the value in register P2
51530 ** and store the result in register P3.
51531 ** If either input is NULL, the result is NULL.
51532 */
51533 /* Opcode: Divide P1 P2 P3 * *
51534 **
51535 ** Divide the value in register P1 by the value in register P2
51536 ** and store the result in register P3.  If the value in register P2
51537 ** is zero, then the result is NULL.
51538 ** If either input is NULL, the result is NULL.
51539 */
51540 /* Opcode: Remainder P1 P2 P3 * *
51541 **
51542 ** Compute the remainder after integer division of the value in
51543 ** register P1 by the value in register P2 and store the result in P3. 
51544 ** If the value in register P2 is zero the result is NULL.
51545 ** If either operand is NULL, the result is NULL.
51546 */
51547 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
51548 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
51549 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
51550 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
51551 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
51552   int flags;
51553   applyNumericAffinity(pIn1);
51554   applyNumericAffinity(pIn2);
51555   flags = pIn1->flags | pIn2->flags;
51556   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
51557   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
51558     i64 a, b;
51559     a = pIn1->u.i;
51560     b = pIn2->u.i;
51561     switch( pOp->opcode ){
51562       case OP_Add:         b += a;       break;
51563       case OP_Subtract:    b -= a;       break;
51564       case OP_Multiply:    b *= a;       break;
51565       case OP_Divide: {
51566         if( a==0 ) goto arithmetic_result_is_null;
51567         /* Dividing the largest possible negative 64-bit integer (1<<63) by 
51568         ** -1 returns an integer too large to store in a 64-bit data-type. On
51569         ** some architectures, the value overflows to (1<<63). On others,
51570         ** a SIGFPE is issued. The following statement normalizes this
51571         ** behavior so that all architectures behave as if integer 
51572         ** overflow occurred.
51573         */
51574         if( a==-1 && b==SMALLEST_INT64 ) a = 1;
51575         b /= a;
51576         break;
51577       }
51578       default: {
51579         if( a==0 ) goto arithmetic_result_is_null;
51580         if( a==-1 ) a = 1;
51581         b %= a;
51582         break;
51583       }
51584     }
51585     pOut->u.i = b;
51586     MemSetTypeFlag(pOut, MEM_Int);
51587   }else{
51588     double a, b;
51589     a = sqlite3VdbeRealValue(pIn1);
51590     b = sqlite3VdbeRealValue(pIn2);
51591     switch( pOp->opcode ){
51592       case OP_Add:         b += a;       break;
51593       case OP_Subtract:    b -= a;       break;
51594       case OP_Multiply:    b *= a;       break;
51595       case OP_Divide: {
51596         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
51597         if( a==(double)0 ) goto arithmetic_result_is_null;
51598         b /= a;
51599         break;
51600       }
51601       default: {
51602         i64 ia = (i64)a;
51603         i64 ib = (i64)b;
51604         if( ia==0 ) goto arithmetic_result_is_null;
51605         if( ia==-1 ) ia = 1;
51606         b = (double)(ib % ia);
51607         break;
51608       }
51609     }
51610     if( sqlite3IsNaN(b) ){
51611       goto arithmetic_result_is_null;
51612     }
51613     pOut->r = b;
51614     MemSetTypeFlag(pOut, MEM_Real);
51615     if( (flags & MEM_Real)==0 ){
51616       sqlite3VdbeIntegerAffinity(pOut);
51617     }
51618   }
51619   break;
51620
51621 arithmetic_result_is_null:
51622   sqlite3VdbeMemSetNull(pOut);
51623   break;
51624 }
51625
51626 /* Opcode: CollSeq * * P4
51627 **
51628 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
51629 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
51630 ** be returned. This is used by the built-in min(), max() and nullif()
51631 ** functions.
51632 **
51633 ** The interface used by the implementation of the aforementioned functions
51634 ** to retrieve the collation sequence set by this opcode is not available
51635 ** publicly, only to user functions defined in func.c.
51636 */
51637 case OP_CollSeq: {
51638   assert( pOp->p4type==P4_COLLSEQ );
51639   break;
51640 }
51641
51642 /* Opcode: Function P1 P2 P3 P4 P5
51643 **
51644 ** Invoke a user function (P4 is a pointer to a Function structure that
51645 ** defines the function) with P5 arguments taken from register P2 and
51646 ** successors.  The result of the function is stored in register P3.
51647 ** Register P3 must not be one of the function inputs.
51648 **
51649 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
51650 ** function was determined to be constant at compile time. If the first
51651 ** argument was constant then bit 0 of P1 is set. This is used to determine
51652 ** whether meta data associated with a user function argument using the
51653 ** sqlite3_set_auxdata() API may be safely retained until the next
51654 ** invocation of this opcode.
51655 **
51656 ** See also: AggStep and AggFinal
51657 */
51658 case OP_Function: {
51659   int i;
51660   Mem *pArg;
51661   sqlite3_context ctx;
51662   sqlite3_value **apVal;
51663   int n = pOp->p5;
51664
51665   apVal = p->apArg;
51666   assert( apVal || n==0 );
51667
51668   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) );
51669   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
51670   pArg = &p->aMem[pOp->p2];
51671   for(i=0; i<n; i++, pArg++){
51672     apVal[i] = pArg;
51673     storeTypeInfo(pArg, encoding);
51674     REGISTER_TRACE(pOp->p2, pArg);
51675   }
51676
51677   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
51678   if( pOp->p4type==P4_FUNCDEF ){
51679     ctx.pFunc = pOp->p4.pFunc;
51680     ctx.pVdbeFunc = 0;
51681   }else{
51682     ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
51683     ctx.pFunc = ctx.pVdbeFunc->pFunc;
51684   }
51685
51686   assert( pOp->p3>0 && pOp->p3<=p->nMem );
51687   pOut = &p->aMem[pOp->p3];
51688   ctx.s.flags = MEM_Null;
51689   ctx.s.db = db;
51690   ctx.s.xDel = 0;
51691   ctx.s.zMalloc = 0;
51692
51693   /* The output cell may already have a buffer allocated. Move
51694   ** the pointer to ctx.s so in case the user-function can use
51695   ** the already allocated buffer instead of allocating a new one.
51696   */
51697   sqlite3VdbeMemMove(&ctx.s, pOut);
51698   MemSetTypeFlag(&ctx.s, MEM_Null);
51699
51700   ctx.isError = 0;
51701   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
51702     assert( pOp>p->aOp );
51703     assert( pOp[-1].p4type==P4_COLLSEQ );
51704     assert( pOp[-1].opcode==OP_CollSeq );
51705     ctx.pColl = pOp[-1].p4.pColl;
51706   }
51707   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
51708   (*ctx.pFunc->xFunc)(&ctx, n, apVal);
51709   if( sqlite3SafetyOn(db) ){
51710     sqlite3VdbeMemRelease(&ctx.s);
51711     goto abort_due_to_misuse;
51712   }
51713   if( db->mallocFailed ){
51714     /* Even though a malloc() has failed, the implementation of the
51715     ** user function may have called an sqlite3_result_XXX() function
51716     ** to return a value. The following call releases any resources
51717     ** associated with such a value.
51718     **
51719     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
51720     ** fails also (the if(...) statement above). But if people are
51721     ** misusing sqlite, they have bigger problems than a leaked value.
51722     */
51723     sqlite3VdbeMemRelease(&ctx.s);
51724     goto no_mem;
51725   }
51726
51727   /* If any auxiliary data functions have been called by this user function,
51728   ** immediately call the destructor for any non-static values.
51729   */
51730   if( ctx.pVdbeFunc ){
51731     sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1);
51732     pOp->p4.pVdbeFunc = ctx.pVdbeFunc;
51733     pOp->p4type = P4_VDBEFUNC;
51734   }
51735
51736   /* If the function returned an error, throw an exception */
51737   if( ctx.isError ){
51738     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
51739     rc = ctx.isError;
51740   }
51741
51742   /* Copy the result of the function into register P3 */
51743   sqlite3VdbeChangeEncoding(&ctx.s, encoding);
51744   sqlite3VdbeMemMove(pOut, &ctx.s);
51745   if( sqlite3VdbeMemTooBig(pOut) ){
51746     goto too_big;
51747   }
51748   REGISTER_TRACE(pOp->p3, pOut);
51749   UPDATE_MAX_BLOBSIZE(pOut);
51750   break;
51751 }
51752
51753 /* Opcode: BitAnd P1 P2 P3 * *
51754 **
51755 ** Take the bit-wise AND of the values in register P1 and P2 and
51756 ** store the result in register P3.
51757 ** If either input is NULL, the result is NULL.
51758 */
51759 /* Opcode: BitOr P1 P2 P3 * *
51760 **
51761 ** Take the bit-wise OR of the values in register P1 and P2 and
51762 ** store the result in register P3.
51763 ** If either input is NULL, the result is NULL.
51764 */
51765 /* Opcode: ShiftLeft P1 P2 P3 * *
51766 **
51767 ** Shift the integer value in register P2 to the left by the
51768 ** number of bits specified by the integer in regiser P1.
51769 ** Store the result in register P3.
51770 ** If either input is NULL, the result is NULL.
51771 */
51772 /* Opcode: ShiftRight P1 P2 P3 * *
51773 **
51774 ** Shift the integer value in register P2 to the right by the
51775 ** number of bits specified by the integer in register P1.
51776 ** Store the result in register P3.
51777 ** If either input is NULL, the result is NULL.
51778 */
51779 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
51780 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
51781 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
51782 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
51783   i64 a, b;
51784
51785   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
51786     sqlite3VdbeMemSetNull(pOut);
51787     break;
51788   }
51789   a = sqlite3VdbeIntValue(pIn2);
51790   b = sqlite3VdbeIntValue(pIn1);
51791   switch( pOp->opcode ){
51792     case OP_BitAnd:      a &= b;     break;
51793     case OP_BitOr:       a |= b;     break;
51794     case OP_ShiftLeft:   a <<= b;    break;
51795     default:  assert( pOp->opcode==OP_ShiftRight );
51796                          a >>= b;    break;
51797   }
51798   pOut->u.i = a;
51799   MemSetTypeFlag(pOut, MEM_Int);
51800   break;
51801 }
51802
51803 /* Opcode: AddImm  P1 P2 * * *
51804 ** 
51805 ** Add the constant P2 to the value in register P1.
51806 ** The result is always an integer.
51807 **
51808 ** To force any register to be an integer, just add 0.
51809 */
51810 case OP_AddImm: {            /* in1 */
51811   sqlite3VdbeMemIntegerify(pIn1);
51812   pIn1->u.i += pOp->p2;
51813   break;
51814 }
51815
51816 /* Opcode: MustBeInt P1 P2 * * *
51817 ** 
51818 ** Force the value in register P1 to be an integer.  If the value
51819 ** in P1 is not an integer and cannot be converted into an integer
51820 ** without data loss, then jump immediately to P2, or if P2==0
51821 ** raise an SQLITE_MISMATCH exception.
51822 */
51823 case OP_MustBeInt: {            /* jump, in1 */
51824   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
51825   if( (pIn1->flags & MEM_Int)==0 ){
51826     if( pOp->p2==0 ){
51827       rc = SQLITE_MISMATCH;
51828       goto abort_due_to_error;
51829     }else{
51830       pc = pOp->p2 - 1;
51831     }
51832   }else{
51833     MemSetTypeFlag(pIn1, MEM_Int);
51834   }
51835   break;
51836 }
51837
51838 /* Opcode: RealAffinity P1 * * * *
51839 **
51840 ** If register P1 holds an integer convert it to a real value.
51841 **
51842 ** This opcode is used when extracting information from a column that
51843 ** has REAL affinity.  Such column values may still be stored as
51844 ** integers, for space efficiency, but after extraction we want them
51845 ** to have only a real value.
51846 */
51847 case OP_RealAffinity: {                  /* in1 */
51848   if( pIn1->flags & MEM_Int ){
51849     sqlite3VdbeMemRealify(pIn1);
51850   }
51851   break;
51852 }
51853
51854 #ifndef SQLITE_OMIT_CAST
51855 /* Opcode: ToText P1 * * * *
51856 **
51857 ** Force the value in register P1 to be text.
51858 ** If the value is numeric, convert it to a string using the
51859 ** equivalent of printf().  Blob values are unchanged and
51860 ** are afterwards simply interpreted as text.
51861 **
51862 ** A NULL value is not changed by this routine.  It remains NULL.
51863 */
51864 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
51865   if( pIn1->flags & MEM_Null ) break;
51866   assert( MEM_Str==(MEM_Blob>>3) );
51867   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
51868   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
51869   rc = ExpandBlob(pIn1);
51870   assert( pIn1->flags & MEM_Str || db->mallocFailed );
51871   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
51872   UPDATE_MAX_BLOBSIZE(pIn1);
51873   break;
51874 }
51875
51876 /* Opcode: ToBlob P1 * * * *
51877 **
51878 ** Force the value in register P1 to be a BLOB.
51879 ** If the value is numeric, convert it to a string first.
51880 ** Strings are simply reinterpreted as blobs with no change
51881 ** to the underlying data.
51882 **
51883 ** A NULL value is not changed by this routine.  It remains NULL.
51884 */
51885 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
51886   if( pIn1->flags & MEM_Null ) break;
51887   if( (pIn1->flags & MEM_Blob)==0 ){
51888     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
51889     assert( pIn1->flags & MEM_Str || db->mallocFailed );
51890     MemSetTypeFlag(pIn1, MEM_Blob);
51891   }else{
51892     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
51893   }
51894   UPDATE_MAX_BLOBSIZE(pIn1);
51895   break;
51896 }
51897
51898 /* Opcode: ToNumeric P1 * * * *
51899 **
51900 ** Force the value in register P1 to be numeric (either an
51901 ** integer or a floating-point number.)
51902 ** If the value is text or blob, try to convert it to an using the
51903 ** equivalent of atoi() or atof() and store 0 if no such conversion 
51904 ** is possible.
51905 **
51906 ** A NULL value is not changed by this routine.  It remains NULL.
51907 */
51908 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
51909   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
51910     sqlite3VdbeMemNumerify(pIn1);
51911   }
51912   break;
51913 }
51914 #endif /* SQLITE_OMIT_CAST */
51915
51916 /* Opcode: ToInt P1 * * * *
51917 **
51918 ** Force the value in register P1 be an integer.  If
51919 ** The value is currently a real number, drop its fractional part.
51920 ** If the value is text or blob, try to convert it to an integer using the
51921 ** equivalent of atoi() and store 0 if no such conversion is possible.
51922 **
51923 ** A NULL value is not changed by this routine.  It remains NULL.
51924 */
51925 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
51926   if( (pIn1->flags & MEM_Null)==0 ){
51927     sqlite3VdbeMemIntegerify(pIn1);
51928   }
51929   break;
51930 }
51931
51932 #ifndef SQLITE_OMIT_CAST
51933 /* Opcode: ToReal P1 * * * *
51934 **
51935 ** Force the value in register P1 to be a floating point number.
51936 ** If The value is currently an integer, convert it.
51937 ** If the value is text or blob, try to convert it to an integer using the
51938 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
51939 **
51940 ** A NULL value is not changed by this routine.  It remains NULL.
51941 */
51942 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
51943   if( (pIn1->flags & MEM_Null)==0 ){
51944     sqlite3VdbeMemRealify(pIn1);
51945   }
51946   break;
51947 }
51948 #endif /* SQLITE_OMIT_CAST */
51949
51950 /* Opcode: Lt P1 P2 P3 P4 P5
51951 **
51952 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
51953 ** jump to address P2.  
51954 **
51955 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
51956 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
51957 ** bit is clear then fall thru if either operand is NULL.
51958 **
51959 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
51960 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
51961 ** to coerce both inputs according to this affinity before the
51962 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
51963 ** affinity is used. Note that the affinity conversions are stored
51964 ** back into the input registers P1 and P3.  So this opcode can cause
51965 ** persistent changes to registers P1 and P3.
51966 **
51967 ** Once any conversions have taken place, and neither value is NULL, 
51968 ** the values are compared. If both values are blobs then memcmp() is
51969 ** used to determine the results of the comparison.  If both values
51970 ** are text, then the appropriate collating function specified in
51971 ** P4 is  used to do the comparison.  If P4 is not specified then
51972 ** memcmp() is used to compare text string.  If both values are
51973 ** numeric, then a numeric comparison is used. If the two values
51974 ** are of different types, then numbers are considered less than
51975 ** strings and strings are considered less than blobs.
51976 **
51977 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
51978 ** store a boolean result (either 0, or 1, or NULL) in register P2.
51979 */
51980 /* Opcode: Ne P1 P2 P3 P4 P5
51981 **
51982 ** This works just like the Lt opcode except that the jump is taken if
51983 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
51984 ** additional information.
51985 */
51986 /* Opcode: Eq P1 P2 P3 P4 P5
51987 **
51988 ** This works just like the Lt opcode except that the jump is taken if
51989 ** the operands in registers P1 and P3 are equal.
51990 ** See the Lt opcode for additional information.
51991 */
51992 /* Opcode: Le P1 P2 P3 P4 P5
51993 **
51994 ** This works just like the Lt opcode except that the jump is taken if
51995 ** the content of register P3 is less than or equal to the content of
51996 ** register P1.  See the Lt opcode for additional information.
51997 */
51998 /* Opcode: Gt P1 P2 P3 P4 P5
51999 **
52000 ** This works just like the Lt opcode except that the jump is taken if
52001 ** the content of register P3 is greater than the content of
52002 ** register P1.  See the Lt opcode for additional information.
52003 */
52004 /* Opcode: Ge P1 P2 P3 P4 P5
52005 **
52006 ** This works just like the Lt opcode except that the jump is taken if
52007 ** the content of register P3 is greater than or equal to the content of
52008 ** register P1.  See the Lt opcode for additional information.
52009 */
52010 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
52011 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
52012 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
52013 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
52014 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
52015 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
52016   int flags;
52017   int res;
52018   char affinity;
52019
52020   flags = pIn1->flags|pIn3->flags;
52021
52022   if( flags&MEM_Null ){
52023     /* If either operand is NULL then the result is always NULL.
52024     ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
52025     */
52026     if( pOp->p5 & SQLITE_STOREP2 ){
52027       pOut = &p->aMem[pOp->p2];
52028       MemSetTypeFlag(pOut, MEM_Null);
52029       REGISTER_TRACE(pOp->p2, pOut);
52030     }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
52031       pc = pOp->p2-1;
52032     }
52033     break;
52034   }
52035
52036   affinity = pOp->p5 & SQLITE_AFF_MASK;
52037   if( affinity ){
52038     applyAffinity(pIn1, affinity, encoding);
52039     applyAffinity(pIn3, affinity, encoding);
52040     if( db->mallocFailed ) goto no_mem;
52041   }
52042
52043   assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
52044   ExpandBlob(pIn1);
52045   ExpandBlob(pIn3);
52046   res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
52047   switch( pOp->opcode ){
52048     case OP_Eq:    res = res==0;     break;
52049     case OP_Ne:    res = res!=0;     break;
52050     case OP_Lt:    res = res<0;      break;
52051     case OP_Le:    res = res<=0;     break;
52052     case OP_Gt:    res = res>0;      break;
52053     default:       res = res>=0;     break;
52054   }
52055
52056   if( pOp->p5 & SQLITE_STOREP2 ){
52057     pOut = &p->aMem[pOp->p2];
52058     MemSetTypeFlag(pOut, MEM_Int);
52059     pOut->u.i = res;
52060     REGISTER_TRACE(pOp->p2, pOut);
52061   }else if( res ){
52062     pc = pOp->p2-1;
52063   }
52064   break;
52065 }
52066
52067 /* Opcode: Permutation * * * P4 *
52068 **
52069 ** Set the permuation used by the OP_Compare operator to be the array
52070 ** of integers in P4.
52071 **
52072 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
52073 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
52074 ** immediately prior to the OP_Compare.
52075 */
52076 case OP_Permutation: {
52077   assert( pOp->p4type==P4_INTARRAY );
52078   assert( pOp->p4.ai );
52079   aPermute = pOp->p4.ai;
52080   break;
52081 }
52082
52083 /* Opcode: Compare P1 P2 P3 P4 *
52084 **
52085 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
52086 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
52087 ** the comparison for use by the next OP_Jump instruct.
52088 **
52089 ** P4 is a KeyInfo structure that defines collating sequences and sort
52090 ** orders for the comparison.  The permutation applies to registers
52091 ** only.  The KeyInfo elements are used sequentially.
52092 **
52093 ** The comparison is a sort comparison, so NULLs compare equal,
52094 ** NULLs are less than numbers, numbers are less than strings,
52095 ** and strings are less than blobs.
52096 */
52097 case OP_Compare: {
52098   int n = pOp->p3;
52099   int i, p1, p2;
52100   const KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
52101   assert( n>0 );
52102   assert( pKeyInfo!=0 );
52103   p1 = pOp->p1;
52104   assert( p1>0 && p1+n-1<p->nMem );
52105   p2 = pOp->p2;
52106   assert( p2>0 && p2+n-1<p->nMem );
52107   for(i=0; i<n; i++){
52108     int idx = aPermute ? aPermute[i] : i;
52109     CollSeq *pColl;    /* Collating sequence to use on this term */
52110     int bRev;          /* True for DESCENDING sort order */
52111     REGISTER_TRACE(p1+idx, &p->aMem[p1+idx]);
52112     REGISTER_TRACE(p2+idx, &p->aMem[p2+idx]);
52113     assert( i<pKeyInfo->nField );
52114     pColl = pKeyInfo->aColl[i];
52115     bRev = pKeyInfo->aSortOrder[i];
52116     iCompare = sqlite3MemCompare(&p->aMem[p1+idx], &p->aMem[p2+idx], pColl);
52117     if( iCompare ){
52118       if( bRev ) iCompare = -iCompare;
52119       break;
52120     }
52121   }
52122   aPermute = 0;
52123   break;
52124 }
52125
52126 /* Opcode: Jump P1 P2 P3 * *
52127 **
52128 ** Jump to the instruction at address P1, P2, or P3 depending on whether
52129 ** in the most recent OP_Compare instruction the P1 vector was less than
52130 ** equal to, or greater than the P2 vector, respectively.
52131 */
52132 case OP_Jump: {             /* jump */
52133   if( iCompare<0 ){
52134     pc = pOp->p1 - 1;
52135   }else if( iCompare==0 ){
52136     pc = pOp->p2 - 1;
52137   }else{
52138     pc = pOp->p3 - 1;
52139   }
52140   break;
52141 }
52142
52143 /* Opcode: And P1 P2 P3 * *
52144 **
52145 ** Take the logical AND of the values in registers P1 and P2 and
52146 ** write the result into register P3.
52147 **
52148 ** If either P1 or P2 is 0 (false) then the result is 0 even if
52149 ** the other input is NULL.  A NULL and true or two NULLs give
52150 ** a NULL output.
52151 */
52152 /* Opcode: Or P1 P2 P3 * *
52153 **
52154 ** Take the logical OR of the values in register P1 and P2 and
52155 ** store the answer in register P3.
52156 **
52157 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
52158 ** even if the other input is NULL.  A NULL and false or two NULLs
52159 ** give a NULL output.
52160 */
52161 case OP_And:              /* same as TK_AND, in1, in2, out3 */
52162 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
52163   int v1, v2;    /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52164
52165   if( pIn1->flags & MEM_Null ){
52166     v1 = 2;
52167   }else{
52168     v1 = sqlite3VdbeIntValue(pIn1)!=0;
52169   }
52170   if( pIn2->flags & MEM_Null ){
52171     v2 = 2;
52172   }else{
52173     v2 = sqlite3VdbeIntValue(pIn2)!=0;
52174   }
52175   if( pOp->opcode==OP_And ){
52176     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
52177     v1 = and_logic[v1*3+v2];
52178   }else{
52179     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
52180     v1 = or_logic[v1*3+v2];
52181   }
52182   if( v1==2 ){
52183     MemSetTypeFlag(pOut, MEM_Null);
52184   }else{
52185     pOut->u.i = v1;
52186     MemSetTypeFlag(pOut, MEM_Int);
52187   }
52188   break;
52189 }
52190
52191 /* Opcode: Not P1 P2 * * *
52192 **
52193 ** Interpret the value in register P1 as a boolean value.  Store the
52194 ** boolean complement in register P2.  If the value in register P1 is 
52195 ** NULL, then a NULL is stored in P2.
52196 */
52197 case OP_Not: {                /* same as TK_NOT, in1 */
52198   pOut = &p->aMem[pOp->p2];
52199   if( pIn1->flags & MEM_Null ){
52200     sqlite3VdbeMemSetNull(pOut);
52201   }else{
52202     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
52203   }
52204   break;
52205 }
52206
52207 /* Opcode: BitNot P1 P2 * * *
52208 **
52209 ** Interpret the content of register P1 as an integer.  Store the
52210 ** ones-complement of the P1 value into register P2.  If P1 holds
52211 ** a NULL then store a NULL in P2.
52212 */
52213 case OP_BitNot: {             /* same as TK_BITNOT, in1 */
52214   pOut = &p->aMem[pOp->p2];
52215   if( pIn1->flags & MEM_Null ){
52216     sqlite3VdbeMemSetNull(pOut);
52217   }else{
52218     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
52219   }
52220   break;
52221 }
52222
52223 /* Opcode: If P1 P2 P3 * *
52224 **
52225 ** Jump to P2 if the value in register P1 is true.  The value is
52226 ** is considered true if it is numeric and non-zero.  If the value
52227 ** in P1 is NULL then take the jump if P3 is true.
52228 */
52229 /* Opcode: IfNot P1 P2 P3 * *
52230 **
52231 ** Jump to P2 if the value in register P1 is False.  The value is
52232 ** is considered true if it has a numeric value of zero.  If the value
52233 ** in P1 is NULL then take the jump if P3 is true.
52234 */
52235 case OP_If:                 /* jump, in1 */
52236 case OP_IfNot: {            /* jump, in1 */
52237   int c;
52238   if( pIn1->flags & MEM_Null ){
52239     c = pOp->p3;
52240   }else{
52241 #ifdef SQLITE_OMIT_FLOATING_POINT
52242     c = sqlite3VdbeIntValue(pIn1)!=0;
52243 #else
52244     c = sqlite3VdbeRealValue(pIn1)!=0.0;
52245 #endif
52246     if( pOp->opcode==OP_IfNot ) c = !c;
52247   }
52248   if( c ){
52249     pc = pOp->p2-1;
52250   }
52251   break;
52252 }
52253
52254 /* Opcode: IsNull P1 P2 P3 * *
52255 **
52256 ** Jump to P2 if the value in register P1 is NULL.  If P3 is greater
52257 ** than zero, then check all values reg(P1), reg(P1+1), 
52258 ** reg(P1+2), ..., reg(P1+P3-1).
52259 */
52260 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
52261   int n = pOp->p3;
52262   assert( pOp->p3==0 || pOp->p1>0 );
52263   do{
52264     if( (pIn1->flags & MEM_Null)!=0 ){
52265       pc = pOp->p2 - 1;
52266       break;
52267     }
52268     pIn1++;
52269   }while( --n > 0 );
52270   break;
52271 }
52272
52273 /* Opcode: NotNull P1 P2 * * *
52274 **
52275 ** Jump to P2 if the value in register P1 is not NULL.  
52276 */
52277 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
52278   if( (pIn1->flags & MEM_Null)==0 ){
52279     pc = pOp->p2 - 1;
52280   }
52281   break;
52282 }
52283
52284 /* Opcode: SetNumColumns * P2 * * *
52285 **
52286 ** This opcode sets the number of columns for the cursor opened by the
52287 ** following instruction to P2.
52288 **
52289 ** An OP_SetNumColumns is only useful if it occurs immediately before 
52290 ** one of the following opcodes:
52291 **
52292 **     OpenRead
52293 **     OpenWrite
52294 **     OpenPseudo
52295 **
52296 ** If the OP_Column opcode is to be executed on a cursor, then
52297 ** this opcode must be present immediately before the opcode that
52298 ** opens the cursor.
52299 */
52300 case OP_SetNumColumns: {
52301   break;
52302 }
52303
52304 /* Opcode: Column P1 P2 P3 P4 *
52305 **
52306 ** Interpret the data that cursor P1 points to as a structure built using
52307 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
52308 ** information about the format of the data.)  Extract the P2-th column
52309 ** from this record.  If there are less that (P2+1) 
52310 ** values in the record, extract a NULL.
52311 **
52312 ** The value extracted is stored in register P3.
52313 **
52314 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
52315 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
52316 ** the result.
52317 */
52318 case OP_Column: {
52319   int payloadSize;   /* Number of bytes in the record */
52320   int p1 = pOp->p1;  /* P1 value of the opcode */
52321   int p2 = pOp->p2;  /* column number to retrieve */
52322   VdbeCursor *pC = 0;/* The VDBE cursor */
52323   char *zRec;        /* Pointer to complete record-data */
52324   BtCursor *pCrsr;   /* The BTree cursor */
52325   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52326   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52327   int nField;        /* number of fields in the record */
52328   int len;           /* The length of the serialized data for the column */
52329   int i;             /* Loop counter */
52330   char *zData;       /* Part of the record being decoded */
52331   Mem *pDest;        /* Where to write the extracted value */
52332   Mem sMem;          /* For storing the record being decoded */
52333
52334   memset(&sMem, 0, sizeof(sMem));
52335   assert( p1<p->nCursor );
52336   assert( pOp->p3>0 && pOp->p3<=p->nMem );
52337   pDest = &p->aMem[pOp->p3];
52338   MemSetTypeFlag(pDest, MEM_Null);
52339
52340   /* This block sets the variable payloadSize to be the total number of
52341   ** bytes in the record.
52342   **
52343   ** zRec is set to be the complete text of the record if it is available.
52344   ** The complete record text is always available for pseudo-tables
52345   ** If the record is stored in a cursor, the complete record text
52346   ** might be available in the  pC->aRow cache.  Or it might not be.
52347   ** If the data is unavailable,  zRec is set to NULL.
52348   **
52349   ** We also compute the number of columns in the record.  For cursors,
52350   ** the number of columns is stored in the VdbeCursor.nField element.
52351   */
52352   pC = p->apCsr[p1];
52353   assert( pC!=0 );
52354 #ifndef SQLITE_OMIT_VIRTUALTABLE
52355   assert( pC->pVtabCursor==0 );
52356 #endif
52357   if( pC->pCursor!=0 ){
52358     /* The record is stored in a B-Tree */
52359     rc = sqlite3VdbeCursorMoveto(pC);
52360     if( rc ) goto abort_due_to_error;
52361     zRec = 0;
52362     pCrsr = pC->pCursor;
52363     if( pC->nullRow ){
52364       payloadSize = 0;
52365     }else if( pC->cacheStatus==p->cacheCtr ){
52366       payloadSize = pC->payloadSize;
52367       zRec = (char*)pC->aRow;
52368     }else if( pC->isIndex ){
52369       i64 payloadSize64;
52370       sqlite3BtreeKeySize(pCrsr, &payloadSize64);
52371       payloadSize = (int)payloadSize64;
52372     }else{
52373       sqlite3BtreeDataSize(pCrsr, (u32 *)&payloadSize);
52374     }
52375     nField = pC->nField;
52376   }else{
52377     assert( pC->pseudoTable );
52378     /* The record is the sole entry of a pseudo-table */
52379     payloadSize = pC->nData;
52380     zRec = pC->pData;
52381     pC->cacheStatus = CACHE_STALE;
52382     assert( payloadSize==0 || zRec!=0 );
52383     nField = pC->nField;
52384     pCrsr = 0;
52385   }
52386
52387   /* If payloadSize is 0, then just store a NULL */
52388   if( payloadSize==0 ){
52389     assert( pDest->flags&MEM_Null );
52390     goto op_column_out;
52391   }
52392   if( payloadSize>db->aLimit[SQLITE_LIMIT_LENGTH] ){
52393     goto too_big;
52394   }
52395
52396   assert( p2<nField );
52397
52398   /* Read and parse the table header.  Store the results of the parse
52399   ** into the record header cache fields of the cursor.
52400   */
52401   aType = pC->aType;
52402   if( pC->cacheStatus==p->cacheCtr ){
52403     aOffset = pC->aOffset;
52404   }else{
52405     u8 *zIdx;        /* Index into header */
52406     u8 *zEndHdr;     /* Pointer to first byte after the header */
52407     int offset;      /* Offset into the data */
52408     int szHdrSz;     /* Size of the header size field at start of record */
52409     int avail = 0;   /* Number of bytes of available data */
52410
52411     assert(aType);
52412     pC->aOffset = aOffset = &aType[nField];
52413     pC->payloadSize = payloadSize;
52414     pC->cacheStatus = p->cacheCtr;
52415
52416     /* Figure out how many bytes are in the header */
52417     if( zRec ){
52418       zData = zRec;
52419     }else{
52420       if( pC->isIndex ){
52421         zData = (char*)sqlite3BtreeKeyFetch(pCrsr, &avail);
52422       }else{
52423         zData = (char*)sqlite3BtreeDataFetch(pCrsr, &avail);
52424       }
52425       /* If KeyFetch()/DataFetch() managed to get the entire payload,
52426       ** save the payload in the pC->aRow cache.  That will save us from
52427       ** having to make additional calls to fetch the content portion of
52428       ** the record.
52429       */
52430       if( avail>=payloadSize ){
52431         zRec = zData;
52432         pC->aRow = (u8*)zData;
52433       }else{
52434         pC->aRow = 0;
52435       }
52436     }
52437     /* The following assert is true in all cases accept when
52438     ** the database file has been corrupted externally.
52439     **    assert( zRec!=0 || avail>=payloadSize || avail>=9 ); */
52440     szHdrSz = getVarint32((u8*)zData, offset);
52441
52442     /* The KeyFetch() or DataFetch() above are fast and will get the entire
52443     ** record header in most cases.  But they will fail to get the complete
52444     ** record header if the record header does not fit on a single page
52445     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
52446     ** acquire the complete header text.
52447     */
52448     if( !zRec && avail<offset ){
52449       sMem.flags = 0;
52450       sMem.db = 0;
52451       rc = sqlite3VdbeMemFromBtree(pCrsr, 0, offset, pC->isIndex, &sMem);
52452       if( rc!=SQLITE_OK ){
52453         goto op_column_out;
52454       }
52455       zData = sMem.z;
52456     }
52457     zEndHdr = (u8 *)&zData[offset];
52458     zIdx = (u8 *)&zData[szHdrSz];
52459
52460     /* Scan the header and use it to fill in the aType[] and aOffset[]
52461     ** arrays.  aType[i] will contain the type integer for the i-th
52462     ** column and aOffset[i] will contain the offset from the beginning
52463     ** of the record to the start of the data for the i-th column
52464     */
52465     for(i=0; i<nField; i++){
52466       if( zIdx<zEndHdr ){
52467         aOffset[i] = offset;
52468         zIdx += getVarint32(zIdx, aType[i]);
52469         offset += sqlite3VdbeSerialTypeLen(aType[i]);
52470       }else{
52471         /* If i is less that nField, then there are less fields in this
52472         ** record than SetNumColumns indicated there are columns in the
52473         ** table. Set the offset for any extra columns not present in
52474         ** the record to 0. This tells code below to store a NULL
52475         ** instead of deserializing a value from the record.
52476         */
52477         aOffset[i] = 0;
52478       }
52479     }
52480     sqlite3VdbeMemRelease(&sMem);
52481     sMem.flags = MEM_Null;
52482
52483     /* If we have read more header data than was contained in the header,
52484     ** or if the end of the last field appears to be past the end of the
52485     ** record, or if the end of the last field appears to be before the end
52486     ** of the record (when all fields present), then we must be dealing 
52487     ** with a corrupt database.
52488     */
52489     if( zIdx>zEndHdr || offset>payloadSize 
52490      || (zIdx==zEndHdr && offset!=payloadSize) ){
52491       rc = SQLITE_CORRUPT_BKPT;
52492       goto op_column_out;
52493     }
52494   }
52495
52496   /* Get the column information. If aOffset[p2] is non-zero, then 
52497   ** deserialize the value from the record. If aOffset[p2] is zero,
52498   ** then there are not enough fields in the record to satisfy the
52499   ** request.  In this case, set the value NULL or to P4 if P4 is
52500   ** a pointer to a Mem object.
52501   */
52502   if( aOffset[p2] ){
52503     assert( rc==SQLITE_OK );
52504     if( zRec ){
52505       sqlite3VdbeMemReleaseExternal(pDest);
52506       sqlite3VdbeSerialGet((u8 *)&zRec[aOffset[p2]], aType[p2], pDest);
52507     }else{
52508       len = sqlite3VdbeSerialTypeLen(aType[p2]);
52509       sqlite3VdbeMemMove(&sMem, pDest);
52510       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, pC->isIndex, &sMem);
52511       if( rc!=SQLITE_OK ){
52512         goto op_column_out;
52513       }
52514       zData = sMem.z;
52515       sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest);
52516     }
52517     pDest->enc = encoding;
52518   }else{
52519     if( pOp->p4type==P4_MEM ){
52520       sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
52521     }else{
52522       assert( pDest->flags&MEM_Null );
52523     }
52524   }
52525
52526   /* If we dynamically allocated space to hold the data (in the
52527   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
52528   ** dynamically allocated space over to the pDest structure.
52529   ** This prevents a memory copy.
52530   */
52531   if( sMem.zMalloc ){
52532     assert( sMem.z==sMem.zMalloc );
52533     assert( !(pDest->flags & MEM_Dyn) );
52534     assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
52535     pDest->flags &= ~(MEM_Ephem|MEM_Static);
52536     pDest->flags |= MEM_Term;
52537     pDest->z = sMem.z;
52538     pDest->zMalloc = sMem.zMalloc;
52539   }
52540
52541   rc = sqlite3VdbeMemMakeWriteable(pDest);
52542
52543 op_column_out:
52544   UPDATE_MAX_BLOBSIZE(pDest);
52545   REGISTER_TRACE(pOp->p3, pDest);
52546   break;
52547 }
52548
52549 /* Opcode: Affinity P1 P2 * P4 *
52550 **
52551 ** Apply affinities to a range of P2 registers starting with P1.
52552 **
52553 ** P4 is a string that is P2 characters long. The nth character of the
52554 ** string indicates the column affinity that should be used for the nth
52555 ** memory cell in the range.
52556 */
52557 case OP_Affinity: {
52558   char *zAffinity = pOp->p4.z;
52559   Mem *pData0 = &p->aMem[pOp->p1];
52560   Mem *pLast = &pData0[pOp->p2-1];
52561   Mem *pRec;
52562
52563   for(pRec=pData0; pRec<=pLast; pRec++){
52564     ExpandBlob(pRec);
52565     applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
52566   }
52567   break;
52568 }
52569
52570 /* Opcode: MakeRecord P1 P2 P3 P4 *
52571 **
52572 ** Convert P2 registers beginning with P1 into a single entry
52573 ** suitable for use as a data record in a database table or as a key
52574 ** in an index.  The details of the format are irrelevant as long as
52575 ** the OP_Column opcode can decode the record later.
52576 ** Refer to source code comments for the details of the record
52577 ** format.
52578 **
52579 ** P4 may be a string that is P2 characters long.  The nth character of the
52580 ** string indicates the column affinity that should be used for the nth
52581 ** field of the index key.
52582 **
52583 ** The mapping from character to affinity is given by the SQLITE_AFF_
52584 ** macros defined in sqliteInt.h.
52585 **
52586 ** If P4 is NULL then all index fields have the affinity NONE.
52587 */
52588 case OP_MakeRecord: {
52589   /* Assuming the record contains N fields, the record format looks
52590   ** like this:
52591   **
52592   ** ------------------------------------------------------------------------
52593   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
52594   ** ------------------------------------------------------------------------
52595   **
52596   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
52597   ** and so froth.
52598   **
52599   ** Each type field is a varint representing the serial type of the 
52600   ** corresponding data element (see sqlite3VdbeSerialType()). The
52601   ** hdr-size field is also a varint which is the offset from the beginning
52602   ** of the record to data0.
52603   */
52604   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52605   Mem *pRec;             /* The new record */
52606   u64 nData = 0;         /* Number of bytes of data space */
52607   int nHdr = 0;          /* Number of bytes of header space */
52608   i64 nByte = 0;         /* Data space required for this record */
52609   int nZero = 0;         /* Number of zero bytes at the end of the record */
52610   int nVarint;           /* Number of bytes in a varint */
52611   u32 serial_type;       /* Type field */
52612   Mem *pData0;           /* First field to be combined into the record */
52613   Mem *pLast;            /* Last field of the record */
52614   int nField;            /* Number of fields in the record */
52615   char *zAffinity;       /* The affinity string for the record */
52616   int file_format;       /* File format to use for encoding */
52617   int i;                 /* Space used in zNewRecord[] */
52618
52619   nField = pOp->p1;
52620   zAffinity = pOp->p4.z;
52621   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem );
52622   pData0 = &p->aMem[nField];
52623   nField = pOp->p2;
52624   pLast = &pData0[nField-1];
52625   file_format = p->minWriteFileFormat;
52626
52627   /* Loop through the elements that will make up the record to figure
52628   ** out how much space is required for the new record.
52629   */
52630   for(pRec=pData0; pRec<=pLast; pRec++){
52631     int len;
52632     if( zAffinity ){
52633       applyAffinity(pRec, zAffinity[pRec-pData0], encoding);
52634     }
52635     if( pRec->flags&MEM_Zero && pRec->n>0 ){
52636       sqlite3VdbeMemExpandBlob(pRec);
52637     }
52638     serial_type = sqlite3VdbeSerialType(pRec, file_format);
52639     len = sqlite3VdbeSerialTypeLen(serial_type);
52640     nData += len;
52641     nHdr += sqlite3VarintLen(serial_type);
52642     if( pRec->flags & MEM_Zero ){
52643       /* Only pure zero-filled BLOBs can be input to this Opcode.
52644       ** We do not allow blobs with a prefix and a zero-filled tail. */
52645       nZero += pRec->u.nZero;
52646     }else if( len ){
52647       nZero = 0;
52648     }
52649   }
52650
52651   /* Add the initial header varint and total the size */
52652   nHdr += nVarint = sqlite3VarintLen(nHdr);
52653   if( nVarint<sqlite3VarintLen(nHdr) ){
52654     nHdr++;
52655   }
52656   nByte = nHdr+nData-nZero;
52657   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
52658     goto too_big;
52659   }
52660
52661   /* Make sure the output register has a buffer large enough to store 
52662   ** the new record. The output register (pOp->p3) is not allowed to
52663   ** be one of the input registers (because the following call to
52664   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
52665   */
52666   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
52667   pOut = &p->aMem[pOp->p3];
52668   if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
52669     goto no_mem;
52670   }
52671   zNewRecord = (u8 *)pOut->z;
52672
52673   /* Write the record */
52674   i = putVarint32(zNewRecord, nHdr);
52675   for(pRec=pData0; pRec<=pLast; pRec++){
52676     serial_type = sqlite3VdbeSerialType(pRec, file_format);
52677     i += putVarint32(&zNewRecord[i], serial_type);      /* serial type */
52678   }
52679   for(pRec=pData0; pRec<=pLast; pRec++){  /* serial data */
52680     i += sqlite3VdbeSerialPut(&zNewRecord[i], (int)(nByte-i), pRec,file_format);
52681   }
52682   assert( i==nByte );
52683
52684   assert( pOp->p3>0 && pOp->p3<=p->nMem );
52685   pOut->n = (int)nByte;
52686   pOut->flags = MEM_Blob | MEM_Dyn;
52687   pOut->xDel = 0;
52688   if( nZero ){
52689     pOut->u.nZero = nZero;
52690     pOut->flags |= MEM_Zero;
52691   }
52692   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
52693   REGISTER_TRACE(pOp->p3, pOut);
52694   UPDATE_MAX_BLOBSIZE(pOut);
52695   break;
52696 }
52697
52698 /* Opcode: Statement P1 * * * *
52699 **
52700 ** Begin an individual statement transaction which is part of a larger
52701 ** transaction.  This is needed so that the statement
52702 ** can be rolled back after an error without having to roll back the
52703 ** entire transaction.  The statement transaction will automatically
52704 ** commit when the VDBE halts.
52705 **
52706 ** If the database connection is currently in autocommit mode (that 
52707 ** is to say, if it is in between BEGIN and COMMIT)
52708 ** and if there are no other active statements on the same database
52709 ** connection, then this operation is a no-op.  No statement transaction
52710 ** is needed since any error can use the normal ROLLBACK process to
52711 ** undo changes.
52712 **
52713 ** If a statement transaction is started, then a statement journal file
52714 ** will be allocated and initialized.
52715 **
52716 ** The statement is begun on the database file with index P1.  The main
52717 ** database file has an index of 0 and the file used for temporary tables
52718 ** has an index of 1.
52719 */
52720 case OP_Statement: {
52721   if( db->autoCommit==0 || db->activeVdbeCnt>1 ){
52722     int i = pOp->p1;
52723     Btree *pBt;
52724     assert( i>=0 && i<db->nDb );
52725     assert( db->aDb[i].pBt!=0 );
52726     pBt = db->aDb[i].pBt;
52727     assert( sqlite3BtreeIsInTrans(pBt) );
52728     assert( (p->btreeMask & (1<<i))!=0 );
52729     if( !sqlite3BtreeIsInStmt(pBt) ){
52730       rc = sqlite3BtreeBeginStmt(pBt);
52731       p->openedStatement = 1;
52732     }
52733   }
52734   break;
52735 }
52736
52737 /* Opcode: Savepoint P1 * * P4 *
52738 **
52739 ** Open, release or rollback the savepoint named by parameter P4, depending
52740 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
52741 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
52742 */
52743 case OP_Savepoint: {
52744   int p1 = pOp->p1;
52745   char *zName = pOp->p4.z;         /* Name of savepoint */
52746
52747   /* Assert that the p1 parameter is valid. Also that if there is no open
52748   ** transaction, then there cannot be any savepoints. 
52749   */
52750   assert( db->pSavepoint==0 || db->autoCommit==0 );
52751   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
52752   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
52753   assert( checkSavepointCount(db) );
52754
52755   if( p1==SAVEPOINT_BEGIN ){
52756     if( db->writeVdbeCnt>0 ){
52757       /* A new savepoint cannot be created if there are active write 
52758       ** statements (i.e. open read/write incremental blob handles).
52759       */
52760       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
52761         "SQL statements in progress");
52762       rc = SQLITE_BUSY;
52763     }else{
52764       int nName = sqlite3Strlen30(zName);
52765       Savepoint *pNew;
52766
52767       /* Create a new savepoint structure. */
52768       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
52769       if( pNew ){
52770         pNew->zName = (char *)&pNew[1];
52771         memcpy(pNew->zName, zName, nName+1);
52772     
52773         /* If there is no open transaction, then mark this as a special
52774         ** "transaction savepoint". */
52775         if( db->autoCommit ){
52776           db->autoCommit = 0;
52777           db->isTransactionSavepoint = 1;
52778         }else{
52779           db->nSavepoint++;
52780         }
52781     
52782         /* Link the new savepoint into the database handle's list. */
52783         pNew->pNext = db->pSavepoint;
52784         db->pSavepoint = pNew;
52785       }
52786     }
52787   }else{
52788     Savepoint *pSavepoint;
52789     int iSavepoint = 0;
52790
52791     /* Find the named savepoint. If there is no such savepoint, then an
52792     ** an error is returned to the user.  */
52793     for(
52794       pSavepoint=db->pSavepoint; 
52795       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
52796       pSavepoint=pSavepoint->pNext
52797     ){
52798       iSavepoint++;
52799     }
52800     if( !pSavepoint ){
52801       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
52802       rc = SQLITE_ERROR;
52803     }else if( 
52804         db->writeVdbeCnt>0 || (p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1) 
52805     ){
52806       /* It is not possible to release (commit) a savepoint if there are 
52807       ** active write statements. It is not possible to rollback a savepoint
52808       ** if there are any active statements at all.
52809       */
52810       sqlite3SetString(&p->zErrMsg, db, 
52811         "cannot %s savepoint - SQL statements in progress",
52812         (p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
52813       );
52814       rc = SQLITE_BUSY;
52815     }else{
52816
52817       /* Determine whether or not this is a transaction savepoint. If so,
52818       ** and this is a RELEASE command, then the current transaction 
52819       ** is committed. 
52820       */
52821       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
52822       if( isTransaction && p1==SAVEPOINT_RELEASE ){
52823         db->autoCommit = 1;
52824         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
52825           p->pc = pc;
52826           db->autoCommit = 0;
52827           p->rc = rc = SQLITE_BUSY;
52828           goto vdbe_return;
52829         }
52830         db->isTransactionSavepoint = 0;
52831         rc = p->rc;
52832       }else{
52833         int ii;
52834         iSavepoint = db->nSavepoint - iSavepoint - 1;
52835         for(ii=0; ii<db->nDb; ii++){
52836           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
52837           if( rc!=SQLITE_OK ){
52838             goto abort_due_to_error;
52839           }
52840         }
52841         if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
52842           sqlite3ExpirePreparedStatements(db);
52843           sqlite3ResetInternalSchema(db, 0);
52844         }
52845       }
52846   
52847       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
52848       ** savepoints nested inside of the savepoint being operated on. */
52849       while( db->pSavepoint!=pSavepoint ){
52850         Savepoint *pTmp = db->pSavepoint;
52851         db->pSavepoint = pTmp->pNext;
52852         sqlite3DbFree(db, pTmp);
52853         db->nSavepoint--;
52854       }
52855
52856       /* If it is a RELEASE, then destroy the savepoint being operated on too */
52857       if( p1==SAVEPOINT_RELEASE ){
52858         assert( pSavepoint==db->pSavepoint );
52859         db->pSavepoint = pSavepoint->pNext;
52860         sqlite3DbFree(db, pSavepoint);
52861         if( !isTransaction ){
52862           db->nSavepoint--;
52863         }
52864       }
52865     }
52866   }
52867
52868   break;
52869 }
52870
52871 /* Opcode: AutoCommit P1 P2 * * *
52872 **
52873 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
52874 ** back any currently active btree transactions. If there are any active
52875 ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails.
52876 **
52877 ** This instruction causes the VM to halt.
52878 */
52879 case OP_AutoCommit: {
52880   int desiredAutoCommit = pOp->p1;
52881   int rollback = pOp->p2;
52882   int turnOnAC = desiredAutoCommit && !db->autoCommit;
52883
52884   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
52885   assert( desiredAutoCommit==1 || rollback==0 );
52886
52887   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
52888
52889   if( turnOnAC && rollback && db->activeVdbeCnt>1 ){
52890     /* If this instruction implements a ROLLBACK and other VMs are
52891     ** still running, and a transaction is active, return an error indicating
52892     ** that the other VMs must complete first. 
52893     */
52894     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
52895         "SQL statements in progress");
52896     rc = SQLITE_BUSY;
52897   }else if( turnOnAC && !rollback && db->writeVdbeCnt>1 ){
52898     /* If this instruction implements a COMMIT and other VMs are writing
52899     ** return an error indicating that the other VMs must complete first. 
52900     */
52901     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
52902         "SQL statements in progress");
52903     rc = SQLITE_BUSY;
52904   }else if( desiredAutoCommit!=db->autoCommit ){
52905     if( rollback ){
52906       assert( desiredAutoCommit==1 );
52907       sqlite3RollbackAll(db);
52908       db->autoCommit = 1;
52909     }else{
52910       db->autoCommit = (u8)desiredAutoCommit;
52911       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
52912         p->pc = pc;
52913         db->autoCommit = (u8)(1-desiredAutoCommit);
52914         p->rc = rc = SQLITE_BUSY;
52915         goto vdbe_return;
52916       }
52917     }
52918     sqlite3CloseSavepoints(db);
52919     if( p->rc==SQLITE_OK ){
52920       rc = SQLITE_DONE;
52921     }else{
52922       rc = SQLITE_ERROR;
52923     }
52924     goto vdbe_return;
52925   }else{
52926     sqlite3SetString(&p->zErrMsg, db,
52927         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
52928         (rollback)?"cannot rollback - no transaction is active":
52929                    "cannot commit - no transaction is active"));
52930          
52931     rc = SQLITE_ERROR;
52932   }
52933   break;
52934 }
52935
52936 /* Opcode: Transaction P1 P2 * * *
52937 **
52938 ** Begin a transaction.  The transaction ends when a Commit or Rollback
52939 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
52940 ** transaction might also be rolled back if an error is encountered.
52941 **
52942 ** P1 is the index of the database file on which the transaction is
52943 ** started.  Index 0 is the main database file and index 1 is the
52944 ** file used for temporary tables.  Indices of 2 or more are used for
52945 ** attached databases.
52946 **
52947 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
52948 ** obtained on the database file when a write-transaction is started.  No
52949 ** other process can start another write transaction while this transaction is
52950 ** underway.  Starting a write transaction also creates a rollback journal. A
52951 ** write transaction must be started before any changes can be made to the
52952 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
52953 ** on the file.
52954 **
52955 ** If P2 is zero, then a read-lock is obtained on the database file.
52956 */
52957 case OP_Transaction: {
52958   int i = pOp->p1;
52959   Btree *pBt;
52960
52961   assert( i>=0 && i<db->nDb );
52962   assert( (p->btreeMask & (1<<i))!=0 );
52963   pBt = db->aDb[i].pBt;
52964
52965   if( pBt ){
52966     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
52967     if( rc==SQLITE_BUSY ){
52968       p->pc = pc;
52969       p->rc = rc = SQLITE_BUSY;
52970       goto vdbe_return;
52971     }
52972     if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){
52973       goto abort_due_to_error;
52974     }
52975   }
52976   break;
52977 }
52978
52979 /* Opcode: ReadCookie P1 P2 P3 * *
52980 **
52981 ** Read cookie number P3 from database P1 and write it into register P2.
52982 ** P3==0 is the schema version.  P3==1 is the database format.
52983 ** P3==2 is the recommended pager cache size, and so forth.  P1==0 is
52984 ** the main database file and P1==1 is the database file used to store
52985 ** temporary tables.
52986 **
52987 ** If P1 is negative, then this is a request to read the size of a
52988 ** databases free-list. P3 must be set to 1 in this case. The actual
52989 ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
52990 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
52991 **
52992 ** There must be a read-lock on the database (either a transaction
52993 ** must be started or there must be an open cursor) before
52994 ** executing this instruction.
52995 */
52996 case OP_ReadCookie: {               /* out2-prerelease */
52997   int iMeta;
52998   int iDb = pOp->p1;
52999   int iCookie = pOp->p3;
53000
53001   assert( pOp->p3<SQLITE_N_BTREE_META );
53002   if( iDb<0 ){
53003     iDb = (-1*(iDb+1));
53004     iCookie *= -1;
53005   }
53006   assert( iDb>=0 && iDb<db->nDb );
53007   assert( db->aDb[iDb].pBt!=0 );
53008   assert( (p->btreeMask & (1<<iDb))!=0 );
53009   /* The indexing of meta values at the schema layer is off by one from
53010   ** the indexing in the btree layer.  The btree considers meta[0] to
53011   ** be the number of free pages in the database (a read-only value)
53012   ** and meta[1] to be the schema cookie.  The schema layer considers
53013   ** meta[1] to be the schema cookie.  So we have to shift the index
53014   ** by one in the following statement.
53015   */
53016   rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
53017   pOut->u.i = iMeta;
53018   MemSetTypeFlag(pOut, MEM_Int);
53019   break;
53020 }
53021
53022 /* Opcode: SetCookie P1 P2 P3 * *
53023 **
53024 ** Write the content of register P3 (interpreted as an integer)
53025 ** into cookie number P2 of database P1.
53026 ** P2==0 is the schema version.  P2==1 is the database format.
53027 ** P2==2 is the recommended pager cache size, and so forth.  P1==0 is
53028 ** the main database file and P1==1 is the database file used to store
53029 ** temporary tables.
53030 **
53031 ** A transaction must be started before executing this opcode.
53032 */
53033 case OP_SetCookie: {       /* in3 */
53034   Db *pDb;
53035   assert( pOp->p2<SQLITE_N_BTREE_META );
53036   assert( pOp->p1>=0 && pOp->p1<db->nDb );
53037   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
53038   pDb = &db->aDb[pOp->p1];
53039   assert( pDb->pBt!=0 );
53040   sqlite3VdbeMemIntegerify(pIn3);
53041   /* See note about index shifting on OP_ReadCookie */
53042   rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i);
53043   if( pOp->p2==0 ){
53044     /* When the schema cookie changes, record the new cookie internally */
53045     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
53046     db->flags |= SQLITE_InternChanges;
53047   }else if( pOp->p2==1 ){
53048     /* Record changes in the file format */
53049     pDb->pSchema->file_format = (u8)pIn3->u.i;
53050   }
53051   if( pOp->p1==1 ){
53052     /* Invalidate all prepared statements whenever the TEMP database
53053     ** schema is changed.  Ticket #1644 */
53054     sqlite3ExpirePreparedStatements(db);
53055   }
53056   break;
53057 }
53058
53059 /* Opcode: VerifyCookie P1 P2 *
53060 **
53061 ** Check the value of global database parameter number 0 (the
53062 ** schema version) and make sure it is equal to P2.  
53063 ** P1 is the database number which is 0 for the main database file
53064 ** and 1 for the file holding temporary tables and some higher number
53065 ** for auxiliary databases.
53066 **
53067 ** The cookie changes its value whenever the database schema changes.
53068 ** This operation is used to detect when that the cookie has changed
53069 ** and that the current process needs to reread the schema.
53070 **
53071 ** Either a transaction needs to have been started or an OP_Open needs
53072 ** to be executed (to establish a read lock) before this opcode is
53073 ** invoked.
53074 */
53075 case OP_VerifyCookie: {
53076   int iMeta;
53077   Btree *pBt;
53078   assert( pOp->p1>=0 && pOp->p1<db->nDb );
53079   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
53080   pBt = db->aDb[pOp->p1].pBt;
53081   if( pBt ){
53082     rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&iMeta);
53083   }else{
53084     rc = SQLITE_OK;
53085     iMeta = 0;
53086   }
53087   if( rc==SQLITE_OK && iMeta!=pOp->p2 ){
53088     sqlite3DbFree(db, p->zErrMsg);
53089     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
53090     /* If the schema-cookie from the database file matches the cookie 
53091     ** stored with the in-memory representation of the schema, do
53092     ** not reload the schema from the database file.
53093     **
53094     ** If virtual-tables are in use, this is not just an optimization.
53095     ** Often, v-tables store their data in other SQLite tables, which
53096     ** are queried from within xNext() and other v-table methods using
53097     ** prepared queries. If such a query is out-of-date, we do not want to
53098     ** discard the database schema, as the user code implementing the
53099     ** v-table would have to be ready for the sqlite3_vtab structure itself
53100     ** to be invalidated whenever sqlite3_step() is called from within 
53101     ** a v-table method.
53102     */
53103     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
53104       sqlite3ResetInternalSchema(db, pOp->p1);
53105     }
53106
53107     sqlite3ExpirePreparedStatements(db);
53108     rc = SQLITE_SCHEMA;
53109   }
53110   break;
53111 }
53112
53113 /* Opcode: OpenRead P1 P2 P3 P4 P5
53114 **
53115 ** Open a read-only cursor for the database table whose root page is
53116 ** P2 in a database file.  The database file is determined by P3. 
53117 ** P3==0 means the main database, P3==1 means the database used for 
53118 ** temporary tables, and P3>1 means used the corresponding attached
53119 ** database.  Give the new cursor an identifier of P1.  The P1
53120 ** values need not be contiguous but all P1 values should be small integers.
53121 ** It is an error for P1 to be negative.
53122 **
53123 ** If P5!=0 then use the content of register P2 as the root page, not
53124 ** the value of P2 itself.
53125 **
53126 ** There will be a read lock on the database whenever there is an
53127 ** open cursor.  If the database was unlocked prior to this instruction
53128 ** then a read lock is acquired as part of this instruction.  A read
53129 ** lock allows other processes to read the database but prohibits
53130 ** any other process from modifying the database.  The read lock is
53131 ** released when all cursors are closed.  If this instruction attempts
53132 ** to get a read lock but fails, the script terminates with an
53133 ** SQLITE_BUSY error code.
53134 **
53135 ** The P4 value is a pointer to a KeyInfo structure that defines the
53136 ** content and collating sequence of indices.  P4 is NULL for cursors
53137 ** that are not pointing to indices.
53138 **
53139 ** See also OpenWrite.
53140 */
53141 /* Opcode: OpenWrite P1 P2 P3 P4 P5
53142 **
53143 ** Open a read/write cursor named P1 on the table or index whose root
53144 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
53145 ** root page.
53146 **
53147 ** The P4 value is a pointer to a KeyInfo structure that defines the
53148 ** content and collating sequence of indices.  P4 is NULL for cursors
53149 ** that are not pointing to indices.
53150 **
53151 ** This instruction works just like OpenRead except that it opens the cursor
53152 ** in read/write mode.  For a given table, there can be one or more read-only
53153 ** cursors or a single read/write cursor but not both.
53154 **
53155 ** See also OpenRead.
53156 */
53157 case OP_OpenRead:
53158 case OP_OpenWrite: {
53159   int i = pOp->p1;
53160   int p2 = pOp->p2;
53161   int iDb = pOp->p3;
53162   int wrFlag;
53163   Btree *pX;
53164   VdbeCursor *pCur;
53165   Db *pDb;
53166   
53167   assert( iDb>=0 && iDb<db->nDb );
53168   assert( (p->btreeMask & (1<<iDb))!=0 );
53169   pDb = &db->aDb[iDb];
53170   pX = pDb->pBt;
53171   assert( pX!=0 );
53172   if( pOp->opcode==OP_OpenWrite ){
53173     wrFlag = 1;
53174     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
53175       p->minWriteFileFormat = pDb->pSchema->file_format;
53176     }
53177   }else{
53178     wrFlag = 0;
53179   }
53180   if( pOp->p5 ){
53181     assert( p2>0 );
53182     assert( p2<=p->nMem );
53183     pIn2 = &p->aMem[p2];
53184     sqlite3VdbeMemIntegerify(pIn2);
53185     p2 = (int)pIn2->u.i;
53186     if( p2<2 ) {
53187       rc = SQLITE_CORRUPT_BKPT;
53188       goto abort_due_to_error;
53189     }
53190   }
53191   assert( i>=0 );
53192   pCur = allocateCursor(p, i, &pOp[-1], iDb, 1);
53193   if( pCur==0 ) goto no_mem;
53194   pCur->nullRow = 1;
53195   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pOp->p4.p, pCur->pCursor);
53196   if( pOp->p4type==P4_KEYINFO ){
53197     pCur->pKeyInfo = pOp->p4.pKeyInfo;
53198     pCur->pKeyInfo->enc = ENC(p->db);
53199   }else{
53200     pCur->pKeyInfo = 0;
53201   }
53202   switch( rc ){
53203     case SQLITE_BUSY: {
53204       p->pc = pc;
53205       p->rc = rc = SQLITE_BUSY;
53206       goto vdbe_return;
53207     }
53208     case SQLITE_OK: {
53209       int flags = sqlite3BtreeFlags(pCur->pCursor);
53210       /* Sanity checking.  Only the lower four bits of the flags byte should
53211       ** be used.  Bit 3 (mask 0x08) is unpredictable.  The lower 3 bits
53212       ** (mask 0x07) should be either 5 (intkey+leafdata for tables) or
53213       ** 2 (zerodata for indices).  If these conditions are not met it can
53214       ** only mean that we are dealing with a corrupt database file
53215       */
53216       if( (flags & 0xf0)!=0 || ((flags & 0x07)!=5 && (flags & 0x07)!=2) ){
53217         rc = SQLITE_CORRUPT_BKPT;
53218         goto abort_due_to_error;
53219       }
53220       pCur->isTable = (flags & BTREE_INTKEY)!=0 ?1:0;
53221       pCur->isIndex = (flags & BTREE_ZERODATA)!=0 ?1:0;
53222       /* If P4==0 it means we are expected to open a table.  If P4!=0 then
53223       ** we expect to be opening an index.  If this is not what happened,
53224       ** then the database is corrupt
53225       */
53226       if( (pCur->isTable && pOp->p4type==P4_KEYINFO)
53227        || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){
53228         rc = SQLITE_CORRUPT_BKPT;
53229         goto abort_due_to_error;
53230       }
53231       break;
53232     }
53233     case SQLITE_EMPTY: {
53234       pCur->isTable = pOp->p4type!=P4_KEYINFO;
53235       pCur->isIndex = !pCur->isTable;
53236       pCur->pCursor = 0;
53237       rc = SQLITE_OK;
53238       break;
53239     }
53240     default: {
53241       goto abort_due_to_error;
53242     }
53243   }
53244   break;
53245 }
53246
53247 /* Opcode: OpenEphemeral P1 P2 * P4 *
53248 **
53249 ** Open a new cursor P1 to a transient table.
53250 ** The cursor is always opened read/write even if 
53251 ** the main database is read-only.  The transient or virtual
53252 ** table is deleted automatically when the cursor is closed.
53253 **
53254 ** P2 is the number of columns in the virtual table.
53255 ** The cursor points to a BTree table if P4==0 and to a BTree index
53256 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
53257 ** that defines the format of keys in the index.
53258 **
53259 ** This opcode was once called OpenTemp.  But that created
53260 ** confusion because the term "temp table", might refer either
53261 ** to a TEMP table at the SQL level, or to a table opened by
53262 ** this opcode.  Then this opcode was call OpenVirtual.  But
53263 ** that created confusion with the whole virtual-table idea.
53264 */
53265 case OP_OpenEphemeral: {
53266   int i = pOp->p1;
53267   VdbeCursor *pCx;
53268   static const int openFlags = 
53269       SQLITE_OPEN_READWRITE |
53270       SQLITE_OPEN_CREATE |
53271       SQLITE_OPEN_EXCLUSIVE |
53272       SQLITE_OPEN_DELETEONCLOSE |
53273       SQLITE_OPEN_TRANSIENT_DB;
53274
53275   assert( i>=0 );
53276   pCx = allocateCursor(p, i, pOp, -1, 1);
53277   if( pCx==0 ) goto no_mem;
53278   pCx->nullRow = 1;
53279   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
53280                            &pCx->pBt);
53281   if( rc==SQLITE_OK ){
53282     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
53283   }
53284   if( rc==SQLITE_OK ){
53285     /* If a transient index is required, create it by calling
53286     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
53287     ** opening it. If a transient table is required, just use the
53288     ** automatically created table with root-page 1 (an INTKEY table).
53289     */
53290     if( pOp->p4.pKeyInfo ){
53291       int pgno;
53292       assert( pOp->p4type==P4_KEYINFO );
53293       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); 
53294       if( rc==SQLITE_OK ){
53295         assert( pgno==MASTER_ROOT+1 );
53296         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, 
53297                                 (KeyInfo*)pOp->p4.z, pCx->pCursor);
53298         pCx->pKeyInfo = pOp->p4.pKeyInfo;
53299         pCx->pKeyInfo->enc = ENC(p->db);
53300       }
53301       pCx->isTable = 0;
53302     }else{
53303       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
53304       pCx->isTable = 1;
53305     }
53306   }
53307   pCx->isIndex = !pCx->isTable;
53308   break;
53309 }
53310
53311 /* Opcode: OpenPseudo P1 P2 * * *
53312 **
53313 ** Open a new cursor that points to a fake table that contains a single
53314 ** row of data.  Any attempt to write a second row of data causes the
53315 ** first row to be deleted.  All data is deleted when the cursor is
53316 ** closed.
53317 **
53318 ** A pseudo-table created by this opcode is useful for holding the
53319 ** NEW or OLD tables in a trigger.  Also used to hold the a single
53320 ** row output from the sorter so that the row can be decomposed into
53321 ** individual columns using the OP_Column opcode.
53322 **
53323 ** When OP_Insert is executed to insert a row in to the pseudo table,
53324 ** the pseudo-table cursor may or may not make it's own copy of the
53325 ** original row data. If P2 is 0, then the pseudo-table will copy the
53326 ** original row data. Otherwise, a pointer to the original memory cell
53327 ** is stored. In this case, the vdbe program must ensure that the 
53328 ** memory cell containing the row data is not overwritten until the
53329 ** pseudo table is closed (or a new row is inserted into it).
53330 */
53331 case OP_OpenPseudo: {
53332   int i = pOp->p1;
53333   VdbeCursor *pCx;
53334   assert( i>=0 );
53335   pCx = allocateCursor(p, i, &pOp[-1], -1, 0);
53336   if( pCx==0 ) goto no_mem;
53337   pCx->nullRow = 1;
53338   pCx->pseudoTable = 1;
53339   pCx->ephemPseudoTable = (u8)pOp->p2;
53340   pCx->isTable = 1;
53341   pCx->isIndex = 0;
53342   break;
53343 }
53344
53345 /* Opcode: Close P1 * * * *
53346 **
53347 ** Close a cursor previously opened as P1.  If P1 is not
53348 ** currently open, this instruction is a no-op.
53349 */
53350 case OP_Close: {
53351   int i = pOp->p1;
53352   assert( i>=0 && i<p->nCursor );
53353   sqlite3VdbeFreeCursor(p, p->apCsr[i]);
53354   p->apCsr[i] = 0;
53355   break;
53356 }
53357
53358 /* Opcode: SeekGe P1 P2 P3 P4 *
53359 **
53360 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
53361 ** use the value in register P3 as the key.  If cursor P1 refers 
53362 ** to an SQL index, then P3 is the first in an array of P4 registers 
53363 ** that are used as an unpacked index key. 
53364 **
53365 ** Reposition cursor P1 so that  it points to the smallest entry that 
53366 ** is greater than or equal to the key value. If there are no records 
53367 ** greater than or equal to the key and P2 is not zero, then jump to P2.
53368 **
53369 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
53370 */
53371 /* Opcode: SeekGt P1 P2 P3 P4 *
53372 **
53373 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
53374 ** use the value in register P3 as a key. If cursor P1 refers 
53375 ** to an SQL index, then P3 is the first in an array of P4 registers 
53376 ** that are used as an unpacked index key. 
53377 **
53378 ** Reposition cursor P1 so that  it points to the smallest entry that 
53379 ** is greater than the key value. If there are no records greater than 
53380 ** the key and P2 is not zero, then jump to P2.
53381 **
53382 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
53383 */
53384 /* Opcode: SeekLt P1 P2 P3 P4 * 
53385 **
53386 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
53387 ** use the value in register P3 as a key. If cursor P1 refers 
53388 ** to an SQL index, then P3 is the first in an array of P4 registers 
53389 ** that are used as an unpacked index key. 
53390 **
53391 ** Reposition cursor P1 so that  it points to the largest entry that 
53392 ** is less than the key value. If there are no records less than 
53393 ** the key and P2 is not zero, then jump to P2.
53394 **
53395 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
53396 */
53397 /* Opcode: SeekLe P1 P2 P3 P4 *
53398 **
53399 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
53400 ** use the value in register P3 as a key. If cursor P1 refers 
53401 ** to an SQL index, then P3 is the first in an array of P4 registers 
53402 ** that are used as an unpacked index key. 
53403 **
53404 ** Reposition cursor P1 so that it points to the largest entry that 
53405 ** is less than or equal to the key value. If there are no records 
53406 ** less than or equal to the key and P2 is not zero, then jump to P2.
53407 **
53408 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
53409 */
53410 case OP_SeekLt:         /* jump, in3 */
53411 case OP_SeekLe:         /* jump, in3 */
53412 case OP_SeekGe:         /* jump, in3 */
53413 case OP_SeekGt: {       /* jump, in3 */
53414   int i = pOp->p1;
53415   VdbeCursor *pC;
53416
53417   assert( i>=0 && i<p->nCursor );
53418   assert( pOp->p2!=0 );
53419   pC = p->apCsr[i];
53420   assert( pC!=0 );
53421   if( pC->pCursor!=0 ){
53422     int res, oc;
53423     oc = pOp->opcode;
53424     pC->nullRow = 0;
53425     if( pC->isTable ){
53426       i64 iKey;      /* The rowid we are to seek to */
53427
53428       /* The input value in P3 might be of any type: integer, real, string,
53429       ** blob, or NULL.  But it needs to be an integer before we can do
53430       ** the seek, so covert it. */
53431       applyNumericAffinity(pIn3);
53432       iKey = sqlite3VdbeIntValue(pIn3);
53433       pC->rowidIsValid = 0;
53434
53435       /* If the P3 value could not be converted into an integer without
53436       ** loss of information, then special processing is required... */
53437       if( (pIn3->flags & MEM_Int)==0 ){
53438         if( (pIn3->flags & MEM_Real)==0 ){
53439           /* If the P3 value cannot be converted into any kind of a number,
53440           ** then the seek is not possible, so jump to P2 */
53441           pc = pOp->p2 - 1;
53442           break;
53443         }
53444         /* If we reach this point, then the P3 value must be a floating
53445         ** point number. */
53446         assert( (pIn3->flags & MEM_Real)!=0 );
53447
53448         if( iKey==SMALLEST_INT64 && (pIn3->r<(double)iKey || pIn3->r>0) ){
53449           /* The P3 value is to large in magnitude to be expressed as an
53450           ** integer. */
53451           res = 1;
53452           if( pIn3->r<0 ){
53453             if( oc==OP_SeekGt || oc==OP_SeekGe ){
53454               rc = sqlite3BtreeFirst(pC->pCursor, &res);
53455               if( rc!=SQLITE_OK ) goto abort_due_to_error;
53456             }
53457           }else{
53458             if( oc==OP_SeekLt || oc==OP_SeekLe ){
53459               rc = sqlite3BtreeLast(pC->pCursor, &res);
53460               if( rc!=SQLITE_OK ) goto abort_due_to_error;
53461             }
53462           }
53463           if( res ){
53464             pc = pOp->p2 - 1;
53465           }
53466           break;
53467         }else if( oc==OP_SeekLt || oc==OP_SeekGe ){
53468           /* Use the ceiling() function to convert real->int */
53469           if( pIn3->r > (double)iKey ) iKey++;
53470         }else{
53471           /* Use the floor() function to convert real->int */
53472           assert( oc==OP_SeekLe || oc==OP_SeekGt );
53473           if( pIn3->r < (double)iKey ) iKey--;
53474         }
53475       } 
53476       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
53477       if( rc!=SQLITE_OK ){
53478         goto abort_due_to_error;
53479       }
53480       if( res==0 ){
53481         pC->rowidIsValid = 1;
53482         pC->lastRowid = iKey;
53483       }
53484     }else{
53485       UnpackedRecord r;
53486       int nField = pOp->p4.i;
53487       assert( pOp->p4type==P4_INT32 );
53488       assert( nField>0 );
53489       r.pKeyInfo = pC->pKeyInfo;
53490       r.nField = (u16)nField;
53491       if( oc==OP_SeekGt || oc==OP_SeekLe ){
53492         r.flags = UNPACKED_INCRKEY;
53493       }else{
53494         r.flags = 0;
53495       }
53496       r.aMem = &p->aMem[pOp->p3];
53497       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
53498       if( rc!=SQLITE_OK ){
53499         goto abort_due_to_error;
53500       }
53501       pC->rowidIsValid = 0;
53502     }
53503     pC->deferredMoveto = 0;
53504     pC->cacheStatus = CACHE_STALE;
53505 #ifdef SQLITE_TEST
53506     sqlite3_search_count++;
53507 #endif
53508     if( oc==OP_SeekGe || oc==OP_SeekGt ){
53509       if( res<0 || (res==0 && oc==OP_SeekGt) ){
53510         rc = sqlite3BtreeNext(pC->pCursor, &res);
53511         if( rc!=SQLITE_OK ) goto abort_due_to_error;
53512         pC->rowidIsValid = 0;
53513       }else{
53514         res = 0;
53515       }
53516     }else{
53517       assert( oc==OP_SeekLt || oc==OP_SeekLe );
53518       if( res>0 || (res==0 && oc==OP_SeekLt) ){
53519         rc = sqlite3BtreePrevious(pC->pCursor, &res);
53520         if( rc!=SQLITE_OK ) goto abort_due_to_error;
53521         pC->rowidIsValid = 0;
53522       }else{
53523         /* res might be negative because the table is empty.  Check to
53524         ** see if this is the case.
53525         */
53526         res = sqlite3BtreeEof(pC->pCursor);
53527       }
53528     }
53529     assert( pOp->p2>0 );
53530     if( res ){
53531       pc = pOp->p2 - 1;
53532     }
53533   }else if( !pC->pseudoTable ){
53534     /* This happens when attempting to open the sqlite3_master table
53535     ** for read access returns SQLITE_EMPTY. In this case always
53536     ** take the jump (since there are no records in the table).
53537     */
53538     pc = pOp->p2 - 1;
53539   }
53540   break;
53541 }
53542
53543 /* Opcode: Seek P1 P2 * * *
53544 **
53545 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
53546 ** for P1 to move so that it points to the rowid given by P2.
53547 **
53548 ** This is actually a deferred seek.  Nothing actually happens until
53549 ** the cursor is used to read a record.  That way, if no reads
53550 ** occur, no unnecessary I/O happens.
53551 */
53552 case OP_Seek: {    /* in2 */
53553   int i = pOp->p1;
53554   VdbeCursor *pC;
53555
53556   assert( i>=0 && i<p->nCursor );
53557   pC = p->apCsr[i];
53558   assert( pC!=0 );
53559   if( pC->pCursor!=0 ){
53560     assert( pC->isTable );
53561     pC->nullRow = 0;
53562     pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
53563     pC->rowidIsValid = 0;
53564     pC->deferredMoveto = 1;
53565   }
53566   break;
53567 }
53568   
53569
53570 /* Opcode: Found P1 P2 P3 * *
53571 **
53572 ** Register P3 holds a blob constructed by MakeRecord.  P1 is an index.
53573 ** If an entry that matches the value in register p3 exists in P1 then
53574 ** jump to P2.  If the P3 value does not match any entry in P1
53575 ** then fall thru.  The P1 cursor is left pointing at the matching entry
53576 ** if it exists.
53577 **
53578 ** This instruction is used to implement the IN operator where the
53579 ** left-hand side is a SELECT statement.  P1 may be a true index, or it
53580 ** may be a temporary index that holds the results of the SELECT
53581 ** statement.   This instruction is also used to implement the
53582 ** DISTINCT keyword in SELECT statements.
53583 **
53584 ** This instruction checks if index P1 contains a record for which 
53585 ** the first N serialized values exactly match the N serialized values
53586 ** in the record in register P3, where N is the total number of values in
53587 ** the P3 record (the P3 record is a prefix of the P1 record). 
53588 **
53589 ** See also: NotFound, IsUnique, NotExists
53590 */
53591 /* Opcode: NotFound P1 P2 P3 * *
53592 **
53593 ** Register P3 holds a blob constructed by MakeRecord.  P1 is
53594 ** an index.  If no entry exists in P1 that matches the blob then jump
53595 ** to P2.  If an entry does existing, fall through.  The cursor is left
53596 ** pointing to the entry that matches.
53597 **
53598 ** See also: Found, NotExists, IsUnique
53599 */
53600 case OP_NotFound:       /* jump, in3 */
53601 case OP_Found: {        /* jump, in3 */
53602   int i = pOp->p1;
53603   int alreadyExists = 0;
53604   VdbeCursor *pC;
53605   assert( i>=0 && i<p->nCursor );
53606   assert( p->apCsr[i]!=0 );
53607   if( (pC = p->apCsr[i])->pCursor!=0 ){
53608     int res;
53609     UnpackedRecord *pIdxKey;
53610
53611     assert( pC->isTable==0 );
53612     assert( pIn3->flags & MEM_Blob );
53613     pIdxKey = sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z,
53614                                       aTempRec, sizeof(aTempRec));
53615     if( pIdxKey==0 ){
53616       goto no_mem;
53617     }
53618     if( pOp->opcode==OP_Found ){
53619       pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
53620     }
53621     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
53622     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
53623     if( rc!=SQLITE_OK ){
53624       break;
53625     }
53626     alreadyExists = (res==0);
53627     pC->deferredMoveto = 0;
53628     pC->cacheStatus = CACHE_STALE;
53629   }
53630   if( pOp->opcode==OP_Found ){
53631     if( alreadyExists ) pc = pOp->p2 - 1;
53632   }else{
53633     if( !alreadyExists ) pc = pOp->p2 - 1;
53634   }
53635   break;
53636 }
53637
53638 /* Opcode: IsUnique P1 P2 P3 P4 *
53639 **
53640 ** The P3 register contains an integer record number.  Call this
53641 ** record number R.  The P4 register contains an index key created
53642 ** using MakeRecord.  Call it K.
53643 **
53644 ** P1 is an index.  So it has no data and its key consists of a
53645 ** record generated by OP_MakeRecord where the last field is the 
53646 ** rowid of the entry that the index refers to.
53647 ** 
53648 ** This instruction asks if there is an entry in P1 where the
53649 ** fields matches K but the rowid is different from R.
53650 ** If there is no such entry, then there is an immediate
53651 ** jump to P2.  If any entry does exist where the index string
53652 ** matches K but the record number is not R, then the record
53653 ** number for that entry is written into P3 and control
53654 ** falls through to the next instruction.
53655 **
53656 ** See also: NotFound, NotExists, Found
53657 */
53658 case OP_IsUnique: {        /* jump, in3 */
53659   int i = pOp->p1;
53660   VdbeCursor *pCx;
53661   BtCursor *pCrsr;
53662   Mem *pK;
53663   i64 R;
53664
53665   /* Pop the value R off the top of the stack
53666   */
53667   assert( pOp->p4type==P4_INT32 );
53668   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
53669   pK = &p->aMem[pOp->p4.i];
53670   sqlite3VdbeMemIntegerify(pIn3);
53671   R = pIn3->u.i;
53672   assert( i>=0 && i<p->nCursor );
53673   pCx = p->apCsr[i];
53674   assert( pCx!=0 );
53675   pCrsr = pCx->pCursor;
53676   if( pCrsr!=0 ){
53677     int res;
53678     i64 v;                     /* The record number that matches K */
53679     UnpackedRecord *pIdxKey;   /* Unpacked version of P4 */
53680
53681     /* Make sure K is a string and make zKey point to K
53682     */
53683     assert( pK->flags & MEM_Blob );
53684     pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
53685                                       aTempRec, sizeof(aTempRec));
53686     if( pIdxKey==0 ){
53687       goto no_mem;
53688     }
53689     pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
53690
53691     /* Search for an entry in P1 where all but the last rowid match K
53692     ** If there is no such entry, jump immediately to P2.
53693     */
53694     assert( pCx->deferredMoveto==0 );
53695     pCx->cacheStatus = CACHE_STALE;
53696     rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
53697     if( rc!=SQLITE_OK ){
53698       sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
53699       goto abort_due_to_error;
53700     }
53701     if( res<0 ){
53702       rc = sqlite3BtreeNext(pCrsr, &res);
53703       if( res ){
53704         pc = pOp->p2 - 1;
53705         sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
53706         break;
53707       }
53708     }
53709     rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res); 
53710     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
53711     if( rc!=SQLITE_OK ) goto abort_due_to_error;
53712     if( res>0 ){
53713       pc = pOp->p2 - 1;
53714       break;
53715     }
53716
53717     /* At this point, pCrsr is pointing to an entry in P1 where all but
53718     ** the final entry (the rowid) matches K.  Check to see if the
53719     ** final rowid column is different from R.  If it equals R then jump
53720     ** immediately to P2.
53721     */
53722     rc = sqlite3VdbeIdxRowid(pCrsr, &v);
53723     if( rc!=SQLITE_OK ){
53724       goto abort_due_to_error;
53725     }
53726     if( v==R ){
53727       pc = pOp->p2 - 1;
53728       break;
53729     }
53730
53731     /* The final varint of the key is different from R.  Store it back
53732     ** into register R3.  (The record number of an entry that violates
53733     ** a UNIQUE constraint.)
53734     */
53735     pIn3->u.i = v;
53736     assert( pIn3->flags&MEM_Int );
53737   }
53738   break;
53739 }
53740
53741 /* Opcode: NotExists P1 P2 P3 * *
53742 **
53743 ** Use the content of register P3 as a integer key.  If a record 
53744 ** with that key does not exist in table of P1, then jump to P2. 
53745 ** If the record does exist, then fall thru.  The cursor is left 
53746 ** pointing to the record if it exists.
53747 **
53748 ** The difference between this operation and NotFound is that this
53749 ** operation assumes the key is an integer and that P1 is a table whereas
53750 ** NotFound assumes key is a blob constructed from MakeRecord and
53751 ** P1 is an index.
53752 **
53753 ** See also: Found, NotFound, IsUnique
53754 */
53755 case OP_NotExists: {        /* jump, in3 */
53756   int i = pOp->p1;
53757   VdbeCursor *pC;
53758   BtCursor *pCrsr;
53759   assert( i>=0 && i<p->nCursor );
53760   assert( p->apCsr[i]!=0 );
53761   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
53762     int res = 0;
53763     u64 iKey;
53764     assert( pIn3->flags & MEM_Int );
53765     assert( p->apCsr[i]->isTable );
53766     iKey = intToKey(pIn3->u.i);
53767     rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
53768     pC->lastRowid = pIn3->u.i;
53769     pC->rowidIsValid = res==0 ?1:0;
53770     pC->nullRow = 0;
53771     pC->cacheStatus = CACHE_STALE;
53772     if( res!=0 ){
53773       pc = pOp->p2 - 1;
53774       assert( pC->rowidIsValid==0 );
53775     }
53776   }else if( !pC->pseudoTable ){
53777     /* This happens when an attempt to open a read cursor on the 
53778     ** sqlite_master table returns SQLITE_EMPTY.
53779     */
53780     assert( pC->isTable );
53781     pc = pOp->p2 - 1;
53782     assert( pC->rowidIsValid==0 );
53783   }
53784   break;
53785 }
53786
53787 /* Opcode: Sequence P1 P2 * * *
53788 **
53789 ** Find the next available sequence number for cursor P1.
53790 ** Write the sequence number into register P2.
53791 ** The sequence number on the cursor is incremented after this
53792 ** instruction.  
53793 */
53794 case OP_Sequence: {           /* out2-prerelease */
53795   int i = pOp->p1;
53796   assert( i>=0 && i<p->nCursor );
53797   assert( p->apCsr[i]!=0 );
53798   pOut->u.i = p->apCsr[i]->seqCount++;
53799   MemSetTypeFlag(pOut, MEM_Int);
53800   break;
53801 }
53802
53803
53804 /* Opcode: NewRowid P1 P2 P3 * *
53805 **
53806 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
53807 ** The record number is not previously used as a key in the database
53808 ** table that cursor P1 points to.  The new record number is written
53809 ** written to register P2.
53810 **
53811 ** If P3>0 then P3 is a register that holds the largest previously
53812 ** generated record number.  No new record numbers are allowed to be less
53813 ** than this value.  When this value reaches its maximum, a SQLITE_FULL
53814 ** error is generated.  The P3 register is updated with the generated
53815 ** record number.  This P3 mechanism is used to help implement the
53816 ** AUTOINCREMENT feature.
53817 */
53818 case OP_NewRowid: {           /* out2-prerelease */
53819   int i = pOp->p1;
53820   i64 v = 0;
53821   VdbeCursor *pC;
53822   assert( i>=0 && i<p->nCursor );
53823   assert( p->apCsr[i]!=0 );
53824   if( (pC = p->apCsr[i])->pCursor==0 ){
53825     /* The zero initialization above is all that is needed */
53826   }else{
53827     /* The next rowid or record number (different terms for the same
53828     ** thing) is obtained in a two-step algorithm.
53829     **
53830     ** First we attempt to find the largest existing rowid and add one
53831     ** to that.  But if the largest existing rowid is already the maximum
53832     ** positive integer, we have to fall through to the second
53833     ** probabilistic algorithm
53834     **
53835     ** The second algorithm is to select a rowid at random and see if
53836     ** it already exists in the table.  If it does not exist, we have
53837     ** succeeded.  If the random rowid does exist, we select a new one
53838     ** and try again, up to 1000 times.
53839     **
53840     ** For a table with less than 2 billion entries, the probability
53841     ** of not finding a unused rowid is about 1.0e-300.  This is a 
53842     ** non-zero probability, but it is still vanishingly small and should
53843     ** never cause a problem.  You are much, much more likely to have a
53844     ** hardware failure than for this algorithm to fail.
53845     **
53846     ** The analysis in the previous paragraph assumes that you have a good
53847     ** source of random numbers.  Is a library function like lrand48()
53848     ** good enough?  Maybe. Maybe not. It's hard to know whether there
53849     ** might be subtle bugs is some implementations of lrand48() that
53850     ** could cause problems. To avoid uncertainty, SQLite uses its own 
53851     ** random number generator based on the RC4 algorithm.
53852     **
53853     ** To promote locality of reference for repetitive inserts, the
53854     ** first few attempts at choosing a random rowid pick values just a little
53855     ** larger than the previous rowid.  This has been shown experimentally
53856     ** to double the speed of the COPY operation.
53857     */
53858     int res=0, rx=SQLITE_OK, cnt;
53859     i64 x;
53860     cnt = 0;
53861     if( (sqlite3BtreeFlags(pC->pCursor)&(BTREE_INTKEY|BTREE_ZERODATA)) !=
53862           BTREE_INTKEY ){
53863       rc = SQLITE_CORRUPT_BKPT;
53864       goto abort_due_to_error;
53865     }
53866     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_INTKEY)!=0 );
53867     assert( (sqlite3BtreeFlags(pC->pCursor) & BTREE_ZERODATA)==0 );
53868
53869 #ifdef SQLITE_32BIT_ROWID
53870 #   define MAX_ROWID 0x7fffffff
53871 #else
53872     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
53873     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
53874     ** to provide the constant while making all compilers happy.
53875     */
53876 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
53877 #endif
53878
53879     if( !pC->useRandomRowid ){
53880       if( pC->nextRowidValid ){
53881         v = pC->nextRowid;
53882       }else{
53883         rc = sqlite3BtreeLast(pC->pCursor, &res);
53884         if( rc!=SQLITE_OK ){
53885           goto abort_due_to_error;
53886         }
53887         if( res ){
53888           v = 1;
53889         }else{
53890           sqlite3BtreeKeySize(pC->pCursor, &v);
53891           v = keyToInt(v);
53892           if( v==MAX_ROWID ){
53893             pC->useRandomRowid = 1;
53894           }else{
53895             v++;
53896           }
53897         }
53898       }
53899
53900 #ifndef SQLITE_OMIT_AUTOINCREMENT
53901       if( pOp->p3 ){
53902         Mem *pMem;
53903         assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */
53904         pMem = &p->aMem[pOp->p3];
53905         REGISTER_TRACE(pOp->p3, pMem);
53906         sqlite3VdbeMemIntegerify(pMem);
53907         assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
53908         if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
53909           rc = SQLITE_FULL;
53910           goto abort_due_to_error;
53911         }
53912         if( v<pMem->u.i+1 ){
53913           v = pMem->u.i + 1;
53914         }
53915         pMem->u.i = v;
53916       }
53917 #endif
53918
53919       if( v<MAX_ROWID ){
53920         pC->nextRowidValid = 1;
53921         pC->nextRowid = v+1;
53922       }else{
53923         pC->nextRowidValid = 0;
53924       }
53925     }
53926     if( pC->useRandomRowid ){
53927       assert( pOp->p3==0 );  /* SQLITE_FULL must have occurred prior to this */
53928       v = db->priorNewRowid;
53929       cnt = 0;
53930       do{
53931         if( cnt==0 && (v&0xffffff)==v ){
53932           v++;
53933         }else{
53934           sqlite3_randomness(sizeof(v), &v);
53935           if( cnt<5 ) v &= 0xffffff;
53936         }
53937         if( v==0 ) continue;
53938         x = intToKey(v);
53939         rx = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)x, 0, &res);
53940         cnt++;
53941       }while( cnt<100 && rx==SQLITE_OK && res==0 );
53942       db->priorNewRowid = v;
53943       if( rx==SQLITE_OK && res==0 ){
53944         rc = SQLITE_FULL;
53945         goto abort_due_to_error;
53946       }
53947     }
53948     pC->rowidIsValid = 0;
53949     pC->deferredMoveto = 0;
53950     pC->cacheStatus = CACHE_STALE;
53951   }
53952   MemSetTypeFlag(pOut, MEM_Int);
53953   pOut->u.i = v;
53954   break;
53955 }
53956
53957 /* Opcode: Insert P1 P2 P3 P4 P5
53958 **
53959 ** Write an entry into the table of cursor P1.  A new entry is
53960 ** created if it doesn't already exist or the data for an existing
53961 ** entry is overwritten.  The data is the value stored register
53962 ** number P2. The key is stored in register P3. The key must
53963 ** be an integer.
53964 **
53965 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
53966 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
53967 ** then rowid is stored for subsequent return by the
53968 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
53969 **
53970 ** Parameter P4 may point to a string containing the table-name, or
53971 ** may be NULL. If it is not NULL, then the update-hook 
53972 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
53973 **
53974 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
53975 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
53976 ** and register P2 becomes ephemeral.  If the cursor is changed, the
53977 ** value of register P2 will then change.  Make sure this does not
53978 ** cause any problems.)
53979 **
53980 ** This instruction only works on tables.  The equivalent instruction
53981 ** for indices is OP_IdxInsert.
53982 */
53983 case OP_Insert: {
53984   Mem *pData = &p->aMem[pOp->p2];
53985   Mem *pKey = &p->aMem[pOp->p3];
53986
53987   i64 iKey;   /* The integer ROWID or key for the record to be inserted */
53988   int i = pOp->p1;
53989   VdbeCursor *pC;
53990   assert( i>=0 && i<p->nCursor );
53991   pC = p->apCsr[i];
53992   assert( pC!=0 );
53993   assert( pC->pCursor!=0 || pC->pseudoTable );
53994   assert( pKey->flags & MEM_Int );
53995   assert( pC->isTable );
53996   REGISTER_TRACE(pOp->p2, pData);
53997   REGISTER_TRACE(pOp->p3, pKey);
53998
53999   iKey = intToKey(pKey->u.i);
54000   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
54001   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i;
54002   if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){
54003     pC->nextRowidValid = 0;
54004   }
54005   if( pData->flags & MEM_Null ){
54006     pData->z = 0;
54007     pData->n = 0;
54008   }else{
54009     assert( pData->flags & (MEM_Blob|MEM_Str) );
54010   }
54011   if( pC->pseudoTable ){
54012     if( !pC->ephemPseudoTable ){
54013       sqlite3DbFree(db, pC->pData);
54014     }
54015     pC->iKey = iKey;
54016     pC->nData = pData->n;
54017     if( pData->z==pData->zMalloc || pC->ephemPseudoTable ){
54018       pC->pData = pData->z;
54019       if( !pC->ephemPseudoTable ){
54020         pData->flags &= ~MEM_Dyn;
54021         pData->flags |= MEM_Ephem;
54022         pData->zMalloc = 0;
54023       }
54024     }else{
54025       pC->pData = sqlite3Malloc( pC->nData+2 );
54026       if( !pC->pData ) goto no_mem;
54027       memcpy(pC->pData, pData->z, pC->nData);
54028       pC->pData[pC->nData] = 0;
54029       pC->pData[pC->nData+1] = 0;
54030     }
54031     pC->nullRow = 0;
54032   }else{
54033     int nZero;
54034     if( pData->flags & MEM_Zero ){
54035       nZero = pData->u.nZero;
54036     }else{
54037       nZero = 0;
54038     }
54039     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
54040                             pData->z, pData->n, nZero,
54041                             pOp->p5 & OPFLAG_APPEND);
54042   }
54043   
54044   pC->rowidIsValid = 0;
54045   pC->deferredMoveto = 0;
54046   pC->cacheStatus = CACHE_STALE;
54047
54048   /* Invoke the update-hook if required. */
54049   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
54050     const char *zDb = db->aDb[pC->iDb].zName;
54051     const char *zTbl = pOp->p4.z;
54052     int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
54053     assert( pC->isTable );
54054     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
54055     assert( pC->iDb>=0 );
54056   }
54057   break;
54058 }
54059
54060 /* Opcode: Delete P1 P2 * P4 *
54061 **
54062 ** Delete the record at which the P1 cursor is currently pointing.
54063 **
54064 ** The cursor will be left pointing at either the next or the previous
54065 ** record in the table. If it is left pointing at the next record, then
54066 ** the next Next instruction will be a no-op.  Hence it is OK to delete
54067 ** a record from within an Next loop.
54068 **
54069 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
54070 ** incremented (otherwise not).
54071 **
54072 ** P1 must not be pseudo-table.  It has to be a real table with
54073 ** multiple rows.
54074 **
54075 ** If P4 is not NULL, then it is the name of the table that P1 is
54076 ** pointing to.  The update hook will be invoked, if it exists.
54077 ** If P4 is not NULL then the P1 cursor must have been positioned
54078 ** using OP_NotFound prior to invoking this opcode.
54079 */
54080 case OP_Delete: {
54081   int i = pOp->p1;
54082   i64 iKey = 0;
54083   VdbeCursor *pC;
54084
54085   assert( i>=0 && i<p->nCursor );
54086   pC = p->apCsr[i];
54087   assert( pC!=0 );
54088   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
54089
54090   /* If the update-hook will be invoked, set iKey to the rowid of the
54091   ** row being deleted.
54092   */
54093   if( db->xUpdateCallback && pOp->p4.z ){
54094     assert( pC->isTable );
54095     assert( pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
54096     iKey = pC->lastRowid;
54097   }
54098
54099   rc = sqlite3VdbeCursorMoveto(pC);
54100   if( rc ) goto abort_due_to_error;
54101   rc = sqlite3BtreeDelete(pC->pCursor);
54102   pC->nextRowidValid = 0;
54103   pC->cacheStatus = CACHE_STALE;
54104
54105   /* Invoke the update-hook if required. */
54106   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
54107     const char *zDb = db->aDb[pC->iDb].zName;
54108     const char *zTbl = pOp->p4.z;
54109     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey);
54110     assert( pC->iDb>=0 );
54111   }
54112   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
54113   break;
54114 }
54115
54116 /* Opcode: ResetCount P1 * *
54117 **
54118 ** This opcode resets the VMs internal change counter to 0. If P1 is true,
54119 ** then the value of the change counter is copied to the database handle
54120 ** change counter (returned by subsequent calls to sqlite3_changes())
54121 ** before it is reset. This is used by trigger programs.
54122 */
54123 case OP_ResetCount: {
54124   if( pOp->p1 ){
54125     sqlite3VdbeSetChanges(db, p->nChange);
54126   }
54127   p->nChange = 0;
54128   break;
54129 }
54130
54131 /* Opcode: RowData P1 P2 * * *
54132 **
54133 ** Write into register P2 the complete row data for cursor P1.
54134 ** There is no interpretation of the data.  
54135 ** It is just copied onto the P2 register exactly as 
54136 ** it is found in the database file.
54137 **
54138 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
54139 ** of a real table, not a pseudo-table.
54140 */
54141 /* Opcode: RowKey P1 P2 * * *
54142 **
54143 ** Write into register P2 the complete row key for cursor P1.
54144 ** There is no interpretation of the data.  
54145 ** The key is copied onto the P3 register exactly as 
54146 ** it is found in the database file.
54147 **
54148 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
54149 ** of a real table, not a pseudo-table.
54150 */
54151 case OP_RowKey:
54152 case OP_RowData: {
54153   int i = pOp->p1;
54154   VdbeCursor *pC;
54155   BtCursor *pCrsr;
54156   u32 n;
54157
54158   pOut = &p->aMem[pOp->p2];
54159
54160   /* Note that RowKey and RowData are really exactly the same instruction */
54161   assert( i>=0 && i<p->nCursor );
54162   pC = p->apCsr[i];
54163   assert( pC->isTable || pOp->opcode==OP_RowKey );
54164   assert( pC->isIndex || pOp->opcode==OP_RowData );
54165   assert( pC!=0 );
54166   assert( pC->nullRow==0 );
54167   assert( pC->pseudoTable==0 );
54168   assert( pC->pCursor!=0 );
54169   pCrsr = pC->pCursor;
54170   rc = sqlite3VdbeCursorMoveto(pC);
54171   if( rc ) goto abort_due_to_error;
54172   if( pC->isIndex ){
54173     i64 n64;
54174     assert( !pC->isTable );
54175     sqlite3BtreeKeySize(pCrsr, &n64);
54176     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54177       goto too_big;
54178     }
54179     n = (int)n64;
54180   }else{
54181     sqlite3BtreeDataSize(pCrsr, &n);
54182     if( (int)n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54183       goto too_big;
54184     }
54185   }
54186   if( sqlite3VdbeMemGrow(pOut, n, 0) ){
54187     goto no_mem;
54188   }
54189   pOut->n = n;
54190   MemSetTypeFlag(pOut, MEM_Blob);
54191   if( pC->isIndex ){
54192     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
54193   }else{
54194     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
54195   }
54196   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
54197   UPDATE_MAX_BLOBSIZE(pOut);
54198   break;
54199 }
54200
54201 /* Opcode: Rowid P1 P2 * * *
54202 **
54203 ** Store in register P2 an integer which is the key of the table entry that
54204 ** P1 is currently point to.
54205 */
54206 case OP_Rowid: {                 /* out2-prerelease */
54207   int i = pOp->p1;
54208   VdbeCursor *pC;
54209   i64 v;
54210
54211   assert( i>=0 && i<p->nCursor );
54212   pC = p->apCsr[i];
54213   assert( pC!=0 );
54214   rc = sqlite3VdbeCursorMoveto(pC);
54215   if( rc ) goto abort_due_to_error;
54216   if( pC->rowidIsValid ){
54217     v = pC->lastRowid;
54218   }else if( pC->pseudoTable ){
54219     v = keyToInt(pC->iKey);
54220   }else if( pC->nullRow ){
54221     /* Leave the rowid set to a NULL */
54222     break;
54223   }else{
54224     assert( pC->pCursor!=0 );
54225     sqlite3BtreeKeySize(pC->pCursor, &v);
54226     v = keyToInt(v);
54227   }
54228   pOut->u.i = v;
54229   MemSetTypeFlag(pOut, MEM_Int);
54230   break;
54231 }
54232
54233 /* Opcode: NullRow P1 * * * *
54234 **
54235 ** Move the cursor P1 to a null row.  Any OP_Column operations
54236 ** that occur while the cursor is on the null row will always
54237 ** write a NULL.
54238 */
54239 case OP_NullRow: {
54240   int i = pOp->p1;
54241   VdbeCursor *pC;
54242
54243   assert( i>=0 && i<p->nCursor );
54244   pC = p->apCsr[i];
54245   assert( pC!=0 );
54246   pC->nullRow = 1;
54247   pC->rowidIsValid = 0;
54248   if( pC->pCursor ){
54249     sqlite3BtreeClearCursor(pC->pCursor);
54250   }
54251   break;
54252 }
54253
54254 /* Opcode: Last P1 P2 * * *
54255 **
54256 ** The next use of the Rowid or Column or Next instruction for P1 
54257 ** will refer to the last entry in the database table or index.
54258 ** If the table or index is empty and P2>0, then jump immediately to P2.
54259 ** If P2 is 0 or if the table or index is not empty, fall through
54260 ** to the following instruction.
54261 */
54262 case OP_Last: {        /* jump */
54263   int i = pOp->p1;
54264   VdbeCursor *pC;
54265   BtCursor *pCrsr;
54266   int res;
54267
54268   assert( i>=0 && i<p->nCursor );
54269   pC = p->apCsr[i];
54270   assert( pC!=0 );
54271   pCrsr = pC->pCursor;
54272   assert( pCrsr!=0 );
54273   rc = sqlite3BtreeLast(pCrsr, &res);
54274   pC->nullRow = (u8)res;
54275   pC->deferredMoveto = 0;
54276   pC->rowidIsValid = 0;
54277   pC->cacheStatus = CACHE_STALE;
54278   if( res && pOp->p2>0 ){
54279     pc = pOp->p2 - 1;
54280   }
54281   break;
54282 }
54283
54284
54285 /* Opcode: Sort P1 P2 * * *
54286 **
54287 ** This opcode does exactly the same thing as OP_Rewind except that
54288 ** it increments an undocumented global variable used for testing.
54289 **
54290 ** Sorting is accomplished by writing records into a sorting index,
54291 ** then rewinding that index and playing it back from beginning to
54292 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
54293 ** rewinding so that the global variable will be incremented and
54294 ** regression tests can determine whether or not the optimizer is
54295 ** correctly optimizing out sorts.
54296 */
54297 case OP_Sort: {        /* jump */
54298 #ifdef SQLITE_TEST
54299   sqlite3_sort_count++;
54300   sqlite3_search_count--;
54301 #endif
54302   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
54303   /* Fall through into OP_Rewind */
54304 }
54305 /* Opcode: Rewind P1 P2 * * *
54306 **
54307 ** The next use of the Rowid or Column or Next instruction for P1 
54308 ** will refer to the first entry in the database table or index.
54309 ** If the table or index is empty and P2>0, then jump immediately to P2.
54310 ** If P2 is 0 or if the table or index is not empty, fall through
54311 ** to the following instruction.
54312 */
54313 case OP_Rewind: {        /* jump */
54314   int i = pOp->p1;
54315   VdbeCursor *pC;
54316   BtCursor *pCrsr;
54317   int res;
54318
54319   assert( i>=0 && i<p->nCursor );
54320   pC = p->apCsr[i];
54321   assert( pC!=0 );
54322   if( (pCrsr = pC->pCursor)!=0 ){
54323     rc = sqlite3BtreeFirst(pCrsr, &res);
54324     pC->atFirst = res==0 ?1:0;
54325     pC->deferredMoveto = 0;
54326     pC->cacheStatus = CACHE_STALE;
54327     pC->rowidIsValid = 0;
54328   }else{
54329     res = 1;
54330   }
54331   pC->nullRow = (u8)res;
54332   assert( pOp->p2>0 && pOp->p2<p->nOp );
54333   if( res ){
54334     pc = pOp->p2 - 1;
54335   }
54336   break;
54337 }
54338
54339 /* Opcode: Next P1 P2 * * *
54340 **
54341 ** Advance cursor P1 so that it points to the next key/data pair in its
54342 ** table or index.  If there are no more key/value pairs then fall through
54343 ** to the following instruction.  But if the cursor advance was successful,
54344 ** jump immediately to P2.
54345 **
54346 ** The P1 cursor must be for a real table, not a pseudo-table.
54347 **
54348 ** See also: Prev
54349 */
54350 /* Opcode: Prev P1 P2 * * *
54351 **
54352 ** Back up cursor P1 so that it points to the previous key/data pair in its
54353 ** table or index.  If there is no previous key/value pairs then fall through
54354 ** to the following instruction.  But if the cursor backup was successful,
54355 ** jump immediately to P2.
54356 **
54357 ** The P1 cursor must be for a real table, not a pseudo-table.
54358 */
54359 case OP_Prev:          /* jump */
54360 case OP_Next: {        /* jump */
54361   VdbeCursor *pC;
54362   BtCursor *pCrsr;
54363   int res;
54364
54365   CHECK_FOR_INTERRUPT;
54366   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
54367   pC = p->apCsr[pOp->p1];
54368   if( pC==0 ){
54369     break;  /* See ticket #2273 */
54370   }
54371   pCrsr = pC->pCursor;
54372   assert( pCrsr );
54373   res = 1;
54374   assert( pC->deferredMoveto==0 );
54375   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) :
54376                               sqlite3BtreePrevious(pCrsr, &res);
54377   pC->nullRow = (u8)res;
54378   pC->cacheStatus = CACHE_STALE;
54379   if( res==0 ){
54380     pc = pOp->p2 - 1;
54381     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
54382 #ifdef SQLITE_TEST
54383     sqlite3_search_count++;
54384 #endif
54385   }
54386   pC->rowidIsValid = 0;
54387   break;
54388 }
54389
54390 /* Opcode: IdxInsert P1 P2 P3 * *
54391 **
54392 ** Register P2 holds a SQL index key made using the
54393 ** MakeRecord instructions.  This opcode writes that key
54394 ** into the index P1.  Data for the entry is nil.
54395 **
54396 ** P3 is a flag that provides a hint to the b-tree layer that this
54397 ** insert is likely to be an append.
54398 **
54399 ** This instruction only works for indices.  The equivalent instruction
54400 ** for tables is OP_Insert.
54401 */
54402 case OP_IdxInsert: {        /* in2 */
54403   int i = pOp->p1;
54404   VdbeCursor *pC;
54405   BtCursor *pCrsr;
54406   assert( i>=0 && i<p->nCursor );
54407   assert( p->apCsr[i]!=0 );
54408   assert( pIn2->flags & MEM_Blob );
54409   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
54410     assert( pC->isTable==0 );
54411     rc = ExpandBlob(pIn2);
54412     if( rc==SQLITE_OK ){
54413       int nKey = pIn2->n;
54414       const char *zKey = pIn2->z;
54415       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
54416       assert( pC->deferredMoveto==0 );
54417       pC->cacheStatus = CACHE_STALE;
54418     }
54419   }
54420   break;
54421 }
54422
54423 /* Opcode: IdxDelete P1 P2 P3 * *
54424 **
54425 ** The content of P3 registers starting at register P2 form
54426 ** an unpacked index key. This opcode removes that entry from the 
54427 ** index opened by cursor P1.
54428 */
54429 case OP_IdxDelete: {
54430   int i = pOp->p1;
54431   VdbeCursor *pC;
54432   BtCursor *pCrsr;
54433   assert( pOp->p3>0 );
54434   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem );
54435   assert( i>=0 && i<p->nCursor );
54436   assert( p->apCsr[i]!=0 );
54437   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
54438     int res;
54439     UnpackedRecord r;
54440     r.pKeyInfo = pC->pKeyInfo;
54441     r.nField = (u16)pOp->p3;
54442     r.flags = 0;
54443     r.aMem = &p->aMem[pOp->p2];
54444     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
54445     if( rc==SQLITE_OK && res==0 ){
54446       rc = sqlite3BtreeDelete(pCrsr);
54447     }
54448     assert( pC->deferredMoveto==0 );
54449     pC->cacheStatus = CACHE_STALE;
54450   }
54451   break;
54452 }
54453
54454 /* Opcode: IdxRowid P1 P2 * * *
54455 **
54456 ** Write into register P2 an integer which is the last entry in the record at
54457 ** the end of the index key pointed to by cursor P1.  This integer should be
54458 ** the rowid of the table entry to which this index entry points.
54459 **
54460 ** See also: Rowid, MakeRecord.
54461 */
54462 case OP_IdxRowid: {              /* out2-prerelease */
54463   int i = pOp->p1;
54464   BtCursor *pCrsr;
54465   VdbeCursor *pC;
54466
54467   assert( i>=0 && i<p->nCursor );
54468   assert( p->apCsr[i]!=0 );
54469   if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){
54470     i64 rowid;
54471
54472     assert( pC->deferredMoveto==0 );
54473     assert( pC->isTable==0 );
54474     if( !pC->nullRow ){
54475       rc = sqlite3VdbeIdxRowid(pCrsr, &rowid);
54476       if( rc!=SQLITE_OK ){
54477         goto abort_due_to_error;
54478       }
54479       MemSetTypeFlag(pOut, MEM_Int);
54480       pOut->u.i = rowid;
54481     }
54482   }
54483   break;
54484 }
54485
54486 /* Opcode: IdxGE P1 P2 P3 P4 P5
54487 **
54488 ** The P4 register values beginning with P3 form an unpacked index 
54489 ** key that omits the ROWID.  Compare this key value against the index 
54490 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
54491 **
54492 ** If the P1 index entry is greater than or equal to the key value
54493 ** then jump to P2.  Otherwise fall through to the next instruction.
54494 **
54495 ** If P5 is non-zero then the key value is increased by an epsilon 
54496 ** prior to the comparison.  This make the opcode work like IdxGT except
54497 ** that if the key from register P3 is a prefix of the key in the cursor,
54498 ** the result is false whereas it would be true with IdxGT.
54499 */
54500 /* Opcode: IdxLT P1 P2 P3 * P5
54501 **
54502 ** The P4 register values beginning with P3 form an unpacked index 
54503 ** key that omits the ROWID.  Compare this key value against the index 
54504 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
54505 **
54506 ** If the P1 index entry is less than the key value then jump to P2.
54507 ** Otherwise fall through to the next instruction.
54508 **
54509 ** If P5 is non-zero then the key value is increased by an epsilon prior 
54510 ** to the comparison.  This makes the opcode work like IdxLE.
54511 */
54512 case OP_IdxLT:          /* jump, in3 */
54513 case OP_IdxGE: {        /* jump, in3 */
54514   int i= pOp->p1;
54515   VdbeCursor *pC;
54516
54517   assert( i>=0 && i<p->nCursor );
54518   assert( p->apCsr[i]!=0 );
54519   if( (pC = p->apCsr[i])->pCursor!=0 ){
54520     int res;
54521     UnpackedRecord r;
54522     assert( pC->deferredMoveto==0 );
54523     assert( pOp->p5==0 || pOp->p5==1 );
54524     assert( pOp->p4type==P4_INT32 );
54525     r.pKeyInfo = pC->pKeyInfo;
54526     r.nField = (u16)pOp->p4.i;
54527     if( pOp->p5 ){
54528       r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
54529     }else{
54530       r.flags = UNPACKED_IGNORE_ROWID;
54531     }
54532     r.aMem = &p->aMem[pOp->p3];
54533     rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
54534     if( pOp->opcode==OP_IdxLT ){
54535       res = -res;
54536     }else{
54537       assert( pOp->opcode==OP_IdxGE );
54538       res++;
54539     }
54540     if( res>0 ){
54541       pc = pOp->p2 - 1 ;
54542     }
54543   }
54544   break;
54545 }
54546
54547 /* Opcode: Destroy P1 P2 P3 * *
54548 **
54549 ** Delete an entire database table or index whose root page in the database
54550 ** file is given by P1.
54551 **
54552 ** The table being destroyed is in the main database file if P3==0.  If
54553 ** P3==1 then the table to be clear is in the auxiliary database file
54554 ** that is used to store tables create using CREATE TEMPORARY TABLE.
54555 **
54556 ** If AUTOVACUUM is enabled then it is possible that another root page
54557 ** might be moved into the newly deleted root page in order to keep all
54558 ** root pages contiguous at the beginning of the database.  The former
54559 ** value of the root page that moved - its value before the move occurred -
54560 ** is stored in register P2.  If no page 
54561 ** movement was required (because the table being dropped was already 
54562 ** the last one in the database) then a zero is stored in register P2.
54563 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
54564 **
54565 ** See also: Clear
54566 */
54567 case OP_Destroy: {     /* out2-prerelease */
54568   int iMoved;
54569   int iCnt;
54570 #ifndef SQLITE_OMIT_VIRTUALTABLE
54571   Vdbe *pVdbe;
54572   iCnt = 0;
54573   for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
54574     if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->inVtabMethod<2 && pVdbe->pc>=0 ){
54575       iCnt++;
54576     }
54577   }
54578 #else
54579   iCnt = db->activeVdbeCnt;
54580 #endif
54581   if( iCnt>1 ){
54582     rc = SQLITE_LOCKED;
54583     p->errorAction = OE_Abort;
54584   }else{
54585     int iDb = pOp->p3;
54586     assert( iCnt==1 );
54587     assert( (p->btreeMask & (1<<iDb))!=0 );
54588     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
54589     MemSetTypeFlag(pOut, MEM_Int);
54590     pOut->u.i = iMoved;
54591 #ifndef SQLITE_OMIT_AUTOVACUUM
54592     if( rc==SQLITE_OK && iMoved!=0 ){
54593       sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1);
54594     }
54595 #endif
54596   }
54597   break;
54598 }
54599
54600 /* Opcode: Clear P1 P2 P3
54601 **
54602 ** Delete all contents of the database table or index whose root page
54603 ** in the database file is given by P1.  But, unlike Destroy, do not
54604 ** remove the table or index from the database file.
54605 **
54606 ** The table being clear is in the main database file if P2==0.  If
54607 ** P2==1 then the table to be clear is in the auxiliary database file
54608 ** that is used to store tables create using CREATE TEMPORARY TABLE.
54609 **
54610 ** If the P3 value is non-zero, then the table refered to must be an
54611 ** intkey table (an SQL table, not an index). In this case the row change 
54612 ** count is incremented by the number of rows in the table being cleared. 
54613 ** If P3 is greater than zero, then the value stored in register P3 is
54614 ** also incremented by the number of rows in the table being cleared.
54615 **
54616 ** See also: Destroy
54617 */
54618 case OP_Clear: {
54619   int nChange = 0;
54620   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
54621   rc = sqlite3BtreeClearTable(
54622       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
54623   );
54624   if( pOp->p3 ){
54625     p->nChange += nChange;
54626     if( pOp->p3>0 ){
54627       p->aMem[pOp->p3].u.i += nChange;
54628     }
54629   }
54630   break;
54631 }
54632
54633 /* Opcode: CreateTable P1 P2 * * *
54634 **
54635 ** Allocate a new table in the main database file if P1==0 or in the
54636 ** auxiliary database file if P1==1 or in an attached database if
54637 ** P1>1.  Write the root page number of the new table into
54638 ** register P2
54639 **
54640 ** The difference between a table and an index is this:  A table must
54641 ** have a 4-byte integer key and can have arbitrary data.  An index
54642 ** has an arbitrary key but no data.
54643 **
54644 ** See also: CreateIndex
54645 */
54646 /* Opcode: CreateIndex P1 P2 * * *
54647 **
54648 ** Allocate a new index in the main database file if P1==0 or in the
54649 ** auxiliary database file if P1==1 or in an attached database if
54650 ** P1>1.  Write the root page number of the new table into
54651 ** register P2.
54652 **
54653 ** See documentation on OP_CreateTable for additional information.
54654 */
54655 case OP_CreateIndex:            /* out2-prerelease */
54656 case OP_CreateTable: {          /* out2-prerelease */
54657   int pgno = 0;
54658   int flags;
54659   Db *pDb;
54660   assert( pOp->p1>=0 && pOp->p1<db->nDb );
54661   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54662   pDb = &db->aDb[pOp->p1];
54663   assert( pDb->pBt!=0 );
54664   if( pOp->opcode==OP_CreateTable ){
54665     /* flags = BTREE_INTKEY; */
54666     flags = BTREE_LEAFDATA|BTREE_INTKEY;
54667   }else{
54668     flags = BTREE_ZERODATA;
54669   }
54670   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
54671   pOut->u.i = pgno;
54672   MemSetTypeFlag(pOut, MEM_Int);
54673   break;
54674 }
54675
54676 /* Opcode: ParseSchema P1 P2 * P4 *
54677 **
54678 ** Read and parse all entries from the SQLITE_MASTER table of database P1
54679 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
54680 ** the parsing if P2 is true.  If P2 is false, then this routine is a
54681 ** no-op if the schema is not currently loaded.  In other words, if P2
54682 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
54683 ** schema is already loaded into the symbol table.
54684 **
54685 ** This opcode invokes the parser to create a new virtual machine,
54686 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
54687 */
54688 case OP_ParseSchema: {
54689   char *zSql;
54690   int iDb = pOp->p1;
54691   const char *zMaster;
54692   InitData initData;
54693
54694   assert( iDb>=0 && iDb<db->nDb );
54695   if( !pOp->p2 && !DbHasProperty(db, iDb, DB_SchemaLoaded) ){
54696     break;
54697   }
54698   zMaster = SCHEMA_TABLE(iDb);
54699   initData.db = db;
54700   initData.iDb = pOp->p1;
54701   initData.pzErrMsg = &p->zErrMsg;
54702   zSql = sqlite3MPrintf(db,
54703      "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
54704      db->aDb[iDb].zName, zMaster, pOp->p4.z);
54705   if( zSql==0 ) goto no_mem;
54706   (void)sqlite3SafetyOff(db);
54707   assert( db->init.busy==0 );
54708   db->init.busy = 1;
54709   initData.rc = SQLITE_OK;
54710   assert( !db->mallocFailed );
54711   rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
54712   if( rc==SQLITE_OK ) rc = initData.rc;
54713   sqlite3DbFree(db, zSql);
54714   db->init.busy = 0;
54715   (void)sqlite3SafetyOn(db);
54716   if( rc==SQLITE_NOMEM ){
54717     goto no_mem;
54718   }
54719   break;  
54720 }
54721
54722 #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)
54723 /* Opcode: LoadAnalysis P1 * * * *
54724 **
54725 ** Read the sqlite_stat1 table for database P1 and load the content
54726 ** of that table into the internal index hash table.  This will cause
54727 ** the analysis to be used when preparing all subsequent queries.
54728 */
54729 case OP_LoadAnalysis: {
54730   int iDb = pOp->p1;
54731   assert( iDb>=0 && iDb<db->nDb );
54732   rc = sqlite3AnalysisLoad(db, iDb);
54733   break;  
54734 }
54735 #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER)  */
54736
54737 /* Opcode: DropTable P1 * * P4 *
54738 **
54739 ** Remove the internal (in-memory) data structures that describe
54740 ** the table named P4 in database P1.  This is called after a table
54741 ** is dropped in order to keep the internal representation of the
54742 ** schema consistent with what is on disk.
54743 */
54744 case OP_DropTable: {
54745   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
54746   break;
54747 }
54748
54749 /* Opcode: DropIndex P1 * * P4 *
54750 **
54751 ** Remove the internal (in-memory) data structures that describe
54752 ** the index named P4 in database P1.  This is called after an index
54753 ** is dropped in order to keep the internal representation of the
54754 ** schema consistent with what is on disk.
54755 */
54756 case OP_DropIndex: {
54757   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
54758   break;
54759 }
54760
54761 /* Opcode: DropTrigger P1 * * P4 *
54762 **
54763 ** Remove the internal (in-memory) data structures that describe
54764 ** the trigger named P4 in database P1.  This is called after a trigger
54765 ** is dropped in order to keep the internal representation of the
54766 ** schema consistent with what is on disk.
54767 */
54768 case OP_DropTrigger: {
54769   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
54770   break;
54771 }
54772
54773
54774 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54775 /* Opcode: IntegrityCk P1 P2 P3 * P5
54776 **
54777 ** Do an analysis of the currently open database.  Store in
54778 ** register P1 the text of an error message describing any problems.
54779 ** If no problems are found, store a NULL in register P1.
54780 **
54781 ** The register P3 contains the maximum number of allowed errors.
54782 ** At most reg(P3) errors will be reported.
54783 ** In other words, the analysis stops as soon as reg(P1) errors are 
54784 ** seen.  Reg(P1) is updated with the number of errors remaining.
54785 **
54786 ** The root page numbers of all tables in the database are integer
54787 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
54788 ** total.
54789 **
54790 ** If P5 is not zero, the check is done on the auxiliary database
54791 ** file, not the main database file.
54792 **
54793 ** This opcode is used to implement the integrity_check pragma.
54794 */
54795 case OP_IntegrityCk: {
54796   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
54797   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
54798   int j;          /* Loop counter */
54799   int nErr;       /* Number of errors reported */
54800   char *z;        /* Text of the error report */
54801   Mem *pnErr;     /* Register keeping track of errors remaining */
54802   
54803   nRoot = pOp->p2;
54804   assert( nRoot>0 );
54805   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
54806   if( aRoot==0 ) goto no_mem;
54807   assert( pOp->p3>0 && pOp->p3<=p->nMem );
54808   pnErr = &p->aMem[pOp->p3];
54809   assert( (pnErr->flags & MEM_Int)!=0 );
54810   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
54811   pIn1 = &p->aMem[pOp->p1];
54812   for(j=0; j<nRoot; j++){
54813     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
54814   }
54815   aRoot[j] = 0;
54816   assert( pOp->p5<db->nDb );
54817   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
54818   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
54819                                  (int)pnErr->u.i, &nErr);
54820   sqlite3DbFree(db, aRoot);
54821   pnErr->u.i -= nErr;
54822   sqlite3VdbeMemSetNull(pIn1);
54823   if( nErr==0 ){
54824     assert( z==0 );
54825   }else if( z==0 ){
54826     goto no_mem;
54827   }else{
54828     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
54829   }
54830   UPDATE_MAX_BLOBSIZE(pIn1);
54831   sqlite3VdbeChangeEncoding(pIn1, encoding);
54832   break;
54833 }
54834 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54835
54836 /* Opcode: RowSetAdd P1 P2 * * *
54837 **
54838 ** Insert the integer value held by register P2 into a boolean index
54839 ** held in register P1.
54840 **
54841 ** An assertion fails if P2 is not an integer.
54842 */
54843 case OP_RowSetAdd: {       /* in2 */
54844   Mem *pIdx;
54845   Mem *pVal;
54846   assert( pOp->p1>0 && pOp->p1<=p->nMem );
54847   pIdx = &p->aMem[pOp->p1];
54848   assert( pOp->p2>0 && pOp->p2<=p->nMem );
54849   pVal = &p->aMem[pOp->p2];
54850   assert( (pVal->flags & MEM_Int)!=0 );
54851   if( (pIdx->flags & MEM_RowSet)==0 ){
54852     sqlite3VdbeMemSetRowSet(pIdx);
54853     if( (pIdx->flags & MEM_RowSet)==0 ) goto no_mem;
54854   }
54855   sqlite3RowSetInsert(pIdx->u.pRowSet, pVal->u.i);
54856   break;
54857 }
54858
54859 /* Opcode: RowSetRead P1 P2 P3 * *
54860 **
54861 ** Extract the smallest value from boolean index P1 and put that value into
54862 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
54863 ** unchanged and jump to instruction P2.
54864 */
54865 case OP_RowSetRead: {       /* jump, out3 */
54866   Mem *pIdx;
54867   i64 val;
54868   assert( pOp->p1>0 && pOp->p1<=p->nMem );
54869   CHECK_FOR_INTERRUPT;
54870   pIdx = &p->aMem[pOp->p1];
54871   pOut = &p->aMem[pOp->p3];
54872   if( (pIdx->flags & MEM_RowSet)==0 
54873    || sqlite3RowSetNext(pIdx->u.pRowSet, &val)==0
54874   ){
54875     /* The boolean index is empty */
54876     sqlite3VdbeMemSetNull(pIdx);
54877     pc = pOp->p2 - 1;
54878   }else{
54879     /* A value was pulled from the index */
54880     assert( pOp->p3>0 && pOp->p3<=p->nMem );
54881     sqlite3VdbeMemSetInt64(pOut, val);
54882   }
54883   break;
54884 }
54885
54886
54887 #ifndef SQLITE_OMIT_TRIGGER
54888 /* Opcode: ContextPush * * * 
54889 **
54890 ** Save the current Vdbe context such that it can be restored by a ContextPop
54891 ** opcode. The context stores the last insert row id, the last statement change
54892 ** count, and the current statement change count.
54893 */
54894 case OP_ContextPush: {
54895   int i = p->contextStackTop++;
54896   Context *pContext;
54897
54898   assert( i>=0 );
54899   /* FIX ME: This should be allocated as part of the vdbe at compile-time */
54900   if( i>=p->contextStackDepth ){
54901     p->contextStackDepth = i+1;
54902     p->contextStack = sqlite3DbReallocOrFree(db, p->contextStack,
54903                                           sizeof(Context)*(i+1));
54904     if( p->contextStack==0 ) goto no_mem;
54905   }
54906   pContext = &p->contextStack[i];
54907   pContext->lastRowid = db->lastRowid;
54908   pContext->nChange = p->nChange;
54909   break;
54910 }
54911
54912 /* Opcode: ContextPop * * * 
54913 **
54914 ** Restore the Vdbe context to the state it was in when contextPush was last
54915 ** executed. The context stores the last insert row id, the last statement
54916 ** change count, and the current statement change count.
54917 */
54918 case OP_ContextPop: {
54919   Context *pContext = &p->contextStack[--p->contextStackTop];
54920   assert( p->contextStackTop>=0 );
54921   db->lastRowid = pContext->lastRowid;
54922   p->nChange = pContext->nChange;
54923   break;
54924 }
54925 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
54926
54927 #ifndef SQLITE_OMIT_AUTOINCREMENT
54928 /* Opcode: MemMax P1 P2 * * *
54929 **
54930 ** Set the value of register P1 to the maximum of its current value
54931 ** and the value in register P2.
54932 **
54933 ** This instruction throws an error if the memory cell is not initially
54934 ** an integer.
54935 */
54936 case OP_MemMax: {        /* in1, in2 */
54937   sqlite3VdbeMemIntegerify(pIn1);
54938   sqlite3VdbeMemIntegerify(pIn2);
54939   if( pIn1->u.i<pIn2->u.i){
54940     pIn1->u.i = pIn2->u.i;
54941   }
54942   break;
54943 }
54944 #endif /* SQLITE_OMIT_AUTOINCREMENT */
54945
54946 /* Opcode: IfPos P1 P2 * * *
54947 **
54948 ** If the value of register P1 is 1 or greater, jump to P2.
54949 **
54950 ** It is illegal to use this instruction on a register that does
54951 ** not contain an integer.  An assertion fault will result if you try.
54952 */
54953 case OP_IfPos: {        /* jump, in1 */
54954   assert( pIn1->flags&MEM_Int );
54955   if( pIn1->u.i>0 ){
54956      pc = pOp->p2 - 1;
54957   }
54958   break;
54959 }
54960
54961 /* Opcode: IfNeg P1 P2 * * *
54962 **
54963 ** If the value of register P1 is less than zero, jump to P2. 
54964 **
54965 ** It is illegal to use this instruction on a register that does
54966 ** not contain an integer.  An assertion fault will result if you try.
54967 */
54968 case OP_IfNeg: {        /* jump, in1 */
54969   assert( pIn1->flags&MEM_Int );
54970   if( pIn1->u.i<0 ){
54971      pc = pOp->p2 - 1;
54972   }
54973   break;
54974 }
54975
54976 /* Opcode: IfZero P1 P2 * * *
54977 **
54978 ** If the value of register P1 is exactly 0, jump to P2. 
54979 **
54980 ** It is illegal to use this instruction on a register that does
54981 ** not contain an integer.  An assertion fault will result if you try.
54982 */
54983 case OP_IfZero: {        /* jump, in1 */
54984   assert( pIn1->flags&MEM_Int );
54985   if( pIn1->u.i==0 ){
54986      pc = pOp->p2 - 1;
54987   }
54988   break;
54989 }
54990
54991 /* Opcode: AggStep * P2 P3 P4 P5
54992 **
54993 ** Execute the step function for an aggregate.  The
54994 ** function has P5 arguments.   P4 is a pointer to the FuncDef
54995 ** structure that specifies the function.  Use register
54996 ** P3 as the accumulator.
54997 **
54998 ** The P5 arguments are taken from register P2 and its
54999 ** successors.
55000 */
55001 case OP_AggStep: {
55002   int n = pOp->p5;
55003   int i;
55004   Mem *pMem, *pRec;
55005   sqlite3_context ctx;
55006   sqlite3_value **apVal;
55007
55008   assert( n>=0 );
55009   pRec = &p->aMem[pOp->p2];
55010   apVal = p->apArg;
55011   assert( apVal || n==0 );
55012   for(i=0; i<n; i++, pRec++){
55013     apVal[i] = pRec;
55014     storeTypeInfo(pRec, encoding);
55015   }
55016   ctx.pFunc = pOp->p4.pFunc;
55017   assert( pOp->p3>0 && pOp->p3<=p->nMem );
55018   ctx.pMem = pMem = &p->aMem[pOp->p3];
55019   pMem->n++;
55020   ctx.s.flags = MEM_Null;
55021   ctx.s.z = 0;
55022   ctx.s.zMalloc = 0;
55023   ctx.s.xDel = 0;
55024   ctx.s.db = db;
55025   ctx.isError = 0;
55026   ctx.pColl = 0;
55027   if( ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
55028     assert( pOp>p->aOp );
55029     assert( pOp[-1].p4type==P4_COLLSEQ );
55030     assert( pOp[-1].opcode==OP_CollSeq );
55031     ctx.pColl = pOp[-1].p4.pColl;
55032   }
55033   (ctx.pFunc->xStep)(&ctx, n, apVal);
55034   if( ctx.isError ){
55035     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
55036     rc = ctx.isError;
55037   }
55038   sqlite3VdbeMemRelease(&ctx.s);
55039   break;
55040 }
55041
55042 /* Opcode: AggFinal P1 P2 * P4 *
55043 **
55044 ** Execute the finalizer function for an aggregate.  P1 is
55045 ** the memory location that is the accumulator for the aggregate.
55046 **
55047 ** P2 is the number of arguments that the step function takes and
55048 ** P4 is a pointer to the FuncDef for this function.  The P2
55049 ** argument is not used by this opcode.  It is only there to disambiguate
55050 ** functions that can take varying numbers of arguments.  The
55051 ** P4 argument is only needed for the degenerate case where
55052 ** the step function was not previously called.
55053 */
55054 case OP_AggFinal: {
55055   Mem *pMem;
55056   assert( pOp->p1>0 && pOp->p1<=p->nMem );
55057   pMem = &p->aMem[pOp->p1];
55058   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
55059   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
55060   if( rc==SQLITE_ERROR ){
55061     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
55062   }
55063   sqlite3VdbeChangeEncoding(pMem, encoding);
55064   UPDATE_MAX_BLOBSIZE(pMem);
55065   if( sqlite3VdbeMemTooBig(pMem) ){
55066     goto too_big;
55067   }
55068   break;
55069 }
55070
55071
55072 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
55073 /* Opcode: Vacuum * * * * *
55074 **
55075 ** Vacuum the entire database.  This opcode will cause other virtual
55076 ** machines to be created and run.  It may not be called from within
55077 ** a transaction.
55078 */
55079 case OP_Vacuum: {
55080   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
55081   rc = sqlite3RunVacuum(&p->zErrMsg, db);
55082   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55083   break;
55084 }
55085 #endif
55086
55087 #if !defined(SQLITE_OMIT_AUTOVACUUM)
55088 /* Opcode: IncrVacuum P1 P2 * * *
55089 **
55090 ** Perform a single step of the incremental vacuum procedure on
55091 ** the P1 database. If the vacuum has finished, jump to instruction
55092 ** P2. Otherwise, fall through to the next instruction.
55093 */
55094 case OP_IncrVacuum: {        /* jump */
55095   Btree *pBt;
55096
55097   assert( pOp->p1>=0 && pOp->p1<db->nDb );
55098   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55099   pBt = db->aDb[pOp->p1].pBt;
55100   rc = sqlite3BtreeIncrVacuum(pBt);
55101   if( rc==SQLITE_DONE ){
55102     pc = pOp->p2 - 1;
55103     rc = SQLITE_OK;
55104   }
55105   break;
55106 }
55107 #endif
55108
55109 /* Opcode: Expire P1 * * * *
55110 **
55111 ** Cause precompiled statements to become expired. An expired statement
55112 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
55113 ** (via sqlite3_step()).
55114 ** 
55115 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
55116 ** then only the currently executing statement is affected. 
55117 */
55118 case OP_Expire: {
55119   if( !pOp->p1 ){
55120     sqlite3ExpirePreparedStatements(db);
55121   }else{
55122     p->expired = 1;
55123   }
55124   break;
55125 }
55126
55127 #ifndef SQLITE_OMIT_SHARED_CACHE
55128 /* Opcode: TableLock P1 P2 P3 P4 *
55129 **
55130 ** Obtain a lock on a particular table. This instruction is only used when
55131 ** the shared-cache feature is enabled. 
55132 **
55133 ** If P1 is  the index of the database in sqlite3.aDb[] of the database
55134 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
55135 ** a write lock if P3==1.
55136 **
55137 ** P2 contains the root-page of the table to lock.
55138 **
55139 ** P4 contains a pointer to the name of the table being locked. This is only
55140 ** used to generate an error message if the lock cannot be obtained.
55141 */
55142 case OP_TableLock: {
55143   int p1 = pOp->p1; 
55144   u8 isWriteLock = (u8)pOp->p3;
55145   assert( p1>=0 && p1<db->nDb );
55146   assert( (p->btreeMask & (1<<p1))!=0 );
55147   assert( isWriteLock==0 || isWriteLock==1 );
55148   rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
55149   if( rc==SQLITE_LOCKED ){
55150     const char *z = pOp->p4.z;
55151     sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
55152   }
55153   break;
55154 }
55155 #endif /* SQLITE_OMIT_SHARED_CACHE */
55156
55157 #ifndef SQLITE_OMIT_VIRTUALTABLE
55158 /* Opcode: VBegin * * * P4 *
55159 **
55160 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
55161 ** xBegin method for that table.
55162 **
55163 ** Also, whether or not P4 is set, check that this is not being called from
55164 ** within a callback to a virtual table xSync() method. If it is, set the
55165 ** error code to SQLITE_LOCKED.
55166 */
55167 case OP_VBegin: {
55168   sqlite3_vtab *pVtab = pOp->p4.pVtab;
55169   rc = sqlite3VtabBegin(db, pVtab);
55170   if( pVtab ){
55171     sqlite3DbFree(db, p->zErrMsg);
55172     p->zErrMsg = pVtab->zErrMsg;
55173     pVtab->zErrMsg = 0;
55174   }
55175   break;
55176 }
55177 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55178
55179 #ifndef SQLITE_OMIT_VIRTUALTABLE
55180 /* Opcode: VCreate P1 * * P4 *
55181 **
55182 ** P4 is the name of a virtual table in database P1. Call the xCreate method
55183 ** for that table.
55184 */
55185 case OP_VCreate: {
55186   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
55187   break;
55188 }
55189 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55190
55191 #ifndef SQLITE_OMIT_VIRTUALTABLE
55192 /* Opcode: VDestroy P1 * * P4 *
55193 **
55194 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
55195 ** of that table.
55196 */
55197 case OP_VDestroy: {
55198   p->inVtabMethod = 2;
55199   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
55200   p->inVtabMethod = 0;
55201   break;
55202 }
55203 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55204
55205 #ifndef SQLITE_OMIT_VIRTUALTABLE
55206 /* Opcode: VOpen P1 * * P4 *
55207 **
55208 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
55209 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
55210 ** table and stores that cursor in P1.
55211 */
55212 case OP_VOpen: {
55213   VdbeCursor *pCur = 0;
55214   sqlite3_vtab_cursor *pVtabCursor = 0;
55215
55216   sqlite3_vtab *pVtab = pOp->p4.pVtab;
55217   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
55218
55219   assert(pVtab && pModule);
55220   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55221   rc = pModule->xOpen(pVtab, &pVtabCursor);
55222   sqlite3DbFree(db, p->zErrMsg);
55223   p->zErrMsg = pVtab->zErrMsg;
55224   pVtab->zErrMsg = 0;
55225   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55226   if( SQLITE_OK==rc ){
55227     /* Initialize sqlite3_vtab_cursor base class */
55228     pVtabCursor->pVtab = pVtab;
55229
55230     /* Initialise vdbe cursor object */
55231     pCur = allocateCursor(p, pOp->p1, &pOp[-1], -1, 0);
55232     if( pCur ){
55233       pCur->pVtabCursor = pVtabCursor;
55234       pCur->pModule = pVtabCursor->pVtab->pModule;
55235     }else{
55236       db->mallocFailed = 1;
55237       pModule->xClose(pVtabCursor);
55238     }
55239   }
55240   break;
55241 }
55242 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55243
55244 #ifndef SQLITE_OMIT_VIRTUALTABLE
55245 /* Opcode: VFilter P1 P2 P3 P4 *
55246 **
55247 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
55248 ** the filtered result set is empty.
55249 **
55250 ** P4 is either NULL or a string that was generated by the xBestIndex
55251 ** method of the module.  The interpretation of the P4 string is left
55252 ** to the module implementation.
55253 **
55254 ** This opcode invokes the xFilter method on the virtual table specified
55255 ** by P1.  The integer query plan parameter to xFilter is stored in register
55256 ** P3. Register P3+1 stores the argc parameter to be passed to the
55257 ** xFilter method. Registers P3+2..P3+1+argc are the argc
55258 ** additional parameters which are passed to
55259 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
55260 **
55261 ** A jump is made to P2 if the result set after filtering would be empty.
55262 */
55263 case OP_VFilter: {   /* jump */
55264   int nArg;
55265   int iQuery;
55266   const sqlite3_module *pModule;
55267   Mem *pQuery = &p->aMem[pOp->p3];
55268   Mem *pArgc = &pQuery[1];
55269   sqlite3_vtab_cursor *pVtabCursor;
55270   sqlite3_vtab *pVtab;
55271
55272   VdbeCursor *pCur = p->apCsr[pOp->p1];
55273
55274   REGISTER_TRACE(pOp->p3, pQuery);
55275   assert( pCur->pVtabCursor );
55276   pVtabCursor = pCur->pVtabCursor;
55277   pVtab = pVtabCursor->pVtab;
55278   pModule = pVtab->pModule;
55279
55280   /* Grab the index number and argc parameters */
55281   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
55282   nArg = (int)pArgc->u.i;
55283   iQuery = (int)pQuery->u.i;
55284
55285   /* Invoke the xFilter method */
55286   {
55287     int res = 0;
55288     int i;
55289     Mem **apArg = p->apArg;
55290     for(i = 0; i<nArg; i++){
55291       apArg[i] = &pArgc[i+1];
55292       storeTypeInfo(apArg[i], 0);
55293     }
55294
55295     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55296     sqlite3VtabLock(pVtab);
55297     p->inVtabMethod = 1;
55298     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
55299     p->inVtabMethod = 0;
55300     sqlite3DbFree(db, p->zErrMsg);
55301     p->zErrMsg = pVtab->zErrMsg;
55302     pVtab->zErrMsg = 0;
55303     sqlite3VtabUnlock(db, pVtab);
55304     if( rc==SQLITE_OK ){
55305       res = pModule->xEof(pVtabCursor);
55306     }
55307     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55308
55309     if( res ){
55310       pc = pOp->p2 - 1;
55311     }
55312   }
55313   pCur->nullRow = 0;
55314
55315   break;
55316 }
55317 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55318
55319 #ifndef SQLITE_OMIT_VIRTUALTABLE
55320 /* Opcode: VRowid P1 P2 * * *
55321 **
55322 ** Store into register P2  the rowid of
55323 ** the virtual-table that the P1 cursor is pointing to.
55324 */
55325 case OP_VRowid: {             /* out2-prerelease */
55326   sqlite3_vtab *pVtab;
55327   const sqlite3_module *pModule;
55328   sqlite_int64 iRow;
55329   VdbeCursor *pCur = p->apCsr[pOp->p1];
55330
55331   assert( pCur->pVtabCursor );
55332   if( pCur->nullRow ){
55333     break;
55334   }
55335   pVtab = pCur->pVtabCursor->pVtab;
55336   pModule = pVtab->pModule;
55337   assert( pModule->xRowid );
55338   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55339   rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
55340   sqlite3DbFree(db, p->zErrMsg);
55341   p->zErrMsg = pVtab->zErrMsg;
55342   pVtab->zErrMsg = 0;
55343   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55344   MemSetTypeFlag(pOut, MEM_Int);
55345   pOut->u.i = iRow;
55346   break;
55347 }
55348 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55349
55350 #ifndef SQLITE_OMIT_VIRTUALTABLE
55351 /* Opcode: VColumn P1 P2 P3 * *
55352 **
55353 ** Store the value of the P2-th column of
55354 ** the row of the virtual-table that the 
55355 ** P1 cursor is pointing to into register P3.
55356 */
55357 case OP_VColumn: {
55358   sqlite3_vtab *pVtab;
55359   const sqlite3_module *pModule;
55360   Mem *pDest;
55361   sqlite3_context sContext;
55362
55363   VdbeCursor *pCur = p->apCsr[pOp->p1];
55364   assert( pCur->pVtabCursor );
55365   assert( pOp->p3>0 && pOp->p3<=p->nMem );
55366   pDest = &p->aMem[pOp->p3];
55367   if( pCur->nullRow ){
55368     sqlite3VdbeMemSetNull(pDest);
55369     break;
55370   }
55371   pVtab = pCur->pVtabCursor->pVtab;
55372   pModule = pVtab->pModule;
55373   assert( pModule->xColumn );
55374   memset(&sContext, 0, sizeof(sContext));
55375
55376   /* The output cell may already have a buffer allocated. Move
55377   ** the current contents to sContext.s so in case the user-function 
55378   ** can use the already allocated buffer instead of allocating a 
55379   ** new one.
55380   */
55381   sqlite3VdbeMemMove(&sContext.s, pDest);
55382   MemSetTypeFlag(&sContext.s, MEM_Null);
55383
55384   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55385   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
55386   sqlite3DbFree(db, p->zErrMsg);
55387   p->zErrMsg = pVtab->zErrMsg;
55388   pVtab->zErrMsg = 0;
55389
55390   /* Copy the result of the function to the P3 register. We
55391   ** do this regardless of whether or not an error occured to ensure any
55392   ** dynamic allocation in sContext.s (a Mem struct) is  released.
55393   */
55394   sqlite3VdbeChangeEncoding(&sContext.s, encoding);
55395   REGISTER_TRACE(pOp->p3, pDest);
55396   sqlite3VdbeMemMove(pDest, &sContext.s);
55397   UPDATE_MAX_BLOBSIZE(pDest);
55398
55399   if( sqlite3SafetyOn(db) ){
55400     goto abort_due_to_misuse;
55401   }
55402   if( sqlite3VdbeMemTooBig(pDest) ){
55403     goto too_big;
55404   }
55405   break;
55406 }
55407 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55408
55409 #ifndef SQLITE_OMIT_VIRTUALTABLE
55410 /* Opcode: VNext P1 P2 * * *
55411 **
55412 ** Advance virtual table P1 to the next row in its result set and
55413 ** jump to instruction P2.  Or, if the virtual table has reached
55414 ** the end of its result set, then fall through to the next instruction.
55415 */
55416 case OP_VNext: {   /* jump */
55417   sqlite3_vtab *pVtab;
55418   const sqlite3_module *pModule;
55419   int res = 0;
55420
55421   VdbeCursor *pCur = p->apCsr[pOp->p1];
55422   assert( pCur->pVtabCursor );
55423   if( pCur->nullRow ){
55424     break;
55425   }
55426   pVtab = pCur->pVtabCursor->pVtab;
55427   pModule = pVtab->pModule;
55428   assert( pModule->xNext );
55429
55430   /* Invoke the xNext() method of the module. There is no way for the
55431   ** underlying implementation to return an error if one occurs during
55432   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
55433   ** data is available) and the error code returned when xColumn or
55434   ** some other method is next invoked on the save virtual table cursor.
55435   */
55436   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55437   sqlite3VtabLock(pVtab);
55438   p->inVtabMethod = 1;
55439   rc = pModule->xNext(pCur->pVtabCursor);
55440   p->inVtabMethod = 0;
55441   sqlite3DbFree(db, p->zErrMsg);
55442   p->zErrMsg = pVtab->zErrMsg;
55443   pVtab->zErrMsg = 0;
55444   sqlite3VtabUnlock(db, pVtab);
55445   if( rc==SQLITE_OK ){
55446     res = pModule->xEof(pCur->pVtabCursor);
55447   }
55448   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55449
55450   if( !res ){
55451     /* If there is data, jump to P2 */
55452     pc = pOp->p2 - 1;
55453   }
55454   break;
55455 }
55456 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55457
55458 #ifndef SQLITE_OMIT_VIRTUALTABLE
55459 /* Opcode: VRename P1 * * P4 *
55460 **
55461 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
55462 ** This opcode invokes the corresponding xRename method. The value
55463 ** in register P1 is passed as the zName argument to the xRename method.
55464 */
55465 case OP_VRename: {
55466   sqlite3_vtab *pVtab = pOp->p4.pVtab;
55467   Mem *pName = &p->aMem[pOp->p1];
55468   assert( pVtab->pModule->xRename );
55469   REGISTER_TRACE(pOp->p1, pName);
55470
55471   Stringify(pName, encoding);
55472
55473   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55474   sqlite3VtabLock(pVtab);
55475   rc = pVtab->pModule->xRename(pVtab, pName->z);
55476   sqlite3DbFree(db, p->zErrMsg);
55477   p->zErrMsg = pVtab->zErrMsg;
55478   pVtab->zErrMsg = 0;
55479   sqlite3VtabUnlock(db, pVtab);
55480   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55481
55482   break;
55483 }
55484 #endif
55485
55486 #ifndef SQLITE_OMIT_VIRTUALTABLE
55487 /* Opcode: VUpdate P1 P2 P3 P4 *
55488 **
55489 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
55490 ** This opcode invokes the corresponding xUpdate method. P2 values
55491 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
55492 ** invocation. The value in register (P3+P2-1) corresponds to the 
55493 ** p2th element of the argv array passed to xUpdate.
55494 **
55495 ** The xUpdate method will do a DELETE or an INSERT or both.
55496 ** The argv[0] element (which corresponds to memory cell P3)
55497 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
55498 ** deletion occurs.  The argv[1] element is the rowid of the new 
55499 ** row.  This can be NULL to have the virtual table select the new 
55500 ** rowid for itself.  The subsequent elements in the array are 
55501 ** the values of columns in the new row.
55502 **
55503 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
55504 ** a row to delete.
55505 **
55506 ** P1 is a boolean flag. If it is set to true and the xUpdate call
55507 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
55508 ** is set to the value of the rowid for the row just inserted.
55509 */
55510 case OP_VUpdate: {
55511   sqlite3_vtab *pVtab = pOp->p4.pVtab;
55512   sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule;
55513   int nArg = pOp->p2;
55514   assert( pOp->p4type==P4_VTAB );
55515   if( pModule->xUpdate==0 ){
55516     sqlite3SetString(&p->zErrMsg, db, "read-only table");
55517     rc = SQLITE_ERROR;
55518   }else{
55519     int i;
55520     sqlite_int64 rowid;
55521     Mem **apArg = p->apArg;
55522     Mem *pX = &p->aMem[pOp->p3];
55523     for(i=0; i<nArg; i++){
55524       storeTypeInfo(pX, 0);
55525       apArg[i] = pX;
55526       pX++;
55527     }
55528     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
55529     sqlite3VtabLock(pVtab);
55530     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
55531     sqlite3DbFree(db, p->zErrMsg);
55532     p->zErrMsg = pVtab->zErrMsg;
55533     pVtab->zErrMsg = 0;
55534     sqlite3VtabUnlock(db, pVtab);
55535     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
55536     if( pOp->p1 && rc==SQLITE_OK ){
55537       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
55538       db->lastRowid = rowid;
55539     }
55540     p->nChange++;
55541   }
55542   break;
55543 }
55544 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55545
55546 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
55547 /* Opcode: Pagecount P1 P2 * * *
55548 **
55549 ** Write the current number of pages in database P1 to memory cell P2.
55550 */
55551 case OP_Pagecount: {            /* out2-prerelease */
55552   int p1 = pOp->p1; 
55553   int nPage;
55554   Pager *pPager = sqlite3BtreePager(db->aDb[p1].pBt);
55555
55556   rc = sqlite3PagerPagecount(pPager, &nPage);
55557   if( rc==SQLITE_OK ){
55558     pOut->flags = MEM_Int;
55559     pOut->u.i = nPage;
55560   }
55561   break;
55562 }
55563 #endif
55564
55565 #ifndef SQLITE_OMIT_TRACE
55566 /* Opcode: Trace * * * P4 *
55567 **
55568 ** If tracing is enabled (by the sqlite3_trace()) interface, then
55569 ** the UTF-8 string contained in P4 is emitted on the trace callback.
55570 */
55571 case OP_Trace: {
55572   if( pOp->p4.z ){
55573     if( db->xTrace ){
55574       db->xTrace(db->pTraceArg, pOp->p4.z);
55575     }
55576 #ifdef SQLITE_DEBUG
55577     if( (db->flags & SQLITE_SqlTrace)!=0 ){
55578       sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z);
55579     }
55580 #endif /* SQLITE_DEBUG */
55581   }
55582   break;
55583 }
55584 #endif
55585
55586
55587 /* Opcode: Noop * * * * *
55588 **
55589 ** Do nothing.  This instruction is often useful as a jump
55590 ** destination.
55591 */
55592 /*
55593 ** The magic Explain opcode are only inserted when explain==2 (which
55594 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
55595 ** This opcode records information from the optimizer.  It is the
55596 ** the same as a no-op.  This opcodesnever appears in a real VM program.
55597 */
55598 default: {          /* This is really OP_Noop and OP_Explain */
55599   break;
55600 }
55601
55602 /*****************************************************************************
55603 ** The cases of the switch statement above this line should all be indented
55604 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
55605 ** readability.  From this point on down, the normal indentation rules are
55606 ** restored.
55607 *****************************************************************************/
55608     }
55609
55610 #ifdef VDBE_PROFILE
55611     {
55612       u64 elapsed = sqlite3Hwtime() - start;
55613       pOp->cycles += elapsed;
55614       pOp->cnt++;
55615 #if 0
55616         fprintf(stdout, "%10llu ", elapsed);
55617         sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]);
55618 #endif
55619     }
55620 #endif
55621
55622     /* The following code adds nothing to the actual functionality
55623     ** of the program.  It is only here for testing and debugging.
55624     ** On the other hand, it does burn CPU cycles every time through
55625     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
55626     */
55627 #ifndef NDEBUG
55628     assert( pc>=-1 && pc<p->nOp );
55629
55630 #ifdef SQLITE_DEBUG
55631     if( p->trace ){
55632       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
55633       if( opProperty & OPFLG_OUT2_PRERELEASE ){
55634         registerTrace(p->trace, pOp->p2, pOut);
55635       }
55636       if( opProperty & OPFLG_OUT3 ){
55637         registerTrace(p->trace, pOp->p3, pOut);
55638       }
55639     }
55640 #endif  /* SQLITE_DEBUG */
55641 #endif  /* NDEBUG */
55642   }  /* The end of the for(;;) loop the loops through opcodes */
55643
55644   /* If we reach this point, it means that execution is finished with
55645   ** an error of some kind.
55646   */
55647 vdbe_error_halt:
55648   assert( rc );
55649   p->rc = rc;
55650   sqlite3VdbeHalt(p);
55651   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
55652   rc = SQLITE_ERROR;
55653
55654   /* This is the only way out of this procedure.  We have to
55655   ** release the mutexes on btrees that were acquired at the
55656   ** top. */
55657 vdbe_return:
55658   sqlite3BtreeMutexArrayLeave(&p->aMutex);
55659   return rc;
55660
55661   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
55662   ** is encountered.
55663   */
55664 too_big:
55665   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
55666   rc = SQLITE_TOOBIG;
55667   goto vdbe_error_halt;
55668
55669   /* Jump to here if a malloc() fails.
55670   */
55671 no_mem:
55672   db->mallocFailed = 1;
55673   sqlite3SetString(&p->zErrMsg, db, "out of memory");
55674   rc = SQLITE_NOMEM;
55675   goto vdbe_error_halt;
55676
55677   /* Jump to here for an SQLITE_MISUSE error.
55678   */
55679 abort_due_to_misuse:
55680   rc = SQLITE_MISUSE;
55681   /* Fall thru into abort_due_to_error */
55682
55683   /* Jump to here for any other kind of fatal error.  The "rc" variable
55684   ** should hold the error number.
55685   */
55686 abort_due_to_error:
55687   assert( p->zErrMsg==0 );
55688   if( db->mallocFailed ) rc = SQLITE_NOMEM;
55689   if( rc!=SQLITE_IOERR_NOMEM ){
55690     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
55691   }
55692   goto vdbe_error_halt;
55693
55694   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
55695   ** flag.
55696   */
55697 abort_due_to_interrupt:
55698   assert( db->u1.isInterrupted );
55699   rc = SQLITE_INTERRUPT;
55700   p->rc = rc;
55701   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
55702   goto vdbe_error_halt;
55703 }
55704
55705 /************** End of vdbe.c ************************************************/
55706 /************** Begin file vdbeblob.c ****************************************/
55707 /*
55708 ** 2007 May 1
55709 **
55710 ** The author disclaims copyright to this source code.  In place of
55711 ** a legal notice, here is a blessing:
55712 **
55713 **    May you do good and not evil.
55714 **    May you find forgiveness for yourself and forgive others.
55715 **    May you share freely, never taking more than you give.
55716 **
55717 *************************************************************************
55718 **
55719 ** This file contains code used to implement incremental BLOB I/O.
55720 **
55721 ** $Id: vdbeblob.c,v 1.26 2008/10/02 14:49:02 danielk1977 Exp $
55722 */
55723
55724
55725 #ifndef SQLITE_OMIT_INCRBLOB
55726
55727 /*
55728 ** Valid sqlite3_blob* handles point to Incrblob structures.
55729 */
55730 typedef struct Incrblob Incrblob;
55731 struct Incrblob {
55732   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
55733   int nByte;              /* Size of open blob, in bytes */
55734   int iOffset;            /* Byte offset of blob in cursor data */
55735   BtCursor *pCsr;         /* Cursor pointing at blob row */
55736   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
55737   sqlite3 *db;            /* The associated database */
55738 };
55739
55740 /*
55741 ** Open a blob handle.
55742 */
55743 SQLITE_API int sqlite3_blob_open(
55744   sqlite3* db,            /* The database connection */
55745   const char *zDb,        /* The attached database containing the blob */
55746   const char *zTable,     /* The table containing the blob */
55747   const char *zColumn,    /* The column containing the blob */
55748   sqlite_int64 iRow,      /* The row containing the glob */
55749   int flags,              /* True -> read/write access, false -> read-only */
55750   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
55751 ){
55752   int nAttempt = 0;
55753   int iCol;               /* Index of zColumn in row-record */
55754
55755   /* This VDBE program seeks a btree cursor to the identified 
55756   ** db/table/row entry. The reason for using a vdbe program instead
55757   ** of writing code to use the b-tree layer directly is that the
55758   ** vdbe program will take advantage of the various transaction,
55759   ** locking and error handling infrastructure built into the vdbe.
55760   **
55761   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
55762   ** Code external to the Vdbe then "borrows" the b-tree cursor and
55763   ** uses it to implement the blob_read(), blob_write() and 
55764   ** blob_bytes() functions.
55765   **
55766   ** The sqlite3_blob_close() function finalizes the vdbe program,
55767   ** which closes the b-tree cursor and (possibly) commits the 
55768   ** transaction.
55769   */
55770   static const VdbeOpList openBlob[] = {
55771     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
55772     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
55773
55774     /* One of the following two instructions is replaced by an
55775     ** OP_Noop before exection.
55776     */
55777     {OP_SetNumColumns, 0, 0, 0},   /* 2: Num cols for cursor */
55778     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
55779     {OP_SetNumColumns, 0, 0, 0},   /* 4: Num cols for cursor */
55780     {OP_OpenWrite, 0, 0, 0},       /* 5: Open cursor 0 for read/write */
55781
55782     {OP_Variable, 1, 1, 0},        /* 6: Push the rowid to the stack */
55783     {OP_NotExists, 0, 10, 1},      /* 7: Seek the cursor */
55784     {OP_Column, 0, 0, 1},          /* 8  */
55785     {OP_ResultRow, 1, 0, 0},       /* 9  */
55786     {OP_Close, 0, 0, 0},           /* 10  */
55787     {OP_Halt, 0, 0, 0},            /* 11 */
55788   };
55789
55790   Vdbe *v = 0;
55791   int rc = SQLITE_OK;
55792   char zErr[128];
55793
55794   zErr[0] = 0;
55795   sqlite3_mutex_enter(db->mutex);
55796   do {
55797     Parse sParse;
55798     Table *pTab;
55799
55800     memset(&sParse, 0, sizeof(Parse));
55801     sParse.db = db;
55802
55803     if( sqlite3SafetyOn(db) ){
55804       sqlite3_mutex_leave(db->mutex);
55805       return SQLITE_MISUSE;
55806     }
55807
55808     sqlite3BtreeEnterAll(db);
55809     pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
55810     if( pTab && IsVirtual(pTab) ){
55811       pTab = 0;
55812       sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
55813     }
55814 #ifndef SQLITE_OMIT_VIEW
55815     if( pTab && pTab->pSelect ){
55816       pTab = 0;
55817       sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
55818     }
55819 #endif
55820     if( !pTab ){
55821       if( sParse.zErrMsg ){
55822         sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg);
55823       }
55824       sqlite3DbFree(db, sParse.zErrMsg);
55825       rc = SQLITE_ERROR;
55826       (void)sqlite3SafetyOff(db);
55827       sqlite3BtreeLeaveAll(db);
55828       goto blob_open_out;
55829     }
55830
55831     /* Now search pTab for the exact column. */
55832     for(iCol=0; iCol < pTab->nCol; iCol++) {
55833       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
55834         break;
55835       }
55836     }
55837     if( iCol==pTab->nCol ){
55838       sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn);
55839       rc = SQLITE_ERROR;
55840       (void)sqlite3SafetyOff(db);
55841       sqlite3BtreeLeaveAll(db);
55842       goto blob_open_out;
55843     }
55844
55845     /* If the value is being opened for writing, check that the
55846     ** column is not indexed. It is against the rules to open an
55847     ** indexed column for writing.
55848     */
55849     if( flags ){
55850       Index *pIdx;
55851       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
55852         int j;
55853         for(j=0; j<pIdx->nColumn; j++){
55854           if( pIdx->aiColumn[j]==iCol ){
55855             sqlite3_snprintf(sizeof(zErr), zErr,
55856                              "cannot open indexed column for writing");
55857             rc = SQLITE_ERROR;
55858             (void)sqlite3SafetyOff(db);
55859             sqlite3BtreeLeaveAll(db);
55860             goto blob_open_out;
55861           }
55862         }
55863       }
55864     }
55865
55866     v = sqlite3VdbeCreate(db);
55867     if( v ){
55868       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
55869       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
55870
55871       /* Configure the OP_Transaction */
55872       sqlite3VdbeChangeP1(v, 0, iDb);
55873       sqlite3VdbeChangeP2(v, 0, (flags ? 1 : 0));
55874
55875       /* Configure the OP_VerifyCookie */
55876       sqlite3VdbeChangeP1(v, 1, iDb);
55877       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
55878
55879       /* Make sure a mutex is held on the table to be accessed */
55880       sqlite3VdbeUsesBtree(v, iDb); 
55881
55882       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
55883       ** parameter of the other to pTab->tnum. 
55884       */
55885       sqlite3VdbeChangeToNoop(v, (flags ? 3 : 5), 1);
55886       sqlite3VdbeChangeP2(v, (flags ? 5 : 3), pTab->tnum);
55887       sqlite3VdbeChangeP3(v, (flags ? 5 : 3), iDb);
55888
55889       /* Configure the OP_SetNumColumns. Configure the cursor to
55890       ** think that the table has one more column than it really
55891       ** does. An OP_Column to retrieve this imaginary column will
55892       ** always return an SQL NULL. This is useful because it means
55893       ** we can invoke OP_Column to fill in the vdbe cursors type 
55894       ** and offset cache without causing any IO.
55895       */
55896       sqlite3VdbeChangeP2(v, flags ? 4 : 2, pTab->nCol+1);
55897       sqlite3VdbeChangeP2(v, 8, pTab->nCol);
55898       if( !db->mallocFailed ){
55899         sqlite3VdbeMakeReady(v, 1, 1, 1, 0);
55900       }
55901     }
55902    
55903     sqlite3BtreeLeaveAll(db);
55904     rc = sqlite3SafetyOff(db);
55905     if( rc!=SQLITE_OK || db->mallocFailed ){
55906       goto blob_open_out;
55907     }
55908
55909     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
55910     rc = sqlite3_step((sqlite3_stmt *)v);
55911     if( rc!=SQLITE_ROW ){
55912       nAttempt++;
55913       rc = sqlite3_finalize((sqlite3_stmt *)v);
55914       sqlite3_snprintf(sizeof(zErr), zErr, sqlite3_errmsg(db));
55915       v = 0;
55916     }
55917   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
55918
55919   if( rc==SQLITE_ROW ){
55920     /* The row-record has been opened successfully. Check that the
55921     ** column in question contains text or a blob. If it contains
55922     ** text, it is up to the caller to get the encoding right.
55923     */
55924     Incrblob *pBlob;
55925     u32 type = v->apCsr[0]->aType[iCol];
55926
55927     if( type<12 ){
55928       sqlite3_snprintf(sizeof(zErr), zErr, "cannot open value of type %s",
55929           type==0?"null": type==7?"real": "integer"
55930       );
55931       rc = SQLITE_ERROR;
55932       goto blob_open_out;
55933     }
55934     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
55935     if( db->mallocFailed ){
55936       sqlite3DbFree(db, pBlob);
55937       goto blob_open_out;
55938     }
55939     pBlob->flags = flags;
55940     pBlob->pCsr =  v->apCsr[0]->pCursor;
55941     sqlite3BtreeEnterCursor(pBlob->pCsr);
55942     sqlite3BtreeCacheOverflow(pBlob->pCsr);
55943     sqlite3BtreeLeaveCursor(pBlob->pCsr);
55944     pBlob->pStmt = (sqlite3_stmt *)v;
55945     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
55946     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
55947     pBlob->db = db;
55948     *ppBlob = (sqlite3_blob *)pBlob;
55949     rc = SQLITE_OK;
55950   }else if( rc==SQLITE_OK ){
55951     sqlite3_snprintf(sizeof(zErr), zErr, "no such rowid: %lld", iRow);
55952     rc = SQLITE_ERROR;
55953   }
55954
55955 blob_open_out:
55956   zErr[sizeof(zErr)-1] = '\0';
55957   if( rc!=SQLITE_OK || db->mallocFailed ){
55958     sqlite3_finalize((sqlite3_stmt *)v);
55959   }
55960   sqlite3Error(db, rc, (rc==SQLITE_OK?0:zErr));
55961   rc = sqlite3ApiExit(db, rc);
55962   sqlite3_mutex_leave(db->mutex);
55963   return rc;
55964 }
55965
55966 /*
55967 ** Close a blob handle that was previously created using
55968 ** sqlite3_blob_open().
55969 */
55970 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
55971   Incrblob *p = (Incrblob *)pBlob;
55972   int rc;
55973
55974   rc = sqlite3_finalize(p->pStmt);
55975   sqlite3DbFree(p->db, p);
55976   return rc;
55977 }
55978
55979 /*
55980 ** Perform a read or write operation on a blob
55981 */
55982 static int blobReadWrite(
55983   sqlite3_blob *pBlob, 
55984   void *z, 
55985   int n, 
55986   int iOffset, 
55987   int (*xCall)(BtCursor*, u32, u32, void*)
55988 ){
55989   int rc;
55990   Incrblob *p = (Incrblob *)pBlob;
55991   Vdbe *v;
55992   sqlite3 *db = p->db;  
55993
55994   sqlite3_mutex_enter(db->mutex);
55995   v = (Vdbe*)p->pStmt;
55996
55997   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
55998     /* Request is out of range. Return a transient error. */
55999     rc = SQLITE_ERROR;
56000     sqlite3Error(db, SQLITE_ERROR, 0);
56001   } else if( v==0 ){
56002     /* If there is no statement handle, then the blob-handle has
56003     ** already been invalidated. Return SQLITE_ABORT in this case.
56004     */
56005     rc = SQLITE_ABORT;
56006   }else{
56007     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
56008     ** returned, clean-up the statement handle.
56009     */
56010     assert( db == v->db );
56011     sqlite3BtreeEnterCursor(p->pCsr);
56012     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
56013     sqlite3BtreeLeaveCursor(p->pCsr);
56014     if( rc==SQLITE_ABORT ){
56015       sqlite3VdbeFinalize(v);
56016       p->pStmt = 0;
56017     }else{
56018       db->errCode = rc;
56019       v->rc = rc;
56020     }
56021   }
56022   rc = sqlite3ApiExit(db, rc);
56023   sqlite3_mutex_leave(db->mutex);
56024   return rc;
56025 }
56026
56027 /*
56028 ** Read data from a blob handle.
56029 */
56030 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
56031   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
56032 }
56033
56034 /*
56035 ** Write data to a blob handle.
56036 */
56037 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
56038   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
56039 }
56040
56041 /*
56042 ** Query a blob handle for the size of the data.
56043 **
56044 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
56045 ** so no mutex is required for access.
56046 */
56047 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
56048   Incrblob *p = (Incrblob *)pBlob;
56049   return p->nByte;
56050 }
56051
56052 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
56053
56054 /************** End of vdbeblob.c ********************************************/
56055 /************** Begin file journal.c *****************************************/
56056 /*
56057 ** 2007 August 22
56058 **
56059 ** The author disclaims copyright to this source code.  In place of
56060 ** a legal notice, here is a blessing:
56061 **
56062 **    May you do good and not evil.
56063 **    May you find forgiveness for yourself and forgive others.
56064 **    May you share freely, never taking more than you give.
56065 **
56066 *************************************************************************
56067 **
56068 ** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $
56069 */
56070
56071 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
56072
56073 /*
56074 ** This file implements a special kind of sqlite3_file object used
56075 ** by SQLite to create journal files if the atomic-write optimization
56076 ** is enabled.
56077 **
56078 ** The distinctive characteristic of this sqlite3_file is that the
56079 ** actual on disk file is created lazily. When the file is created,
56080 ** the caller specifies a buffer size for an in-memory buffer to
56081 ** be used to service read() and write() requests. The actual file
56082 ** on disk is not created or populated until either:
56083 **
56084 **   1) The in-memory representation grows too large for the allocated 
56085 **      buffer, or
56086 **   2) The sqlite3JournalCreate() function is called.
56087 */
56088
56089
56090
56091 /*
56092 ** A JournalFile object is a subclass of sqlite3_file used by
56093 ** as an open file handle for journal files.
56094 */
56095 struct JournalFile {
56096   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
56097   int nBuf;                       /* Size of zBuf[] in bytes */
56098   char *zBuf;                     /* Space to buffer journal writes */
56099   int iSize;                      /* Amount of zBuf[] currently used */
56100   int flags;                      /* xOpen flags */
56101   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
56102   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
56103   const char *zJournal;           /* Name of the journal file */
56104 };
56105 typedef struct JournalFile JournalFile;
56106
56107 /*
56108 ** If it does not already exists, create and populate the on-disk file 
56109 ** for JournalFile p.
56110 */
56111 static int createFile(JournalFile *p){
56112   int rc = SQLITE_OK;
56113   if( !p->pReal ){
56114     sqlite3_file *pReal = (sqlite3_file *)&p[1];
56115     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
56116     if( rc==SQLITE_OK ){
56117       p->pReal = pReal;
56118       if( p->iSize>0 ){
56119         assert(p->iSize<=p->nBuf);
56120         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
56121       }
56122     }
56123   }
56124   return rc;
56125 }
56126
56127 /*
56128 ** Close the file.
56129 */
56130 static int jrnlClose(sqlite3_file *pJfd){
56131   JournalFile *p = (JournalFile *)pJfd;
56132   if( p->pReal ){
56133     sqlite3OsClose(p->pReal);
56134   }
56135   sqlite3_free(p->zBuf);
56136   return SQLITE_OK;
56137 }
56138
56139 /*
56140 ** Read data from the file.
56141 */
56142 static int jrnlRead(
56143   sqlite3_file *pJfd,    /* The journal file from which to read */
56144   void *zBuf,            /* Put the results here */
56145   int iAmt,              /* Number of bytes to read */
56146   sqlite_int64 iOfst     /* Begin reading at this offset */
56147 ){
56148   int rc = SQLITE_OK;
56149   JournalFile *p = (JournalFile *)pJfd;
56150   if( p->pReal ){
56151     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
56152   }else if( (iAmt+iOfst)>p->iSize ){
56153     rc = SQLITE_IOERR_SHORT_READ;
56154   }else{
56155     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
56156   }
56157   return rc;
56158 }
56159
56160 /*
56161 ** Write data to the file.
56162 */
56163 static int jrnlWrite(
56164   sqlite3_file *pJfd,    /* The journal file into which to write */
56165   const void *zBuf,      /* Take data to be written from here */
56166   int iAmt,              /* Number of bytes to write */
56167   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
56168 ){
56169   int rc = SQLITE_OK;
56170   JournalFile *p = (JournalFile *)pJfd;
56171   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
56172     rc = createFile(p);
56173   }
56174   if( rc==SQLITE_OK ){
56175     if( p->pReal ){
56176       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
56177     }else{
56178       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
56179       if( p->iSize<(iOfst+iAmt) ){
56180         p->iSize = (iOfst+iAmt);
56181       }
56182     }
56183   }
56184   return rc;
56185 }
56186
56187 /*
56188 ** Truncate the file.
56189 */
56190 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
56191   int rc = SQLITE_OK;
56192   JournalFile *p = (JournalFile *)pJfd;
56193   if( p->pReal ){
56194     rc = sqlite3OsTruncate(p->pReal, size);
56195   }else if( size<p->iSize ){
56196     p->iSize = size;
56197   }
56198   return rc;
56199 }
56200
56201 /*
56202 ** Sync the file.
56203 */
56204 static int jrnlSync(sqlite3_file *pJfd, int flags){
56205   int rc;
56206   JournalFile *p = (JournalFile *)pJfd;
56207   if( p->pReal ){
56208     rc = sqlite3OsSync(p->pReal, flags);
56209   }else{
56210     rc = SQLITE_OK;
56211   }
56212   return rc;
56213 }
56214
56215 /*
56216 ** Query the size of the file in bytes.
56217 */
56218 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
56219   int rc = SQLITE_OK;
56220   JournalFile *p = (JournalFile *)pJfd;
56221   if( p->pReal ){
56222     rc = sqlite3OsFileSize(p->pReal, pSize);
56223   }else{
56224     *pSize = (sqlite_int64) p->iSize;
56225   }
56226   return rc;
56227 }
56228
56229 /*
56230 ** Table of methods for JournalFile sqlite3_file object.
56231 */
56232 static struct sqlite3_io_methods JournalFileMethods = {
56233   1,             /* iVersion */
56234   jrnlClose,     /* xClose */
56235   jrnlRead,      /* xRead */
56236   jrnlWrite,     /* xWrite */
56237   jrnlTruncate,  /* xTruncate */
56238   jrnlSync,      /* xSync */
56239   jrnlFileSize,  /* xFileSize */
56240   0,             /* xLock */
56241   0,             /* xUnlock */
56242   0,             /* xCheckReservedLock */
56243   0,             /* xFileControl */
56244   0,             /* xSectorSize */
56245   0              /* xDeviceCharacteristics */
56246 };
56247
56248 /* 
56249 ** Open a journal file.
56250 */
56251 SQLITE_PRIVATE int sqlite3JournalOpen(
56252   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
56253   const char *zName,         /* Name of the journal file */
56254   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
56255   int flags,                 /* Opening flags */
56256   int nBuf                   /* Bytes buffered before opening the file */
56257 ){
56258   JournalFile *p = (JournalFile *)pJfd;
56259   memset(p, 0, sqlite3JournalSize(pVfs));
56260   if( nBuf>0 ){
56261     p->zBuf = sqlite3MallocZero(nBuf);
56262     if( !p->zBuf ){
56263       return SQLITE_NOMEM;
56264     }
56265   }else{
56266     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
56267   }
56268   p->pMethod = &JournalFileMethods;
56269   p->nBuf = nBuf;
56270   p->flags = flags;
56271   p->zJournal = zName;
56272   p->pVfs = pVfs;
56273   return SQLITE_OK;
56274 }
56275
56276 /*
56277 ** If the argument p points to a JournalFile structure, and the underlying
56278 ** file has not yet been created, create it now.
56279 */
56280 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
56281   if( p->pMethods!=&JournalFileMethods ){
56282     return SQLITE_OK;
56283   }
56284   return createFile((JournalFile *)p);
56285 }
56286
56287 /* 
56288 ** Return the number of bytes required to store a JournalFile that uses vfs
56289 ** pVfs to create the underlying on-disk files.
56290 */
56291 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
56292   return (pVfs->szOsFile+sizeof(JournalFile));
56293 }
56294 #endif
56295
56296 /************** End of journal.c *********************************************/
56297 /************** Begin file memjournal.c **************************************/
56298 /*
56299 ** 2008 October 7
56300 **
56301 ** The author disclaims copyright to this source code.  In place of
56302 ** a legal notice, here is a blessing:
56303 **
56304 **    May you do good and not evil.
56305 **    May you find forgiveness for yourself and forgive others.
56306 **    May you share freely, never taking more than you give.
56307 **
56308 *************************************************************************
56309 **
56310 ** This file contains code use to implement an in-memory rollback journal.
56311 ** The in-memory rollback journal is used to journal transactions for
56312 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
56313 **
56314 ** @(#) $Id: memjournal.c,v 1.8 2008/12/20 02:14:40 drh Exp $
56315 */
56316
56317 /* Forward references to internal structures */
56318 typedef struct MemJournal MemJournal;
56319 typedef struct FilePoint FilePoint;
56320 typedef struct FileChunk FileChunk;
56321
56322 /* Space to hold the rollback journal is allocated in increments of
56323 ** this many bytes.
56324 */
56325 #define JOURNAL_CHUNKSIZE 1024
56326
56327 /* Macro to find the minimum of two numeric values.
56328 */
56329 #ifndef MIN
56330 # define MIN(x,y) ((x)<(y)?(x):(y))
56331 #endif
56332
56333 /*
56334 ** The rollback journal is composed of a linked list of these structures.
56335 */
56336 struct FileChunk {
56337   FileChunk *pNext;               /* Next chunk in the journal */
56338   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
56339 };
56340
56341 /*
56342 ** An instance of this object serves as a cursor into the rollback journal.
56343 ** The cursor can be either for reading or writing.
56344 */
56345 struct FilePoint {
56346   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
56347   FileChunk *pChunk;              /* Specific chunk into which cursor points */
56348 };
56349
56350 /*
56351 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
56352 ** is an instance of this class.
56353 */
56354 struct MemJournal {
56355   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
56356   FileChunk *pFirst;              /* Head of in-memory chunk-list */
56357   FilePoint endpoint;             /* Pointer to the end of the file */
56358   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
56359 };
56360
56361 /*
56362 ** Read data from the file.
56363 */
56364 static int memjrnlRead(
56365   sqlite3_file *pJfd,    /* The journal file from which to read */
56366   void *zBuf,            /* Put the results here */
56367   int iAmt,              /* Number of bytes to read */
56368   sqlite_int64 iOfst     /* Begin reading at this offset */
56369 ){
56370   MemJournal *p = (MemJournal *)pJfd;
56371   u8 *zOut = zBuf;
56372   int nRead = iAmt;
56373   int iChunkOffset;
56374   FileChunk *pChunk;
56375
56376   assert( iOfst+iAmt<=p->endpoint.iOffset );
56377
56378   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
56379     sqlite3_int64 iOff = 0;
56380     for(pChunk=p->pFirst; 
56381         pChunk && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
56382         pChunk=pChunk->pNext
56383     ){
56384       iOff += JOURNAL_CHUNKSIZE;
56385     }
56386   }else{
56387     pChunk = p->readpoint.pChunk;
56388   }
56389
56390   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
56391   do {
56392     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
56393     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
56394     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
56395     zOut += nCopy;
56396     nRead -= iSpace;
56397     iChunkOffset = 0;
56398   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
56399   p->readpoint.iOffset = iOfst+iAmt;
56400   p->readpoint.pChunk = pChunk;
56401
56402   return SQLITE_OK;
56403 }
56404
56405 /*
56406 ** Write data to the file.
56407 */
56408 static int memjrnlWrite(
56409   sqlite3_file *pJfd,    /* The journal file into which to write */
56410   const void *zBuf,      /* Take data to be written from here */
56411   int iAmt,              /* Number of bytes to write */
56412   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
56413 ){
56414   MemJournal *p = (MemJournal *)pJfd;
56415   int nWrite = iAmt;
56416   u8 *zWrite = (u8 *)zBuf;
56417
56418   /* An in-memory journal file should only ever be appended to. Random
56419   ** access writes are not required by sqlite.
56420   */
56421   assert(iOfst==p->endpoint.iOffset);
56422   UNUSED_PARAMETER(iOfst);
56423
56424   while( nWrite>0 ){
56425     FileChunk *pChunk = p->endpoint.pChunk;
56426     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
56427     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
56428
56429     if( iChunkOffset==0 ){
56430       /* New chunk is required to extend the file. */
56431       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
56432       if( !pNew ){
56433         return SQLITE_IOERR_NOMEM;
56434       }
56435       pNew->pNext = 0;
56436       if( pChunk ){
56437         assert( p->pFirst );
56438         pChunk->pNext = pNew;
56439       }else{
56440         assert( !p->pFirst );
56441         p->pFirst = pNew;
56442       }
56443       p->endpoint.pChunk = pNew;
56444     }
56445
56446     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
56447     zWrite += iSpace;
56448     nWrite -= iSpace;
56449     p->endpoint.iOffset += iSpace;
56450   }
56451
56452   return SQLITE_OK;
56453 }
56454
56455 /*
56456 ** Truncate the file.
56457 */
56458 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
56459   MemJournal *p = (MemJournal *)pJfd;
56460   FileChunk *pChunk;
56461   assert(size==0);
56462   UNUSED_PARAMETER(size);
56463   pChunk = p->pFirst;
56464   while( pChunk ){
56465     FileChunk *pTmp = pChunk;
56466     pChunk = pChunk->pNext;
56467     sqlite3_free(pTmp);
56468   }
56469   sqlite3MemJournalOpen(pJfd);
56470   return SQLITE_OK;
56471 }
56472
56473 /*
56474 ** Close the file.
56475 */
56476 static int memjrnlClose(sqlite3_file *pJfd){
56477   memjrnlTruncate(pJfd, 0);
56478   return SQLITE_OK;
56479 }
56480
56481
56482 /*
56483 ** Sync the file.
56484 */
56485 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
56486   UNUSED_PARAMETER2(NotUsed, NotUsed2);
56487   return SQLITE_OK;
56488 }
56489
56490 /*
56491 ** Query the size of the file in bytes.
56492 */
56493 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
56494   MemJournal *p = (MemJournal *)pJfd;
56495   *pSize = (sqlite_int64) p->endpoint.iOffset;
56496   return SQLITE_OK;
56497 }
56498
56499 /*
56500 ** Table of methods for MemJournal sqlite3_file object.
56501 */
56502 static struct sqlite3_io_methods MemJournalMethods = {
56503   1,                /* iVersion */
56504   memjrnlClose,     /* xClose */
56505   memjrnlRead,      /* xRead */
56506   memjrnlWrite,     /* xWrite */
56507   memjrnlTruncate,  /* xTruncate */
56508   memjrnlSync,      /* xSync */
56509   memjrnlFileSize,  /* xFileSize */
56510   0,                /* xLock */
56511   0,                /* xUnlock */
56512   0,                /* xCheckReservedLock */
56513   0,                /* xFileControl */
56514   0,                /* xSectorSize */
56515   0                 /* xDeviceCharacteristics */
56516 };
56517
56518 /* 
56519 ** Open a journal file.
56520 */
56521 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
56522   MemJournal *p = (MemJournal *)pJfd;
56523   memset(p, 0, sqlite3MemJournalSize());
56524   p->pMethod = &MemJournalMethods;
56525 }
56526
56527 /*
56528 ** Return true if the file-handle passed as an argument is 
56529 ** an in-memory journal 
56530 */
56531 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
56532   return pJfd->pMethods==&MemJournalMethods;
56533 }
56534
56535 /* 
56536 ** Return the number of bytes required to store a MemJournal that uses vfs
56537 ** pVfs to create the underlying on-disk files.
56538 */
56539 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
56540   return sizeof(MemJournal);
56541 }
56542
56543 /************** End of memjournal.c ******************************************/
56544 /************** Begin file walker.c ******************************************/
56545 /*
56546 ** 2008 August 16
56547 **
56548 ** The author disclaims copyright to this source code.  In place of
56549 ** a legal notice, here is a blessing:
56550 **
56551 **    May you do good and not evil.
56552 **    May you find forgiveness for yourself and forgive others.
56553 **    May you share freely, never taking more than you give.
56554 **
56555 *************************************************************************
56556 ** This file contains routines used for walking the parser tree for
56557 ** an SQL statement.
56558 **
56559 ** $Id: walker.c,v 1.1 2008/08/20 16:35:10 drh Exp $
56560 */
56561
56562
56563 /*
56564 ** Walk an expression tree.  Invoke the callback once for each node
56565 ** of the expression, while decending.  (In other words, the callback
56566 ** is invoked before visiting children.)
56567 **
56568 ** The return value from the callback should be one of the WRC_*
56569 ** constants to specify how to proceed with the walk.
56570 **
56571 **    WRC_Continue      Continue descending down the tree.
56572 **
56573 **    WRC_Prune         Do not descend into child nodes.  But allow
56574 **                      the walk to continue with sibling nodes.
56575 **
56576 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
56577 **                      return the top-level walk call.
56578 **
56579 ** The return value from this routine is WRC_Abort to abandon the tree walk
56580 ** and WRC_Continue to continue.
56581 */
56582 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
56583   int rc;
56584   if( pExpr==0 ) return WRC_Continue;
56585   rc = pWalker->xExprCallback(pWalker, pExpr);
56586   if( rc==WRC_Continue ){
56587     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
56588     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
56589     if( sqlite3WalkExprList(pWalker, pExpr->pList) ) return WRC_Abort;
56590     if( sqlite3WalkSelect(pWalker, pExpr->pSelect) ){
56591       return WRC_Abort;
56592     }
56593   }
56594   return rc & WRC_Abort;
56595 }
56596
56597 /*
56598 ** Call sqlite3WalkExpr() for every expression in list p or until
56599 ** an abort request is seen.
56600 */
56601 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
56602   int i, rc = WRC_Continue;
56603   struct ExprList_item *pItem;
56604   if( p ){
56605     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
56606       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
56607     }
56608   }
56609   return rc & WRC_Continue;
56610 }
56611
56612 /*
56613 ** Walk all expressions associated with SELECT statement p.  Do
56614 ** not invoke the SELECT callback on p, but do (of course) invoke
56615 ** any expr callbacks and SELECT callbacks that come from subqueries.
56616 ** Return WRC_Abort or WRC_Continue.
56617 */
56618 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
56619   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
56620   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
56621   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
56622   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
56623   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
56624   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
56625   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
56626   return WRC_Continue;
56627 }
56628
56629 /*
56630 ** Walk the parse trees associated with all subqueries in the
56631 ** FROM clause of SELECT statement p.  Do not invoke the select
56632 ** callback on p, but do invoke it on each FROM clause subquery
56633 ** and on any subqueries further down in the tree.  Return 
56634 ** WRC_Abort or WRC_Continue;
56635 */
56636 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
56637   SrcList *pSrc;
56638   int i;
56639   struct SrcList_item *pItem;
56640
56641   pSrc = p->pSrc;
56642   if( pSrc ){
56643     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
56644       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
56645         return WRC_Abort;
56646       }
56647     }
56648   }
56649   return WRC_Continue;
56650
56651
56652 /*
56653 ** Call sqlite3WalkExpr() for every expression in Select statement p.
56654 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
56655 ** on the compound select chain, p->pPrior.
56656 **
56657 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
56658 ** there is an abort request.
56659 **
56660 ** If the Walker does not have an xSelectCallback() then this routine
56661 ** is a no-op returning WRC_Continue.
56662 */
56663 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
56664   int rc;
56665   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
56666   rc = WRC_Continue;
56667   while( p  ){
56668     rc = pWalker->xSelectCallback(pWalker, p);
56669     if( rc ) break;
56670     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
56671     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
56672     p = p->pPrior;
56673   }
56674   return rc & WRC_Abort;
56675 }
56676
56677 /************** End of walker.c **********************************************/
56678 /************** Begin file resolve.c *****************************************/
56679 /*
56680 ** 2008 August 18
56681 **
56682 ** The author disclaims copyright to this source code.  In place of
56683 ** a legal notice, here is a blessing:
56684 **
56685 **    May you do good and not evil.
56686 **    May you find forgiveness for yourself and forgive others.
56687 **    May you share freely, never taking more than you give.
56688 **
56689 *************************************************************************
56690 **
56691 ** This file contains routines used for walking the parser tree and
56692 ** resolve all identifiers by associating them with a particular
56693 ** table and column.
56694 **
56695 ** $Id: resolve.c,v 1.15 2008/12/10 19:26:24 drh Exp $
56696 */
56697
56698 /*
56699 ** Turn the pExpr expression into an alias for the iCol-th column of the
56700 ** result set in pEList.
56701 **
56702 ** If the result set column is a simple column reference, then this routine
56703 ** makes an exact copy.  But for any other kind of expression, this
56704 ** routine make a copy of the result set column as the argument to the
56705 ** TK_AS operator.  The TK_AS operator causes the expression to be
56706 ** evaluated just once and then reused for each alias.
56707 **
56708 ** The reason for suppressing the TK_AS term when the expression is a simple
56709 ** column reference is so that the column reference will be recognized as
56710 ** usable by indices within the WHERE clause processing logic. 
56711 **
56712 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
56713 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
56714 **
56715 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
56716 **
56717 ** Is equivalent to:
56718 **
56719 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
56720 **
56721 ** The result of random()%5 in the GROUP BY clause is probably different
56722 ** from the result in the result-set.  We might fix this someday.  Or
56723 ** then again, we might not...
56724 */
56725 static void resolveAlias(
56726   Parse *pParse,         /* Parsing context */
56727   ExprList *pEList,      /* A result set */
56728   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
56729   Expr *pExpr,           /* Transform this into an alias to the result set */
56730   const char *zType      /* "GROUP" or "ORDER" or "" */
56731 ){
56732   Expr *pOrig;           /* The iCol-th column of the result set */
56733   Expr *pDup;            /* Copy of pOrig */
56734   sqlite3 *db;           /* The database connection */
56735
56736   assert( iCol>=0 && iCol<pEList->nExpr );
56737   pOrig = pEList->a[iCol].pExpr;
56738   assert( pOrig!=0 );
56739   assert( pOrig->flags & EP_Resolved );
56740   db = pParse->db;
56741   pDup = sqlite3ExprDup(db, pOrig);
56742   if( pDup==0 ) return;
56743   if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
56744     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
56745     if( pDup==0 ) return;
56746     if( pEList->a[iCol].iAlias==0 ){
56747       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
56748     }
56749     pDup->iTable = pEList->a[iCol].iAlias;
56750   }
56751   if( pExpr->flags & EP_ExpCollate ){
56752     pDup->pColl = pExpr->pColl;
56753     pDup->flags |= EP_ExpCollate;
56754   }
56755   sqlite3ExprClear(db, pExpr);
56756   memcpy(pExpr, pDup, sizeof(*pExpr));
56757   sqlite3DbFree(db, pDup);
56758 }
56759
56760 /*
56761 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
56762 ** that name in the set of source tables in pSrcList and make the pExpr 
56763 ** expression node refer back to that source column.  The following changes
56764 ** are made to pExpr:
56765 **
56766 **    pExpr->iDb           Set the index in db->aDb[] of the database X
56767 **                         (even if X is implied).
56768 **    pExpr->iTable        Set to the cursor number for the table obtained
56769 **                         from pSrcList.
56770 **    pExpr->pTab          Points to the Table structure of X.Y (even if
56771 **                         X and/or Y are implied.)
56772 **    pExpr->iColumn       Set to the column number within the table.
56773 **    pExpr->op            Set to TK_COLUMN.
56774 **    pExpr->pLeft         Any expression this points to is deleted
56775 **    pExpr->pRight        Any expression this points to is deleted.
56776 **
56777 ** The pDbToken is the name of the database (the "X").  This value may be
56778 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
56779 ** can be used.  The pTableToken is the name of the table (the "Y").  This
56780 ** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
56781 ** means that the form of the name is Z and that columns from any table
56782 ** can be used.
56783 **
56784 ** If the name cannot be resolved unambiguously, leave an error message
56785 ** in pParse and return non-zero.  Return zero on success.
56786 */
56787 static int lookupName(
56788   Parse *pParse,       /* The parsing context */
56789   Token *pDbToken,     /* Name of the database containing table, or NULL */
56790   Token *pTableToken,  /* Name of table containing column, or NULL */
56791   Token *pColumnToken, /* Name of the column. */
56792   NameContext *pNC,    /* The name context used to resolve the name */
56793   Expr *pExpr          /* Make this EXPR node point to the selected column */
56794 ){
56795   char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
56796   char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
56797   char *zCol = 0;      /* Name of the column.  The "Z" */
56798   int i, j;            /* Loop counters */
56799   int cnt = 0;                      /* Number of matching column names */
56800   int cntTab = 0;                   /* Number of matching table names */
56801   sqlite3 *db = pParse->db;         /* The database connection */
56802   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
56803   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
56804   NameContext *pTopNC = pNC;        /* First namecontext in the list */
56805   Schema *pSchema = 0;              /* Schema of the expression */
56806
56807   assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
56808
56809   /* Dequote and zero-terminate the names */
56810   zDb = sqlite3NameFromToken(db, pDbToken);
56811   zTab = sqlite3NameFromToken(db, pTableToken);
56812   zCol = sqlite3NameFromToken(db, pColumnToken);
56813   if( db->mallocFailed ){
56814     goto lookupname_end;
56815   }
56816
56817   /* Initialize the node to no-match */
56818   pExpr->iTable = -1;
56819   pExpr->pTab = 0;
56820
56821   /* Start at the inner-most context and move outward until a match is found */
56822   while( pNC && cnt==0 ){
56823     ExprList *pEList;
56824     SrcList *pSrcList = pNC->pSrcList;
56825
56826     if( pSrcList ){
56827       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
56828         Table *pTab;
56829         int iDb;
56830         Column *pCol;
56831   
56832         pTab = pItem->pTab;
56833         assert( pTab!=0 && pTab->zName!=0 );
56834         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
56835         assert( pTab->nCol>0 );
56836         if( zTab ){
56837           if( pItem->zAlias ){
56838             char *zTabName = pItem->zAlias;
56839             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
56840           }else{
56841             char *zTabName = pTab->zName;
56842             if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
56843             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
56844               continue;
56845             }
56846           }
56847         }
56848         if( 0==(cntTab++) ){
56849           pExpr->iTable = pItem->iCursor;
56850           pExpr->pTab = pTab;
56851           pSchema = pTab->pSchema;
56852           pMatch = pItem;
56853         }
56854         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
56855           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
56856             IdList *pUsing;
56857             cnt++;
56858             pExpr->iTable = pItem->iCursor;
56859             pExpr->pTab = pTab;
56860             pMatch = pItem;
56861             pSchema = pTab->pSchema;
56862             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
56863             pExpr->iColumn = j==pTab->iPKey ? -1 : j;
56864             if( i<pSrcList->nSrc-1 ){
56865               if( pItem[1].jointype & JT_NATURAL ){
56866                 /* If this match occurred in the left table of a natural join,
56867                 ** then skip the right table to avoid a duplicate match */
56868                 pItem++;
56869                 i++;
56870               }else if( (pUsing = pItem[1].pUsing)!=0 ){
56871                 /* If this match occurs on a column that is in the USING clause
56872                 ** of a join, skip the search of the right table of the join
56873                 ** to avoid a duplicate match there. */
56874                 int k;
56875                 for(k=0; k<pUsing->nId; k++){
56876                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
56877                     pItem++;
56878                     i++;
56879                     break;
56880                   }
56881                 }
56882               }
56883             }
56884             break;
56885           }
56886         }
56887       }
56888     }
56889
56890 #ifndef SQLITE_OMIT_TRIGGER
56891     /* If we have not already resolved the name, then maybe 
56892     ** it is a new.* or old.* trigger argument reference
56893     */
56894     if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
56895       TriggerStack *pTriggerStack = pParse->trigStack;
56896       Table *pTab = 0;
56897       u32 *piColMask = 0;
56898       if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
56899         pExpr->iTable = pTriggerStack->newIdx;
56900         assert( pTriggerStack->pTab );
56901         pTab = pTriggerStack->pTab;
56902         piColMask = &(pTriggerStack->newColMask);
56903       }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
56904         pExpr->iTable = pTriggerStack->oldIdx;
56905         assert( pTriggerStack->pTab );
56906         pTab = pTriggerStack->pTab;
56907         piColMask = &(pTriggerStack->oldColMask);
56908       }
56909
56910       if( pTab ){ 
56911         int iCol;
56912         Column *pCol = pTab->aCol;
56913
56914         pSchema = pTab->pSchema;
56915         cntTab++;
56916         for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
56917           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
56918             cnt++;
56919             pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
56920             pExpr->pTab = pTab;
56921             if( iCol>=0 ){
56922               testcase( iCol==31 );
56923               testcase( iCol==32 );
56924               *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
56925             }
56926             break;
56927           }
56928         }
56929       }
56930     }
56931 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
56932
56933     /*
56934     ** Perhaps the name is a reference to the ROWID
56935     */
56936     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
56937       cnt = 1;
56938       pExpr->iColumn = -1;
56939       pExpr->affinity = SQLITE_AFF_INTEGER;
56940     }
56941
56942     /*
56943     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
56944     ** might refer to an result-set alias.  This happens, for example, when
56945     ** we are resolving names in the WHERE clause of the following command:
56946     **
56947     **     SELECT a+b AS x FROM table WHERE x<10;
56948     **
56949     ** In cases like this, replace pExpr with a copy of the expression that
56950     ** forms the result set entry ("a+b" in the example) and return immediately.
56951     ** Note that the expression in the result set should have already been
56952     ** resolved by the time the WHERE clause is resolved.
56953     */
56954     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
56955       for(j=0; j<pEList->nExpr; j++){
56956         char *zAs = pEList->a[j].zName;
56957         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
56958           Expr *pOrig;
56959           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
56960           assert( pExpr->pList==0 );
56961           assert( pExpr->pSelect==0 );
56962           pOrig = pEList->a[j].pExpr;
56963           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
56964             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
56965             sqlite3DbFree(db, zCol);
56966             return 2;
56967           }
56968           resolveAlias(pParse, pEList, j, pExpr, "");
56969           cnt = 1;
56970           pMatch = 0;
56971           assert( zTab==0 && zDb==0 );
56972           goto lookupname_end_2;
56973         }
56974       } 
56975     }
56976
56977     /* Advance to the next name context.  The loop will exit when either
56978     ** we have a match (cnt>0) or when we run out of name contexts.
56979     */
56980     if( cnt==0 ){
56981       pNC = pNC->pNext;
56982     }
56983   }
56984
56985   /*
56986   ** If X and Y are NULL (in other words if only the column name Z is
56987   ** supplied) and the value of Z is enclosed in double-quotes, then
56988   ** Z is a string literal if it doesn't match any column names.  In that
56989   ** case, we need to return right away and not make any changes to
56990   ** pExpr.
56991   **
56992   ** Because no reference was made to outer contexts, the pNC->nRef
56993   ** fields are not changed in any context.
56994   */
56995   if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
56996     sqlite3DbFree(db, zCol);
56997     pExpr->op = TK_STRING;
56998     pExpr->pTab = 0;
56999     return 0;
57000   }
57001
57002   /*
57003   ** cnt==0 means there was not match.  cnt>1 means there were two or
57004   ** more matches.  Either way, we have an error.
57005   */
57006   if( cnt!=1 ){
57007     const char *zErr;
57008     zErr = cnt==0 ? "no such column" : "ambiguous column name";
57009     if( zDb ){
57010       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
57011     }else if( zTab ){
57012       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
57013     }else{
57014       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
57015     }
57016     pTopNC->nErr++;
57017   }
57018
57019   /* If a column from a table in pSrcList is referenced, then record
57020   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
57021   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
57022   ** column number is greater than the number of bits in the bitmask
57023   ** then set the high-order bit of the bitmask.
57024   */
57025   if( pExpr->iColumn>=0 && pMatch!=0 ){
57026     int n = pExpr->iColumn;
57027     testcase( n==BMS-1 );
57028     if( n>=BMS ){
57029       n = BMS-1;
57030     }
57031     assert( pMatch->iCursor==pExpr->iTable );
57032     pMatch->colUsed |= ((Bitmask)1)<<n;
57033   }
57034
57035 lookupname_end:
57036   /* Clean up and return
57037   */
57038   sqlite3DbFree(db, zDb);
57039   sqlite3DbFree(db, zTab);
57040   sqlite3ExprDelete(db, pExpr->pLeft);
57041   pExpr->pLeft = 0;
57042   sqlite3ExprDelete(db, pExpr->pRight);
57043   pExpr->pRight = 0;
57044   pExpr->op = TK_COLUMN;
57045 lookupname_end_2:
57046   sqlite3DbFree(db, zCol);
57047   if( cnt==1 ){
57048     assert( pNC!=0 );
57049     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
57050     /* Increment the nRef value on all name contexts from TopNC up to
57051     ** the point where the name matched. */
57052     for(;;){
57053       assert( pTopNC!=0 );
57054       pTopNC->nRef++;
57055       if( pTopNC==pNC ) break;
57056       pTopNC = pTopNC->pNext;
57057     }
57058     return 0;
57059   } else {
57060     return 1;
57061   }
57062 }
57063
57064 /*
57065 ** This routine is callback for sqlite3WalkExpr().
57066 **
57067 ** Resolve symbolic names into TK_COLUMN operators for the current
57068 ** node in the expression tree.  Return 0 to continue the search down
57069 ** the tree or 2 to abort the tree walk.
57070 **
57071 ** This routine also does error checking and name resolution for
57072 ** function names.  The operator for aggregate functions is changed
57073 ** to TK_AGG_FUNCTION.
57074 */
57075 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
57076   NameContext *pNC;
57077   Parse *pParse;
57078
57079   pNC = pWalker->u.pNC;
57080   assert( pNC!=0 );
57081   pParse = pNC->pParse;
57082   assert( pParse==pWalker->pParse );
57083
57084   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
57085   ExprSetProperty(pExpr, EP_Resolved);
57086 #ifndef NDEBUG
57087   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
57088     SrcList *pSrcList = pNC->pSrcList;
57089     int i;
57090     for(i=0; i<pNC->pSrcList->nSrc; i++){
57091       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
57092     }
57093   }
57094 #endif
57095   switch( pExpr->op ){
57096
57097 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
57098     /* The special operator TK_ROW means use the rowid for the first
57099     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
57100     ** clause processing on UPDATE and DELETE statements.
57101     */
57102     case TK_ROW: {
57103       SrcList *pSrcList = pNC->pSrcList;
57104       struct SrcList_item *pItem;
57105       assert( pSrcList && pSrcList->nSrc==1 );
57106       pItem = pSrcList->a; 
57107       pExpr->op = TK_COLUMN;
57108       pExpr->pTab = pItem->pTab;
57109       pExpr->iTable = pItem->iCursor;
57110       pExpr->iColumn = -1;
57111       pExpr->affinity = SQLITE_AFF_INTEGER;
57112       break;
57113     }
57114 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
57115
57116     /* A lone identifier is the name of a column.
57117     */
57118     case TK_ID: {
57119       lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
57120       return WRC_Prune;
57121     }
57122   
57123     /* A table name and column name:     ID.ID
57124     ** Or a database, table and column:  ID.ID.ID
57125     */
57126     case TK_DOT: {
57127       Token *pColumn;
57128       Token *pTable;
57129       Token *pDb;
57130       Expr *pRight;
57131
57132       /* if( pSrcList==0 ) break; */
57133       pRight = pExpr->pRight;
57134       if( pRight->op==TK_ID ){
57135         pDb = 0;
57136         pTable = &pExpr->pLeft->token;
57137         pColumn = &pRight->token;
57138       }else{
57139         assert( pRight->op==TK_DOT );
57140         pDb = &pExpr->pLeft->token;
57141         pTable = &pRight->pLeft->token;
57142         pColumn = &pRight->pRight->token;
57143       }
57144       lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
57145       return WRC_Prune;
57146     }
57147
57148     /* Resolve function names
57149     */
57150     case TK_CONST_FUNC:
57151     case TK_FUNCTION: {
57152       ExprList *pList = pExpr->pList;    /* The argument list */
57153       int n = pList ? pList->nExpr : 0;  /* Number of arguments */
57154       int no_such_func = 0;       /* True if no such function exists */
57155       int wrong_num_args = 0;     /* True if wrong number of arguments */
57156       int is_agg = 0;             /* True if is an aggregate function */
57157       int auth;                   /* Authorization to use the function */
57158       int nId;                    /* Number of characters in function name */
57159       const char *zId;            /* The function name. */
57160       FuncDef *pDef;              /* Information about the function */
57161       u8 enc = ENC(pParse->db);   /* The database encoding */
57162
57163       zId = (char*)pExpr->token.z;
57164       nId = pExpr->token.n;
57165       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
57166       if( pDef==0 ){
57167         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
57168         if( pDef==0 ){
57169           no_such_func = 1;
57170         }else{
57171           wrong_num_args = 1;
57172         }
57173       }else{
57174         is_agg = pDef->xFunc==0;
57175       }
57176 #ifndef SQLITE_OMIT_AUTHORIZATION
57177       if( pDef ){
57178         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
57179         if( auth!=SQLITE_OK ){
57180           if( auth==SQLITE_DENY ){
57181             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
57182                                     pDef->zName);
57183             pNC->nErr++;
57184           }
57185           pExpr->op = TK_NULL;
57186           return WRC_Prune;
57187         }
57188       }
57189 #endif
57190       if( is_agg && !pNC->allowAgg ){
57191         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
57192         pNC->nErr++;
57193         is_agg = 0;
57194       }else if( no_such_func ){
57195         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
57196         pNC->nErr++;
57197       }else if( wrong_num_args ){
57198         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
57199              nId, zId);
57200         pNC->nErr++;
57201       }
57202       if( is_agg ){
57203         pExpr->op = TK_AGG_FUNCTION;
57204         pNC->hasAgg = 1;
57205       }
57206       if( is_agg ) pNC->allowAgg = 0;
57207       sqlite3WalkExprList(pWalker, pList);
57208       if( is_agg ) pNC->allowAgg = 1;
57209       /* FIX ME:  Compute pExpr->affinity based on the expected return
57210       ** type of the function 
57211       */
57212       return WRC_Prune;
57213     }
57214 #ifndef SQLITE_OMIT_SUBQUERY
57215     case TK_SELECT:
57216     case TK_EXISTS:
57217 #endif
57218     case TK_IN: {
57219       if( pExpr->pSelect ){
57220         int nRef = pNC->nRef;
57221 #ifndef SQLITE_OMIT_CHECK
57222         if( pNC->isCheck ){
57223           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
57224         }
57225 #endif
57226         sqlite3WalkSelect(pWalker, pExpr->pSelect);
57227         assert( pNC->nRef>=nRef );
57228         if( nRef!=pNC->nRef ){
57229           ExprSetProperty(pExpr, EP_VarSelect);
57230         }
57231       }
57232       break;
57233     }
57234 #ifndef SQLITE_OMIT_CHECK
57235     case TK_VARIABLE: {
57236       if( pNC->isCheck ){
57237         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
57238       }
57239       break;
57240     }
57241 #endif
57242   }
57243   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
57244 }
57245
57246 /*
57247 ** pEList is a list of expressions which are really the result set of the
57248 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
57249 ** This routine checks to see if pE is a simple identifier which corresponds
57250 ** to the AS-name of one of the terms of the expression list.  If it is,
57251 ** this routine return an integer between 1 and N where N is the number of
57252 ** elements in pEList, corresponding to the matching entry.  If there is
57253 ** no match, or if pE is not a simple identifier, then this routine
57254 ** return 0.
57255 **
57256 ** pEList has been resolved.  pE has not.
57257 */
57258 static int resolveAsName(
57259   Parse *pParse,     /* Parsing context for error messages */
57260   ExprList *pEList,  /* List of expressions to scan */
57261   Expr *pE           /* Expression we are trying to match */
57262 ){
57263   int i;             /* Loop counter */
57264
57265   if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
57266     sqlite3 *db = pParse->db;
57267     char *zCol = sqlite3NameFromToken(db, &pE->token);
57268     if( zCol==0 ){
57269       return -1;
57270     }
57271     for(i=0; i<pEList->nExpr; i++){
57272       char *zAs = pEList->a[i].zName;
57273       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
57274         sqlite3DbFree(db, zCol);
57275         return i+1;
57276       }
57277     }
57278     sqlite3DbFree(db, zCol);
57279   }
57280   return 0;
57281 }
57282
57283 /*
57284 ** pE is a pointer to an expression which is a single term in the
57285 ** ORDER BY of a compound SELECT.  The expression has not been
57286 ** name resolved.
57287 **
57288 ** At the point this routine is called, we already know that the
57289 ** ORDER BY term is not an integer index into the result set.  That
57290 ** case is handled by the calling routine.
57291 **
57292 ** Attempt to match pE against result set columns in the left-most
57293 ** SELECT statement.  Return the index i of the matching column,
57294 ** as an indication to the caller that it should sort by the i-th column.
57295 ** The left-most column is 1.  In other words, the value returned is the
57296 ** same integer value that would be used in the SQL statement to indicate
57297 ** the column.
57298 **
57299 ** If there is no match, return 0.  Return -1 if an error occurs.
57300 */
57301 static int resolveOrderByTermToExprList(
57302   Parse *pParse,     /* Parsing context for error messages */
57303   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
57304   Expr *pE           /* The specific ORDER BY term */
57305 ){
57306   int i;             /* Loop counter */
57307   ExprList *pEList;  /* The columns of the result set */
57308   NameContext nc;    /* Name context for resolving pE */
57309
57310   assert( sqlite3ExprIsInteger(pE, &i)==0 );
57311   pEList = pSelect->pEList;
57312
57313   /* Resolve all names in the ORDER BY term expression
57314   */
57315   memset(&nc, 0, sizeof(nc));
57316   nc.pParse = pParse;
57317   nc.pSrcList = pSelect->pSrc;
57318   nc.pEList = pEList;
57319   nc.allowAgg = 1;
57320   nc.nErr = 0;
57321   if( sqlite3ResolveExprNames(&nc, pE) ){
57322     sqlite3ErrorClear(pParse);
57323     return 0;
57324   }
57325
57326   /* Try to match the ORDER BY expression against an expression
57327   ** in the result set.  Return an 1-based index of the matching
57328   ** result-set entry.
57329   */
57330   for(i=0; i<pEList->nExpr; i++){
57331     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
57332       return i+1;
57333     }
57334   }
57335
57336   /* If no match, return 0. */
57337   return 0;
57338 }
57339
57340 /*
57341 ** Generate an ORDER BY or GROUP BY term out-of-range error.
57342 */
57343 static void resolveOutOfRangeError(
57344   Parse *pParse,         /* The error context into which to write the error */
57345   const char *zType,     /* "ORDER" or "GROUP" */
57346   int i,                 /* The index (1-based) of the term out of range */
57347   int mx                 /* Largest permissible value of i */
57348 ){
57349   sqlite3ErrorMsg(pParse, 
57350     "%r %s BY term out of range - should be "
57351     "between 1 and %d", i, zType, mx);
57352 }
57353
57354 /*
57355 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
57356 ** each term of the ORDER BY clause is a constant integer between 1
57357 ** and N where N is the number of columns in the compound SELECT.
57358 **
57359 ** ORDER BY terms that are already an integer between 1 and N are
57360 ** unmodified.  ORDER BY terms that are integers outside the range of
57361 ** 1 through N generate an error.  ORDER BY terms that are expressions
57362 ** are matched against result set expressions of compound SELECT
57363 ** beginning with the left-most SELECT and working toward the right.
57364 ** At the first match, the ORDER BY expression is transformed into
57365 ** the integer column number.
57366 **
57367 ** Return the number of errors seen.
57368 */
57369 static int resolveCompoundOrderBy(
57370   Parse *pParse,        /* Parsing context.  Leave error messages here */
57371   Select *pSelect       /* The SELECT statement containing the ORDER BY */
57372 ){
57373   int i;
57374   ExprList *pOrderBy;
57375   ExprList *pEList;
57376   sqlite3 *db;
57377   int moreToDo = 1;
57378
57379   pOrderBy = pSelect->pOrderBy;
57380   if( pOrderBy==0 ) return 0;
57381   db = pParse->db;
57382 #if SQLITE_MAX_COLUMN
57383   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
57384     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
57385     return 1;
57386   }
57387 #endif
57388   for(i=0; i<pOrderBy->nExpr; i++){
57389     pOrderBy->a[i].done = 0;
57390   }
57391   pSelect->pNext = 0;
57392   while( pSelect->pPrior ){
57393     pSelect->pPrior->pNext = pSelect;
57394     pSelect = pSelect->pPrior;
57395   }
57396   while( pSelect && moreToDo ){
57397     struct ExprList_item *pItem;
57398     moreToDo = 0;
57399     pEList = pSelect->pEList;
57400     assert( pEList!=0 );
57401     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
57402       int iCol = -1;
57403       Expr *pE, *pDup;
57404       if( pItem->done ) continue;
57405       pE = pItem->pExpr;
57406       if( sqlite3ExprIsInteger(pE, &iCol) ){
57407         if( iCol<0 || iCol>pEList->nExpr ){
57408           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
57409           return 1;
57410         }
57411       }else{
57412         iCol = resolveAsName(pParse, pEList, pE);
57413         if( iCol==0 ){
57414           pDup = sqlite3ExprDup(db, pE);
57415           if( !db->mallocFailed ){
57416             assert(pDup);
57417             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
57418           }
57419           sqlite3ExprDelete(db, pDup);
57420         }
57421         if( iCol<0 ){
57422           return 1;
57423         }
57424       }
57425       if( iCol>0 ){
57426         CollSeq *pColl = pE->pColl;
57427         int flags = pE->flags & EP_ExpCollate;
57428         sqlite3ExprDelete(db, pE);
57429         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
57430         if( pE==0 ) return 1;
57431         pE->pColl = pColl;
57432         pE->flags |= EP_IntValue | flags;
57433         pE->iTable = iCol;
57434         pItem->iCol = (u16)iCol;
57435         pItem->done = 1;
57436       }else{
57437         moreToDo = 1;
57438       }
57439     }
57440     pSelect = pSelect->pNext;
57441   }
57442   for(i=0; i<pOrderBy->nExpr; i++){
57443     if( pOrderBy->a[i].done==0 ){
57444       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
57445             "column in the result set", i+1);
57446       return 1;
57447     }
57448   }
57449   return 0;
57450 }
57451
57452 /*
57453 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
57454 ** the SELECT statement pSelect.  If any term is reference to a
57455 ** result set expression (as determined by the ExprList.a.iCol field)
57456 ** then convert that term into a copy of the corresponding result set
57457 ** column.
57458 **
57459 ** If any errors are detected, add an error message to pParse and
57460 ** return non-zero.  Return zero if no errors are seen.
57461 */
57462 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
57463   Parse *pParse,        /* Parsing context.  Leave error messages here */
57464   Select *pSelect,      /* The SELECT statement containing the clause */
57465   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
57466   const char *zType     /* "ORDER" or "GROUP" */
57467 ){
57468   int i;
57469   sqlite3 *db = pParse->db;
57470   ExprList *pEList;
57471   struct ExprList_item *pItem;
57472
57473   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
57474 #if SQLITE_MAX_COLUMN
57475   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
57476     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
57477     return 1;
57478   }
57479 #endif
57480   pEList = pSelect->pEList;
57481   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
57482   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
57483     if( pItem->iCol ){
57484       if( pItem->iCol>pEList->nExpr ){
57485         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
57486         return 1;
57487       }
57488       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
57489     }
57490   }
57491   return 0;
57492 }
57493
57494 /*
57495 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
57496 ** The Name context of the SELECT statement is pNC.  zType is either
57497 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
57498 **
57499 ** This routine resolves each term of the clause into an expression.
57500 ** If the order-by term is an integer I between 1 and N (where N is the
57501 ** number of columns in the result set of the SELECT) then the expression
57502 ** in the resolution is a copy of the I-th result-set expression.  If
57503 ** the order-by term is an identify that corresponds to the AS-name of
57504 ** a result-set expression, then the term resolves to a copy of the
57505 ** result-set expression.  Otherwise, the expression is resolved in
57506 ** the usual way - using sqlite3ResolveExprNames().
57507 **
57508 ** This routine returns the number of errors.  If errors occur, then
57509 ** an appropriate error message might be left in pParse.  (OOM errors
57510 ** excepted.)
57511 */
57512 static int resolveOrderGroupBy(
57513   NameContext *pNC,     /* The name context of the SELECT statement */
57514   Select *pSelect,      /* The SELECT statement holding pOrderBy */
57515   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
57516   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
57517 ){
57518   int i;                         /* Loop counter */
57519   int iCol;                      /* Column number */
57520   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
57521   Parse *pParse;                 /* Parsing context */
57522   int nResult;                   /* Number of terms in the result set */
57523
57524   if( pOrderBy==0 ) return 0;
57525   nResult = pSelect->pEList->nExpr;
57526   pParse = pNC->pParse;
57527   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
57528     Expr *pE = pItem->pExpr;
57529     iCol = resolveAsName(pParse, pSelect->pEList, pE);
57530     if( iCol<0 ){
57531       return 1;  /* OOM error */
57532     }
57533     if( iCol>0 ){
57534       /* If an AS-name match is found, mark this ORDER BY column as being
57535       ** a copy of the iCol-th result-set column.  The subsequent call to
57536       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
57537       ** copy of the iCol-th result-set expression. */
57538       pItem->iCol = (u16)iCol;
57539       continue;
57540     }
57541     if( sqlite3ExprIsInteger(pE, &iCol) ){
57542       /* The ORDER BY term is an integer constant.  Again, set the column
57543       ** number so that sqlite3ResolveOrderGroupBy() will convert the
57544       ** order-by term to a copy of the result-set expression */
57545       if( iCol<1 ){
57546         resolveOutOfRangeError(pParse, zType, i+1, nResult);
57547         return 1;
57548       }
57549       pItem->iCol = (u16)iCol;
57550       continue;
57551     }
57552
57553     /* Otherwise, treat the ORDER BY term as an ordinary expression */
57554     pItem->iCol = 0;
57555     if( sqlite3ResolveExprNames(pNC, pE) ){
57556       return 1;
57557     }
57558   }
57559   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
57560 }
57561
57562 /*
57563 ** Resolve names in the SELECT statement p and all of its descendents.
57564 */
57565 static int resolveSelectStep(Walker *pWalker, Select *p){
57566   NameContext *pOuterNC;  /* Context that contains this SELECT */
57567   NameContext sNC;        /* Name context of this SELECT */
57568   int isCompound;         /* True if p is a compound select */
57569   int nCompound;          /* Number of compound terms processed so far */
57570   Parse *pParse;          /* Parsing context */
57571   ExprList *pEList;       /* Result set expression list */
57572   int i;                  /* Loop counter */
57573   ExprList *pGroupBy;     /* The GROUP BY clause */
57574   Select *pLeftmost;      /* Left-most of SELECT of a compound */
57575   sqlite3 *db;            /* Database connection */
57576   
57577
57578   assert( p!=0 );
57579   if( p->selFlags & SF_Resolved ){
57580     return WRC_Prune;
57581   }
57582   pOuterNC = pWalker->u.pNC;
57583   pParse = pWalker->pParse;
57584   db = pParse->db;
57585
57586   /* Normally sqlite3SelectExpand() will be called first and will have
57587   ** already expanded this SELECT.  However, if this is a subquery within
57588   ** an expression, sqlite3ResolveExprNames() will be called without a
57589   ** prior call to sqlite3SelectExpand().  When that happens, let
57590   ** sqlite3SelectPrep() do all of the processing for this SELECT.
57591   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
57592   ** this routine in the correct order.
57593   */
57594   if( (p->selFlags & SF_Expanded)==0 ){
57595     sqlite3SelectPrep(pParse, p, pOuterNC);
57596     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
57597   }
57598
57599   isCompound = p->pPrior!=0;
57600   nCompound = 0;
57601   pLeftmost = p;
57602   while( p ){
57603     assert( (p->selFlags & SF_Expanded)!=0 );
57604     assert( (p->selFlags & SF_Resolved)==0 );
57605     p->selFlags |= SF_Resolved;
57606
57607     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
57608     ** are not allowed to refer to any names, so pass an empty NameContext.
57609     */
57610     memset(&sNC, 0, sizeof(sNC));
57611     sNC.pParse = pParse;
57612     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
57613         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
57614       return WRC_Abort;
57615     }
57616   
57617     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
57618     ** resolve the result-set expression list.
57619     */
57620     sNC.allowAgg = 1;
57621     sNC.pSrcList = p->pSrc;
57622     sNC.pNext = pOuterNC;
57623   
57624     /* Resolve names in the result set. */
57625     pEList = p->pEList;
57626     assert( pEList!=0 );
57627     for(i=0; i<pEList->nExpr; i++){
57628       Expr *pX = pEList->a[i].pExpr;
57629       if( sqlite3ResolveExprNames(&sNC, pX) ){
57630         return WRC_Abort;
57631       }
57632     }
57633   
57634     /* Recursively resolve names in all subqueries
57635     */
57636     for(i=0; i<p->pSrc->nSrc; i++){
57637       struct SrcList_item *pItem = &p->pSrc->a[i];
57638       if( pItem->pSelect ){
57639         const char *zSavedContext = pParse->zAuthContext;
57640         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
57641         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
57642         pParse->zAuthContext = zSavedContext;
57643         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
57644       }
57645     }
57646   
57647     /* If there are no aggregate functions in the result-set, and no GROUP BY 
57648     ** expression, do not allow aggregates in any of the other expressions.
57649     */
57650     assert( (p->selFlags & SF_Aggregate)==0 );
57651     pGroupBy = p->pGroupBy;
57652     if( pGroupBy || sNC.hasAgg ){
57653       p->selFlags |= SF_Aggregate;
57654     }else{
57655       sNC.allowAgg = 0;
57656     }
57657   
57658     /* If a HAVING clause is present, then there must be a GROUP BY clause.
57659     */
57660     if( p->pHaving && !pGroupBy ){
57661       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
57662       return WRC_Abort;
57663     }
57664   
57665     /* Add the expression list to the name-context before parsing the
57666     ** other expressions in the SELECT statement. This is so that
57667     ** expressions in the WHERE clause (etc.) can refer to expressions by
57668     ** aliases in the result set.
57669     **
57670     ** Minor point: If this is the case, then the expression will be
57671     ** re-evaluated for each reference to it.
57672     */
57673     sNC.pEList = p->pEList;
57674     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
57675        sqlite3ResolveExprNames(&sNC, p->pHaving)
57676     ){
57677       return WRC_Abort;
57678     }
57679
57680     /* The ORDER BY and GROUP BY clauses may not refer to terms in
57681     ** outer queries 
57682     */
57683     sNC.pNext = 0;
57684     sNC.allowAgg = 1;
57685
57686     /* Process the ORDER BY clause for singleton SELECT statements.
57687     ** The ORDER BY clause for compounds SELECT statements is handled
57688     ** below, after all of the result-sets for all of the elements of
57689     ** the compound have been resolved.
57690     */
57691     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
57692       return WRC_Abort;
57693     }
57694     if( db->mallocFailed ){
57695       return WRC_Abort;
57696     }
57697   
57698     /* Resolve the GROUP BY clause.  At the same time, make sure 
57699     ** the GROUP BY clause does not contain aggregate functions.
57700     */
57701     if( pGroupBy ){
57702       struct ExprList_item *pItem;
57703     
57704       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
57705         return WRC_Abort;
57706       }
57707       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
57708         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
57709           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
57710               "the GROUP BY clause");
57711           return WRC_Abort;
57712         }
57713       }
57714     }
57715
57716     /* Advance to the next term of the compound
57717     */
57718     p = p->pPrior;
57719     nCompound++;
57720   }
57721
57722   /* Resolve the ORDER BY on a compound SELECT after all terms of
57723   ** the compound have been resolved.
57724   */
57725   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
57726     return WRC_Abort;
57727   }
57728
57729   return WRC_Prune;
57730 }
57731
57732 /*
57733 ** This routine walks an expression tree and resolves references to
57734 ** table columns and result-set columns.  At the same time, do error
57735 ** checking on function usage and set a flag if any aggregate functions
57736 ** are seen.
57737 **
57738 ** To resolve table columns references we look for nodes (or subtrees) of the 
57739 ** form X.Y.Z or Y.Z or just Z where
57740 **
57741 **      X:   The name of a database.  Ex:  "main" or "temp" or
57742 **           the symbolic name assigned to an ATTACH-ed database.
57743 **
57744 **      Y:   The name of a table in a FROM clause.  Or in a trigger
57745 **           one of the special names "old" or "new".
57746 **
57747 **      Z:   The name of a column in table Y.
57748 **
57749 ** The node at the root of the subtree is modified as follows:
57750 **
57751 **    Expr.op        Changed to TK_COLUMN
57752 **    Expr.pTab      Points to the Table object for X.Y
57753 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
57754 **    Expr.iTable    The VDBE cursor number for X.Y
57755 **
57756 **
57757 ** To resolve result-set references, look for expression nodes of the
57758 ** form Z (with no X and Y prefix) where the Z matches the right-hand
57759 ** size of an AS clause in the result-set of a SELECT.  The Z expression
57760 ** is replaced by a copy of the left-hand side of the result-set expression.
57761 ** Table-name and function resolution occurs on the substituted expression
57762 ** tree.  For example, in:
57763 **
57764 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
57765 **
57766 ** The "x" term of the order by is replaced by "a+b" to render:
57767 **
57768 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
57769 **
57770 ** Function calls are checked to make sure that the function is 
57771 ** defined and that the correct number of arguments are specified.
57772 ** If the function is an aggregate function, then the pNC->hasAgg is
57773 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
57774 ** If an expression contains aggregate functions then the EP_Agg
57775 ** property on the expression is set.
57776 **
57777 ** An error message is left in pParse if anything is amiss.  The number
57778 ** if errors is returned.
57779 */
57780 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
57781   NameContext *pNC,       /* Namespace to resolve expressions in. */
57782   Expr *pExpr             /* The expression to be analyzed. */
57783 ){
57784   int savedHasAgg;
57785   Walker w;
57786
57787   if( pExpr==0 ) return 0;
57788 #if SQLITE_MAX_EXPR_DEPTH>0
57789   {
57790     Parse *pParse = pNC->pParse;
57791     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
57792       return 1;
57793     }
57794     pParse->nHeight += pExpr->nHeight;
57795   }
57796 #endif
57797   savedHasAgg = pNC->hasAgg;
57798   pNC->hasAgg = 0;
57799   w.xExprCallback = resolveExprStep;
57800   w.xSelectCallback = resolveSelectStep;
57801   w.pParse = pNC->pParse;
57802   w.u.pNC = pNC;
57803   sqlite3WalkExpr(&w, pExpr);
57804 #if SQLITE_MAX_EXPR_DEPTH>0
57805   pNC->pParse->nHeight -= pExpr->nHeight;
57806 #endif
57807   if( pNC->nErr>0 ){
57808     ExprSetProperty(pExpr, EP_Error);
57809   }
57810   if( pNC->hasAgg ){
57811     ExprSetProperty(pExpr, EP_Agg);
57812   }else if( savedHasAgg ){
57813     pNC->hasAgg = 1;
57814   }
57815   return ExprHasProperty(pExpr, EP_Error);
57816 }
57817
57818
57819 /*
57820 ** Resolve all names in all expressions of a SELECT and in all
57821 ** decendents of the SELECT, including compounds off of p->pPrior,
57822 ** subqueries in expressions, and subqueries used as FROM clause
57823 ** terms.
57824 **
57825 ** See sqlite3ResolveExprNames() for a description of the kinds of
57826 ** transformations that occur.
57827 **
57828 ** All SELECT statements should have been expanded using
57829 ** sqlite3SelectExpand() prior to invoking this routine.
57830 */
57831 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
57832   Parse *pParse,         /* The parser context */
57833   Select *p,             /* The SELECT statement being coded. */
57834   NameContext *pOuterNC  /* Name context for parent SELECT statement */
57835 ){
57836   Walker w;
57837
57838   assert( p!=0 );
57839   w.xExprCallback = resolveExprStep;
57840   w.xSelectCallback = resolveSelectStep;
57841   w.pParse = pParse;
57842   w.u.pNC = pOuterNC;
57843   sqlite3WalkSelect(&w, p);
57844 }
57845
57846 /************** End of resolve.c *********************************************/
57847 /************** Begin file expr.c ********************************************/
57848 /*
57849 ** 2001 September 15
57850 **
57851 ** The author disclaims copyright to this source code.  In place of
57852 ** a legal notice, here is a blessing:
57853 **
57854 **    May you do good and not evil.
57855 **    May you find forgiveness for yourself and forgive others.
57856 **    May you share freely, never taking more than you give.
57857 **
57858 *************************************************************************
57859 ** This file contains routines used for analyzing expressions and
57860 ** for generating VDBE code that evaluates expressions in SQLite.
57861 **
57862 ** $Id: expr.c,v 1.411 2009/02/04 03:59:25 shane Exp $
57863 */
57864
57865 /*
57866 ** Return the 'affinity' of the expression pExpr if any.
57867 **
57868 ** If pExpr is a column, a reference to a column via an 'AS' alias,
57869 ** or a sub-select with a column as the return value, then the 
57870 ** affinity of that column is returned. Otherwise, 0x00 is returned,
57871 ** indicating no affinity for the expression.
57872 **
57873 ** i.e. the WHERE clause expresssions in the following statements all
57874 ** have an affinity:
57875 **
57876 ** CREATE TABLE t1(a);
57877 ** SELECT * FROM t1 WHERE a;
57878 ** SELECT a AS b FROM t1 WHERE b;
57879 ** SELECT * FROM t1 WHERE (select a from t1);
57880 */
57881 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
57882   int op = pExpr->op;
57883   if( op==TK_SELECT ){
57884     return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
57885   }
57886 #ifndef SQLITE_OMIT_CAST
57887   if( op==TK_CAST ){
57888     return sqlite3AffinityType(&pExpr->token);
57889   }
57890 #endif
57891   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
57892    && pExpr->pTab!=0
57893   ){
57894     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
57895     ** a TK_COLUMN but was previously evaluated and cached in a register */
57896     int j = pExpr->iColumn;
57897     if( j<0 ) return SQLITE_AFF_INTEGER;
57898     assert( pExpr->pTab && j<pExpr->pTab->nCol );
57899     return pExpr->pTab->aCol[j].affinity;
57900   }
57901   return pExpr->affinity;
57902 }
57903
57904 /*
57905 ** Set the collating sequence for expression pExpr to be the collating
57906 ** sequence named by pToken.   Return a pointer to the revised expression.
57907 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
57908 ** flag.  An explicit collating sequence will override implicit
57909 ** collating sequences.
57910 */
57911 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
57912   char *zColl = 0;            /* Dequoted name of collation sequence */
57913   CollSeq *pColl;
57914   sqlite3 *db = pParse->db;
57915   zColl = sqlite3NameFromToken(db, pCollName);
57916   if( pExpr && zColl ){
57917     pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
57918     if( pColl ){
57919       pExpr->pColl = pColl;
57920       pExpr->flags |= EP_ExpCollate;
57921     }
57922   }
57923   sqlite3DbFree(db, zColl);
57924   return pExpr;
57925 }
57926
57927 /*
57928 ** Return the default collation sequence for the expression pExpr. If
57929 ** there is no default collation type, return 0.
57930 */
57931 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
57932   CollSeq *pColl = 0;
57933   Expr *p = pExpr;
57934   while( p ){
57935     int op;
57936     pColl = p->pColl;
57937     if( pColl ) break;
57938     op = p->op;
57939     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) && p->pTab!=0 ){
57940       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
57941       ** a TK_COLUMN but was previously evaluated and cached in a register */
57942       const char *zColl;
57943       int j = p->iColumn;
57944       if( j>=0 ){
57945         sqlite3 *db = pParse->db;
57946         zColl = p->pTab->aCol[j].zColl;
57947         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
57948         pExpr->pColl = pColl;
57949       }
57950       break;
57951     }
57952     if( op!=TK_CAST && op!=TK_UPLUS ){
57953       break;
57954     }
57955     p = p->pLeft;
57956   }
57957   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
57958     pColl = 0;
57959   }
57960   return pColl;
57961 }
57962
57963 /*
57964 ** pExpr is an operand of a comparison operator.  aff2 is the
57965 ** type affinity of the other operand.  This routine returns the
57966 ** type affinity that should be used for the comparison operator.
57967 */
57968 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
57969   char aff1 = sqlite3ExprAffinity(pExpr);
57970   if( aff1 && aff2 ){
57971     /* Both sides of the comparison are columns. If one has numeric
57972     ** affinity, use that. Otherwise use no affinity.
57973     */
57974     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
57975       return SQLITE_AFF_NUMERIC;
57976     }else{
57977       return SQLITE_AFF_NONE;
57978     }
57979   }else if( !aff1 && !aff2 ){
57980     /* Neither side of the comparison is a column.  Compare the
57981     ** results directly.
57982     */
57983     return SQLITE_AFF_NONE;
57984   }else{
57985     /* One side is a column, the other is not. Use the columns affinity. */
57986     assert( aff1==0 || aff2==0 );
57987     return (aff1 + aff2);
57988   }
57989 }
57990
57991 /*
57992 ** pExpr is a comparison operator.  Return the type affinity that should
57993 ** be applied to both operands prior to doing the comparison.
57994 */
57995 static char comparisonAffinity(Expr *pExpr){
57996   char aff;
57997   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
57998           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
57999           pExpr->op==TK_NE );
58000   assert( pExpr->pLeft );
58001   aff = sqlite3ExprAffinity(pExpr->pLeft);
58002   if( pExpr->pRight ){
58003     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
58004   }
58005   else if( pExpr->pSelect ){
58006     aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
58007   }
58008   else if( !aff ){
58009     aff = SQLITE_AFF_NONE;
58010   }
58011   return aff;
58012 }
58013
58014 /*
58015 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
58016 ** idx_affinity is the affinity of an indexed column. Return true
58017 ** if the index with affinity idx_affinity may be used to implement
58018 ** the comparison in pExpr.
58019 */
58020 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
58021   char aff = comparisonAffinity(pExpr);
58022   switch( aff ){
58023     case SQLITE_AFF_NONE:
58024       return 1;
58025     case SQLITE_AFF_TEXT:
58026       return idx_affinity==SQLITE_AFF_TEXT;
58027     default:
58028       return sqlite3IsNumericAffinity(idx_affinity);
58029   }
58030 }
58031
58032 /*
58033 ** Return the P5 value that should be used for a binary comparison
58034 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
58035 */
58036 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
58037   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
58038   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
58039   return aff;
58040 }
58041
58042 /*
58043 ** Return a pointer to the collation sequence that should be used by
58044 ** a binary comparison operator comparing pLeft and pRight.
58045 **
58046 ** If the left hand expression has a collating sequence type, then it is
58047 ** used. Otherwise the collation sequence for the right hand expression
58048 ** is used, or the default (BINARY) if neither expression has a collating
58049 ** type.
58050 **
58051 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
58052 ** it is not considered.
58053 */
58054 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
58055   Parse *pParse, 
58056   Expr *pLeft, 
58057   Expr *pRight
58058 ){
58059   CollSeq *pColl;
58060   assert( pLeft );
58061   if( pLeft->flags & EP_ExpCollate ){
58062     assert( pLeft->pColl );
58063     pColl = pLeft->pColl;
58064   }else if( pRight && pRight->flags & EP_ExpCollate ){
58065     assert( pRight->pColl );
58066     pColl = pRight->pColl;
58067   }else{
58068     pColl = sqlite3ExprCollSeq(pParse, pLeft);
58069     if( !pColl ){
58070       pColl = sqlite3ExprCollSeq(pParse, pRight);
58071     }
58072   }
58073   return pColl;
58074 }
58075
58076 /*
58077 ** Generate the operands for a comparison operation.  Before
58078 ** generating the code for each operand, set the EP_AnyAff
58079 ** flag on the expression so that it will be able to used a
58080 ** cached column value that has previously undergone an
58081 ** affinity change.
58082 */
58083 static void codeCompareOperands(
58084   Parse *pParse,    /* Parsing and code generating context */
58085   Expr *pLeft,      /* The left operand */
58086   int *pRegLeft,    /* Register where left operand is stored */
58087   int *pFreeLeft,   /* Free this register when done */
58088   Expr *pRight,     /* The right operand */
58089   int *pRegRight,   /* Register where right operand is stored */
58090   int *pFreeRight   /* Write temp register for right operand there */
58091 ){
58092   while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
58093   pLeft->flags |= EP_AnyAff;
58094   *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
58095   while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
58096   pRight->flags |= EP_AnyAff;
58097   *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
58098 }
58099
58100 /*
58101 ** Generate code for a comparison operator.
58102 */
58103 static int codeCompare(
58104   Parse *pParse,    /* The parsing (and code generating) context */
58105   Expr *pLeft,      /* The left operand */
58106   Expr *pRight,     /* The right operand */
58107   int opcode,       /* The comparison opcode */
58108   int in1, int in2, /* Register holding operands */
58109   int dest,         /* Jump here if true.  */
58110   int jumpIfNull    /* If true, jump if either operand is NULL */
58111 ){
58112   int p5;
58113   int addr;
58114   CollSeq *p4;
58115
58116   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
58117   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
58118   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
58119                            (void*)p4, P4_COLLSEQ);
58120   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
58121   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
58122     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
58123     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
58124   }
58125   return addr;
58126 }
58127
58128 #if SQLITE_MAX_EXPR_DEPTH>0
58129 /*
58130 ** Check that argument nHeight is less than or equal to the maximum
58131 ** expression depth allowed. If it is not, leave an error message in
58132 ** pParse.
58133 */
58134 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
58135   int rc = SQLITE_OK;
58136   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
58137   if( nHeight>mxHeight ){
58138     sqlite3ErrorMsg(pParse, 
58139        "Expression tree is too large (maximum depth %d)", mxHeight
58140     );
58141     rc = SQLITE_ERROR;
58142   }
58143   return rc;
58144 }
58145
58146 /* The following three functions, heightOfExpr(), heightOfExprList()
58147 ** and heightOfSelect(), are used to determine the maximum height
58148 ** of any expression tree referenced by the structure passed as the
58149 ** first argument.
58150 **
58151 ** If this maximum height is greater than the current value pointed
58152 ** to by pnHeight, the second parameter, then set *pnHeight to that
58153 ** value.
58154 */
58155 static void heightOfExpr(Expr *p, int *pnHeight){
58156   if( p ){
58157     if( p->nHeight>*pnHeight ){
58158       *pnHeight = p->nHeight;
58159     }
58160   }
58161 }
58162 static void heightOfExprList(ExprList *p, int *pnHeight){
58163   if( p ){
58164     int i;
58165     for(i=0; i<p->nExpr; i++){
58166       heightOfExpr(p->a[i].pExpr, pnHeight);
58167     }
58168   }
58169 }
58170 static void heightOfSelect(Select *p, int *pnHeight){
58171   if( p ){
58172     heightOfExpr(p->pWhere, pnHeight);
58173     heightOfExpr(p->pHaving, pnHeight);
58174     heightOfExpr(p->pLimit, pnHeight);
58175     heightOfExpr(p->pOffset, pnHeight);
58176     heightOfExprList(p->pEList, pnHeight);
58177     heightOfExprList(p->pGroupBy, pnHeight);
58178     heightOfExprList(p->pOrderBy, pnHeight);
58179     heightOfSelect(p->pPrior, pnHeight);
58180   }
58181 }
58182
58183 /*
58184 ** Set the Expr.nHeight variable in the structure passed as an 
58185 ** argument. An expression with no children, Expr.pList or 
58186 ** Expr.pSelect member has a height of 1. Any other expression
58187 ** has a height equal to the maximum height of any other 
58188 ** referenced Expr plus one.
58189 */
58190 static void exprSetHeight(Expr *p){
58191   int nHeight = 0;
58192   heightOfExpr(p->pLeft, &nHeight);
58193   heightOfExpr(p->pRight, &nHeight);
58194   heightOfExprList(p->pList, &nHeight);
58195   heightOfSelect(p->pSelect, &nHeight);
58196   p->nHeight = nHeight + 1;
58197 }
58198
58199 /*
58200 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
58201 ** the height is greater than the maximum allowed expression depth,
58202 ** leave an error in pParse.
58203 */
58204 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
58205   exprSetHeight(p);
58206   sqlite3ExprCheckHeight(pParse, p->nHeight);
58207 }
58208
58209 /*
58210 ** Return the maximum height of any expression tree referenced
58211 ** by the select statement passed as an argument.
58212 */
58213 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
58214   int nHeight = 0;
58215   heightOfSelect(p, &nHeight);
58216   return nHeight;
58217 }
58218 #else
58219   #define exprSetHeight(y)
58220 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
58221
58222 /*
58223 ** Construct a new expression node and return a pointer to it.  Memory
58224 ** for this node is obtained from sqlite3_malloc().  The calling function
58225 ** is responsible for making sure the node eventually gets freed.
58226 */
58227 SQLITE_PRIVATE Expr *sqlite3Expr(
58228   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
58229   int op,                 /* Expression opcode */
58230   Expr *pLeft,            /* Left operand */
58231   Expr *pRight,           /* Right operand */
58232   const Token *pToken     /* Argument token */
58233 ){
58234   Expr *pNew;
58235   pNew = sqlite3DbMallocZero(db, sizeof(Expr));
58236   if( pNew==0 ){
58237     /* When malloc fails, delete pLeft and pRight. Expressions passed to 
58238     ** this function must always be allocated with sqlite3Expr() for this 
58239     ** reason. 
58240     */
58241     sqlite3ExprDelete(db, pLeft);
58242     sqlite3ExprDelete(db, pRight);
58243     return 0;
58244   }
58245   pNew->op = (u8)op;
58246   pNew->pLeft = pLeft;
58247   pNew->pRight = pRight;
58248   pNew->iAgg = -1;
58249   pNew->span.z = (u8*)"";
58250   if( pToken ){
58251     assert( pToken->dyn==0 );
58252     pNew->span = pNew->token = *pToken;
58253   }else if( pLeft ){
58254     if( pRight ){
58255       if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
58256         sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
58257       }
58258       if( pRight->flags & EP_ExpCollate ){
58259         pNew->flags |= EP_ExpCollate;
58260         pNew->pColl = pRight->pColl;
58261       }
58262     }
58263     if( pLeft->flags & EP_ExpCollate ){
58264       pNew->flags |= EP_ExpCollate;
58265       pNew->pColl = pLeft->pColl;
58266     }
58267   }
58268
58269   exprSetHeight(pNew);
58270   return pNew;
58271 }
58272
58273 /*
58274 ** Works like sqlite3Expr() except that it takes an extra Parse*
58275 ** argument and notifies the associated connection object if malloc fails.
58276 */
58277 SQLITE_PRIVATE Expr *sqlite3PExpr(
58278   Parse *pParse,          /* Parsing context */
58279   int op,                 /* Expression opcode */
58280   Expr *pLeft,            /* Left operand */
58281   Expr *pRight,           /* Right operand */
58282   const Token *pToken     /* Argument token */
58283 ){
58284   Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
58285   if( p ){
58286     sqlite3ExprCheckHeight(pParse, p->nHeight);
58287   }
58288   return p;
58289 }
58290
58291 /*
58292 ** When doing a nested parse, you can include terms in an expression
58293 ** that look like this:   #1 #2 ...  These terms refer to registers
58294 ** in the virtual machine.  #N is the N-th register.
58295 **
58296 ** This routine is called by the parser to deal with on of those terms.
58297 ** It immediately generates code to store the value in a memory location.
58298 ** The returns an expression that will code to extract the value from
58299 ** that memory location as needed.
58300 */
58301 SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
58302   Vdbe *v = pParse->pVdbe;
58303   Expr *p;
58304   if( pParse->nested==0 ){
58305     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
58306     return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
58307   }
58308   if( v==0 ) return 0;
58309   p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
58310   if( p==0 ){
58311     return 0;  /* Malloc failed */
58312   }
58313   p->iTable = atoi((char*)&pToken->z[1]);
58314   return p;
58315 }
58316
58317 /*
58318 ** Join two expressions using an AND operator.  If either expression is
58319 ** NULL, then just return the other expression.
58320 */
58321 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
58322   if( pLeft==0 ){
58323     return pRight;
58324   }else if( pRight==0 ){
58325     return pLeft;
58326   }else{
58327     return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
58328   }
58329 }
58330
58331 /*
58332 ** Set the Expr.span field of the given expression to span all
58333 ** text between the two given tokens.  Both tokens must be pointing
58334 ** at the same string.
58335 */
58336 SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
58337   assert( pRight!=0 );
58338   assert( pLeft!=0 );
58339   if( pExpr ){
58340     pExpr->span.z = pLeft->z;
58341     pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
58342   }
58343 }
58344
58345 /*
58346 ** Construct a new expression node for a function with multiple
58347 ** arguments.
58348 */
58349 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
58350   Expr *pNew;
58351   sqlite3 *db = pParse->db;
58352   assert( pToken );
58353   pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
58354   if( pNew==0 ){
58355     sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
58356     return 0;
58357   }
58358   pNew->op = TK_FUNCTION;
58359   pNew->pList = pList;
58360   assert( pToken->dyn==0 );
58361   pNew->token = *pToken;
58362   pNew->span = pNew->token;
58363
58364   sqlite3ExprSetHeight(pParse, pNew);
58365   return pNew;
58366 }
58367
58368 /*
58369 ** Assign a variable number to an expression that encodes a wildcard
58370 ** in the original SQL statement.  
58371 **
58372 ** Wildcards consisting of a single "?" are assigned the next sequential
58373 ** variable number.
58374 **
58375 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
58376 ** sure "nnn" is not too be to avoid a denial of service attack when
58377 ** the SQL statement comes from an external source.
58378 **
58379 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
58380 ** as the previous instance of the same wildcard.  Or if this is the first
58381 ** instance of the wildcard, the next sequenial variable number is
58382 ** assigned.
58383 */
58384 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
58385   Token *pToken;
58386   sqlite3 *db = pParse->db;
58387
58388   if( pExpr==0 ) return;
58389   pToken = &pExpr->token;
58390   assert( pToken->n>=1 );
58391   assert( pToken->z!=0 );
58392   assert( pToken->z[0]!=0 );
58393   if( pToken->n==1 ){
58394     /* Wildcard of the form "?".  Assign the next variable number */
58395     pExpr->iTable = ++pParse->nVar;
58396   }else if( pToken->z[0]=='?' ){
58397     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
58398     ** use it as the variable number */
58399     int i;
58400     pExpr->iTable = i = atoi((char*)&pToken->z[1]);
58401     testcase( i==0 );
58402     testcase( i==1 );
58403     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
58404     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
58405     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
58406       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
58407           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
58408     }
58409     if( i>pParse->nVar ){
58410       pParse->nVar = i;
58411     }
58412   }else{
58413     /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
58414     ** number as the prior appearance of the same name, or if the name
58415     ** has never appeared before, reuse the same variable number
58416     */
58417     int i;
58418     u32 n;
58419     n = pToken->n;
58420     for(i=0; i<pParse->nVarExpr; i++){
58421       Expr *pE;
58422       if( (pE = pParse->apVarExpr[i])!=0
58423           && pE->token.n==n
58424           && memcmp(pE->token.z, pToken->z, n)==0 ){
58425         pExpr->iTable = pE->iTable;
58426         break;
58427       }
58428     }
58429     if( i>=pParse->nVarExpr ){
58430       pExpr->iTable = ++pParse->nVar;
58431       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
58432         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
58433         pParse->apVarExpr =
58434             sqlite3DbReallocOrFree(
58435               db,
58436               pParse->apVarExpr,
58437               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
58438             );
58439       }
58440       if( !db->mallocFailed ){
58441         assert( pParse->apVarExpr!=0 );
58442         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
58443       }
58444     }
58445   } 
58446   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
58447     sqlite3ErrorMsg(pParse, "too many SQL variables");
58448   }
58449 }
58450
58451 /*
58452 ** Clear an expression structure without deleting the structure itself.
58453 ** Substructure is deleted.
58454 */
58455 SQLITE_PRIVATE void sqlite3ExprClear(sqlite3 *db, Expr *p){
58456   if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
58457   if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
58458   sqlite3ExprDelete(db, p->pLeft);
58459   sqlite3ExprDelete(db, p->pRight);
58460   sqlite3ExprListDelete(db, p->pList);
58461   sqlite3SelectDelete(db, p->pSelect);
58462 }
58463
58464 /*
58465 ** Recursively delete an expression tree.
58466 */
58467 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
58468   if( p==0 ) return;
58469   sqlite3ExprClear(db, p);
58470   sqlite3DbFree(db, p);
58471 }
58472
58473 /*
58474 ** The Expr.token field might be a string literal that is quoted.
58475 ** If so, remove the quotation marks.
58476 */
58477 SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
58478   if( ExprHasAnyProperty(p, EP_Dequoted) ){
58479     return;
58480   }
58481   ExprSetProperty(p, EP_Dequoted);
58482   if( p->token.dyn==0 ){
58483     sqlite3TokenCopy(db, &p->token, &p->token);
58484   }
58485   sqlite3Dequote((char*)p->token.z);
58486 }
58487
58488 /*
58489 ** The following group of routines make deep copies of expressions,
58490 ** expression lists, ID lists, and select statements.  The copies can
58491 ** be deleted (by being passed to their respective ...Delete() routines)
58492 ** without effecting the originals.
58493 **
58494 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
58495 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
58496 ** by subsequent calls to sqlite*ListAppend() routines.
58497 **
58498 ** Any tables that the SrcList might point to are not duplicated.
58499 */
58500 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
58501   Expr *pNew;
58502   if( p==0 ) return 0;
58503   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
58504   if( pNew==0 ) return 0;
58505   memcpy(pNew, p, sizeof(*pNew));
58506   if( p->token.z!=0 ){
58507     pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
58508     pNew->token.dyn = 1;
58509   }else{
58510     assert( pNew->token.z==0 );
58511   }
58512   pNew->span.z = 0;
58513   pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
58514   pNew->pRight = sqlite3ExprDup(db, p->pRight);
58515   pNew->pList = sqlite3ExprListDup(db, p->pList);
58516   pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
58517   return pNew;
58518 }
58519 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
58520   if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
58521   if( pFrom->z ){
58522     pTo->n = pFrom->n;
58523     pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
58524     pTo->dyn = 1;
58525   }else{
58526     pTo->z = 0;
58527   }
58528 }
58529 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
58530   ExprList *pNew;
58531   struct ExprList_item *pItem, *pOldItem;
58532   int i;
58533   if( p==0 ) return 0;
58534   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
58535   if( pNew==0 ) return 0;
58536   pNew->iECursor = 0;
58537   pNew->nExpr = pNew->nAlloc = p->nExpr;
58538   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
58539   if( pItem==0 ){
58540     sqlite3DbFree(db, pNew);
58541     return 0;
58542   } 
58543   pOldItem = p->a;
58544   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
58545     Expr *pNewExpr, *pOldExpr;
58546     pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
58547     if( pOldExpr->span.z!=0 && pNewExpr ){
58548       /* Always make a copy of the span for top-level expressions in the
58549       ** expression list.  The logic in SELECT processing that determines
58550       ** the names of columns in the result set needs this information */
58551       sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
58552     }
58553     assert( pNewExpr==0 || pNewExpr->span.z!=0 
58554             || pOldExpr->span.z==0
58555             || db->mallocFailed );
58556     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
58557     pItem->sortOrder = pOldItem->sortOrder;
58558     pItem->done = 0;
58559     pItem->iCol = pOldItem->iCol;
58560     pItem->iAlias = pOldItem->iAlias;
58561   }
58562   return pNew;
58563 }
58564
58565 /*
58566 ** If cursors, triggers, views and subqueries are all omitted from
58567 ** the build, then none of the following routines, except for 
58568 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
58569 ** called with a NULL argument.
58570 */
58571 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
58572  || !defined(SQLITE_OMIT_SUBQUERY)
58573 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
58574   SrcList *pNew;
58575   int i;
58576   int nByte;
58577   if( p==0 ) return 0;
58578   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
58579   pNew = sqlite3DbMallocRaw(db, nByte );
58580   if( pNew==0 ) return 0;
58581   pNew->nSrc = pNew->nAlloc = p->nSrc;
58582   for(i=0; i<p->nSrc; i++){
58583     struct SrcList_item *pNewItem = &pNew->a[i];
58584     struct SrcList_item *pOldItem = &p->a[i];
58585     Table *pTab;
58586     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
58587     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
58588     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
58589     pNewItem->jointype = pOldItem->jointype;
58590     pNewItem->iCursor = pOldItem->iCursor;
58591     pNewItem->isPopulated = pOldItem->isPopulated;
58592     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
58593     pNewItem->notIndexed = pOldItem->notIndexed;
58594     pNewItem->pIndex = pOldItem->pIndex;
58595     pTab = pNewItem->pTab = pOldItem->pTab;
58596     if( pTab ){
58597       pTab->nRef++;
58598     }
58599     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
58600     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
58601     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
58602     pNewItem->colUsed = pOldItem->colUsed;
58603   }
58604   return pNew;
58605 }
58606 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
58607   IdList *pNew;
58608   int i;
58609   if( p==0 ) return 0;
58610   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
58611   if( pNew==0 ) return 0;
58612   pNew->nId = pNew->nAlloc = p->nId;
58613   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
58614   if( pNew->a==0 ){
58615     sqlite3DbFree(db, pNew);
58616     return 0;
58617   }
58618   for(i=0; i<p->nId; i++){
58619     struct IdList_item *pNewItem = &pNew->a[i];
58620     struct IdList_item *pOldItem = &p->a[i];
58621     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
58622     pNewItem->idx = pOldItem->idx;
58623   }
58624   return pNew;
58625 }
58626 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
58627   Select *pNew;
58628   if( p==0 ) return 0;
58629   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
58630   if( pNew==0 ) return 0;
58631   pNew->pEList = sqlite3ExprListDup(db, p->pEList);
58632   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
58633   pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
58634   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
58635   pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
58636   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
58637   pNew->op = p->op;
58638   pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
58639   pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
58640   pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
58641   pNew->iLimit = 0;
58642   pNew->iOffset = 0;
58643   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
58644   pNew->pRightmost = 0;
58645   pNew->addrOpenEphm[0] = -1;
58646   pNew->addrOpenEphm[1] = -1;
58647   pNew->addrOpenEphm[2] = -1;
58648   return pNew;
58649 }
58650 #else
58651 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p){
58652   assert( p==0 );
58653   return 0;
58654 }
58655 #endif
58656
58657
58658 /*
58659 ** Add a new element to the end of an expression list.  If pList is
58660 ** initially NULL, then create a new expression list.
58661 */
58662 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
58663   Parse *pParse,          /* Parsing context */
58664   ExprList *pList,        /* List to which to append. Might be NULL */
58665   Expr *pExpr,            /* Expression to be appended */
58666   Token *pName            /* AS keyword for the expression */
58667 ){
58668   sqlite3 *db = pParse->db;
58669   if( pList==0 ){
58670     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
58671     if( pList==0 ){
58672       goto no_mem;
58673     }
58674     assert( pList->nAlloc==0 );
58675   }
58676   if( pList->nAlloc<=pList->nExpr ){
58677     struct ExprList_item *a;
58678     int n = pList->nAlloc*2 + 4;
58679     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
58680     if( a==0 ){
58681       goto no_mem;
58682     }
58683     pList->a = a;
58684     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
58685   }
58686   assert( pList->a!=0 );
58687   if( pExpr || pName ){
58688     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
58689     memset(pItem, 0, sizeof(*pItem));
58690     pItem->zName = sqlite3NameFromToken(db, pName);
58691     pItem->pExpr = pExpr;
58692     pItem->iAlias = 0;
58693   }
58694   return pList;
58695
58696 no_mem:     
58697   /* Avoid leaking memory if malloc has failed. */
58698   sqlite3ExprDelete(db, pExpr);
58699   sqlite3ExprListDelete(db, pList);
58700   return 0;
58701 }
58702
58703 /*
58704 ** If the expression list pEList contains more than iLimit elements,
58705 ** leave an error message in pParse.
58706 */
58707 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
58708   Parse *pParse,
58709   ExprList *pEList,
58710   const char *zObject
58711 ){
58712   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
58713   testcase( pEList && pEList->nExpr==mx );
58714   testcase( pEList && pEList->nExpr==mx+1 );
58715   if( pEList && pEList->nExpr>mx ){
58716     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
58717   }
58718 }
58719
58720 /*
58721 ** Delete an entire expression list.
58722 */
58723 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
58724   int i;
58725   struct ExprList_item *pItem;
58726   if( pList==0 ) return;
58727   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
58728   assert( pList->nExpr<=pList->nAlloc );
58729   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
58730     sqlite3ExprDelete(db, pItem->pExpr);
58731     sqlite3DbFree(db, pItem->zName);
58732   }
58733   sqlite3DbFree(db, pList->a);
58734   sqlite3DbFree(db, pList);
58735 }
58736
58737 /*
58738 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
58739 ** to an integer.  These routines are checking an expression to see
58740 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
58741 ** not constant.
58742 **
58743 ** These callback routines are used to implement the following:
58744 **
58745 **     sqlite3ExprIsConstant()
58746 **     sqlite3ExprIsConstantNotJoin()
58747 **     sqlite3ExprIsConstantOrFunction()
58748 **
58749 */
58750 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
58751
58752   /* If pWalker->u.i is 3 then any term of the expression that comes from
58753   ** the ON or USING clauses of a join disqualifies the expression
58754   ** from being considered constant. */
58755   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
58756     pWalker->u.i = 0;
58757     return WRC_Abort;
58758   }
58759
58760   switch( pExpr->op ){
58761     /* Consider functions to be constant if all their arguments are constant
58762     ** and pWalker->u.i==2 */
58763     case TK_FUNCTION:
58764       if( pWalker->u.i==2 ) return 0;
58765       /* Fall through */
58766     case TK_ID:
58767     case TK_COLUMN:
58768     case TK_AGG_FUNCTION:
58769     case TK_AGG_COLUMN:
58770 #ifndef SQLITE_OMIT_SUBQUERY
58771     case TK_SELECT:
58772     case TK_EXISTS:
58773       testcase( pExpr->op==TK_SELECT );
58774       testcase( pExpr->op==TK_EXISTS );
58775 #endif
58776       testcase( pExpr->op==TK_ID );
58777       testcase( pExpr->op==TK_COLUMN );
58778       testcase( pExpr->op==TK_AGG_FUNCTION );
58779       testcase( pExpr->op==TK_AGG_COLUMN );
58780       pWalker->u.i = 0;
58781       return WRC_Abort;
58782     default:
58783       return WRC_Continue;
58784   }
58785 }
58786 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
58787   UNUSED_PARAMETER(NotUsed);
58788   pWalker->u.i = 0;
58789   return WRC_Abort;
58790 }
58791 static int exprIsConst(Expr *p, int initFlag){
58792   Walker w;
58793   w.u.i = initFlag;
58794   w.xExprCallback = exprNodeIsConstant;
58795   w.xSelectCallback = selectNodeIsConstant;
58796   sqlite3WalkExpr(&w, p);
58797   return w.u.i;
58798 }
58799
58800 /*
58801 ** Walk an expression tree.  Return 1 if the expression is constant
58802 ** and 0 if it involves variables or function calls.
58803 **
58804 ** For the purposes of this function, a double-quoted string (ex: "abc")
58805 ** is considered a variable but a single-quoted string (ex: 'abc') is
58806 ** a constant.
58807 */
58808 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
58809   return exprIsConst(p, 1);
58810 }
58811
58812 /*
58813 ** Walk an expression tree.  Return 1 if the expression is constant
58814 ** that does no originate from the ON or USING clauses of a join.
58815 ** Return 0 if it involves variables or function calls or terms from
58816 ** an ON or USING clause.
58817 */
58818 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
58819   return exprIsConst(p, 3);
58820 }
58821
58822 /*
58823 ** Walk an expression tree.  Return 1 if the expression is constant
58824 ** or a function call with constant arguments.  Return and 0 if there
58825 ** are any variables.
58826 **
58827 ** For the purposes of this function, a double-quoted string (ex: "abc")
58828 ** is considered a variable but a single-quoted string (ex: 'abc') is
58829 ** a constant.
58830 */
58831 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
58832   return exprIsConst(p, 2);
58833 }
58834
58835 /*
58836 ** If the expression p codes a constant integer that is small enough
58837 ** to fit in a 32-bit integer, return 1 and put the value of the integer
58838 ** in *pValue.  If the expression is not an integer or if it is too big
58839 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
58840 */
58841 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
58842   int rc = 0;
58843   if( p->flags & EP_IntValue ){
58844     *pValue = p->iTable;
58845     return 1;
58846   }
58847   switch( p->op ){
58848     case TK_INTEGER: {
58849       rc = sqlite3GetInt32((char*)p->token.z, pValue);
58850       break;
58851     }
58852     case TK_UPLUS: {
58853       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
58854       break;
58855     }
58856     case TK_UMINUS: {
58857       int v;
58858       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
58859         *pValue = -v;
58860         rc = 1;
58861       }
58862       break;
58863     }
58864     default: break;
58865   }
58866   if( rc ){
58867     p->op = TK_INTEGER;
58868     p->flags |= EP_IntValue;
58869     p->iTable = *pValue;
58870   }
58871   return rc;
58872 }
58873
58874 /*
58875 ** Return TRUE if the given string is a row-id column name.
58876 */
58877 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
58878   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
58879   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
58880   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
58881   return 0;
58882 }
58883
58884 /*
58885 ** Return true if the IN operator optimization is enabled and
58886 ** the SELECT statement p exists and is of the
58887 ** simple form:
58888 **
58889 **     SELECT <column> FROM <table>
58890 **
58891 ** If this is the case, it may be possible to use an existing table
58892 ** or index instead of generating an epheremal table.
58893 */
58894 #ifndef SQLITE_OMIT_SUBQUERY
58895 static int isCandidateForInOpt(Select *p){
58896   SrcList *pSrc;
58897   ExprList *pEList;
58898   Table *pTab;
58899   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
58900   if( p->pPrior ) return 0;              /* Not a compound SELECT */
58901   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
58902       return 0; /* No DISTINCT keyword and no aggregate functions */
58903   }
58904   if( p->pGroupBy ) return 0;            /* Has no GROUP BY clause */
58905   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
58906   if( p->pOffset ) return 0;
58907   if( p->pWhere ) return 0;              /* Has no WHERE clause */
58908   pSrc = p->pSrc;
58909   assert( pSrc!=0 );
58910   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
58911   if( pSrc->a[0].pSelect ) return 0;     /* FROM clause is not a subquery */
58912   pTab = pSrc->a[0].pTab;
58913   if( pTab==0 ) return 0;
58914   if( pTab->pSelect ) return 0;          /* FROM clause is not a view */
58915   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
58916   pEList = p->pEList;
58917   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
58918   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
58919   return 1;
58920 }
58921 #endif /* SQLITE_OMIT_SUBQUERY */
58922
58923 /*
58924 ** This function is used by the implementation of the IN (...) operator.
58925 ** It's job is to find or create a b-tree structure that may be used
58926 ** either to test for membership of the (...) set or to iterate through
58927 ** its members, skipping duplicates.
58928 **
58929 ** The cursor opened on the structure (database table, database index 
58930 ** or ephermal table) is stored in pX->iTable before this function returns.
58931 ** The returned value indicates the structure type, as follows:
58932 **
58933 **   IN_INDEX_ROWID - The cursor was opened on a database table.
58934 **   IN_INDEX_INDEX - The cursor was opened on a database index.
58935 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
58936 **                    populated epheremal table.
58937 **
58938 ** An existing structure may only be used if the SELECT is of the simple
58939 ** form:
58940 **
58941 **     SELECT <column> FROM <table>
58942 **
58943 ** If prNotFound parameter is 0, then the structure will be used to iterate
58944 ** through the set members, skipping any duplicates. In this case an
58945 ** epheremal table must be used unless the selected <column> is guaranteed
58946 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
58947 ** is unique by virtue of a constraint or implicit index.
58948 **
58949 ** If the prNotFound parameter is not 0, then the structure will be used 
58950 ** for fast set membership tests. In this case an epheremal table must 
58951 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
58952 ** be found with <column> as its left-most column.
58953 **
58954 ** When the structure is being used for set membership tests, the user
58955 ** needs to know whether or not the structure contains an SQL NULL 
58956 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
58957 ** If there is a chance that the structure may contain a NULL value at
58958 ** runtime, then a register is allocated and the register number written
58959 ** to *prNotFound. If there is no chance that the structure contains a
58960 ** NULL value, then *prNotFound is left unchanged.
58961 **
58962 ** If a register is allocated and its location stored in *prNotFound, then
58963 ** its initial value is NULL. If the structure does not remain constant
58964 ** for the duration of the query (i.e. the set is a correlated sub-select), 
58965 ** the value of the allocated register is reset to NULL each time the 
58966 ** structure is repopulated. This allows the caller to use vdbe code 
58967 ** equivalent to the following:
58968 **
58969 **   if( register==NULL ){
58970 **     has_null = <test if data structure contains null>
58971 **     register = 1
58972 **   }
58973 **
58974 ** in order to avoid running the <test if data structure contains null>
58975 ** test more often than is necessary.
58976 */
58977 #ifndef SQLITE_OMIT_SUBQUERY
58978 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
58979   Select *p;
58980   int eType = 0;
58981   int iTab = pParse->nTab++;
58982   int mustBeUnique = !prNotFound;
58983
58984   /* The follwing if(...) expression is true if the SELECT is of the 
58985   ** simple form:
58986   **
58987   **     SELECT <column> FROM <table>
58988   **
58989   ** If this is the case, it may be possible to use an existing table
58990   ** or index instead of generating an epheremal table.
58991   */
58992   p = pX->pSelect;
58993   if( isCandidateForInOpt(p) ){
58994     sqlite3 *db = pParse->db;
58995     Index *pIdx;
58996     Expr *pExpr = p->pEList->a[0].pExpr;
58997     int iCol = pExpr->iColumn;
58998     Vdbe *v = sqlite3GetVdbe(pParse);
58999
59000     /* This function is only called from two places. In both cases the vdbe
59001     ** has already been allocated. So assume sqlite3GetVdbe() is always
59002     ** successful here.
59003     */
59004     assert(v);
59005     if( iCol<0 ){
59006       int iMem = ++pParse->nMem;
59007       int iAddr;
59008       Table *pTab = p->pSrc->a[0].pTab;
59009       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59010       sqlite3VdbeUsesBtree(v, iDb);
59011
59012       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
59013       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
59014
59015       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
59016       eType = IN_INDEX_ROWID;
59017
59018       sqlite3VdbeJumpHere(v, iAddr);
59019     }else{
59020       /* The collation sequence used by the comparison. If an index is to 
59021       ** be used in place of a temp-table, it must be ordered according
59022       ** to this collation sequence.
59023       */
59024       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
59025
59026       /* Check that the affinity that will be used to perform the 
59027       ** comparison is the same as the affinity of the column. If
59028       ** it is not, it is not possible to use any index.
59029       */
59030       Table *pTab = p->pSrc->a[0].pTab;
59031       char aff = comparisonAffinity(pX);
59032       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
59033
59034       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
59035         if( (pIdx->aiColumn[0]==iCol)
59036          && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
59037          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
59038         ){
59039           int iDb;
59040           int iMem = ++pParse->nMem;
59041           int iAddr;
59042           char *pKey;
59043   
59044           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
59045           iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
59046           sqlite3VdbeUsesBtree(v, iDb);
59047
59048           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
59049           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
59050   
59051           sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
59052           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
59053                                pKey,P4_KEYINFO_HANDOFF);
59054           VdbeComment((v, "%s", pIdx->zName));
59055           eType = IN_INDEX_INDEX;
59056
59057           sqlite3VdbeJumpHere(v, iAddr);
59058           if( prNotFound && !pTab->aCol[iCol].notNull ){
59059             *prNotFound = ++pParse->nMem;
59060           }
59061         }
59062       }
59063     }
59064   }
59065
59066   if( eType==0 ){
59067     int rMayHaveNull = 0;
59068     eType = IN_INDEX_EPH;
59069     if( prNotFound ){
59070       *prNotFound = rMayHaveNull = ++pParse->nMem;
59071     }else if( pX->pLeft->iColumn<0 && pX->pSelect==0 ){
59072       eType = IN_INDEX_ROWID;
59073     }
59074     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
59075   }else{
59076     pX->iTable = iTab;
59077   }
59078   return eType;
59079 }
59080 #endif
59081
59082 /*
59083 ** Generate code for scalar subqueries used as an expression
59084 ** and IN operators.  Examples:
59085 **
59086 **     (SELECT a FROM b)          -- subquery
59087 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
59088 **     x IN (4,5,11)              -- IN operator with list on right-hand side
59089 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
59090 **
59091 ** The pExpr parameter describes the expression that contains the IN
59092 ** operator or subquery.
59093 **
59094 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
59095 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
59096 ** to some integer key column of a table B-Tree. In this case, use an
59097 ** intkey B-Tree to store the set of IN(...) values instead of the usual
59098 ** (slower) variable length keys B-Tree.
59099 */
59100 #ifndef SQLITE_OMIT_SUBQUERY
59101 SQLITE_PRIVATE void sqlite3CodeSubselect(
59102   Parse *pParse, 
59103   Expr *pExpr, 
59104   int rMayHaveNull,
59105   int isRowid
59106 ){
59107   int testAddr = 0;                       /* One-time test address */
59108   Vdbe *v = sqlite3GetVdbe(pParse);
59109   if( v==0 ) return;
59110
59111
59112   /* This code must be run in its entirety every time it is encountered
59113   ** if any of the following is true:
59114   **
59115   **    *  The right-hand side is a correlated subquery
59116   **    *  The right-hand side is an expression list containing variables
59117   **    *  We are inside a trigger
59118   **
59119   ** If all of the above are false, then we can run this code just once
59120   ** save the results, and reuse the same result on subsequent invocations.
59121   */
59122   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
59123     int mem = ++pParse->nMem;
59124     sqlite3VdbeAddOp1(v, OP_If, mem);
59125     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
59126     assert( testAddr>0 || pParse->db->mallocFailed );
59127   }
59128
59129   switch( pExpr->op ){
59130     case TK_IN: {
59131       char affinity;
59132       KeyInfo keyInfo;
59133       int addr;        /* Address of OP_OpenEphemeral instruction */
59134       Expr *pLeft = pExpr->pLeft;
59135
59136       if( rMayHaveNull ){
59137         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
59138       }
59139
59140       affinity = sqlite3ExprAffinity(pLeft);
59141
59142       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
59143       ** expression it is handled the same way. A virtual table is 
59144       ** filled with single-field index keys representing the results
59145       ** from the SELECT or the <exprlist>.
59146       **
59147       ** If the 'x' expression is a column value, or the SELECT...
59148       ** statement returns a column value, then the affinity of that
59149       ** column is used to build the index keys. If both 'x' and the
59150       ** SELECT... statement are columns, then numeric affinity is used
59151       ** if either column has NUMERIC or INTEGER affinity. If neither
59152       ** 'x' nor the SELECT... statement are columns, then numeric affinity
59153       ** is used.
59154       */
59155       pExpr->iTable = pParse->nTab++;
59156       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
59157       memset(&keyInfo, 0, sizeof(keyInfo));
59158       keyInfo.nField = 1;
59159
59160       if( pExpr->pSelect ){
59161         /* Case 1:     expr IN (SELECT ...)
59162         **
59163         ** Generate code to write the results of the select into the temporary
59164         ** table allocated and opened above.
59165         */
59166         SelectDest dest;
59167         ExprList *pEList;
59168
59169         assert( !isRowid );
59170         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
59171         dest.affinity = (u8)affinity;
59172         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
59173         if( sqlite3Select(pParse, pExpr->pSelect, &dest) ){
59174           return;
59175         }
59176         pEList = pExpr->pSelect->pEList;
59177         if( pEList && pEList->nExpr>0 ){ 
59178           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
59179               pEList->a[0].pExpr);
59180         }
59181       }else if( pExpr->pList ){
59182         /* Case 2:     expr IN (exprlist)
59183         **
59184         ** For each expression, build an index key from the evaluation and
59185         ** store it in the temporary table. If <expr> is a column, then use
59186         ** that columns affinity when building index keys. If <expr> is not
59187         ** a column, use numeric affinity.
59188         */
59189         int i;
59190         ExprList *pList = pExpr->pList;
59191         struct ExprList_item *pItem;
59192         int r1, r2, r3;
59193
59194         if( !affinity ){
59195           affinity = SQLITE_AFF_NONE;
59196         }
59197         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
59198
59199         /* Loop through each expression in <exprlist>. */
59200         r1 = sqlite3GetTempReg(pParse);
59201         r2 = sqlite3GetTempReg(pParse);
59202         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
59203         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
59204           Expr *pE2 = pItem->pExpr;
59205
59206           /* If the expression is not constant then we will need to
59207           ** disable the test that was generated above that makes sure
59208           ** this code only executes once.  Because for a non-constant
59209           ** expression we need to rerun this code each time.
59210           */
59211           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
59212             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
59213             testAddr = 0;
59214           }
59215
59216           /* Evaluate the expression and insert it into the temp table */
59217           pParse->disableColCache++;
59218           r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
59219           assert( pParse->disableColCache>0 );
59220           pParse->disableColCache--;
59221
59222           if( isRowid ){
59223             sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
59224             sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
59225           }else{
59226             sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
59227             sqlite3ExprCacheAffinityChange(pParse, r3, 1);
59228             sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
59229           }
59230         }
59231         sqlite3ReleaseTempReg(pParse, r1);
59232         sqlite3ReleaseTempReg(pParse, r2);
59233       }
59234       if( !isRowid ){
59235         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
59236       }
59237       break;
59238     }
59239
59240     case TK_EXISTS:
59241     case TK_SELECT: {
59242       /* This has to be a scalar SELECT.  Generate code to put the
59243       ** value of this select in a memory cell and record the number
59244       ** of the memory cell in iColumn.
59245       */
59246       static const Token one = { (u8*)"1", 0, 1 };
59247       Select *pSel;
59248       SelectDest dest;
59249
59250       pSel = pExpr->pSelect;
59251       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
59252       if( pExpr->op==TK_SELECT ){
59253         dest.eDest = SRT_Mem;
59254         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
59255         VdbeComment((v, "Init subquery result"));
59256       }else{
59257         dest.eDest = SRT_Exists;
59258         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
59259         VdbeComment((v, "Init EXISTS result"));
59260       }
59261       sqlite3ExprDelete(pParse->db, pSel->pLimit);
59262       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
59263       if( sqlite3Select(pParse, pSel, &dest) ){
59264         return;
59265       }
59266       pExpr->iColumn = dest.iParm;
59267       break;
59268     }
59269   }
59270
59271   if( testAddr ){
59272     sqlite3VdbeJumpHere(v, testAddr-1);
59273   }
59274
59275   return;
59276 }
59277 #endif /* SQLITE_OMIT_SUBQUERY */
59278
59279 /*
59280 ** Duplicate an 8-byte value
59281 */
59282 static char *dup8bytes(Vdbe *v, const char *in){
59283   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
59284   if( out ){
59285     memcpy(out, in, 8);
59286   }
59287   return out;
59288 }
59289
59290 /*
59291 ** Generate an instruction that will put the floating point
59292 ** value described by z[0..n-1] into register iMem.
59293 **
59294 ** The z[] string will probably not be zero-terminated.  But the 
59295 ** z[n] character is guaranteed to be something that does not look
59296 ** like the continuation of the number.
59297 */
59298 static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
59299   assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
59300   assert( !z || !sqlite3Isdigit(z[n]) );
59301   UNUSED_PARAMETER(n);
59302   if( z ){
59303     double value;
59304     char *zV;
59305     sqlite3AtoF(z, &value);
59306     if( sqlite3IsNaN(value) ){
59307       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
59308     }else{
59309       if( negateFlag ) value = -value;
59310       zV = dup8bytes(v, (char*)&value);
59311       sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
59312     }
59313   }
59314 }
59315
59316
59317 /*
59318 ** Generate an instruction that will put the integer describe by
59319 ** text z[0..n-1] into register iMem.
59320 **
59321 ** The z[] string will probably not be zero-terminated.  But the 
59322 ** z[n] character is guaranteed to be something that does not look
59323 ** like the continuation of the number.
59324 */
59325 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
59326   const char *z;
59327   if( pExpr->flags & EP_IntValue ){
59328     int i = pExpr->iTable;
59329     if( negFlag ) i = -i;
59330     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
59331   }else if( (z = (char*)pExpr->token.z)!=0 ){
59332     int i;
59333     int n = pExpr->token.n;
59334     assert( !sqlite3Isdigit(z[n]) );
59335     if( sqlite3GetInt32(z, &i) ){
59336       if( negFlag ) i = -i;
59337       sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
59338     }else if( sqlite3FitsIn64Bits(z, negFlag) ){
59339       i64 value;
59340       char *zV;
59341       sqlite3Atoi64(z, &value);
59342       if( negFlag ) value = -value;
59343       zV = dup8bytes(v, (char*)&value);
59344       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
59345     }else{
59346       codeReal(v, z, n, negFlag, iMem);
59347     }
59348   }
59349 }
59350
59351
59352 /*
59353 ** Generate code that will extract the iColumn-th column from
59354 ** table pTab and store the column value in a register.  An effort
59355 ** is made to store the column value in register iReg, but this is
59356 ** not guaranteed.  The location of the column value is returned.
59357 **
59358 ** There must be an open cursor to pTab in iTable when this routine
59359 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
59360 **
59361 ** This routine might attempt to reuse the value of the column that
59362 ** has already been loaded into a register.  The value will always
59363 ** be used if it has not undergone any affinity changes.  But if
59364 ** an affinity change has occurred, then the cached value will only be
59365 ** used if allowAffChng is true.
59366 */
59367 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
59368   Parse *pParse,   /* Parsing and code generating context */
59369   Table *pTab,     /* Description of the table we are reading from */
59370   int iColumn,     /* Index of the table column */
59371   int iTable,      /* The cursor pointing to the table */
59372   int iReg,        /* Store results here */
59373   int allowAffChng /* True if prior affinity changes are OK */
59374 ){
59375   Vdbe *v = pParse->pVdbe;
59376   int i;
59377   struct yColCache *p;
59378
59379   for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
59380     if( p->iTable==iTable && p->iColumn==iColumn
59381            && (!p->affChange || allowAffChng) ){
59382 #if 0
59383       sqlite3VdbeAddOp0(v, OP_Noop);
59384       VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
59385 #endif
59386       return p->iReg;
59387     }
59388   }  
59389   assert( v!=0 );
59390   if( iColumn<0 ){
59391     int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
59392     sqlite3VdbeAddOp2(v, op, iTable, iReg);
59393   }else if( pTab==0 ){
59394     sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
59395   }else{
59396     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
59397     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
59398     sqlite3ColumnDefault(v, pTab, iColumn);
59399 #ifndef SQLITE_OMIT_FLOATING_POINT
59400     if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
59401       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
59402     }
59403 #endif
59404   }
59405   if( pParse->disableColCache==0 ){
59406     i = pParse->iColCache;
59407     p = &pParse->aColCache[i];
59408     p->iTable = iTable;
59409     p->iColumn = iColumn;
59410     p->iReg = iReg;
59411     p->affChange = 0;
59412     i++;
59413     if( i>=ArraySize(pParse->aColCache) ) i = 0;
59414     if( i>pParse->nColCache ) pParse->nColCache = i;
59415     pParse->iColCache = i;
59416   }
59417   return iReg;
59418 }
59419
59420 /*
59421 ** Clear all column cache entries associated with the vdbe
59422 ** cursor with cursor number iTable.
59423 */
59424 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
59425   if( iTable<0 ){
59426     pParse->nColCache = 0;
59427     pParse->iColCache = 0;
59428   }else{
59429     int i;
59430     for(i=0; i<pParse->nColCache; i++){
59431       if( pParse->aColCache[i].iTable==iTable ){
59432         testcase( i==pParse->nColCache-1 );
59433         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
59434         pParse->iColCache = pParse->nColCache;
59435       }
59436     }
59437   }
59438 }
59439
59440 /*
59441 ** Record the fact that an affinity change has occurred on iCount
59442 ** registers starting with iStart.
59443 */
59444 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
59445   int iEnd = iStart + iCount - 1;
59446   int i;
59447   for(i=0; i<pParse->nColCache; i++){
59448     int r = pParse->aColCache[i].iReg;
59449     if( r>=iStart && r<=iEnd ){
59450       pParse->aColCache[i].affChange = 1;
59451     }
59452   }
59453 }
59454
59455 /*
59456 ** Generate code to move content from registers iFrom...iFrom+nReg-1
59457 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
59458 */
59459 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
59460   int i;
59461   if( iFrom==iTo ) return;
59462   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
59463   for(i=0; i<pParse->nColCache; i++){
59464     int x = pParse->aColCache[i].iReg;
59465     if( x>=iFrom && x<iFrom+nReg ){
59466       pParse->aColCache[i].iReg += iTo-iFrom;
59467     }
59468   }
59469 }
59470
59471 /*
59472 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
59473 ** over to iTo..iTo+nReg-1.
59474 */
59475 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
59476   int i;
59477   if( iFrom==iTo ) return;
59478   for(i=0; i<nReg; i++){
59479     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
59480   }
59481 }
59482
59483 /*
59484 ** Return true if any register in the range iFrom..iTo (inclusive)
59485 ** is used as part of the column cache.
59486 */
59487 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
59488   int i;
59489   for(i=0; i<pParse->nColCache; i++){
59490     int r = pParse->aColCache[i].iReg;
59491     if( r>=iFrom && r<=iTo ) return 1;
59492   }
59493   return 0;
59494 }
59495
59496 /*
59497 ** There is a value in register iReg.
59498 **
59499 ** We are going to modify the value, so we need to make sure it
59500 ** is not a cached register.  If iReg is a cached register,
59501 ** then clear the corresponding cache line.
59502 */
59503 SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse *pParse, int iReg){
59504   int i;
59505   if( usedAsColumnCache(pParse, iReg, iReg) ){
59506     for(i=0; i<pParse->nColCache; i++){
59507       if( pParse->aColCache[i].iReg==iReg ){
59508         pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
59509         pParse->iColCache = pParse->nColCache;
59510       }
59511     }
59512   }
59513 }
59514
59515 /*
59516 ** If the last instruction coded is an ephemeral copy of any of
59517 ** the registers in the nReg registers beginning with iReg, then
59518 ** convert the last instruction from OP_SCopy to OP_Copy.
59519 */
59520 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
59521   int addr;
59522   VdbeOp *pOp;
59523   Vdbe *v;
59524
59525   v = pParse->pVdbe;
59526   addr = sqlite3VdbeCurrentAddr(v);
59527   pOp = sqlite3VdbeGetOp(v, addr-1);
59528   assert( pOp || pParse->db->mallocFailed );
59529   if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
59530     pOp->opcode = OP_Copy;
59531   }
59532 }
59533
59534 /*
59535 ** Generate code to store the value of the iAlias-th alias in register
59536 ** target.  The first time this is called, pExpr is evaluated to compute
59537 ** the value of the alias.  The value is stored in an auxiliary register
59538 ** and the number of that register is returned.  On subsequent calls,
59539 ** the register number is returned without generating any code.
59540 **
59541 ** Note that in order for this to work, code must be generated in the
59542 ** same order that it is executed.
59543 **
59544 ** Aliases are numbered starting with 1.  So iAlias is in the range
59545 ** of 1 to pParse->nAlias inclusive.  
59546 **
59547 ** pParse->aAlias[iAlias-1] records the register number where the value
59548 ** of the iAlias-th alias is stored.  If zero, that means that the
59549 ** alias has not yet been computed.
59550 */
59551 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
59552   sqlite3 *db = pParse->db;
59553   int iReg;
59554   if( pParse->nAliasAlloc<pParse->nAlias ){
59555     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
59556                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
59557     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
59558     if( db->mallocFailed ) return 0;
59559     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
59560            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
59561     pParse->nAliasAlloc = pParse->nAlias;
59562   }
59563   assert( iAlias>0 && iAlias<=pParse->nAlias );
59564   iReg = pParse->aAlias[iAlias-1];
59565   if( iReg==0 ){
59566     if( pParse->disableColCache ){
59567       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
59568     }else{
59569       iReg = ++pParse->nMem;
59570       sqlite3ExprCode(pParse, pExpr, iReg);
59571       pParse->aAlias[iAlias-1] = iReg;
59572     }
59573   }
59574   return iReg;
59575 }
59576
59577 /*
59578 ** Generate code into the current Vdbe to evaluate the given
59579 ** expression.  Attempt to store the results in register "target".
59580 ** Return the register where results are stored.
59581 **
59582 ** With this routine, there is no guarantee that results will
59583 ** be stored in target.  The result might be stored in some other
59584 ** register if it is convenient to do so.  The calling function
59585 ** must check the return code and move the results to the desired
59586 ** register.
59587 */
59588 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
59589   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
59590   int op;                   /* The opcode being coded */
59591   int inReg = target;       /* Results stored in register inReg */
59592   int regFree1 = 0;         /* If non-zero free this temporary register */
59593   int regFree2 = 0;         /* If non-zero free this temporary register */
59594   int r1, r2, r3, r4;       /* Various register numbers */
59595   sqlite3 *db;
59596
59597   db = pParse->db;
59598   assert( v!=0 || db->mallocFailed );
59599   assert( target>0 && target<=pParse->nMem );
59600   if( v==0 ) return 0;
59601
59602   if( pExpr==0 ){
59603     op = TK_NULL;
59604   }else{
59605     op = pExpr->op;
59606   }
59607   switch( op ){
59608     case TK_AGG_COLUMN: {
59609       AggInfo *pAggInfo = pExpr->pAggInfo;
59610       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
59611       if( !pAggInfo->directMode ){
59612         assert( pCol->iMem>0 );
59613         inReg = pCol->iMem;
59614         break;
59615       }else if( pAggInfo->useSortingIdx ){
59616         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
59617                               pCol->iSorterColumn, target);
59618         break;
59619       }
59620       /* Otherwise, fall thru into the TK_COLUMN case */
59621     }
59622     case TK_COLUMN: {
59623       if( pExpr->iTable<0 ){
59624         /* This only happens when coding check constraints */
59625         assert( pParse->ckBase>0 );
59626         inReg = pExpr->iColumn + pParse->ckBase;
59627       }else{
59628         testcase( (pExpr->flags & EP_AnyAff)!=0 );
59629         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
59630                                  pExpr->iColumn, pExpr->iTable, target,
59631                                  pExpr->flags & EP_AnyAff);
59632       }
59633       break;
59634     }
59635     case TK_INTEGER: {
59636       codeInteger(v, pExpr, 0, target);
59637       break;
59638     }
59639     case TK_FLOAT: {
59640       codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
59641       break;
59642     }
59643     case TK_STRING: {
59644       sqlite3DequoteExpr(db, pExpr);
59645       sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
59646                         (char*)pExpr->token.z, pExpr->token.n);
59647       break;
59648     }
59649     case TK_NULL: {
59650       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
59651       break;
59652     }
59653 #ifndef SQLITE_OMIT_BLOB_LITERAL
59654     case TK_BLOB: {
59655       int n;
59656       const char *z;
59657       char *zBlob;
59658       assert( pExpr->token.n>=3 );
59659       assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
59660       assert( pExpr->token.z[1]=='\'' );
59661       assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
59662       n = pExpr->token.n - 3;
59663       z = (char*)pExpr->token.z + 2;
59664       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
59665       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
59666       break;
59667     }
59668 #endif
59669     case TK_VARIABLE: {
59670       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
59671       if( pExpr->token.n>1 ){
59672         sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
59673       }
59674       break;
59675     }
59676     case TK_REGISTER: {
59677       inReg = pExpr->iTable;
59678       break;
59679     }
59680     case TK_AS: {
59681       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
59682       break;
59683     }
59684 #ifndef SQLITE_OMIT_CAST
59685     case TK_CAST: {
59686       /* Expressions of the form:   CAST(pLeft AS token) */
59687       int aff, to_op;
59688       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
59689       aff = sqlite3AffinityType(&pExpr->token);
59690       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
59691       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
59692       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
59693       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
59694       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
59695       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
59696       testcase( to_op==OP_ToText );
59697       testcase( to_op==OP_ToBlob );
59698       testcase( to_op==OP_ToNumeric );
59699       testcase( to_op==OP_ToInt );
59700       testcase( to_op==OP_ToReal );
59701       if( inReg!=target ){
59702         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
59703         inReg = target;
59704       }
59705       sqlite3VdbeAddOp1(v, to_op, inReg);
59706       testcase( usedAsColumnCache(pParse, inReg, inReg) );
59707       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
59708       break;
59709     }
59710 #endif /* SQLITE_OMIT_CAST */
59711     case TK_LT:
59712     case TK_LE:
59713     case TK_GT:
59714     case TK_GE:
59715     case TK_NE:
59716     case TK_EQ: {
59717       assert( TK_LT==OP_Lt );
59718       assert( TK_LE==OP_Le );
59719       assert( TK_GT==OP_Gt );
59720       assert( TK_GE==OP_Ge );
59721       assert( TK_EQ==OP_Eq );
59722       assert( TK_NE==OP_Ne );
59723       testcase( op==TK_LT );
59724       testcase( op==TK_LE );
59725       testcase( op==TK_GT );
59726       testcase( op==TK_GE );
59727       testcase( op==TK_EQ );
59728       testcase( op==TK_NE );
59729       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
59730                                   pExpr->pRight, &r2, &regFree2);
59731       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
59732                   r1, r2, inReg, SQLITE_STOREP2);
59733       testcase( regFree1==0 );
59734       testcase( regFree2==0 );
59735       break;
59736     }
59737     case TK_AND:
59738     case TK_OR:
59739     case TK_PLUS:
59740     case TK_STAR:
59741     case TK_MINUS:
59742     case TK_REM:
59743     case TK_BITAND:
59744     case TK_BITOR:
59745     case TK_SLASH:
59746     case TK_LSHIFT:
59747     case TK_RSHIFT: 
59748     case TK_CONCAT: {
59749       assert( TK_AND==OP_And );
59750       assert( TK_OR==OP_Or );
59751       assert( TK_PLUS==OP_Add );
59752       assert( TK_MINUS==OP_Subtract );
59753       assert( TK_REM==OP_Remainder );
59754       assert( TK_BITAND==OP_BitAnd );
59755       assert( TK_BITOR==OP_BitOr );
59756       assert( TK_SLASH==OP_Divide );
59757       assert( TK_LSHIFT==OP_ShiftLeft );
59758       assert( TK_RSHIFT==OP_ShiftRight );
59759       assert( TK_CONCAT==OP_Concat );
59760       testcase( op==TK_AND );
59761       testcase( op==TK_OR );
59762       testcase( op==TK_PLUS );
59763       testcase( op==TK_MINUS );
59764       testcase( op==TK_REM );
59765       testcase( op==TK_BITAND );
59766       testcase( op==TK_BITOR );
59767       testcase( op==TK_SLASH );
59768       testcase( op==TK_LSHIFT );
59769       testcase( op==TK_RSHIFT );
59770       testcase( op==TK_CONCAT );
59771       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
59772       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
59773       sqlite3VdbeAddOp3(v, op, r2, r1, target);
59774       testcase( regFree1==0 );
59775       testcase( regFree2==0 );
59776       break;
59777     }
59778     case TK_UMINUS: {
59779       Expr *pLeft = pExpr->pLeft;
59780       assert( pLeft );
59781       if( pLeft->op==TK_FLOAT ){
59782         codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
59783       }else if( pLeft->op==TK_INTEGER ){
59784         codeInteger(v, pLeft, 1, target);
59785       }else{
59786         regFree1 = r1 = sqlite3GetTempReg(pParse);
59787         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
59788         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
59789         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
59790         testcase( regFree2==0 );
59791       }
59792       inReg = target;
59793       break;
59794     }
59795     case TK_BITNOT:
59796     case TK_NOT: {
59797       assert( TK_BITNOT==OP_BitNot );
59798       assert( TK_NOT==OP_Not );
59799       testcase( op==TK_BITNOT );
59800       testcase( op==TK_NOT );
59801       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
59802       testcase( regFree1==0 );
59803       inReg = target;
59804       sqlite3VdbeAddOp2(v, op, r1, inReg);
59805       break;
59806     }
59807     case TK_ISNULL:
59808     case TK_NOTNULL: {
59809       int addr;
59810       assert( TK_ISNULL==OP_IsNull );
59811       assert( TK_NOTNULL==OP_NotNull );
59812       testcase( op==TK_ISNULL );
59813       testcase( op==TK_NOTNULL );
59814       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
59815       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
59816       testcase( regFree1==0 );
59817       addr = sqlite3VdbeAddOp1(v, op, r1);
59818       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
59819       sqlite3VdbeJumpHere(v, addr);
59820       break;
59821     }
59822     case TK_AGG_FUNCTION: {
59823       AggInfo *pInfo = pExpr->pAggInfo;
59824       if( pInfo==0 ){
59825         sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
59826             &pExpr->span);
59827       }else{
59828         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
59829       }
59830       break;
59831     }
59832     case TK_CONST_FUNC:
59833     case TK_FUNCTION: {
59834       ExprList *pList = pExpr->pList;
59835       int nExpr = pList ? pList->nExpr : 0;
59836       FuncDef *pDef;
59837       int nId;
59838       const char *zId;
59839       int constMask = 0;
59840       int i;
59841       u8 enc = ENC(db);
59842       CollSeq *pColl = 0;
59843
59844       testcase( op==TK_CONST_FUNC );
59845       testcase( op==TK_FUNCTION );
59846       zId = (char*)pExpr->token.z;
59847       nId = pExpr->token.n;
59848       pDef = sqlite3FindFunction(db, zId, nId, nExpr, enc, 0);
59849       assert( pDef!=0 );
59850       if( pList ){
59851         nExpr = pList->nExpr;
59852         r1 = sqlite3GetTempRange(pParse, nExpr);
59853         sqlite3ExprCodeExprList(pParse, pList, r1, 1);
59854       }else{
59855         nExpr = r1 = 0;
59856       }
59857 #ifndef SQLITE_OMIT_VIRTUALTABLE
59858       /* Possibly overload the function if the first argument is
59859       ** a virtual table column.
59860       **
59861       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
59862       ** second argument, not the first, as the argument to test to
59863       ** see if it is a column in a virtual table.  This is done because
59864       ** the left operand of infix functions (the operand we want to
59865       ** control overloading) ends up as the second argument to the
59866       ** function.  The expression "A glob B" is equivalent to 
59867       ** "glob(B,A).  We want to use the A in "A glob B" to test
59868       ** for function overloading.  But we use the B term in "glob(B,A)".
59869       */
59870       if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
59871         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
59872       }else if( nExpr>0 ){
59873         pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
59874       }
59875 #endif
59876       for(i=0; i<nExpr && i<32; i++){
59877         if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
59878           constMask |= (1<<i);
59879         }
59880         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
59881           pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
59882         }
59883       }
59884       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
59885         if( !pColl ) pColl = db->pDfltColl; 
59886         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
59887       }
59888       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
59889                         (char*)pDef, P4_FUNCDEF);
59890       sqlite3VdbeChangeP5(v, (u8)nExpr);
59891       if( nExpr ){
59892         sqlite3ReleaseTempRange(pParse, r1, nExpr);
59893       }
59894       sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
59895       break;
59896     }
59897 #ifndef SQLITE_OMIT_SUBQUERY
59898     case TK_EXISTS:
59899     case TK_SELECT: {
59900       testcase( op==TK_EXISTS );
59901       testcase( op==TK_SELECT );
59902       if( pExpr->iColumn==0 ){
59903         sqlite3CodeSubselect(pParse, pExpr, 0, 0);
59904       }
59905       inReg = pExpr->iColumn;
59906       break;
59907     }
59908     case TK_IN: {
59909       int rNotFound = 0;
59910       int rMayHaveNull = 0;
59911       int j2, j3, j4, j5;
59912       char affinity;
59913       int eType;
59914
59915       VdbeNoopComment((v, "begin IN expr r%d", target));
59916       eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
59917       if( rMayHaveNull ){
59918         rNotFound = ++pParse->nMem;
59919       }
59920
59921       /* Figure out the affinity to use to create a key from the results
59922       ** of the expression. affinityStr stores a static string suitable for
59923       ** P4 of OP_MakeRecord.
59924       */
59925       affinity = comparisonAffinity(pExpr);
59926
59927
59928       /* Code the <expr> from "<expr> IN (...)". The temporary table
59929       ** pExpr->iTable contains the values that make up the (...) set.
59930       */
59931       pParse->disableColCache++;
59932       sqlite3ExprCode(pParse, pExpr->pLeft, target);
59933       pParse->disableColCache--;
59934       j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
59935       if( eType==IN_INDEX_ROWID ){
59936         j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
59937         j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
59938         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
59939         j5 = sqlite3VdbeAddOp0(v, OP_Goto);
59940         sqlite3VdbeJumpHere(v, j3);
59941         sqlite3VdbeJumpHere(v, j4);
59942         sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
59943       }else{
59944         r2 = regFree2 = sqlite3GetTempReg(pParse);
59945
59946         /* Create a record and test for set membership. If the set contains
59947         ** the value, then jump to the end of the test code. The target
59948         ** register still contains the true (1) value written to it earlier.
59949         */
59950         sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
59951         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
59952         j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
59953
59954         /* If the set membership test fails, then the result of the 
59955         ** "x IN (...)" expression must be either 0 or NULL. If the set
59956         ** contains no NULL values, then the result is 0. If the set 
59957         ** contains one or more NULL values, then the result of the
59958         ** expression is also NULL.
59959         */
59960         if( rNotFound==0 ){
59961           /* This branch runs if it is known at compile time (now) that 
59962           ** the set contains no NULL values. This happens as the result
59963           ** of a "NOT NULL" constraint in the database schema. No need
59964           ** to test the data structure at runtime in this case.
59965           */
59966           sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
59967         }else{
59968           /* This block populates the rNotFound register with either NULL
59969           ** or 0 (an integer value). If the data structure contains one
59970           ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
59971           ** to 0. If register rMayHaveNull is already set to some value
59972           ** other than NULL, then the test has already been run and 
59973           ** rNotFound is already populated.
59974           */
59975           static const char nullRecord[] = { 0x02, 0x00 };
59976           j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
59977           sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
59978           sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, 
59979                              nullRecord, P4_STATIC);
59980           j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
59981           sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
59982           sqlite3VdbeJumpHere(v, j4);
59983           sqlite3VdbeJumpHere(v, j3);
59984
59985           /* Copy the value of register rNotFound (which is either NULL or 0)
59986           ** into the target register. This will be the result of the
59987           ** expression.
59988           */
59989           sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
59990         }
59991       }
59992       sqlite3VdbeJumpHere(v, j2);
59993       sqlite3VdbeJumpHere(v, j5);
59994       VdbeComment((v, "end IN expr r%d", target));
59995       break;
59996     }
59997 #endif
59998     /*
59999     **    x BETWEEN y AND z
60000     **
60001     ** This is equivalent to
60002     **
60003     **    x>=y AND x<=z
60004     **
60005     ** X is stored in pExpr->pLeft.
60006     ** Y is stored in pExpr->pList->a[0].pExpr.
60007     ** Z is stored in pExpr->pList->a[1].pExpr.
60008     */
60009     case TK_BETWEEN: {
60010       Expr *pLeft = pExpr->pLeft;
60011       struct ExprList_item *pLItem = pExpr->pList->a;
60012       Expr *pRight = pLItem->pExpr;
60013
60014       codeCompareOperands(pParse, pLeft, &r1, &regFree1,
60015                                   pRight, &r2, &regFree2);
60016       testcase( regFree1==0 );
60017       testcase( regFree2==0 );
60018       r3 = sqlite3GetTempReg(pParse);
60019       r4 = sqlite3GetTempReg(pParse);
60020       codeCompare(pParse, pLeft, pRight, OP_Ge,
60021                   r1, r2, r3, SQLITE_STOREP2);
60022       pLItem++;
60023       pRight = pLItem->pExpr;
60024       sqlite3ReleaseTempReg(pParse, regFree2);
60025       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
60026       testcase( regFree2==0 );
60027       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
60028       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
60029       sqlite3ReleaseTempReg(pParse, r3);
60030       sqlite3ReleaseTempReg(pParse, r4);
60031       break;
60032     }
60033     case TK_UPLUS: {
60034       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
60035       break;
60036     }
60037
60038     /*
60039     ** Form A:
60040     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
60041     **
60042     ** Form B:
60043     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
60044     **
60045     ** Form A is can be transformed into the equivalent form B as follows:
60046     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
60047     **        WHEN x=eN THEN rN ELSE y END
60048     **
60049     ** X (if it exists) is in pExpr->pLeft.
60050     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
60051     ** ELSE clause and no other term matches, then the result of the
60052     ** exprssion is NULL.
60053     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
60054     **
60055     ** The result of the expression is the Ri for the first matching Ei,
60056     ** or if there is no matching Ei, the ELSE term Y, or if there is
60057     ** no ELSE term, NULL.
60058     */
60059     case TK_CASE: {
60060       int endLabel;                     /* GOTO label for end of CASE stmt */
60061       int nextCase;                     /* GOTO label for next WHEN clause */
60062       int nExpr;                        /* 2x number of WHEN terms */
60063       int i;                            /* Loop counter */
60064       ExprList *pEList;                 /* List of WHEN terms */
60065       struct ExprList_item *aListelem;  /* Array of WHEN terms */
60066       Expr opCompare;                   /* The X==Ei expression */
60067       Expr cacheX;                      /* Cached expression X */
60068       Expr *pX;                         /* The X expression */
60069       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
60070
60071       assert(pExpr->pList);
60072       assert((pExpr->pList->nExpr % 2) == 0);
60073       assert(pExpr->pList->nExpr > 0);
60074       pEList = pExpr->pList;
60075       aListelem = pEList->a;
60076       nExpr = pEList->nExpr;
60077       endLabel = sqlite3VdbeMakeLabel(v);
60078       if( (pX = pExpr->pLeft)!=0 ){
60079         cacheX = *pX;
60080         testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
60081         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
60082         testcase( regFree1==0 );
60083         cacheX.op = TK_REGISTER;
60084         opCompare.op = TK_EQ;
60085         opCompare.pLeft = &cacheX;
60086         pTest = &opCompare;
60087       }
60088       pParse->disableColCache++;
60089       for(i=0; i<nExpr; i=i+2){
60090         if( pX ){
60091           assert( pTest!=0 );
60092           opCompare.pRight = aListelem[i].pExpr;
60093         }else{
60094           pTest = aListelem[i].pExpr;
60095         }
60096         nextCase = sqlite3VdbeMakeLabel(v);
60097         testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
60098         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
60099         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
60100         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
60101         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
60102         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
60103         sqlite3VdbeResolveLabel(v, nextCase);
60104       }
60105       if( pExpr->pRight ){
60106         sqlite3ExprCode(pParse, pExpr->pRight, target);
60107       }else{
60108         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
60109       }
60110       sqlite3VdbeResolveLabel(v, endLabel);
60111       assert( pParse->disableColCache>0 );
60112       pParse->disableColCache--;
60113       break;
60114     }
60115 #ifndef SQLITE_OMIT_TRIGGER
60116     case TK_RAISE: {
60117       if( !pParse->trigStack ){
60118         sqlite3ErrorMsg(pParse,
60119                        "RAISE() may only be used within a trigger-program");
60120         return 0;
60121       }
60122       if( pExpr->iColumn!=OE_Ignore ){
60123          assert( pExpr->iColumn==OE_Rollback ||
60124                  pExpr->iColumn == OE_Abort ||
60125                  pExpr->iColumn == OE_Fail );
60126          sqlite3DequoteExpr(db, pExpr);
60127          sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
60128                         (char*)pExpr->token.z, pExpr->token.n);
60129       } else {
60130          assert( pExpr->iColumn == OE_Ignore );
60131          sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
60132          sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
60133          VdbeComment((v, "raise(IGNORE)"));
60134       }
60135       break;
60136     }
60137 #endif
60138   }
60139   sqlite3ReleaseTempReg(pParse, regFree1);
60140   sqlite3ReleaseTempReg(pParse, regFree2);
60141   return inReg;
60142 }
60143
60144 /*
60145 ** Generate code to evaluate an expression and store the results
60146 ** into a register.  Return the register number where the results
60147 ** are stored.
60148 **
60149 ** If the register is a temporary register that can be deallocated,
60150 ** then write its number into *pReg.  If the result register is not
60151 ** a temporary, then set *pReg to zero.
60152 */
60153 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
60154   int r1 = sqlite3GetTempReg(pParse);
60155   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
60156   if( r2==r1 ){
60157     *pReg = r1;
60158   }else{
60159     sqlite3ReleaseTempReg(pParse, r1);
60160     *pReg = 0;
60161   }
60162   return r2;
60163 }
60164
60165 /*
60166 ** Generate code that will evaluate expression pExpr and store the
60167 ** results in register target.  The results are guaranteed to appear
60168 ** in register target.
60169 */
60170 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
60171   int inReg;
60172
60173   assert( target>0 && target<=pParse->nMem );
60174   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
60175   assert( pParse->pVdbe || pParse->db->mallocFailed );
60176   if( inReg!=target && pParse->pVdbe ){
60177     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
60178   }
60179   return target;
60180 }
60181
60182 /*
60183 ** Generate code that evalutes the given expression and puts the result
60184 ** in register target.
60185 **
60186 ** Also make a copy of the expression results into another "cache" register
60187 ** and modify the expression so that the next time it is evaluated,
60188 ** the result is a copy of the cache register.
60189 **
60190 ** This routine is used for expressions that are used multiple 
60191 ** times.  They are evaluated once and the results of the expression
60192 ** are reused.
60193 */
60194 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
60195   Vdbe *v = pParse->pVdbe;
60196   int inReg;
60197   inReg = sqlite3ExprCode(pParse, pExpr, target);
60198   assert( target>0 );
60199   if( pExpr->op!=TK_REGISTER ){  
60200     int iMem;
60201     iMem = ++pParse->nMem;
60202     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
60203     pExpr->iTable = iMem;
60204     pExpr->op = TK_REGISTER;
60205   }
60206   return inReg;
60207 }
60208
60209 /*
60210 ** Return TRUE if pExpr is an constant expression that is appropriate
60211 ** for factoring out of a loop.  Appropriate expressions are:
60212 **
60213 **    *  Any expression that evaluates to two or more opcodes.
60214 **
60215 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
60216 **       or OP_Variable that does not need to be placed in a 
60217 **       specific register.
60218 **
60219 ** There is no point in factoring out single-instruction constant
60220 ** expressions that need to be placed in a particular register.  
60221 ** We could factor them out, but then we would end up adding an
60222 ** OP_SCopy instruction to move the value into the correct register
60223 ** later.  We might as well just use the original instruction and
60224 ** avoid the OP_SCopy.
60225 */
60226 static int isAppropriateForFactoring(Expr *p){
60227   if( !sqlite3ExprIsConstantNotJoin(p) ){
60228     return 0;  /* Only constant expressions are appropriate for factoring */
60229   }
60230   if( (p->flags & EP_FixedDest)==0 ){
60231     return 1;  /* Any constant without a fixed destination is appropriate */
60232   }
60233   while( p->op==TK_UPLUS ) p = p->pLeft;
60234   switch( p->op ){
60235 #ifndef SQLITE_OMIT_BLOB_LITERAL
60236     case TK_BLOB:
60237 #endif
60238     case TK_VARIABLE:
60239     case TK_INTEGER:
60240     case TK_FLOAT:
60241     case TK_NULL:
60242     case TK_STRING: {
60243       testcase( p->op==TK_BLOB );
60244       testcase( p->op==TK_VARIABLE );
60245       testcase( p->op==TK_INTEGER );
60246       testcase( p->op==TK_FLOAT );
60247       testcase( p->op==TK_NULL );
60248       testcase( p->op==TK_STRING );
60249       /* Single-instruction constants with a fixed destination are
60250       ** better done in-line.  If we factor them, they will just end
60251       ** up generating an OP_SCopy to move the value to the destination
60252       ** register. */
60253       return 0;
60254     }
60255     case TK_UMINUS: {
60256        if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
60257          return 0;
60258        }
60259        break;
60260     }
60261     default: {
60262       break;
60263     }
60264   }
60265   return 1;
60266 }
60267
60268 /*
60269 ** If pExpr is a constant expression that is appropriate for
60270 ** factoring out of a loop, then evaluate the expression
60271 ** into a register and convert the expression into a TK_REGISTER
60272 ** expression.
60273 */
60274 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
60275   Parse *pParse = pWalker->pParse;
60276   switch( pExpr->op ){
60277     case TK_REGISTER: {
60278       return 1;
60279     }
60280     case TK_FUNCTION:
60281     case TK_AGG_FUNCTION:
60282     case TK_CONST_FUNC: {
60283       /* The arguments to a function have a fixed destination.
60284       ** Mark them this way to avoid generated unneeded OP_SCopy
60285       ** instructions. 
60286       */
60287       ExprList *pList = pExpr->pList;
60288       if( pList ){
60289         int i = pList->nExpr;
60290         struct ExprList_item *pItem = pList->a;
60291         for(; i>0; i--, pItem++){
60292           if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
60293         }
60294       }
60295       break;
60296     }
60297   }
60298   if( isAppropriateForFactoring(pExpr) ){
60299     int r1 = ++pParse->nMem;
60300     int r2;
60301     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
60302     if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
60303     pExpr->op = TK_REGISTER;
60304     pExpr->iTable = r2;
60305     return WRC_Prune;
60306   }
60307   return WRC_Continue;
60308 }
60309
60310 /*
60311 ** Preevaluate constant subexpressions within pExpr and store the
60312 ** results in registers.  Modify pExpr so that the constant subexpresions
60313 ** are TK_REGISTER opcodes that refer to the precomputed values.
60314 */
60315 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
60316   Walker w;
60317   w.xExprCallback = evalConstExpr;
60318   w.xSelectCallback = 0;
60319   w.pParse = pParse;
60320   sqlite3WalkExpr(&w, pExpr);
60321 }
60322
60323
60324 /*
60325 ** Generate code that pushes the value of every element of the given
60326 ** expression list into a sequence of registers beginning at target.
60327 **
60328 ** Return the number of elements evaluated.
60329 */
60330 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
60331   Parse *pParse,     /* Parsing context */
60332   ExprList *pList,   /* The expression list to be coded */
60333   int target,        /* Where to write results */
60334   int doHardCopy     /* Make a hard copy of every element */
60335 ){
60336   struct ExprList_item *pItem;
60337   int i, n;
60338   assert( pList!=0 );
60339   assert( target>0 );
60340   n = pList->nExpr;
60341   for(pItem=pList->a, i=0; i<n; i++, pItem++){
60342     if( pItem->iAlias ){
60343       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
60344       Vdbe *v = sqlite3GetVdbe(pParse);
60345       if( iReg!=target+i ){
60346         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
60347       }
60348     }else{
60349       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
60350     }
60351     if( doHardCopy ){
60352       sqlite3ExprHardCopy(pParse, target, n);
60353     }
60354   }
60355   return n;
60356 }
60357
60358 /*
60359 ** Generate code for a boolean expression such that a jump is made
60360 ** to the label "dest" if the expression is true but execution
60361 ** continues straight thru if the expression is false.
60362 **
60363 ** If the expression evaluates to NULL (neither true nor false), then
60364 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
60365 **
60366 ** This code depends on the fact that certain token values (ex: TK_EQ)
60367 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
60368 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
60369 ** the make process cause these values to align.  Assert()s in the code
60370 ** below verify that the numbers are aligned correctly.
60371 */
60372 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
60373   Vdbe *v = pParse->pVdbe;
60374   int op = 0;
60375   int regFree1 = 0;
60376   int regFree2 = 0;
60377   int r1, r2;
60378
60379   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
60380   if( v==0 || pExpr==0 ) return;
60381   op = pExpr->op;
60382   switch( op ){
60383     case TK_AND: {
60384       int d2 = sqlite3VdbeMakeLabel(v);
60385       testcase( jumpIfNull==0 );
60386       testcase( pParse->disableColCache==0 );
60387       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
60388       pParse->disableColCache++;
60389       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
60390       assert( pParse->disableColCache>0 );
60391       pParse->disableColCache--;
60392       sqlite3VdbeResolveLabel(v, d2);
60393       break;
60394     }
60395     case TK_OR: {
60396       testcase( jumpIfNull==0 );
60397       testcase( pParse->disableColCache==0 );
60398       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
60399       pParse->disableColCache++;
60400       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
60401       assert( pParse->disableColCache>0 );
60402       pParse->disableColCache--;
60403       break;
60404     }
60405     case TK_NOT: {
60406       testcase( jumpIfNull==0 );
60407       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
60408       break;
60409     }
60410     case TK_LT:
60411     case TK_LE:
60412     case TK_GT:
60413     case TK_GE:
60414     case TK_NE:
60415     case TK_EQ: {
60416       assert( TK_LT==OP_Lt );
60417       assert( TK_LE==OP_Le );
60418       assert( TK_GT==OP_Gt );
60419       assert( TK_GE==OP_Ge );
60420       assert( TK_EQ==OP_Eq );
60421       assert( TK_NE==OP_Ne );
60422       testcase( op==TK_LT );
60423       testcase( op==TK_LE );
60424       testcase( op==TK_GT );
60425       testcase( op==TK_GE );
60426       testcase( op==TK_EQ );
60427       testcase( op==TK_NE );
60428       testcase( jumpIfNull==0 );
60429       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
60430                                   pExpr->pRight, &r2, &regFree2);
60431       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
60432                   r1, r2, dest, jumpIfNull);
60433       testcase( regFree1==0 );
60434       testcase( regFree2==0 );
60435       break;
60436     }
60437     case TK_ISNULL:
60438     case TK_NOTNULL: {
60439       assert( TK_ISNULL==OP_IsNull );
60440       assert( TK_NOTNULL==OP_NotNull );
60441       testcase( op==TK_ISNULL );
60442       testcase( op==TK_NOTNULL );
60443       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
60444       sqlite3VdbeAddOp2(v, op, r1, dest);
60445       testcase( regFree1==0 );
60446       break;
60447     }
60448     case TK_BETWEEN: {
60449       /*    x BETWEEN y AND z
60450       **
60451       ** Is equivalent to 
60452       **
60453       **    x>=y AND x<=z
60454       **
60455       ** Code it as such, taking care to do the common subexpression
60456       ** elementation of x.
60457       */
60458       Expr exprAnd;
60459       Expr compLeft;
60460       Expr compRight;
60461       Expr exprX;
60462
60463       exprX = *pExpr->pLeft;
60464       exprAnd.op = TK_AND;
60465       exprAnd.pLeft = &compLeft;
60466       exprAnd.pRight = &compRight;
60467       compLeft.op = TK_GE;
60468       compLeft.pLeft = &exprX;
60469       compLeft.pRight = pExpr->pList->a[0].pExpr;
60470       compRight.op = TK_LE;
60471       compRight.pLeft = &exprX;
60472       compRight.pRight = pExpr->pList->a[1].pExpr;
60473       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
60474       testcase( regFree1==0 );
60475       exprX.op = TK_REGISTER;
60476       testcase( jumpIfNull==0 );
60477       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
60478       break;
60479     }
60480     default: {
60481       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
60482       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
60483       testcase( regFree1==0 );
60484       testcase( jumpIfNull==0 );
60485       break;
60486     }
60487   }
60488   sqlite3ReleaseTempReg(pParse, regFree1);
60489   sqlite3ReleaseTempReg(pParse, regFree2);  
60490 }
60491
60492 /*
60493 ** Generate code for a boolean expression such that a jump is made
60494 ** to the label "dest" if the expression is false but execution
60495 ** continues straight thru if the expression is true.
60496 **
60497 ** If the expression evaluates to NULL (neither true nor false) then
60498 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
60499 ** is 0.
60500 */
60501 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
60502   Vdbe *v = pParse->pVdbe;
60503   int op = 0;
60504   int regFree1 = 0;
60505   int regFree2 = 0;
60506   int r1, r2;
60507
60508   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
60509   if( v==0 || pExpr==0 ) return;
60510
60511   /* The value of pExpr->op and op are related as follows:
60512   **
60513   **       pExpr->op            op
60514   **       ---------          ----------
60515   **       TK_ISNULL          OP_NotNull
60516   **       TK_NOTNULL         OP_IsNull
60517   **       TK_NE              OP_Eq
60518   **       TK_EQ              OP_Ne
60519   **       TK_GT              OP_Le
60520   **       TK_LE              OP_Gt
60521   **       TK_GE              OP_Lt
60522   **       TK_LT              OP_Ge
60523   **
60524   ** For other values of pExpr->op, op is undefined and unused.
60525   ** The value of TK_ and OP_ constants are arranged such that we
60526   ** can compute the mapping above using the following expression.
60527   ** Assert()s verify that the computation is correct.
60528   */
60529   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
60530
60531   /* Verify correct alignment of TK_ and OP_ constants
60532   */
60533   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
60534   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
60535   assert( pExpr->op!=TK_NE || op==OP_Eq );
60536   assert( pExpr->op!=TK_EQ || op==OP_Ne );
60537   assert( pExpr->op!=TK_LT || op==OP_Ge );
60538   assert( pExpr->op!=TK_LE || op==OP_Gt );
60539   assert( pExpr->op!=TK_GT || op==OP_Le );
60540   assert( pExpr->op!=TK_GE || op==OP_Lt );
60541
60542   switch( pExpr->op ){
60543     case TK_AND: {
60544       testcase( jumpIfNull==0 );
60545       testcase( pParse->disableColCache==0 );
60546       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
60547       pParse->disableColCache++;
60548       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60549       assert( pParse->disableColCache>0 );
60550       pParse->disableColCache--;
60551       break;
60552     }
60553     case TK_OR: {
60554       int d2 = sqlite3VdbeMakeLabel(v);
60555       testcase( jumpIfNull==0 );
60556       testcase( pParse->disableColCache==0 );
60557       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
60558       pParse->disableColCache++;
60559       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60560       assert( pParse->disableColCache>0 );
60561       pParse->disableColCache--;
60562       sqlite3VdbeResolveLabel(v, d2);
60563       break;
60564     }
60565     case TK_NOT: {
60566       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
60567       break;
60568     }
60569     case TK_LT:
60570     case TK_LE:
60571     case TK_GT:
60572     case TK_GE:
60573     case TK_NE:
60574     case TK_EQ: {
60575       testcase( op==TK_LT );
60576       testcase( op==TK_LE );
60577       testcase( op==TK_GT );
60578       testcase( op==TK_GE );
60579       testcase( op==TK_EQ );
60580       testcase( op==TK_NE );
60581       testcase( jumpIfNull==0 );
60582       codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
60583                                   pExpr->pRight, &r2, &regFree2);
60584       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
60585                   r1, r2, dest, jumpIfNull);
60586       testcase( regFree1==0 );
60587       testcase( regFree2==0 );
60588       break;
60589     }
60590     case TK_ISNULL:
60591     case TK_NOTNULL: {
60592       testcase( op==TK_ISNULL );
60593       testcase( op==TK_NOTNULL );
60594       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
60595       sqlite3VdbeAddOp2(v, op, r1, dest);
60596       testcase( regFree1==0 );
60597       break;
60598     }
60599     case TK_BETWEEN: {
60600       /*    x BETWEEN y AND z
60601       **
60602       ** Is equivalent to 
60603       **
60604       **    x>=y AND x<=z
60605       **
60606       ** Code it as such, taking care to do the common subexpression
60607       ** elementation of x.
60608       */
60609       Expr exprAnd;
60610       Expr compLeft;
60611       Expr compRight;
60612       Expr exprX;
60613
60614       exprX = *pExpr->pLeft;
60615       exprAnd.op = TK_AND;
60616       exprAnd.pLeft = &compLeft;
60617       exprAnd.pRight = &compRight;
60618       compLeft.op = TK_GE;
60619       compLeft.pLeft = &exprX;
60620       compLeft.pRight = pExpr->pList->a[0].pExpr;
60621       compRight.op = TK_LE;
60622       compRight.pLeft = &exprX;
60623       compRight.pRight = pExpr->pList->a[1].pExpr;
60624       exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
60625       testcase( regFree1==0 );
60626       exprX.op = TK_REGISTER;
60627       testcase( jumpIfNull==0 );
60628       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
60629       break;
60630     }
60631     default: {
60632       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
60633       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
60634       testcase( regFree1==0 );
60635       testcase( jumpIfNull==0 );
60636       break;
60637     }
60638   }
60639   sqlite3ReleaseTempReg(pParse, regFree1);
60640   sqlite3ReleaseTempReg(pParse, regFree2);
60641 }
60642
60643 /*
60644 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
60645 ** if they are identical and return FALSE if they differ in any way.
60646 **
60647 ** Sometimes this routine will return FALSE even if the two expressions
60648 ** really are equivalent.  If we cannot prove that the expressions are
60649 ** identical, we return FALSE just to be safe.  So if this routine
60650 ** returns false, then you do not really know for certain if the two
60651 ** expressions are the same.  But if you get a TRUE return, then you
60652 ** can be sure the expressions are the same.  In the places where
60653 ** this routine is used, it does not hurt to get an extra FALSE - that
60654 ** just might result in some slightly slower code.  But returning
60655 ** an incorrect TRUE could lead to a malfunction.
60656 */
60657 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
60658   int i;
60659   if( pA==0||pB==0 ){
60660     return pB==pA;
60661   }
60662   if( pA->op!=pB->op ) return 0;
60663   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
60664   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
60665   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
60666   if( pA->pList ){
60667     if( pB->pList==0 ) return 0;
60668     if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
60669     for(i=0; i<pA->pList->nExpr; i++){
60670       if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
60671         return 0;
60672       }
60673     }
60674   }else if( pB->pList ){
60675     return 0;
60676   }
60677   if( pA->pSelect || pB->pSelect ) return 0;
60678   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
60679   if( pA->op!=TK_COLUMN && pA->token.z ){
60680     if( pB->token.z==0 ) return 0;
60681     if( pB->token.n!=pA->token.n ) return 0;
60682     if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
60683       return 0;
60684     }
60685   }
60686   return 1;
60687 }
60688
60689
60690 /*
60691 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
60692 ** the new element.  Return a negative number if malloc fails.
60693 */
60694 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
60695   int i;
60696   pInfo->aCol = sqlite3ArrayAllocate(
60697        db,
60698        pInfo->aCol,
60699        sizeof(pInfo->aCol[0]),
60700        3,
60701        &pInfo->nColumn,
60702        &pInfo->nColumnAlloc,
60703        &i
60704   );
60705   return i;
60706 }    
60707
60708 /*
60709 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
60710 ** the new element.  Return a negative number if malloc fails.
60711 */
60712 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
60713   int i;
60714   pInfo->aFunc = sqlite3ArrayAllocate(
60715        db, 
60716        pInfo->aFunc,
60717        sizeof(pInfo->aFunc[0]),
60718        3,
60719        &pInfo->nFunc,
60720        &pInfo->nFuncAlloc,
60721        &i
60722   );
60723   return i;
60724 }    
60725
60726 /*
60727 ** This is the xExprCallback for a tree walker.  It is used to
60728 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
60729 ** for additional information.
60730 */
60731 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
60732   int i;
60733   NameContext *pNC = pWalker->u.pNC;
60734   Parse *pParse = pNC->pParse;
60735   SrcList *pSrcList = pNC->pSrcList;
60736   AggInfo *pAggInfo = pNC->pAggInfo;
60737
60738   switch( pExpr->op ){
60739     case TK_AGG_COLUMN:
60740     case TK_COLUMN: {
60741       testcase( pExpr->op==TK_AGG_COLUMN );
60742       testcase( pExpr->op==TK_COLUMN );
60743       /* Check to see if the column is in one of the tables in the FROM
60744       ** clause of the aggregate query */
60745       if( pSrcList ){
60746         struct SrcList_item *pItem = pSrcList->a;
60747         for(i=0; i<pSrcList->nSrc; i++, pItem++){
60748           struct AggInfo_col *pCol;
60749           if( pExpr->iTable==pItem->iCursor ){
60750             /* If we reach this point, it means that pExpr refers to a table
60751             ** that is in the FROM clause of the aggregate query.  
60752             **
60753             ** Make an entry for the column in pAggInfo->aCol[] if there
60754             ** is not an entry there already.
60755             */
60756             int k;
60757             pCol = pAggInfo->aCol;
60758             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
60759               if( pCol->iTable==pExpr->iTable &&
60760                   pCol->iColumn==pExpr->iColumn ){
60761                 break;
60762               }
60763             }
60764             if( (k>=pAggInfo->nColumn)
60765              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
60766             ){
60767               pCol = &pAggInfo->aCol[k];
60768               pCol->pTab = pExpr->pTab;
60769               pCol->iTable = pExpr->iTable;
60770               pCol->iColumn = pExpr->iColumn;
60771               pCol->iMem = ++pParse->nMem;
60772               pCol->iSorterColumn = -1;
60773               pCol->pExpr = pExpr;
60774               if( pAggInfo->pGroupBy ){
60775                 int j, n;
60776                 ExprList *pGB = pAggInfo->pGroupBy;
60777                 struct ExprList_item *pTerm = pGB->a;
60778                 n = pGB->nExpr;
60779                 for(j=0; j<n; j++, pTerm++){
60780                   Expr *pE = pTerm->pExpr;
60781                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
60782                       pE->iColumn==pExpr->iColumn ){
60783                     pCol->iSorterColumn = j;
60784                     break;
60785                   }
60786                 }
60787               }
60788               if( pCol->iSorterColumn<0 ){
60789                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
60790               }
60791             }
60792             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
60793             ** because it was there before or because we just created it).
60794             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
60795             ** pAggInfo->aCol[] entry.
60796             */
60797             pExpr->pAggInfo = pAggInfo;
60798             pExpr->op = TK_AGG_COLUMN;
60799             pExpr->iAgg = k;
60800             break;
60801           } /* endif pExpr->iTable==pItem->iCursor */
60802         } /* end loop over pSrcList */
60803       }
60804       return WRC_Prune;
60805     }
60806     case TK_AGG_FUNCTION: {
60807       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
60808       ** to be ignored */
60809       if( pNC->nDepth==0 ){
60810         /* Check to see if pExpr is a duplicate of another aggregate 
60811         ** function that is already in the pAggInfo structure
60812         */
60813         struct AggInfo_func *pItem = pAggInfo->aFunc;
60814         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
60815           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
60816             break;
60817           }
60818         }
60819         if( i>=pAggInfo->nFunc ){
60820           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
60821           */
60822           u8 enc = ENC(pParse->db);
60823           i = addAggInfoFunc(pParse->db, pAggInfo);
60824           if( i>=0 ){
60825             pItem = &pAggInfo->aFunc[i];
60826             pItem->pExpr = pExpr;
60827             pItem->iMem = ++pParse->nMem;
60828             pItem->pFunc = sqlite3FindFunction(pParse->db,
60829                    (char*)pExpr->token.z, pExpr->token.n,
60830                    pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
60831             if( pExpr->flags & EP_Distinct ){
60832               pItem->iDistinct = pParse->nTab++;
60833             }else{
60834               pItem->iDistinct = -1;
60835             }
60836           }
60837         }
60838         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
60839         */
60840         pExpr->iAgg = i;
60841         pExpr->pAggInfo = pAggInfo;
60842         return WRC_Prune;
60843       }
60844     }
60845   }
60846   return WRC_Continue;
60847 }
60848 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
60849   NameContext *pNC = pWalker->u.pNC;
60850   if( pNC->nDepth==0 ){
60851     pNC->nDepth++;
60852     sqlite3WalkSelect(pWalker, pSelect);
60853     pNC->nDepth--;
60854     return WRC_Prune;
60855   }else{
60856     return WRC_Continue;
60857   }
60858 }
60859
60860 /*
60861 ** Analyze the given expression looking for aggregate functions and
60862 ** for variables that need to be added to the pParse->aAgg[] array.
60863 ** Make additional entries to the pParse->aAgg[] array as necessary.
60864 **
60865 ** This routine should only be called after the expression has been
60866 ** analyzed by sqlite3ResolveExprNames().
60867 */
60868 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
60869   Walker w;
60870   w.xExprCallback = analyzeAggregate;
60871   w.xSelectCallback = analyzeAggregatesInSelect;
60872   w.u.pNC = pNC;
60873   sqlite3WalkExpr(&w, pExpr);
60874 }
60875
60876 /*
60877 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
60878 ** expression list.  Return the number of errors.
60879 **
60880 ** If an error is found, the analysis is cut short.
60881 */
60882 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
60883   struct ExprList_item *pItem;
60884   int i;
60885   if( pList ){
60886     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
60887       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
60888     }
60889   }
60890 }
60891
60892 /*
60893 ** Allocate or deallocate temporary use registers during code generation.
60894 */
60895 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
60896   if( pParse->nTempReg==0 ){
60897     return ++pParse->nMem;
60898   }
60899   return pParse->aTempReg[--pParse->nTempReg];
60900 }
60901 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
60902   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
60903     sqlite3ExprWritableRegister(pParse, iReg);
60904     pParse->aTempReg[pParse->nTempReg++] = iReg;
60905   }
60906 }
60907
60908 /*
60909 ** Allocate or deallocate a block of nReg consecutive registers
60910 */
60911 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
60912   int i, n;
60913   i = pParse->iRangeReg;
60914   n = pParse->nRangeReg;
60915   if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
60916     pParse->iRangeReg += nReg;
60917     pParse->nRangeReg -= nReg;
60918   }else{
60919     i = pParse->nMem+1;
60920     pParse->nMem += nReg;
60921   }
60922   return i;
60923 }
60924 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
60925   if( nReg>pParse->nRangeReg ){
60926     pParse->nRangeReg = nReg;
60927     pParse->iRangeReg = iReg;
60928   }
60929 }
60930
60931 /************** End of expr.c ************************************************/
60932 /************** Begin file alter.c *******************************************/
60933 /*
60934 ** 2005 February 15
60935 **
60936 ** The author disclaims copyright to this source code.  In place of
60937 ** a legal notice, here is a blessing:
60938 **
60939 **    May you do good and not evil.
60940 **    May you find forgiveness for yourself and forgive others.
60941 **    May you share freely, never taking more than you give.
60942 **
60943 *************************************************************************
60944 ** This file contains C code routines that used to generate VDBE code
60945 ** that implements the ALTER TABLE command.
60946 **
60947 ** $Id: alter.c,v 1.53 2009/02/13 03:43:32 drh Exp $
60948 */
60949
60950 /*
60951 ** The code in this file only exists if we are not omitting the
60952 ** ALTER TABLE logic from the build.
60953 */
60954 #ifndef SQLITE_OMIT_ALTERTABLE
60955
60956
60957 /*
60958 ** This function is used by SQL generated to implement the 
60959 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
60960 ** CREATE INDEX command. The second is a table name. The table name in 
60961 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
60962 ** argument and the result returned. Examples:
60963 **
60964 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
60965 **     -> 'CREATE TABLE def(a, b, c)'
60966 **
60967 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
60968 **     -> 'CREATE INDEX i ON def(a, b, c)'
60969 */
60970 static void renameTableFunc(
60971   sqlite3_context *context,
60972   int NotUsed,
60973   sqlite3_value **argv
60974 ){
60975   unsigned char const *zSql = sqlite3_value_text(argv[0]);
60976   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
60977
60978   int token;
60979   Token tname;
60980   unsigned char const *zCsr = zSql;
60981   int len = 0;
60982   char *zRet;
60983
60984   sqlite3 *db = sqlite3_context_db_handle(context);
60985
60986   UNUSED_PARAMETER(NotUsed);
60987
60988   /* The principle used to locate the table name in the CREATE TABLE 
60989   ** statement is that the table name is the first non-space token that
60990   ** is immediately followed by a TK_LP or TK_USING token.
60991   */
60992   if( zSql ){
60993     do {
60994       if( !*zCsr ){
60995         /* Ran out of input before finding an opening bracket. Return NULL. */
60996         return;
60997       }
60998
60999       /* Store the token that zCsr points to in tname. */
61000       tname.z = zCsr;
61001       tname.n = len;
61002
61003       /* Advance zCsr to the next token. Store that token type in 'token',
61004       ** and its length in 'len' (to be used next iteration of this loop).
61005       */
61006       do {
61007         zCsr += len;
61008         len = sqlite3GetToken(zCsr, &token);
61009       } while( token==TK_SPACE );
61010       assert( len>0 );
61011     } while( token!=TK_LP && token!=TK_USING );
61012
61013     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
61014        zTableName, tname.z+tname.n);
61015     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
61016   }
61017 }
61018
61019 #ifndef SQLITE_OMIT_TRIGGER
61020 /* This function is used by SQL generated to implement the
61021 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
61022 ** statement. The second is a table name. The table name in the CREATE 
61023 ** TRIGGER statement is replaced with the third argument and the result 
61024 ** returned. This is analagous to renameTableFunc() above, except for CREATE
61025 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
61026 */
61027 static void renameTriggerFunc(
61028   sqlite3_context *context,
61029   int NotUsed,
61030   sqlite3_value **argv
61031 ){
61032   unsigned char const *zSql = sqlite3_value_text(argv[0]);
61033   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
61034
61035   int token;
61036   Token tname;
61037   int dist = 3;
61038   unsigned char const *zCsr = zSql;
61039   int len = 0;
61040   char *zRet;
61041   sqlite3 *db = sqlite3_context_db_handle(context);
61042
61043   UNUSED_PARAMETER(NotUsed);
61044
61045   /* The principle used to locate the table name in the CREATE TRIGGER 
61046   ** statement is that the table name is the first token that is immediatedly
61047   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
61048   ** of TK_WHEN, TK_BEGIN or TK_FOR.
61049   */
61050   if( zSql ){
61051     do {
61052
61053       if( !*zCsr ){
61054         /* Ran out of input before finding the table name. Return NULL. */
61055         return;
61056       }
61057
61058       /* Store the token that zCsr points to in tname. */
61059       tname.z = zCsr;
61060       tname.n = len;
61061
61062       /* Advance zCsr to the next token. Store that token type in 'token',
61063       ** and its length in 'len' (to be used next iteration of this loop).
61064       */
61065       do {
61066         zCsr += len;
61067         len = sqlite3GetToken(zCsr, &token);
61068       }while( token==TK_SPACE );
61069       assert( len>0 );
61070
61071       /* Variable 'dist' stores the number of tokens read since the most
61072       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
61073       ** token is read and 'dist' equals 2, the condition stated above
61074       ** to be met.
61075       **
61076       ** Note that ON cannot be a database, table or column name, so
61077       ** there is no need to worry about syntax like 
61078       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
61079       */
61080       dist++;
61081       if( token==TK_DOT || token==TK_ON ){
61082         dist = 0;
61083       }
61084     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
61085
61086     /* Variable tname now contains the token that is the old table-name
61087     ** in the CREATE TRIGGER statement.
61088     */
61089     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, 
61090        zTableName, tname.z+tname.n);
61091     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
61092   }
61093 }
61094 #endif   /* !SQLITE_OMIT_TRIGGER */
61095
61096 /*
61097 ** Register built-in functions used to help implement ALTER TABLE
61098 */
61099 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
61100   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
61101                          renameTableFunc, 0, 0);
61102 #ifndef SQLITE_OMIT_TRIGGER
61103   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
61104                          renameTriggerFunc, 0, 0);
61105 #endif
61106 }
61107
61108 /*
61109 ** Generate the text of a WHERE expression which can be used to select all
61110 ** temporary triggers on table pTab from the sqlite_temp_master table. If
61111 ** table pTab has no temporary triggers, or is itself stored in the 
61112 ** temporary database, NULL is returned.
61113 */
61114 static char *whereTempTriggers(Parse *pParse, Table *pTab){
61115   Trigger *pTrig;
61116   char *zWhere = 0;
61117   char *tmp = 0;
61118   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
61119
61120   /* If the table is not located in the temp-db (in which case NULL is 
61121   ** returned, loop through the tables list of triggers. For each trigger
61122   ** that is not part of the temp-db schema, add a clause to the WHERE 
61123   ** expression being built up in zWhere.
61124   */
61125   if( pTab->pSchema!=pTempSchema ){
61126     sqlite3 *db = pParse->db;
61127     for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
61128       if( pTrig->pSchema==pTempSchema ){
61129         if( !zWhere ){
61130           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
61131         }else{
61132           tmp = zWhere;
61133           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
61134           sqlite3DbFree(db, tmp);
61135         }
61136       }
61137     }
61138   }
61139   return zWhere;
61140 }
61141
61142 /*
61143 ** Generate code to drop and reload the internal representation of table
61144 ** pTab from the database, including triggers and temporary triggers.
61145 ** Argument zName is the name of the table in the database schema at
61146 ** the time the generated code is executed. This can be different from
61147 ** pTab->zName if this function is being called to code part of an 
61148 ** "ALTER TABLE RENAME TO" statement.
61149 */
61150 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
61151   Vdbe *v;
61152   char *zWhere;
61153   int iDb;                   /* Index of database containing pTab */
61154 #ifndef SQLITE_OMIT_TRIGGER
61155   Trigger *pTrig;
61156 #endif
61157
61158   v = sqlite3GetVdbe(pParse);
61159   if( !v ) return;
61160   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61161   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61162   assert( iDb>=0 );
61163
61164 #ifndef SQLITE_OMIT_TRIGGER
61165   /* Drop any table triggers from the internal schema. */
61166   for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
61167     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
61168     assert( iTrigDb==iDb || iTrigDb==1 );
61169     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
61170   }
61171 #endif
61172
61173   /* Drop the table and index from the internal schema */
61174   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
61175
61176   /* Reload the table, index and permanent trigger schemas. */
61177   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
61178   if( !zWhere ) return;
61179   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
61180
61181 #ifndef SQLITE_OMIT_TRIGGER
61182   /* Now, if the table is not stored in the temp database, reload any temp 
61183   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
61184   */
61185   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
61186     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
61187   }
61188 #endif
61189 }
61190
61191 /*
61192 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
61193 ** command. 
61194 */
61195 SQLITE_PRIVATE void sqlite3AlterRenameTable(
61196   Parse *pParse,            /* Parser context. */
61197   SrcList *pSrc,            /* The table to rename. */
61198   Token *pName              /* The new table name. */
61199 ){
61200   int iDb;                  /* Database that contains the table */
61201   char *zDb;                /* Name of database iDb */
61202   Table *pTab;              /* Table being renamed */
61203   char *zName = 0;          /* NULL-terminated version of pName */ 
61204   sqlite3 *db = pParse->db; /* Database connection */
61205   int nTabName;             /* Number of UTF-8 characters in zTabName */
61206   const char *zTabName;     /* Original name of the table */
61207   Vdbe *v;
61208 #ifndef SQLITE_OMIT_TRIGGER
61209   char *zWhere = 0;         /* Where clause to locate temp triggers */
61210 #endif
61211   int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
61212   
61213   if( db->mallocFailed ) goto exit_rename_table;
61214   assert( pSrc->nSrc==1 );
61215   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61216
61217   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
61218   if( !pTab ) goto exit_rename_table;
61219   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61220   zDb = db->aDb[iDb].zName;
61221
61222   /* Get a NULL terminated version of the new table name. */
61223   zName = sqlite3NameFromToken(db, pName);
61224   if( !zName ) goto exit_rename_table;
61225
61226   /* Check that a table or index named 'zName' does not already exist
61227   ** in database iDb. If so, this is an error.
61228   */
61229   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
61230     sqlite3ErrorMsg(pParse, 
61231         "there is already another table or index with this name: %s", zName);
61232     goto exit_rename_table;
61233   }
61234
61235   /* Make sure it is not a system table being altered, or a reserved name
61236   ** that the table is being renamed to.
61237   */
61238   if( sqlite3Strlen30(pTab->zName)>6 
61239    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
61240   ){
61241     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
61242     goto exit_rename_table;
61243   }
61244   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
61245     goto exit_rename_table;
61246   }
61247
61248 #ifndef SQLITE_OMIT_VIEW
61249   if( pTab->pSelect ){
61250     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
61251     goto exit_rename_table;
61252   }
61253 #endif
61254
61255 #ifndef SQLITE_OMIT_AUTHORIZATION
61256   /* Invoke the authorization callback. */
61257   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
61258     goto exit_rename_table;
61259   }
61260 #endif
61261
61262 #ifndef SQLITE_OMIT_VIRTUALTABLE
61263   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
61264     goto exit_rename_table;
61265   }
61266   if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
61267     isVirtualRename = 1;
61268   }
61269 #endif
61270
61271   /* Begin a transaction and code the VerifyCookie for database iDb. 
61272   ** Then modify the schema cookie (since the ALTER TABLE modifies the
61273   ** schema). Open a statement transaction if the table is a virtual
61274   ** table.
61275   */
61276   v = sqlite3GetVdbe(pParse);
61277   if( v==0 ){
61278     goto exit_rename_table;
61279   }
61280   sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
61281   sqlite3ChangeCookie(pParse, iDb);
61282
61283   /* If this is a virtual table, invoke the xRename() function if
61284   ** one is defined. The xRename() callback will modify the names
61285   ** of any resources used by the v-table implementation (including other
61286   ** SQLite tables) that are identified by the name of the virtual table.
61287   */
61288 #ifndef SQLITE_OMIT_VIRTUALTABLE
61289   if( isVirtualRename ){
61290     int i = ++pParse->nMem;
61291     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
61292     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB);
61293   }
61294 #endif
61295
61296   /* figure out how many UTF-8 characters are in zName */
61297   zTabName = pTab->zName;
61298   nTabName = sqlite3Utf8CharLen(zTabName, -1);
61299
61300   /* Modify the sqlite_master table to use the new table name. */
61301   sqlite3NestedParse(pParse,
61302       "UPDATE %Q.%s SET "
61303 #ifdef SQLITE_OMIT_TRIGGER
61304           "sql = sqlite_rename_table(sql, %Q), "
61305 #else
61306           "sql = CASE "
61307             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
61308             "ELSE sqlite_rename_table(sql, %Q) END, "
61309 #endif
61310           "tbl_name = %Q, "
61311           "name = CASE "
61312             "WHEN type='table' THEN %Q "
61313             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
61314              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
61315             "ELSE name END "
61316       "WHERE tbl_name=%Q AND "
61317           "(type='table' OR type='index' OR type='trigger');", 
61318       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
61319 #ifndef SQLITE_OMIT_TRIGGER
61320       zName,
61321 #endif
61322       zName, nTabName, zTabName
61323   );
61324
61325 #ifndef SQLITE_OMIT_AUTOINCREMENT
61326   /* If the sqlite_sequence table exists in this database, then update 
61327   ** it with the new table name.
61328   */
61329   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
61330     sqlite3NestedParse(pParse,
61331         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
61332         zDb, zName, pTab->zName);
61333   }
61334 #endif
61335
61336 #ifndef SQLITE_OMIT_TRIGGER
61337   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
61338   ** table. Don't do this if the table being ALTERed is itself located in
61339   ** the temp database.
61340   */
61341   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
61342     sqlite3NestedParse(pParse, 
61343         "UPDATE sqlite_temp_master SET "
61344             "sql = sqlite_rename_trigger(sql, %Q), "
61345             "tbl_name = %Q "
61346             "WHERE %s;", zName, zName, zWhere);
61347     sqlite3DbFree(db, zWhere);
61348   }
61349 #endif
61350
61351   /* Drop and reload the internal table schema. */
61352   reloadTableSchema(pParse, pTab, zName);
61353
61354 exit_rename_table:
61355   sqlite3SrcListDelete(db, pSrc);
61356   sqlite3DbFree(db, zName);
61357 }
61358
61359
61360 /*
61361 ** This function is called after an "ALTER TABLE ... ADD" statement
61362 ** has been parsed. Argument pColDef contains the text of the new
61363 ** column definition.
61364 **
61365 ** The Table structure pParse->pNewTable was extended to include
61366 ** the new column during parsing.
61367 */
61368 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
61369   Table *pNew;              /* Copy of pParse->pNewTable */
61370   Table *pTab;              /* Table being altered */
61371   int iDb;                  /* Database number */
61372   const char *zDb;          /* Database name */
61373   const char *zTab;         /* Table name */
61374   char *zCol;               /* Null-terminated column definition */
61375   Column *pCol;             /* The new column */
61376   Expr *pDflt;              /* Default value for the new column */
61377   sqlite3 *db;              /* The database connection; */
61378
61379   db = pParse->db;
61380   if( pParse->nErr || db->mallocFailed ) return;
61381   pNew = pParse->pNewTable;
61382   assert( pNew );
61383
61384   assert( sqlite3BtreeHoldsAllMutexes(db) );
61385   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
61386   zDb = db->aDb[iDb].zName;
61387   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
61388   pCol = &pNew->aCol[pNew->nCol-1];
61389   pDflt = pCol->pDflt;
61390   pTab = sqlite3FindTable(db, zTab, zDb);
61391   assert( pTab );
61392
61393 #ifndef SQLITE_OMIT_AUTHORIZATION
61394   /* Invoke the authorization callback. */
61395   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
61396     return;
61397   }
61398 #endif
61399
61400   /* If the default value for the new column was specified with a 
61401   ** literal NULL, then set pDflt to 0. This simplifies checking
61402   ** for an SQL NULL default below.
61403   */
61404   if( pDflt && pDflt->op==TK_NULL ){
61405     pDflt = 0;
61406   }
61407
61408   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
61409   ** If there is a NOT NULL constraint, then the default value for the
61410   ** column must not be NULL.
61411   */
61412   if( pCol->isPrimKey ){
61413     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
61414     return;
61415   }
61416   if( pNew->pIndex ){
61417     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
61418     return;
61419   }
61420   if( pCol->notNull && !pDflt ){
61421     sqlite3ErrorMsg(pParse, 
61422         "Cannot add a NOT NULL column with default value NULL");
61423     return;
61424   }
61425
61426   /* Ensure the default expression is something that sqlite3ValueFromExpr()
61427   ** can handle (i.e. not CURRENT_TIME etc.)
61428   */
61429   if( pDflt ){
61430     sqlite3_value *pVal;
61431     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
61432       db->mallocFailed = 1;
61433       return;
61434     }
61435     if( !pVal ){
61436       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
61437       return;
61438     }
61439     sqlite3ValueFree(pVal);
61440   }
61441
61442   /* Modify the CREATE TABLE statement. */
61443   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
61444   if( zCol ){
61445     char *zEnd = &zCol[pColDef->n-1];
61446     while( (zEnd>zCol && *zEnd==';') || sqlite3Isspace(*zEnd) ){
61447       *zEnd-- = '\0';
61448     }
61449     sqlite3NestedParse(pParse, 
61450         "UPDATE \"%w\".%s SET "
61451           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
61452         "WHERE type = 'table' AND name = %Q", 
61453       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
61454       zTab
61455     );
61456     sqlite3DbFree(db, zCol);
61457   }
61458
61459   /* If the default value of the new column is NULL, then set the file
61460   ** format to 2. If the default value of the new column is not NULL,
61461   ** the file format becomes 3.
61462   */
61463   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
61464
61465   /* Reload the schema of the modified table. */
61466   reloadTableSchema(pParse, pTab, pTab->zName);
61467 }
61468
61469 /*
61470 ** This function is called by the parser after the table-name in
61471 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
61472 ** pSrc is the full-name of the table being altered.
61473 **
61474 ** This routine makes a (partial) copy of the Table structure
61475 ** for the table being altered and sets Parse.pNewTable to point
61476 ** to it. Routines called by the parser as the column definition
61477 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
61478 ** the copy. The copy of the Table structure is deleted by tokenize.c 
61479 ** after parsing is finished.
61480 **
61481 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
61482 ** coding the "ALTER TABLE ... ADD" statement.
61483 */
61484 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
61485   Table *pNew;
61486   Table *pTab;
61487   Vdbe *v;
61488   int iDb;
61489   int i;
61490   int nAlloc;
61491   sqlite3 *db = pParse->db;
61492
61493   /* Look up the table being altered. */
61494   assert( pParse->pNewTable==0 );
61495   assert( sqlite3BtreeHoldsAllMutexes(db) );
61496   if( db->mallocFailed ) goto exit_begin_add_column;
61497   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
61498   if( !pTab ) goto exit_begin_add_column;
61499
61500 #ifndef SQLITE_OMIT_VIRTUALTABLE
61501   if( IsVirtual(pTab) ){
61502     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
61503     goto exit_begin_add_column;
61504   }
61505 #endif
61506
61507   /* Make sure this is not an attempt to ALTER a view. */
61508   if( pTab->pSelect ){
61509     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
61510     goto exit_begin_add_column;
61511   }
61512
61513   assert( pTab->addColOffset>0 );
61514   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61515
61516   /* Put a copy of the Table struct in Parse.pNewTable for the
61517   ** sqlite3AddColumn() function and friends to modify.  But modify
61518   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
61519   ** prefix, we insure that the name will not collide with an existing
61520   ** table because user table are not allowed to have the "sqlite_"
61521   ** prefix on their name.
61522   */
61523   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
61524   if( !pNew ) goto exit_begin_add_column;
61525   pParse->pNewTable = pNew;
61526   pNew->nRef = 1;
61527   pNew->db = db;
61528   pNew->nCol = pTab->nCol;
61529   assert( pNew->nCol>0 );
61530   nAlloc = (((pNew->nCol-1)/8)*8)+8;
61531   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
61532   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
61533   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
61534   if( !pNew->aCol || !pNew->zName ){
61535     db->mallocFailed = 1;
61536     goto exit_begin_add_column;
61537   }
61538   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
61539   for(i=0; i<pNew->nCol; i++){
61540     Column *pCol = &pNew->aCol[i];
61541     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
61542     pCol->zColl = 0;
61543     pCol->zType = 0;
61544     pCol->pDflt = 0;
61545   }
61546   pNew->pSchema = db->aDb[iDb].pSchema;
61547   pNew->addColOffset = pTab->addColOffset;
61548   pNew->nRef = 1;
61549
61550   /* Begin a transaction and increment the schema cookie.  */
61551   sqlite3BeginWriteOperation(pParse, 0, iDb);
61552   v = sqlite3GetVdbe(pParse);
61553   if( !v ) goto exit_begin_add_column;
61554   sqlite3ChangeCookie(pParse, iDb);
61555
61556 exit_begin_add_column:
61557   sqlite3SrcListDelete(db, pSrc);
61558   return;
61559 }
61560 #endif  /* SQLITE_ALTER_TABLE */
61561
61562 /************** End of alter.c ***********************************************/
61563 /************** Begin file analyze.c *****************************************/
61564 /*
61565 ** 2005 July 8
61566 **
61567 ** The author disclaims copyright to this source code.  In place of
61568 ** a legal notice, here is a blessing:
61569 **
61570 **    May you do good and not evil.
61571 **    May you find forgiveness for yourself and forgive others.
61572 **    May you share freely, never taking more than you give.
61573 **
61574 *************************************************************************
61575 ** This file contains code associated with the ANALYZE command.
61576 **
61577 ** @(#) $Id: analyze.c,v 1.48 2009/02/13 16:59:53 drh Exp $
61578 */
61579 #ifndef SQLITE_OMIT_ANALYZE
61580
61581 /*
61582 ** This routine generates code that opens the sqlite_stat1 table on cursor
61583 ** iStatCur.
61584 **
61585 ** If the sqlite_stat1 tables does not previously exist, it is created.
61586 ** If it does previously exist, all entires associated with table zWhere
61587 ** are removed.  If zWhere==0 then all entries are removed.
61588 */
61589 static void openStatTable(
61590   Parse *pParse,          /* Parsing context */
61591   int iDb,                /* The database we are looking in */
61592   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
61593   const char *zWhere      /* Delete entries associated with this table */
61594 ){
61595   sqlite3 *db = pParse->db;
61596   Db *pDb;
61597   int iRootPage;
61598   u8 createStat1 = 0;
61599   Table *pStat;
61600   Vdbe *v = sqlite3GetVdbe(pParse);
61601
61602   if( v==0 ) return;
61603   assert( sqlite3BtreeHoldsAllMutexes(db) );
61604   assert( sqlite3VdbeDb(v)==db );
61605   pDb = &db->aDb[iDb];
61606   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
61607     /* The sqlite_stat1 tables does not exist.  Create it.  
61608     ** Note that a side-effect of the CREATE TABLE statement is to leave
61609     ** the rootpage of the new table in register pParse->regRoot.  This is
61610     ** important because the OpenWrite opcode below will be needing it. */
61611     sqlite3NestedParse(pParse,
61612       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
61613       pDb->zName
61614     );
61615     iRootPage = pParse->regRoot;
61616     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
61617   }else if( zWhere ){
61618     /* The sqlite_stat1 table exists.  Delete all entries associated with
61619     ** the table zWhere. */
61620     sqlite3NestedParse(pParse,
61621        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
61622        pDb->zName, zWhere
61623     );
61624     iRootPage = pStat->tnum;
61625   }else{
61626     /* The sqlite_stat1 table already exists.  Delete all rows. */
61627     iRootPage = pStat->tnum;
61628     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
61629   }
61630
61631   /* Open the sqlite_stat1 table for writing. Unless it was created
61632   ** by this vdbe program, lock it for writing at the shared-cache level. 
61633   ** If this vdbe did create the sqlite_stat1 table, then it must have 
61634   ** already obtained a schema-lock, making the write-lock redundant.
61635   */
61636   if( !createStat1 ){
61637     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
61638   }
61639   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
61640   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
61641   sqlite3VdbeChangeP5(v, createStat1);
61642 }
61643
61644 /*
61645 ** Generate code to do an analysis of all indices associated with
61646 ** a single table.
61647 */
61648 static void analyzeOneTable(
61649   Parse *pParse,   /* Parser context */
61650   Table *pTab,     /* Table whose indices are to be analyzed */
61651   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
61652   int iMem         /* Available memory locations begin here */
61653 ){
61654   Index *pIdx;     /* An index to being analyzed */
61655   int iIdxCur;     /* Index of VdbeCursor for index being analyzed */
61656   int nCol;        /* Number of columns in the index */
61657   Vdbe *v;         /* The virtual machine being built up */
61658   int i;           /* Loop counter */
61659   int topOfLoop;   /* The top of the loop */
61660   int endOfLoop;   /* The end of the loop */
61661   int addr;        /* The address of an instruction */
61662   int iDb;         /* Index of database containing pTab */
61663
61664   v = sqlite3GetVdbe(pParse);
61665   if( v==0 || pTab==0 || pTab->pIndex==0 ){
61666     /* Do no analysis for tables that have no indices */
61667     return;
61668   }
61669   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61670   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61671   assert( iDb>=0 );
61672 #ifndef SQLITE_OMIT_AUTHORIZATION
61673   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
61674       pParse->db->aDb[iDb].zName ) ){
61675     return;
61676   }
61677 #endif
61678
61679   /* Establish a read-lock on the table at the shared-cache level. */
61680   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61681
61682   iIdxCur = pParse->nTab;
61683   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
61684     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
61685     int regFields;    /* Register block for building records */
61686     int regRec;       /* Register holding completed record */
61687     int regTemp;      /* Temporary use register */
61688     int regCol;       /* Content of a column from the table being analyzed */
61689     int regRowid;     /* Rowid for the inserted record */
61690     int regF2;
61691
61692     /* Open a cursor to the index to be analyzed
61693     */
61694     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
61695     nCol = pIdx->nColumn;
61696     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
61697     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
61698         (char *)pKey, P4_KEYINFO_HANDOFF);
61699     VdbeComment((v, "%s", pIdx->zName));
61700     regFields = iMem+nCol*2;
61701     regTemp = regRowid = regCol = regFields+3;
61702     regRec = regCol+1;
61703     if( regRec>pParse->nMem ){
61704       pParse->nMem = regRec;
61705     }
61706
61707     /* Memory cells are used as follows:
61708     **
61709     **    mem[iMem]:             The total number of rows in the table.
61710     **    mem[iMem+1]:           Number of distinct values in column 1
61711     **    ...
61712     **    mem[iMem+nCol]:        Number of distinct values in column N
61713     **    mem[iMem+nCol+1]       Last observed value of column 1
61714     **    ...
61715     **    mem[iMem+nCol+nCol]:   Last observed value of column N
61716     **
61717     ** Cells iMem through iMem+nCol are initialized to 0.  The others
61718     ** are initialized to NULL.
61719     */
61720     for(i=0; i<=nCol; i++){
61721       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
61722     }
61723     for(i=0; i<nCol; i++){
61724       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
61725     }
61726
61727     /* Do the analysis.
61728     */
61729     endOfLoop = sqlite3VdbeMakeLabel(v);
61730     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
61731     topOfLoop = sqlite3VdbeCurrentAddr(v);
61732     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
61733     for(i=0; i<nCol; i++){
61734       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
61735       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
61736       /**** TODO:  add collating sequence *****/
61737       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
61738     }
61739     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
61740     for(i=0; i<nCol; i++){
61741       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
61742       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
61743       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
61744     }
61745     sqlite3VdbeResolveLabel(v, endOfLoop);
61746     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
61747     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
61748
61749     /* Store the results.  
61750     **
61751     ** The result is a single row of the sqlite_stat1 table.  The first
61752     ** two columns are the names of the table and index.  The third column
61753     ** is a string composed of a list of integer statistics about the
61754     ** index.  The first integer in the list is the total number of entires
61755     ** in the index.  There is one additional integer in the list for each
61756     ** column of the table.  This additional integer is a guess of how many
61757     ** rows of the table the index will select.  If D is the count of distinct
61758     ** values and K is the total number of rows, then the integer is computed
61759     ** as:
61760     **
61761     **        I = (K+D-1)/D
61762     **
61763     ** If K==0 then no entry is made into the sqlite_stat1 table.  
61764     ** If K>0 then it is always the case the D>0 so division by zero
61765     ** is never possible.
61766     */
61767     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
61768     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
61769     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
61770     regF2 = regFields+2;
61771     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
61772     for(i=0; i<nCol; i++){
61773       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
61774       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
61775       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
61776       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
61777       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
61778       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
61779       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
61780     }
61781     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
61782     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
61783     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
61784     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
61785     sqlite3VdbeJumpHere(v, addr);
61786   }
61787 }
61788
61789 /*
61790 ** Generate code that will cause the most recent index analysis to
61791 ** be laoded into internal hash tables where is can be used.
61792 */
61793 static void loadAnalysis(Parse *pParse, int iDb){
61794   Vdbe *v = sqlite3GetVdbe(pParse);
61795   if( v ){
61796     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
61797   }
61798 }
61799
61800 /*
61801 ** Generate code that will do an analysis of an entire database
61802 */
61803 static void analyzeDatabase(Parse *pParse, int iDb){
61804   sqlite3 *db = pParse->db;
61805   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
61806   HashElem *k;
61807   int iStatCur;
61808   int iMem;
61809
61810   sqlite3BeginWriteOperation(pParse, 0, iDb);
61811   iStatCur = pParse->nTab++;
61812   openStatTable(pParse, iDb, iStatCur, 0);
61813   iMem = pParse->nMem+1;
61814   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
61815     Table *pTab = (Table*)sqliteHashData(k);
61816     analyzeOneTable(pParse, pTab, iStatCur, iMem);
61817   }
61818   loadAnalysis(pParse, iDb);
61819 }
61820
61821 /*
61822 ** Generate code that will do an analysis of a single table in
61823 ** a database.
61824 */
61825 static void analyzeTable(Parse *pParse, Table *pTab){
61826   int iDb;
61827   int iStatCur;
61828
61829   assert( pTab!=0 );
61830   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61831   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61832   sqlite3BeginWriteOperation(pParse, 0, iDb);
61833   iStatCur = pParse->nTab++;
61834   openStatTable(pParse, iDb, iStatCur, pTab->zName);
61835   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
61836   loadAnalysis(pParse, iDb);
61837 }
61838
61839 /*
61840 ** Generate code for the ANALYZE command.  The parser calls this routine
61841 ** when it recognizes an ANALYZE command.
61842 **
61843 **        ANALYZE                            -- 1
61844 **        ANALYZE  <database>                -- 2
61845 **        ANALYZE  ?<database>.?<tablename>  -- 3
61846 **
61847 ** Form 1 causes all indices in all attached databases to be analyzed.
61848 ** Form 2 analyzes all indices the single database named.
61849 ** Form 3 analyzes all indices associated with the named table.
61850 */
61851 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
61852   sqlite3 *db = pParse->db;
61853   int iDb;
61854   int i;
61855   char *z, *zDb;
61856   Table *pTab;
61857   Token *pTableName;
61858
61859   /* Read the database schema. If an error occurs, leave an error message
61860   ** and code in pParse and return NULL. */
61861   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61862   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61863     return;
61864   }
61865
61866   if( pName1==0 ){
61867     /* Form 1:  Analyze everything */
61868     for(i=0; i<db->nDb; i++){
61869       if( i==1 ) continue;  /* Do not analyze the TEMP database */
61870       analyzeDatabase(pParse, i);
61871     }
61872   }else if( pName2==0 || pName2->n==0 ){
61873     /* Form 2:  Analyze the database or table named */
61874     iDb = sqlite3FindDb(db, pName1);
61875     if( iDb>=0 ){
61876       analyzeDatabase(pParse, iDb);
61877     }else{
61878       z = sqlite3NameFromToken(db, pName1);
61879       if( z ){
61880         pTab = sqlite3LocateTable(pParse, 0, z, 0);
61881         sqlite3DbFree(db, z);
61882         if( pTab ){
61883           analyzeTable(pParse, pTab);
61884         }
61885       }
61886     }
61887   }else{
61888     /* Form 3: Analyze the fully qualified table name */
61889     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
61890     if( iDb>=0 ){
61891       zDb = db->aDb[iDb].zName;
61892       z = sqlite3NameFromToken(db, pTableName);
61893       if( z ){
61894         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
61895         sqlite3DbFree(db, z);
61896         if( pTab ){
61897           analyzeTable(pParse, pTab);
61898         }
61899       }
61900     }   
61901   }
61902 }
61903
61904 /*
61905 ** Used to pass information from the analyzer reader through to the
61906 ** callback routine.
61907 */
61908 typedef struct analysisInfo analysisInfo;
61909 struct analysisInfo {
61910   sqlite3 *db;
61911   const char *zDatabase;
61912 };
61913
61914 /*
61915 ** This callback is invoked once for each index when reading the
61916 ** sqlite_stat1 table.  
61917 **
61918 **     argv[0] = name of the index
61919 **     argv[1] = results of analysis - on integer for each column
61920 */
61921 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
61922   analysisInfo *pInfo = (analysisInfo*)pData;
61923   Index *pIndex;
61924   int i, c;
61925   unsigned int v;
61926   const char *z;
61927
61928   assert( argc==2 );
61929   UNUSED_PARAMETER2(NotUsed, argc);
61930
61931   if( argv==0 || argv[0]==0 || argv[1]==0 ){
61932     return 0;
61933   }
61934   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
61935   if( pIndex==0 ){
61936     return 0;
61937   }
61938   z = argv[1];
61939   for(i=0; *z && i<=pIndex->nColumn; i++){
61940     v = 0;
61941     while( (c=z[0])>='0' && c<='9' ){
61942       v = v*10 + c - '0';
61943       z++;
61944     }
61945     pIndex->aiRowEst[i] = v;
61946     if( *z==' ' ) z++;
61947   }
61948   return 0;
61949 }
61950
61951 /*
61952 ** Load the content of the sqlite_stat1 table into the index hash tables.
61953 */
61954 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
61955   analysisInfo sInfo;
61956   HashElem *i;
61957   char *zSql;
61958   int rc;
61959
61960   assert( iDb>=0 && iDb<db->nDb );
61961   assert( db->aDb[iDb].pBt!=0 );
61962   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
61963
61964   /* Clear any prior statistics */
61965   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
61966     Index *pIdx = sqliteHashData(i);
61967     sqlite3DefaultRowEst(pIdx);
61968   }
61969
61970   /* Check to make sure the sqlite_stat1 table existss */
61971   sInfo.db = db;
61972   sInfo.zDatabase = db->aDb[iDb].zName;
61973   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
61974      return SQLITE_ERROR;
61975   }
61976
61977
61978   /* Load new statistics out of the sqlite_stat1 table */
61979   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
61980                         sInfo.zDatabase);
61981   if( zSql==0 ){
61982     rc = SQLITE_NOMEM;
61983   }else{
61984     (void)sqlite3SafetyOff(db);
61985     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
61986     (void)sqlite3SafetyOn(db);
61987     sqlite3DbFree(db, zSql);
61988     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
61989   }
61990   return rc;
61991 }
61992
61993
61994 #endif /* SQLITE_OMIT_ANALYZE */
61995
61996 /************** End of analyze.c *********************************************/
61997 /************** Begin file attach.c ******************************************/
61998 /*
61999 ** 2003 April 6
62000 **
62001 ** The author disclaims copyright to this source code.  In place of
62002 ** a legal notice, here is a blessing:
62003 **
62004 **    May you do good and not evil.
62005 **    May you find forgiveness for yourself and forgive others.
62006 **    May you share freely, never taking more than you give.
62007 **
62008 *************************************************************************
62009 ** This file contains code used to implement the ATTACH and DETACH commands.
62010 **
62011 ** $Id: attach.c,v 1.82 2009/02/03 16:51:25 danielk1977 Exp $
62012 */
62013
62014 #ifndef SQLITE_OMIT_ATTACH
62015 /*
62016 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
62017 ** is slightly different from resolving a normal SQL expression, because simple
62018 ** identifiers are treated as strings, not possible column names or aliases.
62019 **
62020 ** i.e. if the parser sees:
62021 **
62022 **     ATTACH DATABASE abc AS def
62023 **
62024 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
62025 ** looking for columns of the same name.
62026 **
62027 ** This only applies to the root node of pExpr, so the statement:
62028 **
62029 **     ATTACH DATABASE abc||def AS 'db2'
62030 **
62031 ** will fail because neither abc or def can be resolved.
62032 */
62033 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
62034 {
62035   int rc = SQLITE_OK;
62036   if( pExpr ){
62037     if( pExpr->op!=TK_ID ){
62038       rc = sqlite3ResolveExprNames(pName, pExpr);
62039       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
62040         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%T\"", &pExpr->span);
62041         return SQLITE_ERROR;
62042       }
62043     }else{
62044       pExpr->op = TK_STRING;
62045     }
62046   }
62047   return rc;
62048 }
62049
62050 /*
62051 ** An SQL user-function registered to do the work of an ATTACH statement. The
62052 ** three arguments to the function come directly from an attach statement:
62053 **
62054 **     ATTACH DATABASE x AS y KEY z
62055 **
62056 **     SELECT sqlite_attach(x, y, z)
62057 **
62058 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
62059 ** third argument.
62060 */
62061 static void attachFunc(
62062   sqlite3_context *context,
62063   int NotUsed,
62064   sqlite3_value **argv
62065 ){
62066   int i;
62067   int rc = 0;
62068   sqlite3 *db = sqlite3_context_db_handle(context);
62069   const char *zName;
62070   const char *zFile;
62071   Db *aNew;
62072   char *zErrDyn = 0;
62073   char zErr[128];
62074
62075   UNUSED_PARAMETER(NotUsed);
62076
62077   zFile = (const char *)sqlite3_value_text(argv[0]);
62078   zName = (const char *)sqlite3_value_text(argv[1]);
62079   if( zFile==0 ) zFile = "";
62080   if( zName==0 ) zName = "";
62081
62082   /* Check for the following errors:
62083   **
62084   **     * Too many attached databases,
62085   **     * Transaction currently open
62086   **     * Specified database name already being used.
62087   */
62088   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
62089     sqlite3_snprintf(
62090       sizeof(zErr), zErr, "too many attached databases - max %d", 
62091       db->aLimit[SQLITE_LIMIT_ATTACHED]
62092     );
62093     goto attach_error;
62094   }
62095   if( !db->autoCommit ){
62096     sqlite3_snprintf(sizeof(zErr), zErr,
62097                      "cannot ATTACH database within transaction");
62098     goto attach_error;
62099   }
62100   for(i=0; i<db->nDb; i++){
62101     char *z = db->aDb[i].zName;
62102     if( z && zName && sqlite3StrICmp(z, zName)==0 ){
62103       sqlite3_snprintf(sizeof(zErr), zErr, 
62104                        "database %s is already in use", zName);
62105       goto attach_error;
62106     }
62107   }
62108
62109   /* Allocate the new entry in the db->aDb[] array and initialise the schema
62110   ** hash tables.
62111   */
62112   if( db->aDb==db->aDbStatic ){
62113     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
62114     if( aNew==0 ) return;
62115     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
62116   }else{
62117     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
62118     if( aNew==0 ) return;
62119   }
62120   db->aDb = aNew;
62121   aNew = &db->aDb[db->nDb++];
62122   memset(aNew, 0, sizeof(*aNew));
62123
62124   /* Open the database file. If the btree is successfully opened, use
62125   ** it to obtain the database schema. At this point the schema may
62126   ** or may not be initialised.
62127   */
62128   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
62129                            db->openFlags | SQLITE_OPEN_MAIN_DB,
62130                            &aNew->pBt);
62131   if( rc==SQLITE_OK ){
62132     Pager *pPager;
62133     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
62134     if( !aNew->pSchema ){
62135       rc = SQLITE_NOMEM;
62136     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
62137       sqlite3_snprintf(sizeof(zErr), zErr, 
62138         "attached databases must use the same text encoding as main database");
62139       goto attach_error;
62140     }
62141     pPager = sqlite3BtreePager(aNew->pBt);
62142     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
62143     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
62144   }
62145   aNew->zName = sqlite3DbStrDup(db, zName);
62146   aNew->safety_level = 3;
62147
62148 #if SQLITE_HAS_CODEC
62149   {
62150     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
62151     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
62152     int nKey;
62153     char *zKey;
62154     int t = sqlite3_value_type(argv[2]);
62155     switch( t ){
62156       case SQLITE_INTEGER:
62157       case SQLITE_FLOAT:
62158         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
62159         rc = SQLITE_ERROR;
62160         break;
62161         
62162       case SQLITE_TEXT:
62163       case SQLITE_BLOB:
62164         nKey = sqlite3_value_bytes(argv[2]);
62165         zKey = (char *)sqlite3_value_blob(argv[2]);
62166         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
62167         break;
62168
62169       case SQLITE_NULL:
62170         /* No key specified.  Use the key from the main database */
62171         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
62172         sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
62173         break;
62174     }
62175   }
62176 #endif
62177
62178   /* If the file was opened successfully, read the schema for the new database.
62179   ** If this fails, or if opening the file failed, then close the file and 
62180   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
62181   ** we found it.
62182   */
62183   if( rc==SQLITE_OK ){
62184     (void)sqlite3SafetyOn(db);
62185     sqlite3BtreeEnterAll(db);
62186     rc = sqlite3Init(db, &zErrDyn);
62187     sqlite3BtreeLeaveAll(db);
62188     (void)sqlite3SafetyOff(db);
62189   }
62190   if( rc ){
62191     int iDb = db->nDb - 1;
62192     assert( iDb>=2 );
62193     if( db->aDb[iDb].pBt ){
62194       sqlite3BtreeClose(db->aDb[iDb].pBt);
62195       db->aDb[iDb].pBt = 0;
62196       db->aDb[iDb].pSchema = 0;
62197     }
62198     sqlite3ResetInternalSchema(db, 0);
62199     db->nDb = iDb;
62200     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
62201       db->mallocFailed = 1;
62202       sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
62203     }else{
62204       sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
62205     }
62206     goto attach_error;
62207   }
62208   
62209   return;
62210
62211 attach_error:
62212   /* Return an error if we get here */
62213   if( zErrDyn ){
62214     sqlite3_result_error(context, zErrDyn, -1);
62215     sqlite3DbFree(db, zErrDyn);
62216   }else{
62217     zErr[sizeof(zErr)-1] = 0;
62218     sqlite3_result_error(context, zErr, -1);
62219   }
62220   if( rc ) sqlite3_result_error_code(context, rc);
62221 }
62222
62223 /*
62224 ** An SQL user-function registered to do the work of an DETACH statement. The
62225 ** three arguments to the function come directly from a detach statement:
62226 **
62227 **     DETACH DATABASE x
62228 **
62229 **     SELECT sqlite_detach(x)
62230 */
62231 static void detachFunc(
62232   sqlite3_context *context,
62233   int NotUsed,
62234   sqlite3_value **argv
62235 ){
62236   const char *zName = (const char *)sqlite3_value_text(argv[0]);
62237   sqlite3 *db = sqlite3_context_db_handle(context);
62238   int i;
62239   Db *pDb = 0;
62240   char zErr[128];
62241
62242   UNUSED_PARAMETER(NotUsed);
62243
62244   if( zName==0 ) zName = "";
62245   for(i=0; i<db->nDb; i++){
62246     pDb = &db->aDb[i];
62247     if( pDb->pBt==0 ) continue;
62248     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
62249   }
62250
62251   if( i>=db->nDb ){
62252     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
62253     goto detach_error;
62254   }
62255   if( i<2 ){
62256     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
62257     goto detach_error;
62258   }
62259   if( !db->autoCommit ){
62260     sqlite3_snprintf(sizeof(zErr), zErr,
62261                      "cannot DETACH database within transaction");
62262     goto detach_error;
62263   }
62264   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
62265     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
62266     goto detach_error;
62267   }
62268
62269   sqlite3BtreeClose(pDb->pBt);
62270   pDb->pBt = 0;
62271   pDb->pSchema = 0;
62272   sqlite3ResetInternalSchema(db, 0);
62273   return;
62274
62275 detach_error:
62276   sqlite3_result_error(context, zErr, -1);
62277 }
62278
62279 /*
62280 ** This procedure generates VDBE code for a single invocation of either the
62281 ** sqlite_detach() or sqlite_attach() SQL user functions.
62282 */
62283 static void codeAttach(
62284   Parse *pParse,       /* The parser context */
62285   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
62286   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
62287   Expr *pAuthArg,      /* Expression to pass to authorization callback */
62288   Expr *pFilename,     /* Name of database file */
62289   Expr *pDbname,       /* Name of the database to use internally */
62290   Expr *pKey           /* Database key for encryption extension */
62291 ){
62292   int rc;
62293   NameContext sName;
62294   Vdbe *v;
62295   sqlite3* db = pParse->db;
62296   int regArgs;
62297
62298 #ifndef SQLITE_OMIT_AUTHORIZATION
62299   assert( db->mallocFailed || pAuthArg );
62300   if( pAuthArg ){
62301     char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span);
62302     if( !zAuthArg ){
62303       goto attach_end;
62304     }
62305     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
62306     sqlite3DbFree(db, zAuthArg);
62307     if(rc!=SQLITE_OK ){
62308       goto attach_end;
62309     }
62310   }
62311 #endif /* SQLITE_OMIT_AUTHORIZATION */
62312
62313   memset(&sName, 0, sizeof(NameContext));
62314   sName.pParse = pParse;
62315
62316   if( 
62317       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
62318       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
62319       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
62320   ){
62321     pParse->nErr++;
62322     goto attach_end;
62323   }
62324
62325   v = sqlite3GetVdbe(pParse);
62326   regArgs = sqlite3GetTempRange(pParse, 4);
62327   sqlite3ExprCode(pParse, pFilename, regArgs);
62328   sqlite3ExprCode(pParse, pDbname, regArgs+1);
62329   sqlite3ExprCode(pParse, pKey, regArgs+2);
62330
62331   assert( v || db->mallocFailed );
62332   if( v ){
62333     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
62334     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
62335     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
62336     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
62337
62338     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
62339     ** statement only). For DETACH, set it to false (expire all existing
62340     ** statements).
62341     */
62342     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
62343   }
62344   
62345 attach_end:
62346   sqlite3ExprDelete(db, pFilename);
62347   sqlite3ExprDelete(db, pDbname);
62348   sqlite3ExprDelete(db, pKey);
62349 }
62350
62351 /*
62352 ** Called by the parser to compile a DETACH statement.
62353 **
62354 **     DETACH pDbname
62355 */
62356 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
62357   static FuncDef detach_func = {
62358     1,                /* nArg */
62359     SQLITE_UTF8,      /* iPrefEnc */
62360     0,                /* flags */
62361     0,                /* pUserData */
62362     0,                /* pNext */
62363     detachFunc,       /* xFunc */
62364     0,                /* xStep */
62365     0,                /* xFinalize */
62366     "sqlite_detach",  /* zName */
62367     0                 /* pHash */
62368   };
62369   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
62370 }
62371
62372 /*
62373 ** Called by the parser to compile an ATTACH statement.
62374 **
62375 **     ATTACH p AS pDbname KEY pKey
62376 */
62377 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
62378   static FuncDef attach_func = {
62379     3,                /* nArg */
62380     SQLITE_UTF8,      /* iPrefEnc */
62381     0,                /* flags */
62382     0,                /* pUserData */
62383     0,                /* pNext */
62384     attachFunc,       /* xFunc */
62385     0,                /* xStep */
62386     0,                /* xFinalize */
62387     "sqlite_attach",  /* zName */
62388     0                 /* pHash */
62389   };
62390   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
62391 }
62392 #endif /* SQLITE_OMIT_ATTACH */
62393
62394 /*
62395 ** Initialize a DbFixer structure.  This routine must be called prior
62396 ** to passing the structure to one of the sqliteFixAAAA() routines below.
62397 **
62398 ** The return value indicates whether or not fixation is required.  TRUE
62399 ** means we do need to fix the database references, FALSE means we do not.
62400 */
62401 SQLITE_PRIVATE int sqlite3FixInit(
62402   DbFixer *pFix,      /* The fixer to be initialized */
62403   Parse *pParse,      /* Error messages will be written here */
62404   int iDb,            /* This is the database that must be used */
62405   const char *zType,  /* "view", "trigger", or "index" */
62406   const Token *pName  /* Name of the view, trigger, or index */
62407 ){
62408   sqlite3 *db;
62409
62410   if( iDb<0 || iDb==1 ) return 0;
62411   db = pParse->db;
62412   assert( db->nDb>iDb );
62413   pFix->pParse = pParse;
62414   pFix->zDb = db->aDb[iDb].zName;
62415   pFix->zType = zType;
62416   pFix->pName = pName;
62417   return 1;
62418 }
62419
62420 /*
62421 ** The following set of routines walk through the parse tree and assign
62422 ** a specific database to all table references where the database name
62423 ** was left unspecified in the original SQL statement.  The pFix structure
62424 ** must have been initialized by a prior call to sqlite3FixInit().
62425 **
62426 ** These routines are used to make sure that an index, trigger, or
62427 ** view in one database does not refer to objects in a different database.
62428 ** (Exception: indices, triggers, and views in the TEMP database are
62429 ** allowed to refer to anything.)  If a reference is explicitly made
62430 ** to an object in a different database, an error message is added to
62431 ** pParse->zErrMsg and these routines return non-zero.  If everything
62432 ** checks out, these routines return 0.
62433 */
62434 SQLITE_PRIVATE int sqlite3FixSrcList(
62435   DbFixer *pFix,       /* Context of the fixation */
62436   SrcList *pList       /* The Source list to check and modify */
62437 ){
62438   int i;
62439   const char *zDb;
62440   struct SrcList_item *pItem;
62441
62442   if( pList==0 ) return 0;
62443   zDb = pFix->zDb;
62444   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
62445     if( pItem->zDatabase==0 ){
62446       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
62447     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
62448       sqlite3ErrorMsg(pFix->pParse,
62449          "%s %T cannot reference objects in database %s",
62450          pFix->zType, pFix->pName, pItem->zDatabase);
62451       return 1;
62452     }
62453 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
62454     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
62455     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
62456 #endif
62457   }
62458   return 0;
62459 }
62460 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
62461 SQLITE_PRIVATE int sqlite3FixSelect(
62462   DbFixer *pFix,       /* Context of the fixation */
62463   Select *pSelect      /* The SELECT statement to be fixed to one database */
62464 ){
62465   while( pSelect ){
62466     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
62467       return 1;
62468     }
62469     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
62470       return 1;
62471     }
62472     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
62473       return 1;
62474     }
62475     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
62476       return 1;
62477     }
62478     pSelect = pSelect->pPrior;
62479   }
62480   return 0;
62481 }
62482 SQLITE_PRIVATE int sqlite3FixExpr(
62483   DbFixer *pFix,     /* Context of the fixation */
62484   Expr *pExpr        /* The expression to be fixed to one database */
62485 ){
62486   while( pExpr ){
62487     if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
62488       return 1;
62489     }
62490     if( sqlite3FixExprList(pFix, pExpr->pList) ){
62491       return 1;
62492     }
62493     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
62494       return 1;
62495     }
62496     pExpr = pExpr->pLeft;
62497   }
62498   return 0;
62499 }
62500 SQLITE_PRIVATE int sqlite3FixExprList(
62501   DbFixer *pFix,     /* Context of the fixation */
62502   ExprList *pList    /* The expression to be fixed to one database */
62503 ){
62504   int i;
62505   struct ExprList_item *pItem;
62506   if( pList==0 ) return 0;
62507   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
62508     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
62509       return 1;
62510     }
62511   }
62512   return 0;
62513 }
62514 #endif
62515
62516 #ifndef SQLITE_OMIT_TRIGGER
62517 SQLITE_PRIVATE int sqlite3FixTriggerStep(
62518   DbFixer *pFix,     /* Context of the fixation */
62519   TriggerStep *pStep /* The trigger step be fixed to one database */
62520 ){
62521   while( pStep ){
62522     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
62523       return 1;
62524     }
62525     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
62526       return 1;
62527     }
62528     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
62529       return 1;
62530     }
62531     pStep = pStep->pNext;
62532   }
62533   return 0;
62534 }
62535 #endif
62536
62537 /************** End of attach.c **********************************************/
62538 /************** Begin file auth.c ********************************************/
62539 /*
62540 ** 2003 January 11
62541 **
62542 ** The author disclaims copyright to this source code.  In place of
62543 ** a legal notice, here is a blessing:
62544 **
62545 **    May you do good and not evil.
62546 **    May you find forgiveness for yourself and forgive others.
62547 **    May you share freely, never taking more than you give.
62548 **
62549 *************************************************************************
62550 ** This file contains code used to implement the sqlite3_set_authorizer()
62551 ** API.  This facility is an optional feature of the library.  Embedded
62552 ** systems that do not need this facility may omit it by recompiling
62553 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
62554 **
62555 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
62556 */
62557
62558 /*
62559 ** All of the code in this file may be omitted by defining a single
62560 ** macro.
62561 */
62562 #ifndef SQLITE_OMIT_AUTHORIZATION
62563
62564 /*
62565 ** Set or clear the access authorization function.
62566 **
62567 ** The access authorization function is be called during the compilation
62568 ** phase to verify that the user has read and/or write access permission on
62569 ** various fields of the database.  The first argument to the auth function
62570 ** is a copy of the 3rd argument to this routine.  The second argument
62571 ** to the auth function is one of these constants:
62572 **
62573 **       SQLITE_CREATE_INDEX
62574 **       SQLITE_CREATE_TABLE
62575 **       SQLITE_CREATE_TEMP_INDEX
62576 **       SQLITE_CREATE_TEMP_TABLE
62577 **       SQLITE_CREATE_TEMP_TRIGGER
62578 **       SQLITE_CREATE_TEMP_VIEW
62579 **       SQLITE_CREATE_TRIGGER
62580 **       SQLITE_CREATE_VIEW
62581 **       SQLITE_DELETE
62582 **       SQLITE_DROP_INDEX
62583 **       SQLITE_DROP_TABLE
62584 **       SQLITE_DROP_TEMP_INDEX
62585 **       SQLITE_DROP_TEMP_TABLE
62586 **       SQLITE_DROP_TEMP_TRIGGER
62587 **       SQLITE_DROP_TEMP_VIEW
62588 **       SQLITE_DROP_TRIGGER
62589 **       SQLITE_DROP_VIEW
62590 **       SQLITE_INSERT
62591 **       SQLITE_PRAGMA
62592 **       SQLITE_READ
62593 **       SQLITE_SELECT
62594 **       SQLITE_TRANSACTION
62595 **       SQLITE_UPDATE
62596 **
62597 ** The third and fourth arguments to the auth function are the name of
62598 ** the table and the column that are being accessed.  The auth function
62599 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
62600 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
62601 ** means that the SQL statement will never-run - the sqlite3_exec() call
62602 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
62603 ** should run but attempts to read the specified column will return NULL
62604 ** and attempts to write the column will be ignored.
62605 **
62606 ** Setting the auth function to NULL disables this hook.  The default
62607 ** setting of the auth function is NULL.
62608 */
62609 SQLITE_API int sqlite3_set_authorizer(
62610   sqlite3 *db,
62611   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
62612   void *pArg
62613 ){
62614   sqlite3_mutex_enter(db->mutex);
62615   db->xAuth = xAuth;
62616   db->pAuthArg = pArg;
62617   sqlite3ExpirePreparedStatements(db);
62618   sqlite3_mutex_leave(db->mutex);
62619   return SQLITE_OK;
62620 }
62621
62622 /*
62623 ** Write an error message into pParse->zErrMsg that explains that the
62624 ** user-supplied authorization function returned an illegal value.
62625 */
62626 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
62627   sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
62628     "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
62629     "or SQLITE_DENY", rc);
62630   pParse->rc = SQLITE_ERROR;
62631 }
62632
62633 /*
62634 ** The pExpr should be a TK_COLUMN expression.  The table referred to
62635 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
62636 ** Check to see if it is OK to read this particular column.
62637 **
62638 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
62639 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
62640 ** then generate an error.
62641 */
62642 SQLITE_PRIVATE void sqlite3AuthRead(
62643   Parse *pParse,        /* The parser context */
62644   Expr *pExpr,          /* The expression to check authorization on */
62645   Schema *pSchema,      /* The schema of the expression */
62646   SrcList *pTabList     /* All table that pExpr might refer to */
62647 ){
62648   sqlite3 *db = pParse->db;
62649   int rc;
62650   Table *pTab = 0;      /* The table being read */
62651   const char *zCol;     /* Name of the column of the table */
62652   int iSrc;             /* Index in pTabList->a[] of table being read */
62653   const char *zDBase;   /* Name of database being accessed */
62654   TriggerStack *pStack; /* The stack of current triggers */
62655   int iDb;              /* The index of the database the expression refers to */
62656
62657   if( db->xAuth==0 ) return;
62658   if( pExpr->op!=TK_COLUMN ) return;
62659   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
62660   if( iDb<0 ){
62661     /* An attempt to read a column out of a subquery or other
62662     ** temporary table. */
62663     return;
62664   }
62665   for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
62666     if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
62667   }
62668   if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
62669     pTab = pTabList->a[iSrc].pTab;
62670   }else if( (pStack = pParse->trigStack)!=0 ){
62671     /* This must be an attempt to read the NEW or OLD pseudo-tables
62672     ** of a trigger.
62673     */
62674     assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
62675     pTab = pStack->pTab;
62676   }
62677   if( pTab==0 ) return;
62678   if( pExpr->iColumn>=0 ){
62679     assert( pExpr->iColumn<pTab->nCol );
62680     zCol = pTab->aCol[pExpr->iColumn].zName;
62681   }else if( pTab->iPKey>=0 ){
62682     assert( pTab->iPKey<pTab->nCol );
62683     zCol = pTab->aCol[pTab->iPKey].zName;
62684   }else{
62685     zCol = "ROWID";
62686   }
62687   assert( iDb>=0 && iDb<db->nDb );
62688   zDBase = db->aDb[iDb].zName;
62689   rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase, 
62690                  pParse->zAuthContext);
62691   if( rc==SQLITE_IGNORE ){
62692     pExpr->op = TK_NULL;
62693   }else if( rc==SQLITE_DENY ){
62694     if( db->nDb>2 || iDb!=0 ){
62695       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited", 
62696          zDBase, pTab->zName, zCol);
62697     }else{
62698       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
62699     }
62700     pParse->rc = SQLITE_AUTH;
62701   }else if( rc!=SQLITE_OK ){
62702     sqliteAuthBadReturnCode(pParse, rc);
62703   }
62704 }
62705
62706 /*
62707 ** Do an authorization check using the code and arguments given.  Return
62708 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
62709 ** is returned, then the error count and error message in pParse are
62710 ** modified appropriately.
62711 */
62712 SQLITE_PRIVATE int sqlite3AuthCheck(
62713   Parse *pParse,
62714   int code,
62715   const char *zArg1,
62716   const char *zArg2,
62717   const char *zArg3
62718 ){
62719   sqlite3 *db = pParse->db;
62720   int rc;
62721
62722   /* Don't do any authorization checks if the database is initialising
62723   ** or if the parser is being invoked from within sqlite3_declare_vtab.
62724   */
62725   if( db->init.busy || IN_DECLARE_VTAB ){
62726     return SQLITE_OK;
62727   }
62728
62729   if( db->xAuth==0 ){
62730     return SQLITE_OK;
62731   }
62732   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
62733   if( rc==SQLITE_DENY ){
62734     sqlite3ErrorMsg(pParse, "not authorized");
62735     pParse->rc = SQLITE_AUTH;
62736   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
62737     rc = SQLITE_DENY;
62738     sqliteAuthBadReturnCode(pParse, rc);
62739   }
62740   return rc;
62741 }
62742
62743 /*
62744 ** Push an authorization context.  After this routine is called, the
62745 ** zArg3 argument to authorization callbacks will be zContext until
62746 ** popped.  Or if pParse==0, this routine is a no-op.
62747 */
62748 SQLITE_PRIVATE void sqlite3AuthContextPush(
62749   Parse *pParse,
62750   AuthContext *pContext, 
62751   const char *zContext
62752 ){
62753   pContext->pParse = pParse;
62754   if( pParse ){
62755     pContext->zAuthContext = pParse->zAuthContext;
62756     pParse->zAuthContext = zContext;
62757   }
62758 }
62759
62760 /*
62761 ** Pop an authorization context that was previously pushed
62762 ** by sqlite3AuthContextPush
62763 */
62764 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
62765   if( pContext->pParse ){
62766     pContext->pParse->zAuthContext = pContext->zAuthContext;
62767     pContext->pParse = 0;
62768   }
62769 }
62770
62771 #endif /* SQLITE_OMIT_AUTHORIZATION */
62772
62773 /************** End of auth.c ************************************************/
62774 /************** Begin file build.c *******************************************/
62775 /*
62776 ** 2001 September 15
62777 **
62778 ** The author disclaims copyright to this source code.  In place of
62779 ** a legal notice, here is a blessing:
62780 **
62781 **    May you do good and not evil.
62782 **    May you find forgiveness for yourself and forgive others.
62783 **    May you share freely, never taking more than you give.
62784 **
62785 *************************************************************************
62786 ** This file contains C code routines that are called by the SQLite parser
62787 ** when syntax rules are reduced.  The routines in this file handle the
62788 ** following kinds of SQL syntax:
62789 **
62790 **     CREATE TABLE
62791 **     DROP TABLE
62792 **     CREATE INDEX
62793 **     DROP INDEX
62794 **     creating ID lists
62795 **     BEGIN TRANSACTION
62796 **     COMMIT
62797 **     ROLLBACK
62798 **
62799 ** $Id: build.c,v 1.518 2009/02/13 03:43:32 drh Exp $
62800 */
62801
62802 /*
62803 ** This routine is called when a new SQL statement is beginning to
62804 ** be parsed.  Initialize the pParse structure as needed.
62805 */
62806 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
62807   pParse->explain = (u8)explainFlag;
62808   pParse->nVar = 0;
62809 }
62810
62811 #ifndef SQLITE_OMIT_SHARED_CACHE
62812 /*
62813 ** The TableLock structure is only used by the sqlite3TableLock() and
62814 ** codeTableLocks() functions.
62815 */
62816 struct TableLock {
62817   int iDb;             /* The database containing the table to be locked */
62818   int iTab;            /* The root page of the table to be locked */
62819   u8 isWriteLock;      /* True for write lock.  False for a read lock */
62820   const char *zName;   /* Name of the table */
62821 };
62822
62823 /*
62824 ** Record the fact that we want to lock a table at run-time.  
62825 **
62826 ** The table to be locked has root page iTab and is found in database iDb.
62827 ** A read or a write lock can be taken depending on isWritelock.
62828 **
62829 ** This routine just records the fact that the lock is desired.  The
62830 ** code to make the lock occur is generated by a later call to
62831 ** codeTableLocks() which occurs during sqlite3FinishCoding().
62832 */
62833 SQLITE_PRIVATE void sqlite3TableLock(
62834   Parse *pParse,     /* Parsing context */
62835   int iDb,           /* Index of the database containing the table to lock */
62836   int iTab,          /* Root page number of the table to be locked */
62837   u8 isWriteLock,    /* True for a write lock */
62838   const char *zName  /* Name of the table to be locked */
62839 ){
62840   int i;
62841   int nBytes;
62842   TableLock *p;
62843
62844   if( iDb<0 ){
62845     return;
62846   }
62847
62848   for(i=0; i<pParse->nTableLock; i++){
62849     p = &pParse->aTableLock[i];
62850     if( p->iDb==iDb && p->iTab==iTab ){
62851       p->isWriteLock = (p->isWriteLock || isWriteLock);
62852       return;
62853     }
62854   }
62855
62856   nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
62857   pParse->aTableLock = 
62858       sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
62859   if( pParse->aTableLock ){
62860     p = &pParse->aTableLock[pParse->nTableLock++];
62861     p->iDb = iDb;
62862     p->iTab = iTab;
62863     p->isWriteLock = isWriteLock;
62864     p->zName = zName;
62865   }else{
62866     pParse->nTableLock = 0;
62867     pParse->db->mallocFailed = 1;
62868   }
62869 }
62870
62871 /*
62872 ** Code an OP_TableLock instruction for each table locked by the
62873 ** statement (configured by calls to sqlite3TableLock()).
62874 */
62875 static void codeTableLocks(Parse *pParse){
62876   int i;
62877   Vdbe *pVdbe; 
62878
62879   if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
62880     return;
62881   }
62882
62883   for(i=0; i<pParse->nTableLock; i++){
62884     TableLock *p = &pParse->aTableLock[i];
62885     int p1 = p->iDb;
62886     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
62887                       p->zName, P4_STATIC);
62888   }
62889 }
62890 #else
62891   #define codeTableLocks(x)
62892 #endif
62893
62894 /*
62895 ** This routine is called after a single SQL statement has been
62896 ** parsed and a VDBE program to execute that statement has been
62897 ** prepared.  This routine puts the finishing touches on the
62898 ** VDBE program and resets the pParse structure for the next
62899 ** parse.
62900 **
62901 ** Note that if an error occurred, it might be the case that
62902 ** no VDBE code was generated.
62903 */
62904 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
62905   sqlite3 *db;
62906   Vdbe *v;
62907
62908   db = pParse->db;
62909   if( db->mallocFailed ) return;
62910   if( pParse->nested ) return;
62911   if( pParse->nErr ) return;
62912
62913   /* Begin by generating some termination code at the end of the
62914   ** vdbe program
62915   */
62916   v = sqlite3GetVdbe(pParse);
62917   if( v ){
62918     sqlite3VdbeAddOp0(v, OP_Halt);
62919
62920     /* The cookie mask contains one bit for each database file open.
62921     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
62922     ** set for each database that is used.  Generate code to start a
62923     ** transaction on each used database and to verify the schema cookie
62924     ** on each used database.
62925     */
62926     if( pParse->cookieGoto>0 ){
62927       u32 mask;
62928       int iDb;
62929       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
62930       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
62931         if( (mask & pParse->cookieMask)==0 ) continue;
62932         sqlite3VdbeUsesBtree(v, iDb);
62933         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
62934         sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
62935       }
62936 #ifndef SQLITE_OMIT_VIRTUALTABLE
62937       {
62938         int i;
62939         for(i=0; i<pParse->nVtabLock; i++){
62940           char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
62941           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
62942         }
62943         pParse->nVtabLock = 0;
62944       }
62945 #endif
62946
62947       /* Once all the cookies have been verified and transactions opened, 
62948       ** obtain the required table-locks. This is a no-op unless the 
62949       ** shared-cache feature is enabled.
62950       */
62951       codeTableLocks(pParse);
62952       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
62953     }
62954
62955 #ifndef SQLITE_OMIT_TRACE
62956     if( !db->init.busy ){
62957       /* Change the P4 argument of the first opcode (which will always be
62958       ** an OP_Trace) to be the complete text of the current SQL statement.
62959       */
62960       VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
62961       if( pOp && pOp->opcode==OP_Trace ){
62962         sqlite3VdbeChangeP4(v, 0, pParse->zSql,
62963                             (int)(pParse->zTail - pParse->zSql));
62964       }
62965     }
62966 #endif /* SQLITE_OMIT_TRACE */
62967   }
62968
62969
62970   /* Get the VDBE program ready for execution
62971   */
62972   if( v && pParse->nErr==0 && !db->mallocFailed ){
62973 #ifdef SQLITE_DEBUG
62974     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
62975     sqlite3VdbeTrace(v, trace);
62976 #endif
62977     assert( pParse->disableColCache==0 );  /* Disables and re-enables match */
62978     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
62979                          pParse->nTab+3, pParse->explain);
62980     pParse->rc = SQLITE_DONE;
62981     pParse->colNamesSet = 0;
62982   }else if( pParse->rc==SQLITE_OK ){
62983     pParse->rc = SQLITE_ERROR;
62984   }
62985   pParse->nTab = 0;
62986   pParse->nMem = 0;
62987   pParse->nSet = 0;
62988   pParse->nVar = 0;
62989   pParse->cookieMask = 0;
62990   pParse->cookieGoto = 0;
62991 }
62992
62993 /*
62994 ** Run the parser and code generator recursively in order to generate
62995 ** code for the SQL statement given onto the end of the pParse context
62996 ** currently under construction.  When the parser is run recursively
62997 ** this way, the final OP_Halt is not appended and other initialization
62998 ** and finalization steps are omitted because those are handling by the
62999 ** outermost parser.
63000 **
63001 ** Not everything is nestable.  This facility is designed to permit
63002 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
63003 ** care if you decide to try to use this routine for some other purposes.
63004 */
63005 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
63006   va_list ap;
63007   char *zSql;
63008   char *zErrMsg = 0;
63009   sqlite3 *db = pParse->db;
63010 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
63011   char saveBuf[SAVE_SZ];
63012
63013   if( pParse->nErr ) return;
63014   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
63015   va_start(ap, zFormat);
63016   zSql = sqlite3VMPrintf(db, zFormat, ap);
63017   va_end(ap);
63018   if( zSql==0 ){
63019     return;   /* A malloc must have failed */
63020   }
63021   pParse->nested++;
63022   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
63023   memset(&pParse->nVar, 0, SAVE_SZ);
63024   sqlite3RunParser(pParse, zSql, &zErrMsg);
63025   sqlite3DbFree(db, zErrMsg);
63026   sqlite3DbFree(db, zSql);
63027   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
63028   pParse->nested--;
63029 }
63030
63031 /*
63032 ** Locate the in-memory structure that describes a particular database
63033 ** table given the name of that table and (optionally) the name of the
63034 ** database containing the table.  Return NULL if not found.
63035 **
63036 ** If zDatabase is 0, all databases are searched for the table and the
63037 ** first matching table is returned.  (No checking for duplicate table
63038 ** names is done.)  The search order is TEMP first, then MAIN, then any
63039 ** auxiliary databases added using the ATTACH command.
63040 **
63041 ** See also sqlite3LocateTable().
63042 */
63043 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
63044   Table *p = 0;
63045   int i;
63046   int nName;
63047   assert( zName!=0 );
63048   nName = sqlite3Strlen(db, zName) + 1;
63049   for(i=OMIT_TEMPDB; i<db->nDb; i++){
63050     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
63051     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
63052     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
63053     if( p ) break;
63054   }
63055   return p;
63056 }
63057
63058 /*
63059 ** Locate the in-memory structure that describes a particular database
63060 ** table given the name of that table and (optionally) the name of the
63061 ** database containing the table.  Return NULL if not found.  Also leave an
63062 ** error message in pParse->zErrMsg.
63063 **
63064 ** The difference between this routine and sqlite3FindTable() is that this
63065 ** routine leaves an error message in pParse->zErrMsg where
63066 ** sqlite3FindTable() does not.
63067 */
63068 SQLITE_PRIVATE Table *sqlite3LocateTable(
63069   Parse *pParse,         /* context in which to report errors */
63070   int isView,            /* True if looking for a VIEW rather than a TABLE */
63071   const char *zName,     /* Name of the table we are looking for */
63072   const char *zDbase     /* Name of the database.  Might be NULL */
63073 ){
63074   Table *p;
63075
63076   /* Read the database schema. If an error occurs, leave an error message
63077   ** and code in pParse and return NULL. */
63078   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
63079     return 0;
63080   }
63081
63082   p = sqlite3FindTable(pParse->db, zName, zDbase);
63083   if( p==0 ){
63084     const char *zMsg = isView ? "no such view" : "no such table";
63085     if( zDbase ){
63086       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
63087     }else{
63088       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
63089     }
63090     pParse->checkSchema = 1;
63091   }
63092   return p;
63093 }
63094
63095 /*
63096 ** Locate the in-memory structure that describes 
63097 ** a particular index given the name of that index
63098 ** and the name of the database that contains the index.
63099 ** Return NULL if not found.
63100 **
63101 ** If zDatabase is 0, all databases are searched for the
63102 ** table and the first matching index is returned.  (No checking
63103 ** for duplicate index names is done.)  The search order is
63104 ** TEMP first, then MAIN, then any auxiliary databases added
63105 ** using the ATTACH command.
63106 */
63107 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
63108   Index *p = 0;
63109   int i;
63110   int nName = sqlite3Strlen(db, zName)+1;
63111   for(i=OMIT_TEMPDB; i<db->nDb; i++){
63112     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
63113     Schema *pSchema = db->aDb[j].pSchema;
63114     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
63115     assert( pSchema || (j==1 && !db->aDb[1].pBt) );
63116     if( pSchema ){
63117       p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
63118     }
63119     if( p ) break;
63120   }
63121   return p;
63122 }
63123
63124 /*
63125 ** Reclaim the memory used by an index
63126 */
63127 static void freeIndex(Index *p){
63128   sqlite3 *db = p->pTable->db;
63129   sqlite3DbFree(db, p->zColAff);
63130   sqlite3DbFree(db, p);
63131 }
63132
63133 /*
63134 ** Remove the given index from the index hash table, and free
63135 ** its memory structures.
63136 **
63137 ** The index is removed from the database hash tables but
63138 ** it is not unlinked from the Table that it indexes.
63139 ** Unlinking from the Table must be done by the calling function.
63140 */
63141 static void sqlite3DeleteIndex(Index *p){
63142   Index *pOld;
63143   const char *zName = p->zName;
63144
63145   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
63146                            sqlite3Strlen30(zName)+1, 0);
63147   assert( pOld==0 || pOld==p );
63148   freeIndex(p);
63149 }
63150
63151 /*
63152 ** For the index called zIdxName which is found in the database iDb,
63153 ** unlike that index from its Table then remove the index from
63154 ** the index hash table and free all memory structures associated
63155 ** with the index.
63156 */
63157 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
63158   Index *pIndex;
63159   int len;
63160   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
63161
63162   len = sqlite3Strlen(db, zIdxName);
63163   pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
63164   if( pIndex ){
63165     if( pIndex->pTable->pIndex==pIndex ){
63166       pIndex->pTable->pIndex = pIndex->pNext;
63167     }else{
63168       Index *p;
63169       for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
63170       if( p && p->pNext==pIndex ){
63171         p->pNext = pIndex->pNext;
63172       }
63173     }
63174     freeIndex(pIndex);
63175   }
63176   db->flags |= SQLITE_InternChanges;
63177 }
63178
63179 /*
63180 ** Erase all schema information from the in-memory hash tables of
63181 ** a single database.  This routine is called to reclaim memory
63182 ** before the database closes.  It is also called during a rollback
63183 ** if there were schema changes during the transaction or if a
63184 ** schema-cookie mismatch occurs.
63185 **
63186 ** If iDb==0 then reset the internal schema tables for all database
63187 ** files.  If iDb>=1 then reset the internal schema for only the
63188 ** single file indicated.
63189 */
63190 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
63191   int i, j;
63192   assert( iDb>=0 && iDb<db->nDb );
63193
63194   if( iDb==0 ){
63195     sqlite3BtreeEnterAll(db);
63196   }
63197   for(i=iDb; i<db->nDb; i++){
63198     Db *pDb = &db->aDb[i];
63199     if( pDb->pSchema ){
63200       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
63201       sqlite3SchemaFree(pDb->pSchema);
63202     }
63203     if( iDb>0 ) return;
63204   }
63205   assert( iDb==0 );
63206   db->flags &= ~SQLITE_InternChanges;
63207   sqlite3BtreeLeaveAll(db);
63208
63209   /* If one or more of the auxiliary database files has been closed,
63210   ** then remove them from the auxiliary database list.  We take the
63211   ** opportunity to do this here since we have just deleted all of the
63212   ** schema hash tables and therefore do not have to make any changes
63213   ** to any of those tables.
63214   */
63215   for(i=0; i<db->nDb; i++){
63216     struct Db *pDb = &db->aDb[i];
63217     if( pDb->pBt==0 ){
63218       if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
63219       pDb->pAux = 0;
63220     }
63221   }
63222   for(i=j=2; i<db->nDb; i++){
63223     struct Db *pDb = &db->aDb[i];
63224     if( pDb->pBt==0 ){
63225       sqlite3DbFree(db, pDb->zName);
63226       pDb->zName = 0;
63227       continue;
63228     }
63229     if( j<i ){
63230       db->aDb[j] = db->aDb[i];
63231     }
63232     j++;
63233   }
63234   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
63235   db->nDb = j;
63236   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
63237     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
63238     sqlite3DbFree(db, db->aDb);
63239     db->aDb = db->aDbStatic;
63240   }
63241 }
63242
63243 /*
63244 ** This routine is called when a commit occurs.
63245 */
63246 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
63247   db->flags &= ~SQLITE_InternChanges;
63248 }
63249
63250 /*
63251 ** Clear the column names from a table or view.
63252 */
63253 static void sqliteResetColumnNames(Table *pTable){
63254   int i;
63255   Column *pCol;
63256   sqlite3 *db = pTable->db;
63257   assert( pTable!=0 );
63258   if( (pCol = pTable->aCol)!=0 ){
63259     for(i=0; i<pTable->nCol; i++, pCol++){
63260       sqlite3DbFree(db, pCol->zName);
63261       sqlite3ExprDelete(db, pCol->pDflt);
63262       sqlite3DbFree(db, pCol->zType);
63263       sqlite3DbFree(db, pCol->zColl);
63264     }
63265     sqlite3DbFree(db, pTable->aCol);
63266   }
63267   pTable->aCol = 0;
63268   pTable->nCol = 0;
63269 }
63270
63271 /*
63272 ** Remove the memory data structures associated with the given
63273 ** Table.  No changes are made to disk by this routine.
63274 **
63275 ** This routine just deletes the data structure.  It does not unlink
63276 ** the table data structure from the hash table.  Nor does it remove
63277 ** foreign keys from the sqlite.aFKey hash table.  But it does destroy
63278 ** memory structures of the indices and foreign keys associated with 
63279 ** the table.
63280 */
63281 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
63282   Index *pIndex, *pNext;
63283   FKey *pFKey, *pNextFKey;
63284   sqlite3 *db;
63285
63286   if( pTable==0 ) return;
63287   db = pTable->db;
63288
63289   /* Do not delete the table until the reference count reaches zero. */
63290   pTable->nRef--;
63291   if( pTable->nRef>0 ){
63292     return;
63293   }
63294   assert( pTable->nRef==0 );
63295
63296   /* Delete all indices associated with this table
63297   */
63298   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
63299     pNext = pIndex->pNext;
63300     assert( pIndex->pSchema==pTable->pSchema );
63301     sqlite3DeleteIndex(pIndex);
63302   }
63303
63304 #ifndef SQLITE_OMIT_FOREIGN_KEY
63305   /* Delete all foreign keys associated with this table.  The keys
63306   ** should have already been unlinked from the pSchema->aFKey hash table 
63307   */
63308   for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
63309     pNextFKey = pFKey->pNextFrom;
63310     assert( sqlite3HashFind(&pTable->pSchema->aFKey,
63311                            pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
63312     sqlite3DbFree(db, pFKey);
63313   }
63314 #endif
63315
63316   /* Delete the Table structure itself.
63317   */
63318   sqliteResetColumnNames(pTable);
63319   sqlite3DbFree(db, pTable->zName);
63320   sqlite3DbFree(db, pTable->zColAff);
63321   sqlite3SelectDelete(db, pTable->pSelect);
63322 #ifndef SQLITE_OMIT_CHECK
63323   sqlite3ExprDelete(db, pTable->pCheck);
63324 #endif
63325   sqlite3VtabClear(pTable);
63326   sqlite3DbFree(db, pTable);
63327 }
63328
63329 /*
63330 ** Unlink the given table from the hash tables and the delete the
63331 ** table structure with all its indices and foreign keys.
63332 */
63333 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
63334   Table *p;
63335   FKey *pF1, *pF2;
63336   Db *pDb;
63337
63338   assert( db!=0 );
63339   assert( iDb>=0 && iDb<db->nDb );
63340   assert( zTabName && zTabName[0] );
63341   pDb = &db->aDb[iDb];
63342   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
63343                         sqlite3Strlen30(zTabName)+1,0);
63344   if( p ){
63345 #ifndef SQLITE_OMIT_FOREIGN_KEY
63346     for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
63347       int nTo = sqlite3Strlen30(pF1->zTo) + 1;
63348       pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
63349       if( pF2==pF1 ){
63350         sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
63351       }else{
63352         while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
63353         if( pF2 ){
63354           pF2->pNextTo = pF1->pNextTo;
63355         }
63356       }
63357     }
63358 #endif
63359     sqlite3DeleteTable(p);
63360   }
63361   db->flags |= SQLITE_InternChanges;
63362 }
63363
63364 /*
63365 ** Given a token, return a string that consists of the text of that
63366 ** token with any quotations removed.  Space to hold the returned string
63367 ** is obtained from sqliteMalloc() and must be freed by the calling
63368 ** function.
63369 **
63370 ** Tokens are often just pointers into the original SQL text and so
63371 ** are not \000 terminated and are not persistent.  The returned string
63372 ** is \000 terminated and is persistent.
63373 */
63374 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
63375   char *zName;
63376   if( pName ){
63377     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
63378     sqlite3Dequote(zName);
63379   }else{
63380     zName = 0;
63381   }
63382   return zName;
63383 }
63384
63385 /*
63386 ** Open the sqlite_master table stored in database number iDb for
63387 ** writing. The table is opened using cursor 0.
63388 */
63389 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
63390   Vdbe *v = sqlite3GetVdbe(p);
63391   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
63392   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
63393   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
63394 }
63395
63396 /*
63397 ** Parameter zName points to a nul-terminated buffer containing the name
63398 ** of a database ("main", "temp" or the name of an attached db). This
63399 ** function returns the index of the named database in db->aDb[], or
63400 ** -1 if the named db cannot be found.
63401 */
63402 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
63403   int i = -1;         /* Database number */
63404   if( zName ){
63405     Db *pDb;
63406     int n = sqlite3Strlen30(zName);
63407     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
63408       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
63409           0==sqlite3StrICmp(pDb->zName, zName) ){
63410         break;
63411       }
63412     }
63413   }
63414   return i;
63415 }
63416
63417 /*
63418 ** The token *pName contains the name of a database (either "main" or
63419 ** "temp" or the name of an attached db). This routine returns the
63420 ** index of the named database in db->aDb[], or -1 if the named db 
63421 ** does not exist.
63422 */
63423 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
63424   int i;                               /* Database number */
63425   char *zName;                         /* Name we are searching for */
63426   zName = sqlite3NameFromToken(db, pName);
63427   i = sqlite3FindDbName(db, zName);
63428   sqlite3DbFree(db, zName);
63429   return i;
63430 }
63431
63432 /* The table or view or trigger name is passed to this routine via tokens
63433 ** pName1 and pName2. If the table name was fully qualified, for example:
63434 **
63435 ** CREATE TABLE xxx.yyy (...);
63436 ** 
63437 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
63438 ** the table name is not fully qualified, i.e.:
63439 **
63440 ** CREATE TABLE yyy(...);
63441 **
63442 ** Then pName1 is set to "yyy" and pName2 is "".
63443 **
63444 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
63445 ** pName2) that stores the unqualified table name.  The index of the
63446 ** database "xxx" is returned.
63447 */
63448 SQLITE_PRIVATE int sqlite3TwoPartName(
63449   Parse *pParse,      /* Parsing and code generating context */
63450   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
63451   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
63452   Token **pUnqual     /* Write the unqualified object name here */
63453 ){
63454   int iDb;                    /* Database holding the object */
63455   sqlite3 *db = pParse->db;
63456
63457   if( pName2 && pName2->n>0 ){
63458     if( db->init.busy ) {
63459       sqlite3ErrorMsg(pParse, "corrupt database");
63460       pParse->nErr++;
63461       return -1;
63462     }
63463     *pUnqual = pName2;
63464     iDb = sqlite3FindDb(db, pName1);
63465     if( iDb<0 ){
63466       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
63467       pParse->nErr++;
63468       return -1;
63469     }
63470   }else{
63471     assert( db->init.iDb==0 || db->init.busy );
63472     iDb = db->init.iDb;
63473     *pUnqual = pName1;
63474   }
63475   return iDb;
63476 }
63477
63478 /*
63479 ** This routine is used to check if the UTF-8 string zName is a legal
63480 ** unqualified name for a new schema object (table, index, view or
63481 ** trigger). All names are legal except those that begin with the string
63482 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
63483 ** is reserved for internal use.
63484 */
63485 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
63486   if( !pParse->db->init.busy && pParse->nested==0 
63487           && (pParse->db->flags & SQLITE_WriteSchema)==0
63488           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
63489     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
63490     return SQLITE_ERROR;
63491   }
63492   return SQLITE_OK;
63493 }
63494
63495 /*
63496 ** Begin constructing a new table representation in memory.  This is
63497 ** the first of several action routines that get called in response
63498 ** to a CREATE TABLE statement.  In particular, this routine is called
63499 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
63500 ** flag is true if the table should be stored in the auxiliary database
63501 ** file instead of in the main database file.  This is normally the case
63502 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
63503 ** CREATE and TABLE.
63504 **
63505 ** The new table record is initialized and put in pParse->pNewTable.
63506 ** As more of the CREATE TABLE statement is parsed, additional action
63507 ** routines will be called to add more information to this record.
63508 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
63509 ** is called to complete the construction of the new table record.
63510 */
63511 SQLITE_PRIVATE void sqlite3StartTable(
63512   Parse *pParse,   /* Parser context */
63513   Token *pName1,   /* First part of the name of the table or view */
63514   Token *pName2,   /* Second part of the name of the table or view */
63515   int isTemp,      /* True if this is a TEMP table */
63516   int isView,      /* True if this is a VIEW */
63517   int isVirtual,   /* True if this is a VIRTUAL table */
63518   int noErr        /* Do nothing if table already exists */
63519 ){
63520   Table *pTable;
63521   char *zName = 0; /* The name of the new table */
63522   sqlite3 *db = pParse->db;
63523   Vdbe *v;
63524   int iDb;         /* Database number to create the table in */
63525   Token *pName;    /* Unqualified name of the table to create */
63526
63527   /* The table or view name to create is passed to this routine via tokens
63528   ** pName1 and pName2. If the table name was fully qualified, for example:
63529   **
63530   ** CREATE TABLE xxx.yyy (...);
63531   ** 
63532   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
63533   ** the table name is not fully qualified, i.e.:
63534   **
63535   ** CREATE TABLE yyy(...);
63536   **
63537   ** Then pName1 is set to "yyy" and pName2 is "".
63538   **
63539   ** The call below sets the pName pointer to point at the token (pName1 or
63540   ** pName2) that stores the unqualified table name. The variable iDb is
63541   ** set to the index of the database that the table or view is to be
63542   ** created in.
63543   */
63544   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
63545   if( iDb<0 ) return;
63546   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
63547     /* If creating a temp table, the name may not be qualified */
63548     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
63549     return;
63550   }
63551   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
63552
63553   pParse->sNameToken = *pName;
63554   zName = sqlite3NameFromToken(db, pName);
63555   if( zName==0 ) return;
63556   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
63557     goto begin_table_error;
63558   }
63559   if( db->init.iDb==1 ) isTemp = 1;
63560 #ifndef SQLITE_OMIT_AUTHORIZATION
63561   assert( (isTemp & 1)==isTemp );
63562   {
63563     int code;
63564     char *zDb = db->aDb[iDb].zName;
63565     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
63566       goto begin_table_error;
63567     }
63568     if( isView ){
63569       if( !OMIT_TEMPDB && isTemp ){
63570         code = SQLITE_CREATE_TEMP_VIEW;
63571       }else{
63572         code = SQLITE_CREATE_VIEW;
63573       }
63574     }else{
63575       if( !OMIT_TEMPDB && isTemp ){
63576         code = SQLITE_CREATE_TEMP_TABLE;
63577       }else{
63578         code = SQLITE_CREATE_TABLE;
63579       }
63580     }
63581     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
63582       goto begin_table_error;
63583     }
63584   }
63585 #endif
63586
63587   /* Make sure the new table name does not collide with an existing
63588   ** index or table name in the same database.  Issue an error message if
63589   ** it does. The exception is if the statement being parsed was passed
63590   ** to an sqlite3_declare_vtab() call. In that case only the column names
63591   ** and types will be used, so there is no need to test for namespace
63592   ** collisions.
63593   */
63594   if( !IN_DECLARE_VTAB ){
63595     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
63596       goto begin_table_error;
63597     }
63598     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
63599     if( pTable ){
63600       if( !noErr ){
63601         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
63602       }
63603       goto begin_table_error;
63604     }
63605     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
63606       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
63607       goto begin_table_error;
63608     }
63609   }
63610
63611   pTable = sqlite3DbMallocZero(db, sizeof(Table));
63612   if( pTable==0 ){
63613     db->mallocFailed = 1;
63614     pParse->rc = SQLITE_NOMEM;
63615     pParse->nErr++;
63616     goto begin_table_error;
63617   }
63618   pTable->zName = zName;
63619   pTable->iPKey = -1;
63620   pTable->pSchema = db->aDb[iDb].pSchema;
63621   pTable->nRef = 1;
63622   pTable->db = db;
63623   if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
63624   pParse->pNewTable = pTable;
63625
63626   /* If this is the magic sqlite_sequence table used by autoincrement,
63627   ** then record a pointer to this table in the main database structure
63628   ** so that INSERT can find the table easily.
63629   */
63630 #ifndef SQLITE_OMIT_AUTOINCREMENT
63631   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
63632     pTable->pSchema->pSeqTab = pTable;
63633   }
63634 #endif
63635
63636   /* Begin generating the code that will insert the table record into
63637   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
63638   ** and allocate the record number for the table entry now.  Before any
63639   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
63640   ** indices to be created and the table record must come before the 
63641   ** indices.  Hence, the record number for the table must be allocated
63642   ** now.
63643   */
63644   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
63645     int j1;
63646     int fileFormat;
63647     int reg1, reg2, reg3;
63648     sqlite3BeginWriteOperation(pParse, 0, iDb);
63649
63650 #ifndef SQLITE_OMIT_VIRTUALTABLE
63651     if( isVirtual ){
63652       sqlite3VdbeAddOp0(v, OP_VBegin);
63653     }
63654 #endif
63655
63656     /* If the file format and encoding in the database have not been set, 
63657     ** set them now.
63658     */
63659     reg1 = pParse->regRowid = ++pParse->nMem;
63660     reg2 = pParse->regRoot = ++pParse->nMem;
63661     reg3 = ++pParse->nMem;
63662     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1);   /* file_format */
63663     sqlite3VdbeUsesBtree(v, iDb);
63664     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
63665     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
63666                   1 : SQLITE_MAX_FILE_FORMAT;
63667     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
63668     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
63669     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
63670     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
63671     sqlite3VdbeJumpHere(v, j1);
63672
63673     /* This just creates a place-holder record in the sqlite_master table.
63674     ** The record created does not contain anything yet.  It will be replaced
63675     ** by the real entry in code generated at sqlite3EndTable().
63676     **
63677     ** The rowid for the new entry is left on the top of the stack.
63678     ** The rowid value is needed by the code that sqlite3EndTable will
63679     ** generate.
63680     */
63681 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
63682     if( isView || isVirtual ){
63683       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
63684     }else
63685 #endif
63686     {
63687       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
63688     }
63689     sqlite3OpenMasterTable(pParse, iDb);
63690     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
63691     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
63692     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
63693     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
63694     sqlite3VdbeAddOp0(v, OP_Close);
63695   }
63696
63697   /* Normal (non-error) return. */
63698   return;
63699
63700   /* If an error occurs, we jump here */
63701 begin_table_error:
63702   sqlite3DbFree(db, zName);
63703   return;
63704 }
63705
63706 /*
63707 ** This macro is used to compare two strings in a case-insensitive manner.
63708 ** It is slightly faster than calling sqlite3StrICmp() directly, but
63709 ** produces larger code.
63710 **
63711 ** WARNING: This macro is not compatible with the strcmp() family. It
63712 ** returns true if the two strings are equal, otherwise false.
63713 */
63714 #define STRICMP(x, y) (\
63715 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
63716 sqlite3UpperToLower[*(unsigned char *)(y)]     \
63717 && sqlite3StrICmp((x)+1,(y)+1)==0 )
63718
63719 /*
63720 ** Add a new column to the table currently being constructed.
63721 **
63722 ** The parser calls this routine once for each column declaration
63723 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
63724 ** first to get things going.  Then this routine is called for each
63725 ** column.
63726 */
63727 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
63728   Table *p;
63729   int i;
63730   char *z;
63731   Column *pCol;
63732   sqlite3 *db = pParse->db;
63733   if( (p = pParse->pNewTable)==0 ) return;
63734 #if SQLITE_MAX_COLUMN
63735   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
63736     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
63737     return;
63738   }
63739 #endif
63740   z = sqlite3NameFromToken(db, pName);
63741   if( z==0 ) return;
63742   for(i=0; i<p->nCol; i++){
63743     if( STRICMP(z, p->aCol[i].zName) ){
63744       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
63745       sqlite3DbFree(db, z);
63746       return;
63747     }
63748   }
63749   if( (p->nCol & 0x7)==0 ){
63750     Column *aNew;
63751     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
63752     if( aNew==0 ){
63753       sqlite3DbFree(db, z);
63754       return;
63755     }
63756     p->aCol = aNew;
63757   }
63758   pCol = &p->aCol[p->nCol];
63759   memset(pCol, 0, sizeof(p->aCol[0]));
63760   pCol->zName = z;
63761  
63762   /* If there is no type specified, columns have the default affinity
63763   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
63764   ** be called next to set pCol->affinity correctly.
63765   */
63766   pCol->affinity = SQLITE_AFF_NONE;
63767   p->nCol++;
63768 }
63769
63770 /*
63771 ** This routine is called by the parser while in the middle of
63772 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
63773 ** been seen on a column.  This routine sets the notNull flag on
63774 ** the column currently under construction.
63775 */
63776 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
63777   Table *p;
63778   int i;
63779   if( (p = pParse->pNewTable)==0 ) return;
63780   i = p->nCol-1;
63781   if( i>=0 ) p->aCol[i].notNull = (u8)onError;
63782 }
63783
63784 /*
63785 ** Scan the column type name zType (length nType) and return the
63786 ** associated affinity type.
63787 **
63788 ** This routine does a case-independent search of zType for the 
63789 ** substrings in the following table. If one of the substrings is
63790 ** found, the corresponding affinity is returned. If zType contains
63791 ** more than one of the substrings, entries toward the top of 
63792 ** the table take priority. For example, if zType is 'BLOBINT', 
63793 ** SQLITE_AFF_INTEGER is returned.
63794 **
63795 ** Substring     | Affinity
63796 ** --------------------------------
63797 ** 'INT'         | SQLITE_AFF_INTEGER
63798 ** 'CHAR'        | SQLITE_AFF_TEXT
63799 ** 'CLOB'        | SQLITE_AFF_TEXT
63800 ** 'TEXT'        | SQLITE_AFF_TEXT
63801 ** 'BLOB'        | SQLITE_AFF_NONE
63802 ** 'REAL'        | SQLITE_AFF_REAL
63803 ** 'FLOA'        | SQLITE_AFF_REAL
63804 ** 'DOUB'        | SQLITE_AFF_REAL
63805 **
63806 ** If none of the substrings in the above table are found,
63807 ** SQLITE_AFF_NUMERIC is returned.
63808 */
63809 SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
63810   u32 h = 0;
63811   char aff = SQLITE_AFF_NUMERIC;
63812   const unsigned char *zIn = pType->z;
63813   const unsigned char *zEnd = &pType->z[pType->n];
63814
63815   while( zIn!=zEnd ){
63816     h = (h<<8) + sqlite3UpperToLower[*zIn];
63817     zIn++;
63818     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
63819       aff = SQLITE_AFF_TEXT; 
63820     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
63821       aff = SQLITE_AFF_TEXT;
63822     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
63823       aff = SQLITE_AFF_TEXT;
63824     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
63825         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
63826       aff = SQLITE_AFF_NONE;
63827 #ifndef SQLITE_OMIT_FLOATING_POINT
63828     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
63829         && aff==SQLITE_AFF_NUMERIC ){
63830       aff = SQLITE_AFF_REAL;
63831     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
63832         && aff==SQLITE_AFF_NUMERIC ){
63833       aff = SQLITE_AFF_REAL;
63834     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
63835         && aff==SQLITE_AFF_NUMERIC ){
63836       aff = SQLITE_AFF_REAL;
63837 #endif
63838     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
63839       aff = SQLITE_AFF_INTEGER;
63840       break;
63841     }
63842   }
63843
63844   return aff;
63845 }
63846
63847 /*
63848 ** This routine is called by the parser while in the middle of
63849 ** parsing a CREATE TABLE statement.  The pFirst token is the first
63850 ** token in the sequence of tokens that describe the type of the
63851 ** column currently under construction.   pLast is the last token
63852 ** in the sequence.  Use this information to construct a string
63853 ** that contains the typename of the column and store that string
63854 ** in zType.
63855 */ 
63856 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
63857   Table *p;
63858   int i;
63859   Column *pCol;
63860   sqlite3 *db;
63861
63862   if( (p = pParse->pNewTable)==0 ) return;
63863   i = p->nCol-1;
63864   if( i<0 ) return;
63865   pCol = &p->aCol[i];
63866   db = pParse->db;
63867   sqlite3DbFree(db, pCol->zType);
63868   pCol->zType = sqlite3NameFromToken(db, pType);
63869   pCol->affinity = sqlite3AffinityType(pType);
63870 }
63871
63872 /*
63873 ** The expression is the default value for the most recently added column
63874 ** of the table currently under construction.
63875 **
63876 ** Default value expressions must be constant.  Raise an exception if this
63877 ** is not the case.
63878 **
63879 ** This routine is called by the parser while in the middle of
63880 ** parsing a CREATE TABLE statement.
63881 */
63882 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
63883   Table *p;
63884   Column *pCol;
63885   sqlite3 *db = pParse->db;
63886   if( (p = pParse->pNewTable)!=0 ){
63887     pCol = &(p->aCol[p->nCol-1]);
63888     if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
63889       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
63890           pCol->zName);
63891     }else{
63892       Expr *pCopy;
63893       sqlite3ExprDelete(db, pCol->pDflt);
63894       pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
63895       if( pCopy ){
63896         sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
63897       }
63898     }
63899   }
63900   sqlite3ExprDelete(db, pExpr);
63901 }
63902
63903 /*
63904 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
63905 ** of columns that form the primary key.  If pList is NULL, then the
63906 ** most recently added column of the table is the primary key.
63907 **
63908 ** A table can have at most one primary key.  If the table already has
63909 ** a primary key (and this is the second primary key) then create an
63910 ** error.
63911 **
63912 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
63913 ** then we will try to use that column as the rowid.  Set the Table.iPKey
63914 ** field of the table under construction to be the index of the
63915 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
63916 ** no INTEGER PRIMARY KEY.
63917 **
63918 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
63919 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
63920 */
63921 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
63922   Parse *pParse,    /* Parsing context */
63923   ExprList *pList,  /* List of field names to be indexed */
63924   int onError,      /* What to do with a uniqueness conflict */
63925   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
63926   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
63927 ){
63928   Table *pTab = pParse->pNewTable;
63929   char *zType = 0;
63930   int iCol = -1, i;
63931   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
63932   if( pTab->tabFlags & TF_HasPrimaryKey ){
63933     sqlite3ErrorMsg(pParse, 
63934       "table \"%s\" has more than one primary key", pTab->zName);
63935     goto primary_key_exit;
63936   }
63937   pTab->tabFlags |= TF_HasPrimaryKey;
63938   if( pList==0 ){
63939     iCol = pTab->nCol - 1;
63940     pTab->aCol[iCol].isPrimKey = 1;
63941   }else{
63942     for(i=0; i<pList->nExpr; i++){
63943       for(iCol=0; iCol<pTab->nCol; iCol++){
63944         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
63945           break;
63946         }
63947       }
63948       if( iCol<pTab->nCol ){
63949         pTab->aCol[iCol].isPrimKey = 1;
63950       }
63951     }
63952     if( pList->nExpr>1 ) iCol = -1;
63953   }
63954   if( iCol>=0 && iCol<pTab->nCol ){
63955     zType = pTab->aCol[iCol].zType;
63956   }
63957   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
63958         && sortOrder==SQLITE_SO_ASC ){
63959     pTab->iPKey = iCol;
63960     pTab->keyConf = (u8)onError;
63961     assert( autoInc==0 || autoInc==1 );
63962     pTab->tabFlags |= autoInc*TF_Autoincrement;
63963   }else if( autoInc ){
63964 #ifndef SQLITE_OMIT_AUTOINCREMENT
63965     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
63966        "INTEGER PRIMARY KEY");
63967 #endif
63968   }else{
63969     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
63970     pList = 0;
63971   }
63972
63973 primary_key_exit:
63974   sqlite3ExprListDelete(pParse->db, pList);
63975   return;
63976 }
63977
63978 /*
63979 ** Add a new CHECK constraint to the table currently under construction.
63980 */
63981 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
63982   Parse *pParse,    /* Parsing context */
63983   Expr *pCheckExpr  /* The check expression */
63984 ){
63985   sqlite3 *db = pParse->db;
63986 #ifndef SQLITE_OMIT_CHECK
63987   Table *pTab = pParse->pNewTable;
63988   if( pTab && !IN_DECLARE_VTAB ){
63989     /* The CHECK expression must be duplicated so that tokens refer
63990     ** to malloced space and not the (ephemeral) text of the CREATE TABLE
63991     ** statement */
63992     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, 
63993                                   sqlite3ExprDup(db, pCheckExpr));
63994   }
63995 #endif
63996   sqlite3ExprDelete(db, pCheckExpr);
63997 }
63998
63999 /*
64000 ** Set the collation function of the most recently parsed table column
64001 ** to the CollSeq given.
64002 */
64003 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
64004   Table *p;
64005   int i;
64006   char *zColl;              /* Dequoted name of collation sequence */
64007   sqlite3 *db;
64008
64009   if( (p = pParse->pNewTable)==0 ) return;
64010   i = p->nCol-1;
64011   db = pParse->db;
64012   zColl = sqlite3NameFromToken(db, pToken);
64013   if( !zColl ) return;
64014
64015   if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
64016     Index *pIdx;
64017     p->aCol[i].zColl = zColl;
64018   
64019     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
64020     ** then an index may have been created on this column before the
64021     ** collation type was added. Correct this if it is the case.
64022     */
64023     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
64024       assert( pIdx->nColumn==1 );
64025       if( pIdx->aiColumn[0]==i ){
64026         pIdx->azColl[0] = p->aCol[i].zColl;
64027       }
64028     }
64029   }else{
64030     sqlite3DbFree(db, zColl);
64031   }
64032 }
64033
64034 /*
64035 ** This function returns the collation sequence for database native text
64036 ** encoding identified by the string zName, length nName.
64037 **
64038 ** If the requested collation sequence is not available, or not available
64039 ** in the database native encoding, the collation factory is invoked to
64040 ** request it. If the collation factory does not supply such a sequence,
64041 ** and the sequence is available in another text encoding, then that is
64042 ** returned instead.
64043 **
64044 ** If no versions of the requested collations sequence are available, or
64045 ** another error occurs, NULL is returned and an error message written into
64046 ** pParse.
64047 **
64048 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
64049 ** invokes the collation factory if the named collation cannot be found
64050 ** and generates an error message.
64051 */
64052 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
64053   sqlite3 *db = pParse->db;
64054   u8 enc = ENC(db);
64055   u8 initbusy = db->init.busy;
64056   CollSeq *pColl;
64057
64058   pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
64059   if( !initbusy && (!pColl || !pColl->xCmp) ){
64060     pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
64061     if( !pColl ){
64062       if( nName<0 ){
64063         nName = sqlite3Strlen(db, zName);
64064       }
64065       sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
64066       pColl = 0;
64067     }
64068   }
64069
64070   return pColl;
64071 }
64072
64073
64074 /*
64075 ** Generate code that will increment the schema cookie.
64076 **
64077 ** The schema cookie is used to determine when the schema for the
64078 ** database changes.  After each schema change, the cookie value
64079 ** changes.  When a process first reads the schema it records the
64080 ** cookie.  Thereafter, whenever it goes to access the database,
64081 ** it checks the cookie to make sure the schema has not changed
64082 ** since it was last read.
64083 **
64084 ** This plan is not completely bullet-proof.  It is possible for
64085 ** the schema to change multiple times and for the cookie to be
64086 ** set back to prior value.  But schema changes are infrequent
64087 ** and the probability of hitting the same cookie value is only
64088 ** 1 chance in 2^32.  So we're safe enough.
64089 */
64090 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
64091   int r1 = sqlite3GetTempReg(pParse);
64092   sqlite3 *db = pParse->db;
64093   Vdbe *v = pParse->pVdbe;
64094   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
64095   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
64096   sqlite3ReleaseTempReg(pParse, r1);
64097 }
64098
64099 /*
64100 ** Measure the number of characters needed to output the given
64101 ** identifier.  The number returned includes any quotes used
64102 ** but does not include the null terminator.
64103 **
64104 ** The estimate is conservative.  It might be larger that what is
64105 ** really needed.
64106 */
64107 static int identLength(const char *z){
64108   int n;
64109   for(n=0; *z; n++, z++){
64110     if( *z=='"' ){ n++; }
64111   }
64112   return n + 2;
64113 }
64114
64115 /*
64116 ** Write an identifier onto the end of the given string.  Add
64117 ** quote characters as needed.
64118 */
64119 static void identPut(char *z, int *pIdx, char *zSignedIdent){
64120   unsigned char *zIdent = (unsigned char*)zSignedIdent;
64121   int i, j, needQuote;
64122   i = *pIdx;
64123   for(j=0; zIdent[j]; j++){
64124     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
64125   }
64126   needQuote =  zIdent[j]!=0 || sqlite3Isdigit(zIdent[0])
64127                   || sqlite3KeywordCode(zIdent, j)!=TK_ID;
64128   if( needQuote ) z[i++] = '"';
64129   for(j=0; zIdent[j]; j++){
64130     z[i++] = zIdent[j];
64131     if( zIdent[j]=='"' ) z[i++] = '"';
64132   }
64133   if( needQuote ) z[i++] = '"';
64134   z[i] = 0;
64135   *pIdx = i;
64136 }
64137
64138 /*
64139 ** Generate a CREATE TABLE statement appropriate for the given
64140 ** table.  Memory to hold the text of the statement is obtained
64141 ** from sqliteMalloc() and must be freed by the calling function.
64142 */
64143 static char *createTableStmt(sqlite3 *db, Table *p){
64144   int i, k, n;
64145   char *zStmt;
64146   char *zSep, *zSep2, *zEnd, *z;
64147   Column *pCol;
64148   n = 0;
64149   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
64150     n += identLength(pCol->zName);
64151     z = pCol->zType;
64152     if( z ){
64153       n += (sqlite3Strlen30(z) + 1);
64154     }
64155   }
64156   n += identLength(p->zName);
64157   if( n<50 ){
64158     zSep = "";
64159     zSep2 = ",";
64160     zEnd = ")";
64161   }else{
64162     zSep = "\n  ";
64163     zSep2 = ",\n  ";
64164     zEnd = "\n)";
64165   }
64166   n += 35 + 6*p->nCol;
64167   zStmt = sqlite3Malloc( n );
64168   if( zStmt==0 ){
64169     db->mallocFailed = 1;
64170     return 0;
64171   }
64172   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
64173   k = sqlite3Strlen30(zStmt);
64174   identPut(zStmt, &k, p->zName);
64175   zStmt[k++] = '(';
64176   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
64177     sqlite3_snprintf(n-k, &zStmt[k], zSep);
64178     k += sqlite3Strlen30(&zStmt[k]);
64179     zSep = zSep2;
64180     identPut(zStmt, &k, pCol->zName);
64181     if( (z = pCol->zType)!=0 ){
64182       zStmt[k++] = ' ';
64183       assert( (int)(sqlite3Strlen30(z)+k+1)<=n );
64184       sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
64185       k += sqlite3Strlen30(z);
64186     }
64187   }
64188   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
64189   return zStmt;
64190 }
64191
64192 /*
64193 ** This routine is called to report the final ")" that terminates
64194 ** a CREATE TABLE statement.
64195 **
64196 ** The table structure that other action routines have been building
64197 ** is added to the internal hash tables, assuming no errors have
64198 ** occurred.
64199 **
64200 ** An entry for the table is made in the master table on disk, unless
64201 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
64202 ** it means we are reading the sqlite_master table because we just
64203 ** connected to the database or because the sqlite_master table has
64204 ** recently changed, so the entry for this table already exists in
64205 ** the sqlite_master table.  We do not want to create it again.
64206 **
64207 ** If the pSelect argument is not NULL, it means that this routine
64208 ** was called to create a table generated from a 
64209 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
64210 ** the new table will match the result set of the SELECT.
64211 */
64212 SQLITE_PRIVATE void sqlite3EndTable(
64213   Parse *pParse,          /* Parse context */
64214   Token *pCons,           /* The ',' token after the last column defn. */
64215   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
64216   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
64217 ){
64218   Table *p;
64219   sqlite3 *db = pParse->db;
64220   int iDb;
64221
64222   if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
64223     return;
64224   }
64225   p = pParse->pNewTable;
64226   if( p==0 ) return;
64227
64228   assert( !db->init.busy || !pSelect );
64229
64230   iDb = sqlite3SchemaToIndex(db, p->pSchema);
64231
64232 #ifndef SQLITE_OMIT_CHECK
64233   /* Resolve names in all CHECK constraint expressions.
64234   */
64235   if( p->pCheck ){
64236     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
64237     NameContext sNC;                /* Name context for pParse->pNewTable */
64238
64239     memset(&sNC, 0, sizeof(sNC));
64240     memset(&sSrc, 0, sizeof(sSrc));
64241     sSrc.nSrc = 1;
64242     sSrc.a[0].zName = p->zName;
64243     sSrc.a[0].pTab = p;
64244     sSrc.a[0].iCursor = -1;
64245     sNC.pParse = pParse;
64246     sNC.pSrcList = &sSrc;
64247     sNC.isCheck = 1;
64248     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
64249       return;
64250     }
64251   }
64252 #endif /* !defined(SQLITE_OMIT_CHECK) */
64253
64254   /* If the db->init.busy is 1 it means we are reading the SQL off the
64255   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
64256   ** So do not write to the disk again.  Extract the root page number
64257   ** for the table from the db->init.newTnum field.  (The page number
64258   ** should have been put there by the sqliteOpenCb routine.)
64259   */
64260   if( db->init.busy ){
64261     p->tnum = db->init.newTnum;
64262   }
64263
64264   /* If not initializing, then create a record for the new table
64265   ** in the SQLITE_MASTER table of the database.  The record number
64266   ** for the new table entry should already be on the stack.
64267   **
64268   ** If this is a TEMPORARY table, write the entry into the auxiliary
64269   ** file instead of into the main database file.
64270   */
64271   if( !db->init.busy ){
64272     int n;
64273     Vdbe *v;
64274     char *zType;    /* "view" or "table" */
64275     char *zType2;   /* "VIEW" or "TABLE" */
64276     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
64277
64278     v = sqlite3GetVdbe(pParse);
64279     if( v==0 ) return;
64280
64281     sqlite3VdbeAddOp1(v, OP_Close, 0);
64282
64283     /* Create the rootpage for the new table and push it onto the stack.
64284     ** A view has no rootpage, so just push a zero onto the stack for
64285     ** views.  Initialize zType at the same time.
64286     */
64287     if( p->pSelect==0 ){
64288       /* A regular table */
64289       zType = "table";
64290       zType2 = "TABLE";
64291 #ifndef SQLITE_OMIT_VIEW
64292     }else{
64293       /* A view */
64294       zType = "view";
64295       zType2 = "VIEW";
64296 #endif
64297     }
64298
64299     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
64300     ** statement to populate the new table. The root-page number for the
64301     ** new table is on the top of the vdbe stack.
64302     **
64303     ** Once the SELECT has been coded by sqlite3Select(), it is in a
64304     ** suitable state to query for the column names and types to be used
64305     ** by the new table.
64306     **
64307     ** A shared-cache write-lock is not required to write to the new table,
64308     ** as a schema-lock must have already been obtained to create it. Since
64309     ** a schema-lock excludes all other database users, the write-lock would
64310     ** be redundant.
64311     */
64312     if( pSelect ){
64313       SelectDest dest;
64314       Table *pSelTab;
64315
64316       assert(pParse->nTab==0);
64317       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
64318       sqlite3VdbeChangeP5(v, 1);
64319       pParse->nTab = 2;
64320       sqlite3SelectDestInit(&dest, SRT_Table, 1);
64321       sqlite3Select(pParse, pSelect, &dest);
64322       sqlite3VdbeAddOp1(v, OP_Close, 1);
64323       if( pParse->nErr==0 ){
64324         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
64325         if( pSelTab==0 ) return;
64326         assert( p->aCol==0 );
64327         p->nCol = pSelTab->nCol;
64328         p->aCol = pSelTab->aCol;
64329         pSelTab->nCol = 0;
64330         pSelTab->aCol = 0;
64331         sqlite3DeleteTable(pSelTab);
64332       }
64333     }
64334
64335     /* Compute the complete text of the CREATE statement */
64336     if( pSelect ){
64337       zStmt = createTableStmt(db, p);
64338     }else{
64339       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
64340       zStmt = sqlite3MPrintf(db, 
64341           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
64342       );
64343     }
64344
64345     /* A slot for the record has already been allocated in the 
64346     ** SQLITE_MASTER table.  We just need to update that slot with all
64347     ** the information we've collected.  The rowid for the preallocated
64348     ** slot is the 2nd item on the stack.  The top of the stack is the
64349     ** root page for the new table (or a 0 if this is a view).
64350     */
64351     sqlite3NestedParse(pParse,
64352       "UPDATE %Q.%s "
64353          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
64354        "WHERE rowid=#%d",
64355       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
64356       zType,
64357       p->zName,
64358       p->zName,
64359       pParse->regRoot,
64360       zStmt,
64361       pParse->regRowid
64362     );
64363     sqlite3DbFree(db, zStmt);
64364     sqlite3ChangeCookie(pParse, iDb);
64365
64366 #ifndef SQLITE_OMIT_AUTOINCREMENT
64367     /* Check to see if we need to create an sqlite_sequence table for
64368     ** keeping track of autoincrement keys.
64369     */
64370     if( p->tabFlags & TF_Autoincrement ){
64371       Db *pDb = &db->aDb[iDb];
64372       if( pDb->pSchema->pSeqTab==0 ){
64373         sqlite3NestedParse(pParse,
64374           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
64375           pDb->zName
64376         );
64377       }
64378     }
64379 #endif
64380
64381     /* Reparse everything to update our internal data structures */
64382     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
64383         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
64384   }
64385
64386
64387   /* Add the table to the in-memory representation of the database.
64388   */
64389   if( db->init.busy && pParse->nErr==0 ){
64390     Table *pOld;
64391     FKey *pFKey; 
64392     Schema *pSchema = p->pSchema;
64393     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
64394                              sqlite3Strlen30(p->zName)+1,p);
64395     if( pOld ){
64396       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
64397       db->mallocFailed = 1;
64398       return;
64399     }
64400 #ifndef SQLITE_OMIT_FOREIGN_KEY
64401     for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
64402       void *data;
64403       int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
64404       pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
64405       data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
64406       if( data==(void *)pFKey ){
64407         db->mallocFailed = 1;
64408       }
64409     }
64410 #endif
64411     pParse->pNewTable = 0;
64412     db->nTable++;
64413     db->flags |= SQLITE_InternChanges;
64414
64415 #ifndef SQLITE_OMIT_ALTERTABLE
64416     if( !p->pSelect ){
64417       const char *zName = (const char *)pParse->sNameToken.z;
64418       int nName;
64419       assert( !pSelect && pCons && pEnd );
64420       if( pCons->z==0 ){
64421         pCons = pEnd;
64422       }
64423       nName = (int)((const char *)pCons->z - zName);
64424       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
64425     }
64426 #endif
64427   }
64428 }
64429
64430 #ifndef SQLITE_OMIT_VIEW
64431 /*
64432 ** The parser calls this routine in order to create a new VIEW
64433 */
64434 SQLITE_PRIVATE void sqlite3CreateView(
64435   Parse *pParse,     /* The parsing context */
64436   Token *pBegin,     /* The CREATE token that begins the statement */
64437   Token *pName1,     /* The token that holds the name of the view */
64438   Token *pName2,     /* The token that holds the name of the view */
64439   Select *pSelect,   /* A SELECT statement that will become the new view */
64440   int isTemp,        /* TRUE for a TEMPORARY view */
64441   int noErr          /* Suppress error messages if VIEW already exists */
64442 ){
64443   Table *p;
64444   int n;
64445   const unsigned char *z;
64446   Token sEnd;
64447   DbFixer sFix;
64448   Token *pName;
64449   int iDb;
64450   sqlite3 *db = pParse->db;
64451
64452   if( pParse->nVar>0 ){
64453     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
64454     sqlite3SelectDelete(db, pSelect);
64455     return;
64456   }
64457   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
64458   p = pParse->pNewTable;
64459   if( p==0 || pParse->nErr ){
64460     sqlite3SelectDelete(db, pSelect);
64461     return;
64462   }
64463   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
64464   iDb = sqlite3SchemaToIndex(db, p->pSchema);
64465   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
64466     && sqlite3FixSelect(&sFix, pSelect)
64467   ){
64468     sqlite3SelectDelete(db, pSelect);
64469     return;
64470   }
64471
64472   /* Make a copy of the entire SELECT statement that defines the view.
64473   ** This will force all the Expr.token.z values to be dynamically
64474   ** allocated rather than point to the input string - which means that
64475   ** they will persist after the current sqlite3_exec() call returns.
64476   */
64477   p->pSelect = sqlite3SelectDup(db, pSelect);
64478   sqlite3SelectDelete(db, pSelect);
64479   if( db->mallocFailed ){
64480     return;
64481   }
64482   if( !db->init.busy ){
64483     sqlite3ViewGetColumnNames(pParse, p);
64484   }
64485
64486   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
64487   ** the end.
64488   */
64489   sEnd = pParse->sLastToken;
64490   if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
64491     sEnd.z += sEnd.n;
64492   }
64493   sEnd.n = 0;
64494   n = (int)(sEnd.z - pBegin->z);
64495   z = (const unsigned char*)pBegin->z;
64496   while( n>0 && (z[n-1]==';' || sqlite3Isspace(z[n-1])) ){ n--; }
64497   sEnd.z = &z[n-1];
64498   sEnd.n = 1;
64499
64500   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
64501   sqlite3EndTable(pParse, 0, &sEnd, 0);
64502   return;
64503 }
64504 #endif /* SQLITE_OMIT_VIEW */
64505
64506 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
64507 /*
64508 ** The Table structure pTable is really a VIEW.  Fill in the names of
64509 ** the columns of the view in the pTable structure.  Return the number
64510 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
64511 */
64512 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
64513   Table *pSelTab;   /* A fake table from which we get the result set */
64514   Select *pSel;     /* Copy of the SELECT that implements the view */
64515   int nErr = 0;     /* Number of errors encountered */
64516   int n;            /* Temporarily holds the number of cursors assigned */
64517   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
64518   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
64519
64520   assert( pTable );
64521
64522 #ifndef SQLITE_OMIT_VIRTUALTABLE
64523   if( sqlite3VtabCallConnect(pParse, pTable) ){
64524     return SQLITE_ERROR;
64525   }
64526   if( IsVirtual(pTable) ) return 0;
64527 #endif
64528
64529 #ifndef SQLITE_OMIT_VIEW
64530   /* A positive nCol means the columns names for this view are
64531   ** already known.
64532   */
64533   if( pTable->nCol>0 ) return 0;
64534
64535   /* A negative nCol is a special marker meaning that we are currently
64536   ** trying to compute the column names.  If we enter this routine with
64537   ** a negative nCol, it means two or more views form a loop, like this:
64538   **
64539   **     CREATE VIEW one AS SELECT * FROM two;
64540   **     CREATE VIEW two AS SELECT * FROM one;
64541   **
64542   ** Actually, this error is caught previously and so the following test
64543   ** should always fail.  But we will leave it in place just to be safe.
64544   */
64545   if( pTable->nCol<0 ){
64546     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
64547     return 1;
64548   }
64549   assert( pTable->nCol>=0 );
64550
64551   /* If we get this far, it means we need to compute the table names.
64552   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
64553   ** "*" elements in the results set of the view and will assign cursors
64554   ** to the elements of the FROM clause.  But we do not want these changes
64555   ** to be permanent.  So the computation is done on a copy of the SELECT
64556   ** statement that defines the view.
64557   */
64558   assert( pTable->pSelect );
64559   pSel = sqlite3SelectDup(db, pTable->pSelect);
64560   if( pSel ){
64561     n = pParse->nTab;
64562     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
64563     pTable->nCol = -1;
64564 #ifndef SQLITE_OMIT_AUTHORIZATION
64565     xAuth = db->xAuth;
64566     db->xAuth = 0;
64567     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
64568     db->xAuth = xAuth;
64569 #else
64570     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
64571 #endif
64572     pParse->nTab = n;
64573     if( pSelTab ){
64574       assert( pTable->aCol==0 );
64575       pTable->nCol = pSelTab->nCol;
64576       pTable->aCol = pSelTab->aCol;
64577       pSelTab->nCol = 0;
64578       pSelTab->aCol = 0;
64579       sqlite3DeleteTable(pSelTab);
64580       pTable->pSchema->flags |= DB_UnresetViews;
64581     }else{
64582       pTable->nCol = 0;
64583       nErr++;
64584     }
64585     sqlite3SelectDelete(db, pSel);
64586   } else {
64587     nErr++;
64588   }
64589 #endif /* SQLITE_OMIT_VIEW */
64590   return nErr;  
64591 }
64592 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
64593
64594 #ifndef SQLITE_OMIT_VIEW
64595 /*
64596 ** Clear the column names from every VIEW in database idx.
64597 */
64598 static void sqliteViewResetAll(sqlite3 *db, int idx){
64599   HashElem *i;
64600   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
64601   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
64602     Table *pTab = sqliteHashData(i);
64603     if( pTab->pSelect ){
64604       sqliteResetColumnNames(pTab);
64605     }
64606   }
64607   DbClearProperty(db, idx, DB_UnresetViews);
64608 }
64609 #else
64610 # define sqliteViewResetAll(A,B)
64611 #endif /* SQLITE_OMIT_VIEW */
64612
64613 /*
64614 ** This function is called by the VDBE to adjust the internal schema
64615 ** used by SQLite when the btree layer moves a table root page. The
64616 ** root-page of a table or index in database iDb has changed from iFrom
64617 ** to iTo.
64618 **
64619 ** Ticket #1728:  The symbol table might still contain information
64620 ** on tables and/or indices that are the process of being deleted.
64621 ** If you are unlucky, one of those deleted indices or tables might
64622 ** have the same rootpage number as the real table or index that is
64623 ** being moved.  So we cannot stop searching after the first match 
64624 ** because the first match might be for one of the deleted indices
64625 ** or tables and not the table/index that is actually being moved.
64626 ** We must continue looping until all tables and indices with
64627 ** rootpage==iFrom have been converted to have a rootpage of iTo
64628 ** in order to be certain that we got the right one.
64629 */
64630 #ifndef SQLITE_OMIT_AUTOVACUUM
64631 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
64632   HashElem *pElem;
64633   Hash *pHash;
64634
64635   pHash = &pDb->pSchema->tblHash;
64636   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
64637     Table *pTab = sqliteHashData(pElem);
64638     if( pTab->tnum==iFrom ){
64639       pTab->tnum = iTo;
64640     }
64641   }
64642   pHash = &pDb->pSchema->idxHash;
64643   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
64644     Index *pIdx = sqliteHashData(pElem);
64645     if( pIdx->tnum==iFrom ){
64646       pIdx->tnum = iTo;
64647     }
64648   }
64649 }
64650 #endif
64651
64652 /*
64653 ** Write code to erase the table with root-page iTable from database iDb.
64654 ** Also write code to modify the sqlite_master table and internal schema
64655 ** if a root-page of another table is moved by the btree-layer whilst
64656 ** erasing iTable (this can happen with an auto-vacuum database).
64657 */ 
64658 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
64659   Vdbe *v = sqlite3GetVdbe(pParse);
64660   int r1 = sqlite3GetTempReg(pParse);
64661   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
64662 #ifndef SQLITE_OMIT_AUTOVACUUM
64663   /* OP_Destroy stores an in integer r1. If this integer
64664   ** is non-zero, then it is the root page number of a table moved to
64665   ** location iTable. The following code modifies the sqlite_master table to
64666   ** reflect this.
64667   **
64668   ** The "#%d" in the SQL is a special constant that means whatever value
64669   ** is on the top of the stack.  See sqlite3RegisterExpr().
64670   */
64671   sqlite3NestedParse(pParse, 
64672      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
64673      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
64674 #endif
64675   sqlite3ReleaseTempReg(pParse, r1);
64676 }
64677
64678 /*
64679 ** Write VDBE code to erase table pTab and all associated indices on disk.
64680 ** Code to update the sqlite_master tables and internal schema definitions
64681 ** in case a root-page belonging to another table is moved by the btree layer
64682 ** is also added (this can happen with an auto-vacuum database).
64683 */
64684 static void destroyTable(Parse *pParse, Table *pTab){
64685 #ifdef SQLITE_OMIT_AUTOVACUUM
64686   Index *pIdx;
64687   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64688   destroyRootPage(pParse, pTab->tnum, iDb);
64689   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64690     destroyRootPage(pParse, pIdx->tnum, iDb);
64691   }
64692 #else
64693   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
64694   ** is not defined), then it is important to call OP_Destroy on the
64695   ** table and index root-pages in order, starting with the numerically 
64696   ** largest root-page number. This guarantees that none of the root-pages
64697   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
64698   ** following were coded:
64699   **
64700   ** OP_Destroy 4 0
64701   ** ...
64702   ** OP_Destroy 5 0
64703   **
64704   ** and root page 5 happened to be the largest root-page number in the
64705   ** database, then root page 5 would be moved to page 4 by the 
64706   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
64707   ** a free-list page.
64708   */
64709   int iTab = pTab->tnum;
64710   int iDestroyed = 0;
64711
64712   while( 1 ){
64713     Index *pIdx;
64714     int iLargest = 0;
64715
64716     if( iDestroyed==0 || iTab<iDestroyed ){
64717       iLargest = iTab;
64718     }
64719     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64720       int iIdx = pIdx->tnum;
64721       assert( pIdx->pSchema==pTab->pSchema );
64722       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
64723         iLargest = iIdx;
64724       }
64725     }
64726     if( iLargest==0 ){
64727       return;
64728     }else{
64729       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64730       destroyRootPage(pParse, iLargest, iDb);
64731       iDestroyed = iLargest;
64732     }
64733   }
64734 #endif
64735 }
64736
64737 /*
64738 ** This routine is called to do the work of a DROP TABLE statement.
64739 ** pName is the name of the table to be dropped.
64740 */
64741 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
64742   Table *pTab;
64743   Vdbe *v;
64744   sqlite3 *db = pParse->db;
64745   int iDb;
64746
64747   if( pParse->nErr || db->mallocFailed ){
64748     goto exit_drop_table;
64749   }
64750   assert( pName->nSrc==1 );
64751   pTab = sqlite3LocateTable(pParse, isView, 
64752                             pName->a[0].zName, pName->a[0].zDatabase);
64753
64754   if( pTab==0 ){
64755     if( noErr ){
64756       sqlite3ErrorClear(pParse);
64757     }
64758     goto exit_drop_table;
64759   }
64760   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64761   assert( iDb>=0 && iDb<db->nDb );
64762
64763   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
64764   ** it is initialized.
64765   */
64766   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
64767     goto exit_drop_table;
64768   }
64769 #ifndef SQLITE_OMIT_AUTHORIZATION
64770   {
64771     int code;
64772     const char *zTab = SCHEMA_TABLE(iDb);
64773     const char *zDb = db->aDb[iDb].zName;
64774     const char *zArg2 = 0;
64775     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
64776       goto exit_drop_table;
64777     }
64778     if( isView ){
64779       if( !OMIT_TEMPDB && iDb==1 ){
64780         code = SQLITE_DROP_TEMP_VIEW;
64781       }else{
64782         code = SQLITE_DROP_VIEW;
64783       }
64784 #ifndef SQLITE_OMIT_VIRTUALTABLE
64785     }else if( IsVirtual(pTab) ){
64786       code = SQLITE_DROP_VTABLE;
64787       zArg2 = pTab->pMod->zName;
64788 #endif
64789     }else{
64790       if( !OMIT_TEMPDB && iDb==1 ){
64791         code = SQLITE_DROP_TEMP_TABLE;
64792       }else{
64793         code = SQLITE_DROP_TABLE;
64794       }
64795     }
64796     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
64797       goto exit_drop_table;
64798     }
64799     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
64800       goto exit_drop_table;
64801     }
64802   }
64803 #endif
64804   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
64805     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
64806     goto exit_drop_table;
64807   }
64808
64809 #ifndef SQLITE_OMIT_VIEW
64810   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
64811   ** on a table.
64812   */
64813   if( isView && pTab->pSelect==0 ){
64814     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
64815     goto exit_drop_table;
64816   }
64817   if( !isView && pTab->pSelect ){
64818     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
64819     goto exit_drop_table;
64820   }
64821 #endif
64822
64823   /* Generate code to remove the table from the master table
64824   ** on disk.
64825   */
64826   v = sqlite3GetVdbe(pParse);
64827   if( v ){
64828     Trigger *pTrigger;
64829     Db *pDb = &db->aDb[iDb];
64830     sqlite3BeginWriteOperation(pParse, 1, iDb);
64831
64832 #ifndef SQLITE_OMIT_VIRTUALTABLE
64833     if( IsVirtual(pTab) ){
64834       if( v ){
64835         sqlite3VdbeAddOp0(v, OP_VBegin);
64836       }
64837     }
64838 #endif
64839
64840     /* Drop all triggers associated with the table being dropped. Code
64841     ** is generated to remove entries from sqlite_master and/or
64842     ** sqlite_temp_master if required.
64843     */
64844     pTrigger = pTab->pTrigger;
64845     while( pTrigger ){
64846       assert( pTrigger->pSchema==pTab->pSchema || 
64847           pTrigger->pSchema==db->aDb[1].pSchema );
64848       sqlite3DropTriggerPtr(pParse, pTrigger);
64849       pTrigger = pTrigger->pNext;
64850     }
64851
64852 #ifndef SQLITE_OMIT_AUTOINCREMENT
64853     /* Remove any entries of the sqlite_sequence table associated with
64854     ** the table being dropped. This is done before the table is dropped
64855     ** at the btree level, in case the sqlite_sequence table needs to
64856     ** move as a result of the drop (can happen in auto-vacuum mode).
64857     */
64858     if( pTab->tabFlags & TF_Autoincrement ){
64859       sqlite3NestedParse(pParse,
64860         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
64861         pDb->zName, pTab->zName
64862       );
64863     }
64864 #endif
64865
64866     /* Drop all SQLITE_MASTER table and index entries that refer to the
64867     ** table. The program name loops through the master table and deletes
64868     ** every row that refers to a table of the same name as the one being
64869     ** dropped. Triggers are handled seperately because a trigger can be
64870     ** created in the temp database that refers to a table in another
64871     ** database.
64872     */
64873     sqlite3NestedParse(pParse, 
64874         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
64875         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
64876
64877     /* Drop any statistics from the sqlite_stat1 table, if it exists */
64878     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
64879       sqlite3NestedParse(pParse,
64880         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
64881       );
64882     }
64883
64884     if( !isView && !IsVirtual(pTab) ){
64885       destroyTable(pParse, pTab);
64886     }
64887
64888     /* Remove the table entry from SQLite's internal schema and modify
64889     ** the schema cookie.
64890     */
64891     if( IsVirtual(pTab) ){
64892       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
64893     }
64894     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64895     sqlite3ChangeCookie(pParse, iDb);
64896   }
64897   sqliteViewResetAll(db, iDb);
64898
64899 exit_drop_table:
64900   sqlite3SrcListDelete(db, pName);
64901 }
64902
64903 /*
64904 ** This routine is called to create a new foreign key on the table
64905 ** currently under construction.  pFromCol determines which columns
64906 ** in the current table point to the foreign key.  If pFromCol==0 then
64907 ** connect the key to the last column inserted.  pTo is the name of
64908 ** the table referred to.  pToCol is a list of tables in the other
64909 ** pTo table that the foreign key points to.  flags contains all
64910 ** information about the conflict resolution algorithms specified
64911 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
64912 **
64913 ** An FKey structure is created and added to the table currently
64914 ** under construction in the pParse->pNewTable field.  The new FKey
64915 ** is not linked into db->aFKey at this point - that does not happen
64916 ** until sqlite3EndTable().
64917 **
64918 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
64919 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
64920 */
64921 SQLITE_PRIVATE void sqlite3CreateForeignKey(
64922   Parse *pParse,       /* Parsing context */
64923   ExprList *pFromCol,  /* Columns in this table that point to other table */
64924   Token *pTo,          /* Name of the other table */
64925   ExprList *pToCol,    /* Columns in the other table */
64926   int flags            /* Conflict resolution algorithms. */
64927 ){
64928   sqlite3 *db = pParse->db;
64929 #ifndef SQLITE_OMIT_FOREIGN_KEY
64930   FKey *pFKey = 0;
64931   Table *p = pParse->pNewTable;
64932   int nByte;
64933   int i;
64934   int nCol;
64935   char *z;
64936
64937   assert( pTo!=0 );
64938   if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
64939   if( pFromCol==0 ){
64940     int iCol = p->nCol-1;
64941     if( iCol<0 ) goto fk_end;
64942     if( pToCol && pToCol->nExpr!=1 ){
64943       sqlite3ErrorMsg(pParse, "foreign key on %s"
64944          " should reference only one column of table %T",
64945          p->aCol[iCol].zName, pTo);
64946       goto fk_end;
64947     }
64948     nCol = 1;
64949   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
64950     sqlite3ErrorMsg(pParse,
64951         "number of columns in foreign key does not match the number of "
64952         "columns in the referenced table");
64953     goto fk_end;
64954   }else{
64955     nCol = pFromCol->nExpr;
64956   }
64957   nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
64958   if( pToCol ){
64959     for(i=0; i<pToCol->nExpr; i++){
64960       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
64961     }
64962   }
64963   pFKey = sqlite3DbMallocZero(db, nByte );
64964   if( pFKey==0 ){
64965     goto fk_end;
64966   }
64967   pFKey->pFrom = p;
64968   pFKey->pNextFrom = p->pFKey;
64969   z = (char*)&pFKey[1];
64970   pFKey->aCol = (struct sColMap*)z;
64971   z += sizeof(struct sColMap)*nCol;
64972   pFKey->zTo = z;
64973   memcpy(z, pTo->z, pTo->n);
64974   z[pTo->n] = 0;
64975   z += pTo->n+1;
64976   pFKey->pNextTo = 0;
64977   pFKey->nCol = nCol;
64978   if( pFromCol==0 ){
64979     pFKey->aCol[0].iFrom = p->nCol-1;
64980   }else{
64981     for(i=0; i<nCol; i++){
64982       int j;
64983       for(j=0; j<p->nCol; j++){
64984         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
64985           pFKey->aCol[i].iFrom = j;
64986           break;
64987         }
64988       }
64989       if( j>=p->nCol ){
64990         sqlite3ErrorMsg(pParse, 
64991           "unknown column \"%s\" in foreign key definition", 
64992           pFromCol->a[i].zName);
64993         goto fk_end;
64994       }
64995     }
64996   }
64997   if( pToCol ){
64998     for(i=0; i<nCol; i++){
64999       int n = sqlite3Strlen30(pToCol->a[i].zName);
65000       pFKey->aCol[i].zCol = z;
65001       memcpy(z, pToCol->a[i].zName, n);
65002       z[n] = 0;
65003       z += n+1;
65004     }
65005   }
65006   pFKey->isDeferred = 0;
65007   pFKey->deleteConf = (u8)(flags & 0xff);
65008   pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
65009   pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
65010
65011   /* Link the foreign key to the table as the last step.
65012   */
65013   p->pFKey = pFKey;
65014   pFKey = 0;
65015
65016 fk_end:
65017   sqlite3DbFree(db, pFKey);
65018 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
65019   sqlite3ExprListDelete(db, pFromCol);
65020   sqlite3ExprListDelete(db, pToCol);
65021 }
65022
65023 /*
65024 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
65025 ** clause is seen as part of a foreign key definition.  The isDeferred
65026 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
65027 ** The behavior of the most recently created foreign key is adjusted
65028 ** accordingly.
65029 */
65030 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
65031 #ifndef SQLITE_OMIT_FOREIGN_KEY
65032   Table *pTab;
65033   FKey *pFKey;
65034   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
65035   assert( isDeferred==0 || isDeferred==1 );
65036   pFKey->isDeferred = (u8)isDeferred;
65037 #endif
65038 }
65039
65040 /*
65041 ** Generate code that will erase and refill index *pIdx.  This is
65042 ** used to initialize a newly created index or to recompute the
65043 ** content of an index in response to a REINDEX command.
65044 **
65045 ** if memRootPage is not negative, it means that the index is newly
65046 ** created.  The register specified by memRootPage contains the
65047 ** root page number of the index.  If memRootPage is negative, then
65048 ** the index already exists and must be cleared before being refilled and
65049 ** the root page number of the index is taken from pIndex->tnum.
65050 */
65051 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
65052   Table *pTab = pIndex->pTable;  /* The table that is indexed */
65053   int iTab = pParse->nTab;       /* Btree cursor used for pTab */
65054   int iIdx = pParse->nTab+1;     /* Btree cursor used for pIndex */
65055   int addr1;                     /* Address of top of loop */
65056   int tnum;                      /* Root page of index */
65057   Vdbe *v;                       /* Generate code into this virtual machine */
65058   KeyInfo *pKey;                 /* KeyInfo for index */
65059   int regIdxKey;                 /* Registers containing the index key */
65060   int regRecord;                 /* Register holding assemblied index record */
65061   sqlite3 *db = pParse->db;      /* The database connection */
65062   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
65063
65064 #ifndef SQLITE_OMIT_AUTHORIZATION
65065   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
65066       db->aDb[iDb].zName ) ){
65067     return;
65068   }
65069 #endif
65070
65071   /* Require a write-lock on the table to perform this operation */
65072   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
65073
65074   v = sqlite3GetVdbe(pParse);
65075   if( v==0 ) return;
65076   if( memRootPage>=0 ){
65077     tnum = memRootPage;
65078   }else{
65079     tnum = pIndex->tnum;
65080     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
65081   }
65082   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
65083   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
65084                     (char *)pKey, P4_KEYINFO_HANDOFF);
65085   if( memRootPage>=0 ){
65086     sqlite3VdbeChangeP5(v, 1);
65087   }
65088   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
65089   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
65090   regRecord = sqlite3GetTempReg(pParse);
65091   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
65092   if( pIndex->onError!=OE_None ){
65093     int j1, j2;
65094     int regRowid;
65095
65096     regRowid = regIdxKey + pIndex->nColumn;
65097     j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
65098     j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
65099                            0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
65100     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
65101                     "indexed columns are not unique", P4_STATIC);
65102     sqlite3VdbeJumpHere(v, j1);
65103     sqlite3VdbeJumpHere(v, j2);
65104   }
65105   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
65106   sqlite3ReleaseTempReg(pParse, regRecord);
65107   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
65108   sqlite3VdbeJumpHere(v, addr1);
65109   sqlite3VdbeAddOp1(v, OP_Close, iTab);
65110   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
65111 }
65112
65113 /*
65114 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
65115 ** and pTblList is the name of the table that is to be indexed.  Both will 
65116 ** be NULL for a primary key or an index that is created to satisfy a
65117 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
65118 ** as the table to be indexed.  pParse->pNewTable is a table that is
65119 ** currently being constructed by a CREATE TABLE statement.
65120 **
65121 ** pList is a list of columns to be indexed.  pList will be NULL if this
65122 ** is a primary key or unique-constraint on the most recent column added
65123 ** to the table currently under construction.  
65124 */
65125 SQLITE_PRIVATE void sqlite3CreateIndex(
65126   Parse *pParse,     /* All information about this parse */
65127   Token *pName1,     /* First part of index name. May be NULL */
65128   Token *pName2,     /* Second part of index name. May be NULL */
65129   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
65130   ExprList *pList,   /* A list of columns to be indexed */
65131   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
65132   Token *pStart,     /* The CREATE token that begins this statement */
65133   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
65134   int sortOrder,     /* Sort order of primary key when pList==NULL */
65135   int ifNotExist     /* Omit error if index already exists */
65136 ){
65137   Table *pTab = 0;     /* Table to be indexed */
65138   Index *pIndex = 0;   /* The index to be created */
65139   char *zName = 0;     /* Name of the index */
65140   int nName;           /* Number of characters in zName */
65141   int i, j;
65142   Token nullId;        /* Fake token for an empty ID list */
65143   DbFixer sFix;        /* For assigning database names to pTable */
65144   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
65145   sqlite3 *db = pParse->db;
65146   Db *pDb;             /* The specific table containing the indexed database */
65147   int iDb;             /* Index of the database that is being written */
65148   Token *pName = 0;    /* Unqualified name of the index to create */
65149   struct ExprList_item *pListItem; /* For looping over pList */
65150   int nCol;
65151   int nExtra = 0;
65152   char *zExtra;
65153
65154   if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
65155     goto exit_create_index;
65156   }
65157
65158   /*
65159   ** Find the table that is to be indexed.  Return early if not found.
65160   */
65161   if( pTblName!=0 ){
65162
65163     /* Use the two-part index name to determine the database 
65164     ** to search for the table. 'Fix' the table name to this db
65165     ** before looking up the table.
65166     */
65167     assert( pName1 && pName2 );
65168     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
65169     if( iDb<0 ) goto exit_create_index;
65170
65171 #ifndef SQLITE_OMIT_TEMPDB
65172     /* If the index name was unqualified, check if the the table
65173     ** is a temp table. If so, set the database to 1. Do not do this
65174     ** if initialising a database schema.
65175     */
65176     if( !db->init.busy ){
65177       pTab = sqlite3SrcListLookup(pParse, pTblName);
65178       if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
65179         iDb = 1;
65180       }
65181     }
65182 #endif
65183
65184     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
65185         sqlite3FixSrcList(&sFix, pTblName)
65186     ){
65187       /* Because the parser constructs pTblName from a single identifier,
65188       ** sqlite3FixSrcList can never fail. */
65189       assert(0);
65190     }
65191     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
65192         pTblName->a[0].zDatabase);
65193     if( !pTab || db->mallocFailed ) goto exit_create_index;
65194     assert( db->aDb[iDb].pSchema==pTab->pSchema );
65195   }else{
65196     assert( pName==0 );
65197     pTab = pParse->pNewTable;
65198     if( !pTab ) goto exit_create_index;
65199     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65200   }
65201   pDb = &db->aDb[iDb];
65202
65203   if( pTab==0 || pParse->nErr ) goto exit_create_index;
65204   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
65205        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
65206     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
65207     goto exit_create_index;
65208   }
65209 #ifndef SQLITE_OMIT_VIEW
65210   if( pTab->pSelect ){
65211     sqlite3ErrorMsg(pParse, "views may not be indexed");
65212     goto exit_create_index;
65213   }
65214 #endif
65215 #ifndef SQLITE_OMIT_VIRTUALTABLE
65216   if( IsVirtual(pTab) ){
65217     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
65218     goto exit_create_index;
65219   }
65220 #endif
65221
65222   /*
65223   ** Find the name of the index.  Make sure there is not already another
65224   ** index or table with the same name.  
65225   **
65226   ** Exception:  If we are reading the names of permanent indices from the
65227   ** sqlite_master table (because some other process changed the schema) and
65228   ** one of the index names collides with the name of a temporary table or
65229   ** index, then we will continue to process this index.
65230   **
65231   ** If pName==0 it means that we are
65232   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
65233   ** own name.
65234   */
65235   if( pName ){
65236     zName = sqlite3NameFromToken(db, pName);
65237     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
65238     if( zName==0 ) goto exit_create_index;
65239     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
65240       goto exit_create_index;
65241     }
65242     if( !db->init.busy ){
65243       if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
65244       if( sqlite3FindTable(db, zName, 0)!=0 ){
65245         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
65246         goto exit_create_index;
65247       }
65248     }
65249     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
65250       if( !ifNotExist ){
65251         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
65252       }
65253       goto exit_create_index;
65254     }
65255   }else{
65256     int n;
65257     Index *pLoop;
65258     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
65259     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
65260     if( zName==0 ){
65261       goto exit_create_index;
65262     }
65263   }
65264
65265   /* Check for authorization to create an index.
65266   */
65267 #ifndef SQLITE_OMIT_AUTHORIZATION
65268   {
65269     const char *zDb = pDb->zName;
65270     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
65271       goto exit_create_index;
65272     }
65273     i = SQLITE_CREATE_INDEX;
65274     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
65275     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
65276       goto exit_create_index;
65277     }
65278   }
65279 #endif
65280
65281   /* If pList==0, it means this routine was called to make a primary
65282   ** key out of the last column added to the table under construction.
65283   ** So create a fake list to simulate this.
65284   */
65285   if( pList==0 ){
65286     nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
65287     nullId.n = sqlite3Strlen30((char*)nullId.z);
65288     pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
65289     if( pList==0 ) goto exit_create_index;
65290     pList->a[0].sortOrder = (u8)sortOrder;
65291   }
65292
65293   /* Figure out how many bytes of space are required to store explicitly
65294   ** specified collation sequence names.
65295   */
65296   for(i=0; i<pList->nExpr; i++){
65297     Expr *pExpr;
65298     CollSeq *pColl;
65299     if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
65300       nExtra += (1 + sqlite3Strlen30(pColl->zName));
65301     }
65302   }
65303
65304   /* 
65305   ** Allocate the index structure. 
65306   */
65307   nName = sqlite3Strlen30(zName);
65308   nCol = pList->nExpr;
65309   pIndex = sqlite3DbMallocZero(db, 
65310       sizeof(Index) +              /* Index structure  */
65311       sizeof(int)*nCol +           /* Index.aiColumn   */
65312       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
65313       sizeof(char *)*nCol +        /* Index.azColl     */
65314       sizeof(u8)*nCol +            /* Index.aSortOrder */
65315       nName + 1 +                  /* Index.zName      */
65316       nExtra                       /* Collation sequence names */
65317   );
65318   if( db->mallocFailed ){
65319     goto exit_create_index;
65320   }
65321   pIndex->azColl = (char**)(&pIndex[1]);
65322   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
65323   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
65324   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
65325   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
65326   zExtra = (char *)(&pIndex->zName[nName+1]);
65327   memcpy(pIndex->zName, zName, nName+1);
65328   pIndex->pTable = pTab;
65329   pIndex->nColumn = pList->nExpr;
65330   pIndex->onError = (u8)onError;
65331   pIndex->autoIndex = (u8)(pName==0);
65332   pIndex->pSchema = db->aDb[iDb].pSchema;
65333
65334   /* Check to see if we should honor DESC requests on index columns
65335   */
65336   if( pDb->pSchema->file_format>=4 ){
65337     sortOrderMask = -1;   /* Honor DESC */
65338   }else{
65339     sortOrderMask = 0;    /* Ignore DESC */
65340   }
65341
65342   /* Scan the names of the columns of the table to be indexed and
65343   ** load the column indices into the Index structure.  Report an error
65344   ** if any column is not found.
65345   */
65346   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
65347     const char *zColName = pListItem->zName;
65348     Column *pTabCol;
65349     int requestedSortOrder;
65350     char *zColl;                   /* Collation sequence name */
65351
65352     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
65353       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
65354     }
65355     if( j>=pTab->nCol ){
65356       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
65357         pTab->zName, zColName);
65358       goto exit_create_index;
65359     }
65360     /* TODO:  Add a test to make sure that the same column is not named
65361     ** more than once within the same index.  Only the first instance of
65362     ** the column will ever be used by the optimizer.  Note that using the
65363     ** same column more than once cannot be an error because that would 
65364     ** break backwards compatibility - it needs to be a warning.
65365     */
65366     pIndex->aiColumn[i] = j;
65367     if( pListItem->pExpr && pListItem->pExpr->pColl ){
65368       assert( pListItem->pExpr->pColl );
65369       zColl = zExtra;
65370       sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
65371       zExtra += (sqlite3Strlen30(zColl) + 1);
65372     }else{
65373       zColl = pTab->aCol[j].zColl;
65374       if( !zColl ){
65375         zColl = db->pDfltColl->zName;
65376       }
65377     }
65378     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
65379       goto exit_create_index;
65380     }
65381     pIndex->azColl[i] = zColl;
65382     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
65383     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
65384   }
65385   sqlite3DefaultRowEst(pIndex);
65386
65387   if( pTab==pParse->pNewTable ){
65388     /* This routine has been called to create an automatic index as a
65389     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
65390     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
65391     ** i.e. one of:
65392     **
65393     ** CREATE TABLE t(x PRIMARY KEY, y);
65394     ** CREATE TABLE t(x, y, UNIQUE(x, y));
65395     **
65396     ** Either way, check to see if the table already has such an index. If
65397     ** so, don't bother creating this one. This only applies to
65398     ** automatically created indices. Users can do as they wish with
65399     ** explicit indices.
65400     */
65401     Index *pIdx;
65402     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65403       int k;
65404       assert( pIdx->onError!=OE_None );
65405       assert( pIdx->autoIndex );
65406       assert( pIndex->onError!=OE_None );
65407
65408       if( pIdx->nColumn!=pIndex->nColumn ) continue;
65409       for(k=0; k<pIdx->nColumn; k++){
65410         const char *z1 = pIdx->azColl[k];
65411         const char *z2 = pIndex->azColl[k];
65412         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
65413         if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
65414         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
65415       }
65416       if( k==pIdx->nColumn ){
65417         if( pIdx->onError!=pIndex->onError ){
65418           /* This constraint creates the same index as a previous
65419           ** constraint specified somewhere in the CREATE TABLE statement.
65420           ** However the ON CONFLICT clauses are different. If both this 
65421           ** constraint and the previous equivalent constraint have explicit
65422           ** ON CONFLICT clauses this is an error. Otherwise, use the
65423           ** explicitly specified behaviour for the index.
65424           */
65425           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
65426             sqlite3ErrorMsg(pParse, 
65427                 "conflicting ON CONFLICT clauses specified", 0);
65428           }
65429           if( pIdx->onError==OE_Default ){
65430             pIdx->onError = pIndex->onError;
65431           }
65432         }
65433         goto exit_create_index;
65434       }
65435     }
65436   }
65437
65438   /* Link the new Index structure to its table and to the other
65439   ** in-memory database structures. 
65440   */
65441   if( db->init.busy ){
65442     Index *p;
65443     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
65444                           pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
65445                           pIndex);
65446     if( p ){
65447       assert( p==pIndex );  /* Malloc must have failed */
65448       db->mallocFailed = 1;
65449       goto exit_create_index;
65450     }
65451     db->flags |= SQLITE_InternChanges;
65452     if( pTblName!=0 ){
65453       pIndex->tnum = db->init.newTnum;
65454     }
65455   }
65456
65457   /* If the db->init.busy is 0 then create the index on disk.  This
65458   ** involves writing the index into the master table and filling in the
65459   ** index with the current table contents.
65460   **
65461   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
65462   ** command.  db->init.busy is 1 when a database is opened and 
65463   ** CREATE INDEX statements are read out of the master table.  In
65464   ** the latter case the index already exists on disk, which is why
65465   ** we don't want to recreate it.
65466   **
65467   ** If pTblName==0 it means this index is generated as a primary key
65468   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
65469   ** has just been created, it contains no data and the index initialization
65470   ** step can be skipped.
65471   */
65472   else if( db->init.busy==0 ){
65473     Vdbe *v;
65474     char *zStmt;
65475     int iMem = ++pParse->nMem;
65476
65477     v = sqlite3GetVdbe(pParse);
65478     if( v==0 ) goto exit_create_index;
65479
65480
65481     /* Create the rootpage for the index
65482     */
65483     sqlite3BeginWriteOperation(pParse, 1, iDb);
65484     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
65485
65486     /* Gather the complete text of the CREATE INDEX statement into
65487     ** the zStmt variable
65488     */
65489     if( pStart && pEnd ){
65490       /* A named index with an explicit CREATE INDEX statement */
65491       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
65492         onError==OE_None ? "" : " UNIQUE",
65493         pEnd->z - pName->z + 1,
65494         pName->z);
65495     }else{
65496       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
65497       /* zStmt = sqlite3MPrintf(""); */
65498       zStmt = 0;
65499     }
65500
65501     /* Add an entry in sqlite_master for this index
65502     */
65503     sqlite3NestedParse(pParse, 
65504         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
65505         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
65506         pIndex->zName,
65507         pTab->zName,
65508         iMem,
65509         zStmt
65510     );
65511     sqlite3DbFree(db, zStmt);
65512
65513     /* Fill the index with data and reparse the schema. Code an OP_Expire
65514     ** to invalidate all pre-compiled statements.
65515     */
65516     if( pTblName ){
65517       sqlite3RefillIndex(pParse, pIndex, iMem);
65518       sqlite3ChangeCookie(pParse, iDb);
65519       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
65520          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
65521       sqlite3VdbeAddOp1(v, OP_Expire, 0);
65522     }
65523   }
65524
65525   /* When adding an index to the list of indices for a table, make
65526   ** sure all indices labeled OE_Replace come after all those labeled
65527   ** OE_Ignore.  This is necessary for the correct operation of UPDATE
65528   ** and INSERT.
65529   */
65530   if( db->init.busy || pTblName==0 ){
65531     if( onError!=OE_Replace || pTab->pIndex==0
65532          || pTab->pIndex->onError==OE_Replace){
65533       pIndex->pNext = pTab->pIndex;
65534       pTab->pIndex = pIndex;
65535     }else{
65536       Index *pOther = pTab->pIndex;
65537       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
65538         pOther = pOther->pNext;
65539       }
65540       pIndex->pNext = pOther->pNext;
65541       pOther->pNext = pIndex;
65542     }
65543     pIndex = 0;
65544   }
65545
65546   /* Clean up before exiting */
65547 exit_create_index:
65548   if( pIndex ){
65549     freeIndex(pIndex);
65550   }
65551   sqlite3ExprListDelete(db, pList);
65552   sqlite3SrcListDelete(db, pTblName);
65553   sqlite3DbFree(db, zName);
65554   return;
65555 }
65556
65557 /*
65558 ** Generate code to make sure the file format number is at least minFormat.
65559 ** The generated code will increase the file format number if necessary.
65560 */
65561 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
65562   Vdbe *v;
65563   v = sqlite3GetVdbe(pParse);
65564   if( v ){
65565     int r1 = sqlite3GetTempReg(pParse);
65566     int r2 = sqlite3GetTempReg(pParse);
65567     int j1;
65568     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
65569     sqlite3VdbeUsesBtree(v, iDb);
65570     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
65571     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
65572     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
65573     sqlite3VdbeJumpHere(v, j1);
65574     sqlite3ReleaseTempReg(pParse, r1);
65575     sqlite3ReleaseTempReg(pParse, r2);
65576   }
65577 }
65578
65579 /*
65580 ** Fill the Index.aiRowEst[] array with default information - information
65581 ** to be used when we have not run the ANALYZE command.
65582 **
65583 ** aiRowEst[0] is suppose to contain the number of elements in the index.
65584 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
65585 ** number of rows in the table that match any particular value of the
65586 ** first column of the index.  aiRowEst[2] is an estimate of the number
65587 ** of rows that match any particular combiniation of the first 2 columns
65588 ** of the index.  And so forth.  It must always be the case that
65589 *
65590 **           aiRowEst[N]<=aiRowEst[N-1]
65591 **           aiRowEst[N]>=1
65592 **
65593 ** Apart from that, we have little to go on besides intuition as to
65594 ** how aiRowEst[] should be initialized.  The numbers generated here
65595 ** are based on typical values found in actual indices.
65596 */
65597 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
65598   unsigned *a = pIdx->aiRowEst;
65599   int i;
65600   assert( a!=0 );
65601   a[0] = 1000000;
65602   for(i=pIdx->nColumn; i>=5; i--){
65603     a[i] = 5;
65604   }
65605   while( i>=1 ){
65606     a[i] = 11 - i;
65607     i--;
65608   }
65609   if( pIdx->onError!=OE_None ){
65610     a[pIdx->nColumn] = 1;
65611   }
65612 }
65613
65614 /*
65615 ** This routine will drop an existing named index.  This routine
65616 ** implements the DROP INDEX statement.
65617 */
65618 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
65619   Index *pIndex;
65620   Vdbe *v;
65621   sqlite3 *db = pParse->db;
65622   int iDb;
65623
65624   if( pParse->nErr || db->mallocFailed ){
65625     goto exit_drop_index;
65626   }
65627   assert( pName->nSrc==1 );
65628   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65629     goto exit_drop_index;
65630   }
65631   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
65632   if( pIndex==0 ){
65633     if( !ifExists ){
65634       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
65635     }
65636     pParse->checkSchema = 1;
65637     goto exit_drop_index;
65638   }
65639   if( pIndex->autoIndex ){
65640     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
65641       "or PRIMARY KEY constraint cannot be dropped", 0);
65642     goto exit_drop_index;
65643   }
65644   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
65645 #ifndef SQLITE_OMIT_AUTHORIZATION
65646   {
65647     int code = SQLITE_DROP_INDEX;
65648     Table *pTab = pIndex->pTable;
65649     const char *zDb = db->aDb[iDb].zName;
65650     const char *zTab = SCHEMA_TABLE(iDb);
65651     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
65652       goto exit_drop_index;
65653     }
65654     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
65655     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
65656       goto exit_drop_index;
65657     }
65658   }
65659 #endif
65660
65661   /* Generate code to remove the index and from the master table */
65662   v = sqlite3GetVdbe(pParse);
65663   if( v ){
65664     sqlite3BeginWriteOperation(pParse, 1, iDb);
65665     sqlite3NestedParse(pParse,
65666        "DELETE FROM %Q.%s WHERE name=%Q",
65667        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
65668        pIndex->zName
65669     );
65670     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
65671       sqlite3NestedParse(pParse,
65672         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
65673         db->aDb[iDb].zName, pIndex->zName
65674       );
65675     }
65676     sqlite3ChangeCookie(pParse, iDb);
65677     destroyRootPage(pParse, pIndex->tnum, iDb);
65678     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
65679   }
65680
65681 exit_drop_index:
65682   sqlite3SrcListDelete(db, pName);
65683 }
65684
65685 /*
65686 ** pArray is a pointer to an array of objects.  Each object in the
65687 ** array is szEntry bytes in size.  This routine allocates a new
65688 ** object on the end of the array.
65689 **
65690 ** *pnEntry is the number of entries already in use.  *pnAlloc is
65691 ** the previously allocated size of the array.  initSize is the
65692 ** suggested initial array size allocation.
65693 **
65694 ** The index of the new entry is returned in *pIdx.
65695 **
65696 ** This routine returns a pointer to the array of objects.  This
65697 ** might be the same as the pArray parameter or it might be a different
65698 ** pointer if the array was resized.
65699 */
65700 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
65701   sqlite3 *db,      /* Connection to notify of malloc failures */
65702   void *pArray,     /* Array of objects.  Might be reallocated */
65703   int szEntry,      /* Size of each object in the array */
65704   int initSize,     /* Suggested initial allocation, in elements */
65705   int *pnEntry,     /* Number of objects currently in use */
65706   int *pnAlloc,     /* Current size of the allocation, in elements */
65707   int *pIdx         /* Write the index of a new slot here */
65708 ){
65709   char *z;
65710   if( *pnEntry >= *pnAlloc ){
65711     void *pNew;
65712     int newSize;
65713     newSize = (*pnAlloc)*2 + initSize;
65714     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
65715     if( pNew==0 ){
65716       *pIdx = -1;
65717       return pArray;
65718     }
65719     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
65720     pArray = pNew;
65721   }
65722   z = (char*)pArray;
65723   memset(&z[*pnEntry * szEntry], 0, szEntry);
65724   *pIdx = *pnEntry;
65725   ++*pnEntry;
65726   return pArray;
65727 }
65728
65729 /*
65730 ** Append a new element to the given IdList.  Create a new IdList if
65731 ** need be.
65732 **
65733 ** A new IdList is returned, or NULL if malloc() fails.
65734 */
65735 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
65736   int i;
65737   if( pList==0 ){
65738     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
65739     if( pList==0 ) return 0;
65740     pList->nAlloc = 0;
65741   }
65742   pList->a = sqlite3ArrayAllocate(
65743       db,
65744       pList->a,
65745       sizeof(pList->a[0]),
65746       5,
65747       &pList->nId,
65748       &pList->nAlloc,
65749       &i
65750   );
65751   if( i<0 ){
65752     sqlite3IdListDelete(db, pList);
65753     return 0;
65754   }
65755   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
65756   return pList;
65757 }
65758
65759 /*
65760 ** Delete an IdList.
65761 */
65762 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
65763   int i;
65764   if( pList==0 ) return;
65765   for(i=0; i<pList->nId; i++){
65766     sqlite3DbFree(db, pList->a[i].zName);
65767   }
65768   sqlite3DbFree(db, pList->a);
65769   sqlite3DbFree(db, pList);
65770 }
65771
65772 /*
65773 ** Return the index in pList of the identifier named zId.  Return -1
65774 ** if not found.
65775 */
65776 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
65777   int i;
65778   if( pList==0 ) return -1;
65779   for(i=0; i<pList->nId; i++){
65780     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
65781   }
65782   return -1;
65783 }
65784
65785 /*
65786 ** Expand the space allocated for the given SrcList object by
65787 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
65788 ** New slots are zeroed.
65789 **
65790 ** For example, suppose a SrcList initially contains two entries: A,B.
65791 ** To append 3 new entries onto the end, do this:
65792 **
65793 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
65794 **
65795 ** After the call above it would contain:  A, B, nil, nil, nil.
65796 ** If the iStart argument had been 1 instead of 2, then the result
65797 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
65798 ** the iStart value would be 0.  The result then would
65799 ** be: nil, nil, nil, A, B.
65800 **
65801 ** If a memory allocation fails the SrcList is unchanged.  The
65802 ** db->mallocFailed flag will be set to true.
65803 */
65804 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
65805   sqlite3 *db,       /* Database connection to notify of OOM errors */
65806   SrcList *pSrc,     /* The SrcList to be enlarged */
65807   int nExtra,        /* Number of new slots to add to pSrc->a[] */
65808   int iStart         /* Index in pSrc->a[] of first new slot */
65809 ){
65810   int i;
65811
65812   /* Sanity checking on calling parameters */
65813   assert( iStart>=0 );
65814   assert( nExtra>=1 );
65815   if( pSrc==0 || iStart>pSrc->nSrc ){
65816     assert( db->mallocFailed );
65817     return pSrc;
65818   }
65819
65820   /* Allocate additional space if needed */
65821   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
65822     SrcList *pNew;
65823     int nAlloc = pSrc->nSrc+nExtra;
65824     int nGot;
65825     pNew = sqlite3DbRealloc(db, pSrc,
65826                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
65827     if( pNew==0 ){
65828       assert( db->mallocFailed );
65829       return pSrc;
65830     }
65831     pSrc = pNew;
65832     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
65833     pSrc->nAlloc = (u16)nGot;
65834   }
65835
65836   /* Move existing slots that come after the newly inserted slots
65837   ** out of the way */
65838   for(i=pSrc->nSrc-1; i>=iStart; i--){
65839     pSrc->a[i+nExtra] = pSrc->a[i];
65840   }
65841   pSrc->nSrc += (i16)nExtra;
65842
65843   /* Zero the newly allocated slots */
65844   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
65845   for(i=iStart; i<iStart+nExtra; i++){
65846     pSrc->a[i].iCursor = -1;
65847   }
65848
65849   /* Return a pointer to the enlarged SrcList */
65850   return pSrc;
65851 }
65852
65853
65854 /*
65855 ** Append a new table name to the given SrcList.  Create a new SrcList if
65856 ** need be.  A new entry is created in the SrcList even if pToken is NULL.
65857 **
65858 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
65859 ** SrcList might be the same as the SrcList that was input or it might be
65860 ** a new one.  If an OOM error does occurs, then the prior value of pList
65861 ** that is input to this routine is automatically freed.
65862 **
65863 ** If pDatabase is not null, it means that the table has an optional
65864 ** database name prefix.  Like this:  "database.table".  The pDatabase
65865 ** points to the table name and the pTable points to the database name.
65866 ** The SrcList.a[].zName field is filled with the table name which might
65867 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
65868 ** SrcList.a[].zDatabase is filled with the database name from pTable,
65869 ** or with NULL if no database is specified.
65870 **
65871 ** In other words, if call like this:
65872 **
65873 **         sqlite3SrcListAppend(D,A,B,0);
65874 **
65875 ** Then B is a table name and the database name is unspecified.  If called
65876 ** like this:
65877 **
65878 **         sqlite3SrcListAppend(D,A,B,C);
65879 **
65880 ** Then C is the table name and B is the database name.
65881 */
65882 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
65883   sqlite3 *db,        /* Connection to notify of malloc failures */
65884   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
65885   Token *pTable,      /* Table to append */
65886   Token *pDatabase    /* Database of the table */
65887 ){
65888   struct SrcList_item *pItem;
65889   if( pList==0 ){
65890     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
65891     if( pList==0 ) return 0;
65892     pList->nAlloc = 1;
65893   }
65894   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
65895   if( db->mallocFailed ){
65896     sqlite3SrcListDelete(db, pList);
65897     return 0;
65898   }
65899   pItem = &pList->a[pList->nSrc-1];
65900   if( pDatabase && pDatabase->z==0 ){
65901     pDatabase = 0;
65902   }
65903   if( pDatabase && pTable ){
65904     Token *pTemp = pDatabase;
65905     pDatabase = pTable;
65906     pTable = pTemp;
65907   }
65908   pItem->zName = sqlite3NameFromToken(db, pTable);
65909   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
65910   return pList;
65911 }
65912
65913 /*
65914 ** Assign VdbeCursor index numbers to all tables in a SrcList
65915 */
65916 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
65917   int i;
65918   struct SrcList_item *pItem;
65919   assert(pList || pParse->db->mallocFailed );
65920   if( pList ){
65921     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
65922       if( pItem->iCursor>=0 ) break;
65923       pItem->iCursor = pParse->nTab++;
65924       if( pItem->pSelect ){
65925         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
65926       }
65927     }
65928   }
65929 }
65930
65931 /*
65932 ** Delete an entire SrcList including all its substructure.
65933 */
65934 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
65935   int i;
65936   struct SrcList_item *pItem;
65937   if( pList==0 ) return;
65938   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
65939     sqlite3DbFree(db, pItem->zDatabase);
65940     sqlite3DbFree(db, pItem->zName);
65941     sqlite3DbFree(db, pItem->zAlias);
65942     sqlite3DbFree(db, pItem->zIndex);
65943     sqlite3DeleteTable(pItem->pTab);
65944     sqlite3SelectDelete(db, pItem->pSelect);
65945     sqlite3ExprDelete(db, pItem->pOn);
65946     sqlite3IdListDelete(db, pItem->pUsing);
65947   }
65948   sqlite3DbFree(db, pList);
65949 }
65950
65951 /*
65952 ** This routine is called by the parser to add a new term to the
65953 ** end of a growing FROM clause.  The "p" parameter is the part of
65954 ** the FROM clause that has already been constructed.  "p" is NULL
65955 ** if this is the first term of the FROM clause.  pTable and pDatabase
65956 ** are the name of the table and database named in the FROM clause term.
65957 ** pDatabase is NULL if the database name qualifier is missing - the
65958 ** usual case.  If the term has a alias, then pAlias points to the
65959 ** alias token.  If the term is a subquery, then pSubquery is the
65960 ** SELECT statement that the subquery encodes.  The pTable and
65961 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
65962 ** parameters are the content of the ON and USING clauses.
65963 **
65964 ** Return a new SrcList which encodes is the FROM with the new
65965 ** term added.
65966 */
65967 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
65968   Parse *pParse,          /* Parsing context */
65969   SrcList *p,             /* The left part of the FROM clause already seen */
65970   Token *pTable,          /* Name of the table to add to the FROM clause */
65971   Token *pDatabase,       /* Name of the database containing pTable */
65972   Token *pAlias,          /* The right-hand side of the AS subexpression */
65973   Select *pSubquery,      /* A subquery used in place of a table name */
65974   Expr *pOn,              /* The ON clause of a join */
65975   IdList *pUsing          /* The USING clause of a join */
65976 ){
65977   struct SrcList_item *pItem;
65978   sqlite3 *db = pParse->db;
65979   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
65980   if( p==0 || p->nSrc==0 ){
65981     sqlite3ExprDelete(db, pOn);
65982     sqlite3IdListDelete(db, pUsing);
65983     sqlite3SelectDelete(db, pSubquery);
65984     return p;
65985   }
65986   pItem = &p->a[p->nSrc-1];
65987   if( pAlias && pAlias->n ){
65988     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
65989   }
65990   pItem->pSelect = pSubquery;
65991   pItem->pOn = pOn;
65992   pItem->pUsing = pUsing;
65993   return p;
65994 }
65995
65996 /*
65997 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
65998 ** element of the source-list passed as the second argument.
65999 */
66000 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
66001   if( pIndexedBy && p && p->nSrc>0 ){
66002     struct SrcList_item *pItem = &p->a[p->nSrc-1];
66003     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
66004     if( pIndexedBy->n==1 && !pIndexedBy->z ){
66005       /* A "NOT INDEXED" clause was supplied. See parse.y 
66006       ** construct "indexed_opt" for details. */
66007       pItem->notIndexed = 1;
66008     }else{
66009       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
66010     }
66011   }
66012 }
66013
66014 /*
66015 ** When building up a FROM clause in the parser, the join operator
66016 ** is initially attached to the left operand.  But the code generator
66017 ** expects the join operator to be on the right operand.  This routine
66018 ** Shifts all join operators from left to right for an entire FROM
66019 ** clause.
66020 **
66021 ** Example: Suppose the join is like this:
66022 **
66023 **           A natural cross join B
66024 **
66025 ** The operator is "natural cross join".  The A and B operands are stored
66026 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
66027 ** operator with A.  This routine shifts that operator over to B.
66028 */
66029 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
66030   if( p && p->a ){
66031     int i;
66032     for(i=p->nSrc-1; i>0; i--){
66033       p->a[i].jointype = p->a[i-1].jointype;
66034     }
66035     p->a[0].jointype = 0;
66036   }
66037 }
66038
66039 /*
66040 ** Begin a transaction
66041 */
66042 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
66043   sqlite3 *db;
66044   Vdbe *v;
66045   int i;
66046
66047   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
66048   if( pParse->nErr || db->mallocFailed ) return;
66049   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
66050
66051   v = sqlite3GetVdbe(pParse);
66052   if( !v ) return;
66053   if( type!=TK_DEFERRED ){
66054     for(i=0; i<db->nDb; i++){
66055       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
66056       sqlite3VdbeUsesBtree(v, i);
66057     }
66058   }
66059   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
66060 }
66061
66062 /*
66063 ** Commit a transaction
66064 */
66065 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
66066   sqlite3 *db;
66067   Vdbe *v;
66068
66069   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
66070   if( pParse->nErr || db->mallocFailed ) return;
66071   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
66072
66073   v = sqlite3GetVdbe(pParse);
66074   if( v ){
66075     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
66076   }
66077 }
66078
66079 /*
66080 ** Rollback a transaction
66081 */
66082 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
66083   sqlite3 *db;
66084   Vdbe *v;
66085
66086   if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
66087   if( pParse->nErr || db->mallocFailed ) return;
66088   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
66089
66090   v = sqlite3GetVdbe(pParse);
66091   if( v ){
66092     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
66093   }
66094 }
66095
66096 /*
66097 ** This function is called by the parser when it parses a command to create,
66098 ** release or rollback an SQL savepoint. 
66099 */
66100 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
66101   char *zName = sqlite3NameFromToken(pParse->db, pName);
66102   if( zName ){
66103     Vdbe *v = sqlite3GetVdbe(pParse);
66104 #ifndef SQLITE_OMIT_AUTHORIZATION
66105     static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
66106     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
66107 #endif
66108     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
66109       sqlite3DbFree(pParse->db, zName);
66110       return;
66111     }
66112     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
66113   }
66114 }
66115
66116 /*
66117 ** Make sure the TEMP database is open and available for use.  Return
66118 ** the number of errors.  Leave any error messages in the pParse structure.
66119 */
66120 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
66121   sqlite3 *db = pParse->db;
66122   if( db->aDb[1].pBt==0 && !pParse->explain ){
66123     int rc;
66124     static const int flags = 
66125           SQLITE_OPEN_READWRITE |
66126           SQLITE_OPEN_CREATE |
66127           SQLITE_OPEN_EXCLUSIVE |
66128           SQLITE_OPEN_DELETEONCLOSE |
66129           SQLITE_OPEN_TEMP_DB;
66130
66131     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
66132                                  &db->aDb[1].pBt);
66133     if( rc!=SQLITE_OK ){
66134       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
66135         "file for storing temporary tables");
66136       pParse->rc = rc;
66137       return 1;
66138     }
66139     assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
66140     assert( db->aDb[1].pSchema );
66141     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
66142                             db->dfltJournalMode);
66143   }
66144   return 0;
66145 }
66146
66147 /*
66148 ** Generate VDBE code that will verify the schema cookie and start
66149 ** a read-transaction for all named database files.
66150 **
66151 ** It is important that all schema cookies be verified and all
66152 ** read transactions be started before anything else happens in
66153 ** the VDBE program.  But this routine can be called after much other
66154 ** code has been generated.  So here is what we do:
66155 **
66156 ** The first time this routine is called, we code an OP_Goto that
66157 ** will jump to a subroutine at the end of the program.  Then we
66158 ** record every database that needs its schema verified in the
66159 ** pParse->cookieMask field.  Later, after all other code has been
66160 ** generated, the subroutine that does the cookie verifications and
66161 ** starts the transactions will be coded and the OP_Goto P2 value
66162 ** will be made to point to that subroutine.  The generation of the
66163 ** cookie verification subroutine code happens in sqlite3FinishCoding().
66164 **
66165 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
66166 ** schema on any databases.  This can be used to position the OP_Goto
66167 ** early in the code, before we know if any database tables will be used.
66168 */
66169 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
66170   sqlite3 *db;
66171   Vdbe *v;
66172   int mask;
66173
66174   v = sqlite3GetVdbe(pParse);
66175   if( v==0 ) return;  /* This only happens if there was a prior error */
66176   db = pParse->db;
66177   if( pParse->cookieGoto==0 ){
66178     pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
66179   }
66180   if( iDb>=0 ){
66181     assert( iDb<db->nDb );
66182     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
66183     assert( iDb<SQLITE_MAX_ATTACHED+2 );
66184     mask = 1<<iDb;
66185     if( (pParse->cookieMask & mask)==0 ){
66186       pParse->cookieMask |= mask;
66187       pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
66188       if( !OMIT_TEMPDB && iDb==1 ){
66189         sqlite3OpenTempDatabase(pParse);
66190       }
66191     }
66192   }
66193 }
66194
66195 /*
66196 ** Generate VDBE code that prepares for doing an operation that
66197 ** might change the database.
66198 **
66199 ** This routine starts a new transaction if we are not already within
66200 ** a transaction.  If we are already within a transaction, then a checkpoint
66201 ** is set if the setStatement parameter is true.  A checkpoint should
66202 ** be set for operations that might fail (due to a constraint) part of
66203 ** the way through and which will need to undo some writes without having to
66204 ** rollback the whole transaction.  For operations where all constraints
66205 ** can be checked before any changes are made to the database, it is never
66206 ** necessary to undo a write and the checkpoint should not be set.
66207 */
66208 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
66209   Vdbe *v = sqlite3GetVdbe(pParse);
66210   if( v==0 ) return;
66211   sqlite3CodeVerifySchema(pParse, iDb);
66212   pParse->writeMask |= 1<<iDb;
66213   if( setStatement && pParse->nested==0 ){
66214     sqlite3VdbeAddOp1(v, OP_Statement, iDb);
66215   }
66216 }
66217
66218 /*
66219 ** Check to see if pIndex uses the collating sequence pColl.  Return
66220 ** true if it does and false if it does not.
66221 */
66222 #ifndef SQLITE_OMIT_REINDEX
66223 static int collationMatch(const char *zColl, Index *pIndex){
66224   int i;
66225   for(i=0; i<pIndex->nColumn; i++){
66226     const char *z = pIndex->azColl[i];
66227     if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
66228       return 1;
66229     }
66230   }
66231   return 0;
66232 }
66233 #endif
66234
66235 /*
66236 ** Recompute all indices of pTab that use the collating sequence pColl.
66237 ** If pColl==0 then recompute all indices of pTab.
66238 */
66239 #ifndef SQLITE_OMIT_REINDEX
66240 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
66241   Index *pIndex;              /* An index associated with pTab */
66242
66243   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
66244     if( zColl==0 || collationMatch(zColl, pIndex) ){
66245       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
66246       sqlite3BeginWriteOperation(pParse, 0, iDb);
66247       sqlite3RefillIndex(pParse, pIndex, -1);
66248     }
66249   }
66250 }
66251 #endif
66252
66253 /*
66254 ** Recompute all indices of all tables in all databases where the
66255 ** indices use the collating sequence pColl.  If pColl==0 then recompute
66256 ** all indices everywhere.
66257 */
66258 #ifndef SQLITE_OMIT_REINDEX
66259 static void reindexDatabases(Parse *pParse, char const *zColl){
66260   Db *pDb;                    /* A single database */
66261   int iDb;                    /* The database index number */
66262   sqlite3 *db = pParse->db;   /* The database connection */
66263   HashElem *k;                /* For looping over tables in pDb */
66264   Table *pTab;                /* A table in the database */
66265
66266   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
66267     assert( pDb!=0 );
66268     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
66269       pTab = (Table*)sqliteHashData(k);
66270       reindexTable(pParse, pTab, zColl);
66271     }
66272   }
66273 }
66274 #endif
66275
66276 /*
66277 ** Generate code for the REINDEX command.
66278 **
66279 **        REINDEX                            -- 1
66280 **        REINDEX  <collation>               -- 2
66281 **        REINDEX  ?<database>.?<tablename>  -- 3
66282 **        REINDEX  ?<database>.?<indexname>  -- 4
66283 **
66284 ** Form 1 causes all indices in all attached databases to be rebuilt.
66285 ** Form 2 rebuilds all indices in all databases that use the named
66286 ** collating function.  Forms 3 and 4 rebuild the named index or all
66287 ** indices associated with the named table.
66288 */
66289 #ifndef SQLITE_OMIT_REINDEX
66290 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
66291   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
66292   char *z;                    /* Name of a table or index */
66293   const char *zDb;            /* Name of the database */
66294   Table *pTab;                /* A table in the database */
66295   Index *pIndex;              /* An index associated with pTab */
66296   int iDb;                    /* The database index number */
66297   sqlite3 *db = pParse->db;   /* The database connection */
66298   Token *pObjName;            /* Name of the table or index to be reindexed */
66299
66300   /* Read the database schema. If an error occurs, leave an error message
66301   ** and code in pParse and return NULL. */
66302   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66303     return;
66304   }
66305
66306   if( pName1==0 || pName1->z==0 ){
66307     reindexDatabases(pParse, 0);
66308     return;
66309   }else if( pName2==0 || pName2->z==0 ){
66310     char *zColl;
66311     assert( pName1->z );
66312     zColl = sqlite3NameFromToken(pParse->db, pName1);
66313     if( !zColl ) return;
66314     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
66315     if( pColl ){
66316       if( zColl ){
66317         reindexDatabases(pParse, zColl);
66318         sqlite3DbFree(db, zColl);
66319       }
66320       return;
66321     }
66322     sqlite3DbFree(db, zColl);
66323   }
66324   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
66325   if( iDb<0 ) return;
66326   z = sqlite3NameFromToken(db, pObjName);
66327   if( z==0 ) return;
66328   zDb = db->aDb[iDb].zName;
66329   pTab = sqlite3FindTable(db, z, zDb);
66330   if( pTab ){
66331     reindexTable(pParse, pTab, 0);
66332     sqlite3DbFree(db, z);
66333     return;
66334   }
66335   pIndex = sqlite3FindIndex(db, z, zDb);
66336   sqlite3DbFree(db, z);
66337   if( pIndex ){
66338     sqlite3BeginWriteOperation(pParse, 0, iDb);
66339     sqlite3RefillIndex(pParse, pIndex, -1);
66340     return;
66341   }
66342   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
66343 }
66344 #endif
66345
66346 /*
66347 ** Return a dynamicly allocated KeyInfo structure that can be used
66348 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
66349 **
66350 ** If successful, a pointer to the new structure is returned. In this case
66351 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
66352 ** pointer. If an error occurs (out of memory or missing collation 
66353 ** sequence), NULL is returned and the state of pParse updated to reflect
66354 ** the error.
66355 */
66356 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
66357   int i;
66358   int nCol = pIdx->nColumn;
66359   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
66360   sqlite3 *db = pParse->db;
66361   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
66362
66363   if( pKey ){
66364     pKey->db = pParse->db;
66365     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
66366     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
66367     for(i=0; i<nCol; i++){
66368       char *zColl = pIdx->azColl[i];
66369       assert( zColl );
66370       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
66371       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
66372     }
66373     pKey->nField = (u16)nCol;
66374   }
66375
66376   if( pParse->nErr ){
66377     sqlite3DbFree(db, pKey);
66378     pKey = 0;
66379   }
66380   return pKey;
66381 }
66382
66383 /************** End of build.c ***********************************************/
66384 /************** Begin file callback.c ****************************************/
66385 /*
66386 ** 2005 May 23 
66387 **
66388 ** The author disclaims copyright to this source code.  In place of
66389 ** a legal notice, here is a blessing:
66390 **
66391 **    May you do good and not evil.
66392 **    May you find forgiveness for yourself and forgive others.
66393 **    May you share freely, never taking more than you give.
66394 **
66395 *************************************************************************
66396 **
66397 ** This file contains functions used to access the internal hash tables
66398 ** of user defined functions and collation sequences.
66399 **
66400 ** $Id: callback.c,v 1.35 2009/01/31 22:28:49 drh Exp $
66401 */
66402
66403
66404 /*
66405 ** Invoke the 'collation needed' callback to request a collation sequence
66406 ** in the database text encoding of name zName, length nName.
66407 ** If the collation sequence
66408 */
66409 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
66410   assert( !db->xCollNeeded || !db->xCollNeeded16 );
66411   if( nName<0 ) nName = sqlite3Strlen(db, zName);
66412   if( db->xCollNeeded ){
66413     char *zExternal = sqlite3DbStrNDup(db, zName, nName);
66414     if( !zExternal ) return;
66415     db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
66416     sqlite3DbFree(db, zExternal);
66417   }
66418 #ifndef SQLITE_OMIT_UTF16
66419   if( db->xCollNeeded16 ){
66420     char const *zExternal;
66421     sqlite3_value *pTmp = sqlite3ValueNew(db);
66422     sqlite3ValueSetStr(pTmp, nName, zName, SQLITE_UTF8, SQLITE_STATIC);
66423     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
66424     if( zExternal ){
66425       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
66426     }
66427     sqlite3ValueFree(pTmp);
66428   }
66429 #endif
66430 }
66431
66432 /*
66433 ** This routine is called if the collation factory fails to deliver a
66434 ** collation function in the best encoding but there may be other versions
66435 ** of this collation function (for other text encodings) available. Use one
66436 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
66437 ** possible.
66438 */
66439 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
66440   CollSeq *pColl2;
66441   char *z = pColl->zName;
66442   int n = sqlite3Strlen30(z);
66443   int i;
66444   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
66445   for(i=0; i<3; i++){
66446     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
66447     if( pColl2->xCmp!=0 ){
66448       memcpy(pColl, pColl2, sizeof(CollSeq));
66449       pColl->xDel = 0;         /* Do not copy the destructor */
66450       return SQLITE_OK;
66451     }
66452   }
66453   return SQLITE_ERROR;
66454 }
66455
66456 /*
66457 ** This function is responsible for invoking the collation factory callback
66458 ** or substituting a collation sequence of a different encoding when the
66459 ** requested collation sequence is not available in the database native
66460 ** encoding.
66461 ** 
66462 ** If it is not NULL, then pColl must point to the database native encoding 
66463 ** collation sequence with name zName, length nName.
66464 **
66465 ** The return value is either the collation sequence to be used in database
66466 ** db for collation type name zName, length nName, or NULL, if no collation
66467 ** sequence can be found.
66468 */
66469 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
66470   sqlite3* db, 
66471   CollSeq *pColl, 
66472   const char *zName, 
66473   int nName
66474 ){
66475   CollSeq *p;
66476
66477   p = pColl;
66478   if( !p ){
66479     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
66480   }
66481   if( !p || !p->xCmp ){
66482     /* No collation sequence of this type for this encoding is registered.
66483     ** Call the collation factory to see if it can supply us with one.
66484     */
66485     callCollNeeded(db, zName, nName);
66486     p = sqlite3FindCollSeq(db, ENC(db), zName, nName, 0);
66487   }
66488   if( p && !p->xCmp && synthCollSeq(db, p) ){
66489     p = 0;
66490   }
66491   assert( !p || p->xCmp );
66492   return p;
66493 }
66494
66495 /*
66496 ** This routine is called on a collation sequence before it is used to
66497 ** check that it is defined. An undefined collation sequence exists when
66498 ** a database is loaded that contains references to collation sequences
66499 ** that have not been defined by sqlite3_create_collation() etc.
66500 **
66501 ** If required, this routine calls the 'collation needed' callback to
66502 ** request a definition of the collating sequence. If this doesn't work, 
66503 ** an equivalent collating sequence that uses a text encoding different
66504 ** from the main database is substituted, if one is available.
66505 */
66506 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
66507   if( pColl ){
66508     const char *zName = pColl->zName;
66509     CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
66510     if( !p ){
66511       if( pParse->nErr==0 ){
66512         sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
66513       }
66514       pParse->nErr++;
66515       return SQLITE_ERROR;
66516     }
66517     assert( p==pColl );
66518   }
66519   return SQLITE_OK;
66520 }
66521
66522
66523
66524 /*
66525 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
66526 ** specified by zName and nName is not found and parameter 'create' is
66527 ** true, then create a new entry. Otherwise return NULL.
66528 **
66529 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
66530 ** array of three CollSeq structures. The first is the collation sequence
66531 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
66532 **
66533 ** Stored immediately after the three collation sequences is a copy of
66534 ** the collation sequence name. A pointer to this string is stored in
66535 ** each collation sequence structure.
66536 */
66537 static CollSeq *findCollSeqEntry(
66538   sqlite3 *db,
66539   const char *zName,
66540   int nName,
66541   int create
66542 ){
66543   CollSeq *pColl;
66544   if( nName<0 ) nName = sqlite3Strlen(db, zName);
66545   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
66546
66547   if( 0==pColl && create ){
66548     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
66549     if( pColl ){
66550       CollSeq *pDel = 0;
66551       pColl[0].zName = (char*)&pColl[3];
66552       pColl[0].enc = SQLITE_UTF8;
66553       pColl[1].zName = (char*)&pColl[3];
66554       pColl[1].enc = SQLITE_UTF16LE;
66555       pColl[2].zName = (char*)&pColl[3];
66556       pColl[2].enc = SQLITE_UTF16BE;
66557       memcpy(pColl[0].zName, zName, nName);
66558       pColl[0].zName[nName] = 0;
66559       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
66560
66561       /* If a malloc() failure occured in sqlite3HashInsert(), it will 
66562       ** return the pColl pointer to be deleted (because it wasn't added
66563       ** to the hash table).
66564       */
66565       assert( pDel==0 || pDel==pColl );
66566       if( pDel!=0 ){
66567         db->mallocFailed = 1;
66568         sqlite3DbFree(db, pDel);
66569         pColl = 0;
66570       }
66571     }
66572   }
66573   return pColl;
66574 }
66575
66576 /*
66577 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
66578 ** Return the CollSeq* pointer for the collation sequence named zName
66579 ** for the encoding 'enc' from the database 'db'.
66580 **
66581 ** If the entry specified is not found and 'create' is true, then create a
66582 ** new entry.  Otherwise return NULL.
66583 **
66584 ** A separate function sqlite3LocateCollSeq() is a wrapper around
66585 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
66586 ** if necessary and generates an error message if the collating sequence
66587 ** cannot be found.
66588 */
66589 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
66590   sqlite3 *db,
66591   u8 enc,
66592   const char *zName,
66593   int nName,
66594   int create
66595 ){
66596   CollSeq *pColl;
66597   if( zName ){
66598     pColl = findCollSeqEntry(db, zName, nName, create);
66599   }else{
66600     pColl = db->pDfltColl;
66601   }
66602   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
66603   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
66604   if( pColl ) pColl += enc-1;
66605   return pColl;
66606 }
66607
66608 /* During the search for the best function definition, this procedure
66609 ** is called to test how well the function passed as the first argument
66610 ** matches the request for a function with nArg arguments in a system
66611 ** that uses encoding enc. The value returned indicates how well the
66612 ** request is matched. A higher value indicates a better match.
66613 **
66614 ** The returned value is always between 0 and 6, as follows:
66615 **
66616 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
66617 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
66618 **    encoding is requested, or vice versa.
66619 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
66620 **    requested, or vice versa.
66621 ** 3: A variable arguments function using the same text encoding.
66622 ** 4: A function with the exact number of arguments requested that
66623 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
66624 ** 5: A function with the exact number of arguments requested that
66625 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
66626 ** 6: An exact match.
66627 **
66628 */
66629 static int matchQuality(FuncDef *p, int nArg, u8 enc){
66630   int match = 0;
66631   if( p->nArg==-1 || p->nArg==nArg 
66632    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
66633   ){
66634     match = 1;
66635     if( p->nArg==nArg || nArg==-1 ){
66636       match = 4;
66637     }
66638     if( enc==p->iPrefEnc ){
66639       match += 2;
66640     }
66641     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
66642              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
66643       match += 1;
66644     }
66645   }
66646   return match;
66647 }
66648
66649 /*
66650 ** Search a FuncDefHash for a function with the given name.  Return
66651 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
66652 */
66653 static FuncDef *functionSearch(
66654   FuncDefHash *pHash,  /* Hash table to search */
66655   int h,               /* Hash of the name */
66656   const char *zFunc,   /* Name of function */
66657   int nFunc            /* Number of bytes in zFunc */
66658 ){
66659   FuncDef *p;
66660   for(p=pHash->a[h]; p; p=p->pHash){
66661     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
66662       return p;
66663     }
66664   }
66665   return 0;
66666 }
66667
66668 /*
66669 ** Insert a new FuncDef into a FuncDefHash hash table.
66670 */
66671 SQLITE_PRIVATE void sqlite3FuncDefInsert(
66672   FuncDefHash *pHash,  /* The hash table into which to insert */
66673   FuncDef *pDef        /* The function definition to insert */
66674 ){
66675   FuncDef *pOther;
66676   int nName = sqlite3Strlen30(pDef->zName);
66677   u8 c1 = (u8)pDef->zName[0];
66678   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
66679   pOther = functionSearch(pHash, h, pDef->zName, nName);
66680   if( pOther ){
66681     pDef->pNext = pOther->pNext;
66682     pOther->pNext = pDef;
66683   }else{
66684     pDef->pNext = 0;
66685     pDef->pHash = pHash->a[h];
66686     pHash->a[h] = pDef;
66687   }
66688 }
66689   
66690   
66691
66692 /*
66693 ** Locate a user function given a name, a number of arguments and a flag
66694 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
66695 ** pointer to the FuncDef structure that defines that function, or return
66696 ** NULL if the function does not exist.
66697 **
66698 ** If the createFlag argument is true, then a new (blank) FuncDef
66699 ** structure is created and liked into the "db" structure if a
66700 ** no matching function previously existed.  When createFlag is true
66701 ** and the nArg parameter is -1, then only a function that accepts
66702 ** any number of arguments will be returned.
66703 **
66704 ** If createFlag is false and nArg is -1, then the first valid
66705 ** function found is returned.  A function is valid if either xFunc
66706 ** or xStep is non-zero.
66707 **
66708 ** If createFlag is false, then a function with the required name and
66709 ** number of arguments may be returned even if the eTextRep flag does not
66710 ** match that requested.
66711 */
66712 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
66713   sqlite3 *db,       /* An open database */
66714   const char *zName, /* Name of the function.  Not null-terminated */
66715   int nName,         /* Number of characters in the name */
66716   int nArg,          /* Number of arguments.  -1 means any number */
66717   u8 enc,            /* Preferred text encoding */
66718   int createFlag     /* Create new entry if true and does not otherwise exist */
66719 ){
66720   FuncDef *p;         /* Iterator variable */
66721   FuncDef *pBest = 0; /* Best match found so far */
66722   int bestScore = 0;  /* Score of best match */
66723   int h;              /* Hash value */
66724
66725
66726   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
66727   if( nArg<-1 ) nArg = -1;
66728   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
66729
66730   /* First search for a match amongst the application-defined functions.
66731   */
66732   p = functionSearch(&db->aFunc, h, zName, nName);
66733   while( p ){
66734     int score = matchQuality(p, nArg, enc);
66735     if( score>bestScore ){
66736       pBest = p;
66737       bestScore = score;
66738     }
66739     p = p->pNext;
66740   }
66741
66742   /* If no match is found, search the built-in functions.
66743   **
66744   ** Except, if createFlag is true, that means that we are trying to
66745   ** install a new function.  Whatever FuncDef structure is returned will
66746   ** have fields overwritten with new information appropriate for the
66747   ** new function.  But the FuncDefs for built-in functions are read-only.
66748   ** So we must not search for built-ins when creating a new function.
66749   */ 
66750   if( !createFlag && !pBest ){
66751     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
66752     p = functionSearch(pHash, h, zName, nName);
66753     while( p ){
66754       int score = matchQuality(p, nArg, enc);
66755       if( score>bestScore ){
66756         pBest = p;
66757         bestScore = score;
66758       }
66759       p = p->pNext;
66760     }
66761   }
66762
66763   /* If the createFlag parameter is true and the search did not reveal an
66764   ** exact match for the name, number of arguments and encoding, then add a
66765   ** new entry to the hash table and return it.
66766   */
66767   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
66768       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
66769     pBest->zName = (char *)&pBest[1];
66770     pBest->nArg = (u16)nArg;
66771     pBest->iPrefEnc = enc;
66772     memcpy(pBest->zName, zName, nName);
66773     pBest->zName[nName] = 0;
66774     sqlite3FuncDefInsert(&db->aFunc, pBest);
66775   }
66776
66777   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
66778     return pBest;
66779   }
66780   return 0;
66781 }
66782
66783 /*
66784 ** Free all resources held by the schema structure. The void* argument points
66785 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
66786 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
66787 ** of the schema hash tables).
66788 **
66789 ** The Schema.cache_size variable is not cleared.
66790 */
66791 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
66792   Hash temp1;
66793   Hash temp2;
66794   HashElem *pElem;
66795   Schema *pSchema = (Schema *)p;
66796
66797   temp1 = pSchema->tblHash;
66798   temp2 = pSchema->trigHash;
66799   sqlite3HashInit(&pSchema->trigHash, 0);
66800   sqlite3HashClear(&pSchema->aFKey);
66801   sqlite3HashClear(&pSchema->idxHash);
66802   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
66803     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
66804   }
66805   sqlite3HashClear(&temp2);
66806   sqlite3HashInit(&pSchema->tblHash, 0);
66807   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
66808     Table *pTab = sqliteHashData(pElem);
66809     sqlite3DeleteTable(pTab);
66810   }
66811   sqlite3HashClear(&temp1);
66812   pSchema->pSeqTab = 0;
66813   pSchema->flags &= ~DB_SchemaLoaded;
66814 }
66815
66816 /*
66817 ** Find and return the schema associated with a BTree.  Create
66818 ** a new one if necessary.
66819 */
66820 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
66821   Schema * p;
66822   if( pBt ){
66823     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
66824   }else{
66825     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
66826   }
66827   if( !p ){
66828     db->mallocFailed = 1;
66829   }else if ( 0==p->file_format ){
66830     sqlite3HashInit(&p->tblHash, 0);
66831     sqlite3HashInit(&p->idxHash, 0);
66832     sqlite3HashInit(&p->trigHash, 0);
66833     sqlite3HashInit(&p->aFKey, 1);
66834     p->enc = SQLITE_UTF8;
66835   }
66836   return p;
66837 }
66838
66839 /************** End of callback.c ********************************************/
66840 /************** Begin file delete.c ******************************************/
66841 /*
66842 ** 2001 September 15
66843 **
66844 ** The author disclaims copyright to this source code.  In place of
66845 ** a legal notice, here is a blessing:
66846 **
66847 **    May you do good and not evil.
66848 **    May you find forgiveness for yourself and forgive others.
66849 **    May you share freely, never taking more than you give.
66850 **
66851 *************************************************************************
66852 ** This file contains C code routines that are called by the parser
66853 ** in order to generate code for DELETE FROM statements.
66854 **
66855 ** $Id: delete.c,v 1.191 2008/12/23 23:56:22 drh Exp $
66856 */
66857
66858 /*
66859 ** Look up every table that is named in pSrc.  If any table is not found,
66860 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
66861 ** are found, return a pointer to the last table.
66862 */
66863 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
66864   struct SrcList_item *pItem = pSrc->a;
66865   Table *pTab;
66866   assert( pItem && pSrc->nSrc==1 );
66867   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
66868   sqlite3DeleteTable(pItem->pTab);
66869   pItem->pTab = pTab;
66870   if( pTab ){
66871     pTab->nRef++;
66872   }
66873   if( sqlite3IndexedByLookup(pParse, pItem) ){
66874     pTab = 0;
66875   }
66876   return pTab;
66877 }
66878
66879 /*
66880 ** Check to make sure the given table is writable.  If it is not
66881 ** writable, generate an error message and return 1.  If it is
66882 ** writable return 0;
66883 */
66884 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
66885   if( ((pTab->tabFlags & TF_Readonly)!=0
66886         && (pParse->db->flags & SQLITE_WriteSchema)==0
66887         && pParse->nested==0) 
66888 #ifndef SQLITE_OMIT_VIRTUALTABLE
66889       || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
66890 #endif
66891   ){
66892     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
66893     return 1;
66894   }
66895 #ifndef SQLITE_OMIT_VIEW
66896   if( !viewOk && pTab->pSelect ){
66897     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
66898     return 1;
66899   }
66900 #endif
66901   return 0;
66902 }
66903
66904 /*
66905 ** Generate code that will open a table for reading.
66906 */
66907 SQLITE_PRIVATE void sqlite3OpenTable(
66908   Parse *p,       /* Generate code into this VDBE */
66909   int iCur,       /* The cursor number of the table */
66910   int iDb,        /* The database index in sqlite3.aDb[] */
66911   Table *pTab,    /* The table to be opened */
66912   int opcode      /* OP_OpenRead or OP_OpenWrite */
66913 ){
66914   Vdbe *v;
66915   if( IsVirtual(pTab) ) return;
66916   v = sqlite3GetVdbe(p);
66917   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
66918   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
66919   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
66920   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
66921   VdbeComment((v, "%s", pTab->zName));
66922 }
66923
66924
66925 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
66926 /*
66927 ** Evaluate a view and store its result in an ephemeral table.  The
66928 ** pWhere argument is an optional WHERE clause that restricts the
66929 ** set of rows in the view that are to be added to the ephemeral table.
66930 */
66931 SQLITE_PRIVATE void sqlite3MaterializeView(
66932   Parse *pParse,       /* Parsing context */
66933   Table *pView,        /* View definition */
66934   Expr *pWhere,        /* Optional WHERE clause to be added */
66935   int iCur             /* Cursor number for ephemerial table */
66936 ){
66937   SelectDest dest;
66938   Select *pDup;
66939   sqlite3 *db = pParse->db;
66940
66941   pDup = sqlite3SelectDup(db, pView->pSelect);
66942   if( pWhere ){
66943     SrcList *pFrom;
66944     Token viewName;
66945     
66946     pWhere = sqlite3ExprDup(db, pWhere);
66947     viewName.z = (u8*)pView->zName;
66948     viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
66949     pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
66950     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
66951   }
66952   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
66953   sqlite3Select(pParse, pDup, &dest);
66954   sqlite3SelectDelete(db, pDup);
66955 }
66956 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
66957
66958 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
66959 /*
66960 ** Generate an expression tree to implement the WHERE, ORDER BY,
66961 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
66962 **
66963 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
66964 **                            \__________________________/
66965 **                               pLimitWhere (pInClause)
66966 */
66967 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
66968   Parse *pParse,               /* The parser context */
66969   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
66970   Expr *pWhere,                /* The WHERE clause.  May be null */
66971   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
66972   Expr *pLimit,                /* The LIMIT clause.  May be null */
66973   Expr *pOffset,               /* The OFFSET clause.  May be null */
66974   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
66975 ){
66976   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
66977   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
66978   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
66979   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
66980   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
66981   Select *pSelect = NULL;      /* Complete SELECT tree */
66982
66983   /* Check that there isn't an ORDER BY without a LIMIT clause.
66984   */
66985   if( pOrderBy && (pLimit == 0) ) {
66986     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
66987     pParse->parseError = 1;
66988     goto limit_where_cleanup_2;
66989   }
66990
66991   /* We only need to generate a select expression if there
66992   ** is a limit/offset term to enforce.
66993   */
66994   if( pLimit == 0 ) {
66995     /* if pLimit is null, pOffset will always be null as well. */
66996     assert( pOffset == 0 );
66997     return pWhere;
66998   }
66999
67000   /* Generate a select expression tree to enforce the limit/offset 
67001   ** term for the DELETE or UPDATE statement.  For example:
67002   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
67003   ** becomes:
67004   **   DELETE FROM table_a WHERE rowid IN ( 
67005   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
67006   **   );
67007   */
67008
67009   pSelectRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
67010   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
67011   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid, 0);
67012   if( pEList == 0 ) goto limit_where_cleanup_2;
67013
67014   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
67015   ** and the SELECT subtree. */
67016   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc);
67017   if( pSelectSrc == 0 ) {
67018     sqlite3ExprListDelete(pParse->db, pEList);
67019     goto limit_where_cleanup_2;
67020   }
67021
67022   /* generate the SELECT expression tree. */
67023   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,pOrderBy,0,pLimit,pOffset);
67024   if( pSelect == 0 ) return 0;
67025
67026   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
67027   pWhereRowid = sqlite3Expr(pParse->db, TK_ROW, 0, 0, 0);
67028   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
67029   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
67030   if( pInClause == 0 ) goto limit_where_cleanup_1;
67031
67032   pInClause->pSelect = pSelect;
67033   sqlite3ExprSetHeight(pParse, pInClause);
67034   return pInClause;
67035
67036   /* something went wrong. clean up anything allocated. */
67037 limit_where_cleanup_1:
67038   sqlite3SelectDelete(pParse->db, pSelect);
67039   return 0;
67040
67041 limit_where_cleanup_2:
67042   sqlite3ExprDelete(pParse->db, pWhere);
67043   sqlite3ExprListDelete(pParse->db, pOrderBy);
67044   sqlite3ExprDelete(pParse->db, pLimit);
67045   sqlite3ExprDelete(pParse->db, pOffset);
67046   return 0;
67047 }
67048 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
67049
67050 /*
67051 ** Generate code for a DELETE FROM statement.
67052 **
67053 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
67054 **                 \________/       \________________/
67055 **                  pTabList              pWhere
67056 */
67057 SQLITE_PRIVATE void sqlite3DeleteFrom(
67058   Parse *pParse,         /* The parser context */
67059   SrcList *pTabList,     /* The table from which we should delete things */
67060   Expr *pWhere           /* The WHERE clause.  May be null */
67061 ){
67062   Vdbe *v;               /* The virtual database engine */
67063   Table *pTab;           /* The table from which records will be deleted */
67064   const char *zDb;       /* Name of database holding pTab */
67065   int end, addr = 0;     /* A couple addresses of generated code */
67066   int i;                 /* Loop counter */
67067   WhereInfo *pWInfo;     /* Information about the WHERE clause */
67068   Index *pIdx;           /* For looping over indices of the table */
67069   int iCur;              /* VDBE Cursor number for pTab */
67070   sqlite3 *db;           /* Main database structure */
67071   AuthContext sContext;  /* Authorization context */
67072   int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
67073   NameContext sNC;       /* Name context to resolve expressions in */
67074   int iDb;               /* Database number */
67075   int memCnt = -1;       /* Memory cell used for change counting */
67076   int rcauth;            /* Value returned by authorization callback */
67077
67078 #ifndef SQLITE_OMIT_TRIGGER
67079   int isView;                  /* True if attempting to delete from a view */
67080   int triggers_exist = 0;      /* True if any triggers exist */
67081 #endif
67082   int iBeginAfterTrigger = 0;  /* Address of after trigger program */
67083   int iEndAfterTrigger = 0;    /* Exit of after trigger program */
67084   int iBeginBeforeTrigger = 0; /* Address of before trigger program */
67085   int iEndBeforeTrigger = 0;   /* Exit of before trigger program */
67086   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
67087
67088   sContext.pParse = 0;
67089   db = pParse->db;
67090   if( pParse->nErr || db->mallocFailed ){
67091     goto delete_from_cleanup;
67092   }
67093   assert( pTabList->nSrc==1 );
67094
67095   /* Locate the table which we want to delete.  This table has to be
67096   ** put in an SrcList structure because some of the subroutines we
67097   ** will be calling are designed to work with multiple tables and expect
67098   ** an SrcList* parameter instead of just a Table* parameter.
67099   */
67100   pTab = sqlite3SrcListLookup(pParse, pTabList);
67101   if( pTab==0 )  goto delete_from_cleanup;
67102
67103   /* Figure out if we have any triggers and if the table being
67104   ** deleted from is a view
67105   */
67106 #ifndef SQLITE_OMIT_TRIGGER
67107   triggers_exist = sqlite3TriggersExist(pTab, TK_DELETE, 0);
67108   isView = pTab->pSelect!=0;
67109 #else
67110 # define triggers_exist 0
67111 # define isView 0
67112 #endif
67113 #ifdef SQLITE_OMIT_VIEW
67114 # undef isView
67115 # define isView 0
67116 #endif
67117
67118   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
67119     goto delete_from_cleanup;
67120   }
67121   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67122   assert( iDb<db->nDb );
67123   zDb = db->aDb[iDb].zName;
67124   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
67125   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
67126   if( rcauth==SQLITE_DENY ){
67127     goto delete_from_cleanup;
67128   }
67129   assert(!isView || triggers_exist);
67130
67131   /* If pTab is really a view, make sure it has been initialized.
67132   */
67133   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
67134     goto delete_from_cleanup;
67135   }
67136
67137   /* Allocate a cursor used to store the old.* data for a trigger.
67138   */
67139   if( triggers_exist ){ 
67140     oldIdx = pParse->nTab++;
67141   }
67142
67143   /* Assign  cursor number to the table and all its indices.
67144   */
67145   assert( pTabList->nSrc==1 );
67146   iCur = pTabList->a[0].iCursor = pParse->nTab++;
67147   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
67148     pParse->nTab++;
67149   }
67150
67151   /* Start the view context
67152   */
67153   if( isView ){
67154     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
67155   }
67156
67157   /* Begin generating code.
67158   */
67159   v = sqlite3GetVdbe(pParse);
67160   if( v==0 ){
67161     goto delete_from_cleanup;
67162   }
67163   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
67164   sqlite3BeginWriteOperation(pParse, triggers_exist, iDb);
67165
67166   if( triggers_exist ){
67167     int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default);
67168     int iGoto = sqlite3VdbeAddOp0(v, OP_Goto);
67169     addr = sqlite3VdbeMakeLabel(v);
67170
67171     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
67172     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab,
67173         -1, oldIdx, orconf, addr, &old_col_mask, 0);
67174     iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
67175
67176     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
67177     (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1,
67178         oldIdx, orconf, addr, &old_col_mask, 0);
67179     iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto);
67180
67181     sqlite3VdbeJumpHere(v, iGoto);
67182   }
67183
67184   /* If we are trying to delete from a view, realize that view into
67185   ** a ephemeral table.
67186   */
67187 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
67188   if( isView ){
67189     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
67190   }
67191 #endif
67192
67193   /* Resolve the column names in the WHERE clause.
67194   */
67195   memset(&sNC, 0, sizeof(sNC));
67196   sNC.pParse = pParse;
67197   sNC.pSrcList = pTabList;
67198   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
67199     goto delete_from_cleanup;
67200   }
67201
67202   /* Initialize the counter of the number of rows deleted, if
67203   ** we are counting rows.
67204   */
67205   if( db->flags & SQLITE_CountRows ){
67206     memCnt = ++pParse->nMem;
67207     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
67208   }
67209
67210 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
67211   /* Special case: A DELETE without a WHERE clause deletes everything.
67212   ** It is easier just to erase the whole table.  Note, however, that
67213   ** this means that the row change count will be incorrect.
67214   */
67215   if( rcauth==SQLITE_OK && pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){
67216     assert( !isView );
67217     sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
67218     if( !pParse->nested ){
67219       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
67220     }
67221     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
67222       assert( pIdx->pSchema==pTab->pSchema );
67223       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
67224     }
67225   }else
67226 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
67227   /* The usual case: There is a WHERE clause so we have to scan through
67228   ** the table and pick which records to delete.
67229   */
67230   {
67231     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
67232     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
67233
67234     /* Collect rowids of every row to be deleted.
67235     */
67236     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
67237     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
67238                                WHERE_FILL_ROWSET, iRowSet);
67239     if( pWInfo==0 ) goto delete_from_cleanup;
67240     if( db->flags & SQLITE_CountRows ){
67241       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
67242     }
67243     sqlite3WhereEnd(pWInfo);
67244
67245     /* Open the pseudo-table used to store OLD if there are triggers.
67246     */
67247     if( triggers_exist ){
67248       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
67249       sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx);
67250     }
67251
67252     /* Delete every item whose key was written to the list during the
67253     ** database scan.  We have to delete items after the scan is complete
67254     ** because deleting an item can change the scan order.
67255     */
67256     end = sqlite3VdbeMakeLabel(v);
67257
67258     if( !isView ){
67259       /* Open cursors for the table we are deleting from and 
67260       ** all its indices.
67261       */
67262       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
67263     }
67264
67265     /* This is the beginning of the delete loop. If a trigger encounters
67266     ** an IGNORE constraint, it jumps back to here.
67267     */
67268     if( triggers_exist ){
67269       sqlite3VdbeResolveLabel(v, addr);
67270     }
67271     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
67272
67273     if( triggers_exist ){
67274       int iData = ++pParse->nMem;   /* For storing row data of OLD table */
67275
67276       /* If the record is no longer present in the table, jump to the
67277       ** next iteration of the loop through the contents of the fifo.
67278       */
67279       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid);
67280
67281       /* Populate the OLD.* pseudo-table */
67282       if( old_col_mask ){
67283         sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData);
67284       }else{
67285         sqlite3VdbeAddOp2(v, OP_Null, 0, iData);
67286       }
67287       sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid);
67288
67289       /* Jump back and run the BEFORE triggers */
67290       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
67291       sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
67292     }
67293
67294     if( !isView ){
67295       /* Delete the row */
67296 #ifndef SQLITE_OMIT_VIRTUALTABLE
67297       if( IsVirtual(pTab) ){
67298         const char *pVtab = (const char *)pTab->pVtab;
67299         sqlite3VtabMakeWritable(pParse, pTab);
67300         sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB);
67301       }else
67302 #endif
67303       {
67304         sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0);
67305       }
67306     }
67307
67308     /* If there are row triggers, close all cursors then invoke
67309     ** the AFTER triggers
67310     */
67311     if( triggers_exist ){
67312       /* Jump back and run the AFTER triggers */
67313       sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
67314       sqlite3VdbeJumpHere(v, iEndAfterTrigger);
67315     }
67316
67317     /* End of the delete loop */
67318     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
67319     sqlite3VdbeResolveLabel(v, end);
67320
67321     /* Close the cursors after the loop if there are no row triggers */
67322     if( !isView  && !IsVirtual(pTab) ){
67323       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
67324         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
67325       }
67326       sqlite3VdbeAddOp1(v, OP_Close, iCur);
67327     }
67328   }
67329
67330   /*
67331   ** Return the number of rows that were deleted. If this routine is 
67332   ** generating code because of a call to sqlite3NestedParse(), do not
67333   ** invoke the callback function.
67334   */
67335   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
67336     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
67337     sqlite3VdbeSetNumCols(v, 1);
67338     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
67339   }
67340
67341 delete_from_cleanup:
67342   sqlite3AuthContextPop(&sContext);
67343   sqlite3SrcListDelete(db, pTabList);
67344   sqlite3ExprDelete(db, pWhere);
67345   return;
67346 }
67347
67348 /*
67349 ** This routine generates VDBE code that causes a single row of a
67350 ** single table to be deleted.
67351 **
67352 ** The VDBE must be in a particular state when this routine is called.
67353 ** These are the requirements:
67354 **
67355 **   1.  A read/write cursor pointing to pTab, the table containing the row
67356 **       to be deleted, must be opened as cursor number "base".
67357 **
67358 **   2.  Read/write cursors for all indices of pTab must be open as
67359 **       cursor number base+i for the i-th index.
67360 **
67361 **   3.  The record number of the row to be deleted must be stored in
67362 **       memory cell iRowid.
67363 **
67364 ** This routine pops the top of the stack to remove the record number
67365 ** and then generates code to remove both the table record and all index
67366 ** entries that point to that record.
67367 */
67368 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
67369   Parse *pParse,     /* Parsing context */
67370   Table *pTab,       /* Table containing the row to be deleted */
67371   int iCur,          /* Cursor number for the table */
67372   int iRowid,        /* Memory cell that contains the rowid to delete */
67373   int count          /* Increment the row change counter */
67374 ){
67375   int addr;
67376   Vdbe *v;
67377
67378   v = pParse->pVdbe;
67379   addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid);
67380   sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
67381   sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
67382   if( count ){
67383     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
67384   }
67385   sqlite3VdbeJumpHere(v, addr);
67386 }
67387
67388 /*
67389 ** This routine generates VDBE code that causes the deletion of all
67390 ** index entries associated with a single row of a single table.
67391 **
67392 ** The VDBE must be in a particular state when this routine is called.
67393 ** These are the requirements:
67394 **
67395 **   1.  A read/write cursor pointing to pTab, the table containing the row
67396 **       to be deleted, must be opened as cursor number "iCur".
67397 **
67398 **   2.  Read/write cursors for all indices of pTab must be open as
67399 **       cursor number iCur+i for the i-th index.
67400 **
67401 **   3.  The "iCur" cursor must be pointing to the row that is to be
67402 **       deleted.
67403 */
67404 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
67405   Parse *pParse,     /* Parsing and code generating context */
67406   Table *pTab,       /* Table containing the row to be deleted */
67407   int iCur,          /* Cursor number for the table */
67408   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
67409 ){
67410   int i;
67411   Index *pIdx;
67412   int r1;
67413
67414   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
67415     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
67416     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
67417     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
67418   }
67419 }
67420
67421 /*
67422 ** Generate code that will assemble an index key and put it in register
67423 ** regOut.  The key with be for index pIdx which is an index on pTab.
67424 ** iCur is the index of a cursor open on the pTab table and pointing to
67425 ** the entry that needs indexing.
67426 **
67427 ** Return a register number which is the first in a block of
67428 ** registers that holds the elements of the index key.  The
67429 ** block of registers has already been deallocated by the time
67430 ** this routine returns.
67431 */
67432 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
67433   Parse *pParse,     /* Parsing context */
67434   Index *pIdx,       /* The index for which to generate a key */
67435   int iCur,          /* Cursor number for the pIdx->pTable table */
67436   int regOut,        /* Write the new index key to this register */
67437   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
67438 ){
67439   Vdbe *v = pParse->pVdbe;
67440   int j;
67441   Table *pTab = pIdx->pTable;
67442   int regBase;
67443   int nCol;
67444
67445   nCol = pIdx->nColumn;
67446   regBase = sqlite3GetTempRange(pParse, nCol+1);
67447   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
67448   for(j=0; j<nCol; j++){
67449     int idx = pIdx->aiColumn[j];
67450     if( idx==pTab->iPKey ){
67451       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
67452     }else{
67453       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
67454       sqlite3ColumnDefault(v, pTab, idx);
67455     }
67456   }
67457   if( doMakeRec ){
67458     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
67459     sqlite3IndexAffinityStr(v, pIdx);
67460     sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1);
67461   }
67462   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
67463   return regBase;
67464 }
67465
67466 /* Make sure "isView" gets undefined in case this file becomes part of
67467 ** the amalgamation - so that subsequent files do not see isView as a
67468 ** macro. */
67469 #undef isView
67470
67471 /************** End of delete.c **********************************************/
67472 /************** Begin file func.c ********************************************/
67473 /*
67474 ** 2002 February 23
67475 **
67476 ** The author disclaims copyright to this source code.  In place of
67477 ** a legal notice, here is a blessing:
67478 **
67479 **    May you do good and not evil.
67480 **    May you find forgiveness for yourself and forgive others.
67481 **    May you share freely, never taking more than you give.
67482 **
67483 *************************************************************************
67484 ** This file contains the C functions that implement various SQL
67485 ** functions of SQLite.  
67486 **
67487 ** There is only one exported symbol in this file - the function
67488 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
67489 ** All other code has file scope.
67490 **
67491 ** $Id: func.c,v 1.222 2009/02/04 03:59:25 shane Exp $
67492 */
67493
67494 /*
67495 ** Return the collating function associated with a function.
67496 */
67497 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
67498   return context->pColl;
67499 }
67500
67501 /*
67502 ** Implementation of the non-aggregate min() and max() functions
67503 */
67504 static void minmaxFunc(
67505   sqlite3_context *context,
67506   int argc,
67507   sqlite3_value **argv
67508 ){
67509   int i;
67510   int mask;    /* 0 for min() or 0xffffffff for max() */
67511   int iBest;
67512   CollSeq *pColl;
67513
67514   assert( argc>1 );
67515   mask = sqlite3_user_data(context)==0 ? 0 : -1;
67516   pColl = sqlite3GetFuncCollSeq(context);
67517   assert( pColl );
67518   assert( mask==-1 || mask==0 );
67519   iBest = 0;
67520   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
67521   for(i=1; i<argc; i++){
67522     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
67523     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
67524       testcase( mask==0 );
67525       iBest = i;
67526     }
67527   }
67528   sqlite3_result_value(context, argv[iBest]);
67529 }
67530
67531 /*
67532 ** Return the type of the argument.
67533 */
67534 static void typeofFunc(
67535   sqlite3_context *context,
67536   int NotUsed,
67537   sqlite3_value **argv
67538 ){
67539   const char *z = 0;
67540   UNUSED_PARAMETER(NotUsed);
67541   switch( sqlite3_value_type(argv[0]) ){
67542     case SQLITE_INTEGER: z = "integer"; break;
67543     case SQLITE_TEXT:    z = "text";    break;
67544     case SQLITE_FLOAT:   z = "real";    break;
67545     case SQLITE_BLOB:    z = "blob";    break;
67546     default:             z = "null";    break;
67547   }
67548   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
67549 }
67550
67551
67552 /*
67553 ** Implementation of the length() function
67554 */
67555 static void lengthFunc(
67556   sqlite3_context *context,
67557   int argc,
67558   sqlite3_value **argv
67559 ){
67560   int len;
67561
67562   assert( argc==1 );
67563   UNUSED_PARAMETER(argc);
67564   switch( sqlite3_value_type(argv[0]) ){
67565     case SQLITE_BLOB:
67566     case SQLITE_INTEGER:
67567     case SQLITE_FLOAT: {
67568       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
67569       break;
67570     }
67571     case SQLITE_TEXT: {
67572       const unsigned char *z = sqlite3_value_text(argv[0]);
67573       if( z==0 ) return;
67574       len = 0;
67575       while( *z ){
67576         len++;
67577         SQLITE_SKIP_UTF8(z);
67578       }
67579       sqlite3_result_int(context, len);
67580       break;
67581     }
67582     default: {
67583       sqlite3_result_null(context);
67584       break;
67585     }
67586   }
67587 }
67588
67589 /*
67590 ** Implementation of the abs() function
67591 */
67592 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
67593   assert( argc==1 );
67594   UNUSED_PARAMETER(argc);
67595   switch( sqlite3_value_type(argv[0]) ){
67596     case SQLITE_INTEGER: {
67597       i64 iVal = sqlite3_value_int64(argv[0]);
67598       if( iVal<0 ){
67599         if( (iVal<<1)==0 ){
67600           sqlite3_result_error(context, "integer overflow", -1);
67601           return;
67602         }
67603         iVal = -iVal;
67604       } 
67605       sqlite3_result_int64(context, iVal);
67606       break;
67607     }
67608     case SQLITE_NULL: {
67609       sqlite3_result_null(context);
67610       break;
67611     }
67612     default: {
67613       double rVal = sqlite3_value_double(argv[0]);
67614       if( rVal<0 ) rVal = -rVal;
67615       sqlite3_result_double(context, rVal);
67616       break;
67617     }
67618   }
67619 }
67620
67621 /*
67622 ** Implementation of the substr() function.
67623 **
67624 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
67625 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
67626 ** of x.  If x is text, then we actually count UTF-8 characters.
67627 ** If x is a blob, then we count bytes.
67628 **
67629 ** If p1 is negative, then we begin abs(p1) from the end of x[].
67630 */
67631 static void substrFunc(
67632   sqlite3_context *context,
67633   int argc,
67634   sqlite3_value **argv
67635 ){
67636   const unsigned char *z;
67637   const unsigned char *z2;
67638   int len;
67639   int p0type;
67640   i64 p1, p2;
67641   int negP2 = 0;
67642
67643   assert( argc==3 || argc==2 );
67644   if( sqlite3_value_type(argv[1])==SQLITE_NULL
67645    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
67646   ){
67647     return;
67648   }
67649   p0type = sqlite3_value_type(argv[0]);
67650   if( p0type==SQLITE_BLOB ){
67651     len = sqlite3_value_bytes(argv[0]);
67652     z = sqlite3_value_blob(argv[0]);
67653     if( z==0 ) return;
67654     assert( len==sqlite3_value_bytes(argv[0]) );
67655   }else{
67656     z = sqlite3_value_text(argv[0]);
67657     if( z==0 ) return;
67658     len = 0;
67659     for(z2=z; *z2; len++){
67660       SQLITE_SKIP_UTF8(z2);
67661     }
67662   }
67663   p1 = sqlite3_value_int(argv[1]);
67664   if( argc==3 ){
67665     p2 = sqlite3_value_int(argv[2]);
67666     if( p2<0 ){
67667       p2 = -p2;
67668       negP2 = 1;
67669     }
67670   }else{
67671     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
67672   }
67673   if( p1<0 ){
67674     p1 += len;
67675     if( p1<0 ){
67676       p2 += p1;
67677       if( p2<0 ) p2 = 0;
67678       p1 = 0;
67679     }
67680   }else if( p1>0 ){
67681     p1--;
67682   }else if( p2>0 ){
67683     p2--;
67684   }
67685   if( negP2 ){
67686     p1 -= p2;
67687     if( p1<0 ){
67688       p2 += p1;
67689       p1 = 0;
67690     }
67691   }
67692   assert( p1>=0 && p2>=0 );
67693   if( p1+p2>len ){
67694     p2 = len-p1;
67695     if( p2<0 ) p2 = 0;
67696   }
67697   if( p0type!=SQLITE_BLOB ){
67698     while( *z && p1 ){
67699       SQLITE_SKIP_UTF8(z);
67700       p1--;
67701     }
67702     for(z2=z; *z2 && p2; p2--){
67703       SQLITE_SKIP_UTF8(z2);
67704     }
67705     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
67706   }else{
67707     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
67708   }
67709 }
67710
67711 /*
67712 ** Implementation of the round() function
67713 */
67714 #ifndef SQLITE_OMIT_FLOATING_POINT
67715 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
67716   int n = 0;
67717   double r;
67718   char zBuf[500];  /* larger than the %f representation of the largest double */
67719   assert( argc==1 || argc==2 );
67720   if( argc==2 ){
67721     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
67722     n = sqlite3_value_int(argv[1]);
67723     if( n>30 ) n = 30;
67724     if( n<0 ) n = 0;
67725   }
67726   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
67727   r = sqlite3_value_double(argv[0]);
67728   sqlite3_snprintf(sizeof(zBuf),zBuf,"%.*f",n,r);
67729   sqlite3AtoF(zBuf, &r);
67730   sqlite3_result_double(context, r);
67731 }
67732 #endif
67733
67734 /*
67735 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
67736 ** allocation fails, call sqlite3_result_error_nomem() to notify
67737 ** the database handle that malloc() has failed.
67738 */
67739 static void *contextMalloc(sqlite3_context *context, i64 nByte){
67740   char *z;
67741   if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){
67742     sqlite3_result_error_toobig(context);
67743     z = 0;
67744   }else{
67745     z = sqlite3Malloc((int)nByte);
67746     if( !z && nByte>0 ){
67747       sqlite3_result_error_nomem(context);
67748     }
67749   }
67750   return z;
67751 }
67752
67753 /*
67754 ** Implementation of the upper() and lower() SQL functions.
67755 */
67756 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
67757   char *z1;
67758   const char *z2;
67759   int i, n;
67760   UNUSED_PARAMETER(argc);
67761   z2 = (char*)sqlite3_value_text(argv[0]);
67762   n = sqlite3_value_bytes(argv[0]);
67763   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
67764   assert( z2==(char*)sqlite3_value_text(argv[0]) );
67765   if( z2 ){
67766     z1 = contextMalloc(context, ((i64)n)+1);
67767     if( z1 ){
67768       memcpy(z1, z2, n+1);
67769       for(i=0; z1[i]; i++){
67770         z1[i] = (char)sqlite3Toupper(z1[i]);
67771       }
67772       sqlite3_result_text(context, z1, -1, sqlite3_free);
67773     }
67774   }
67775 }
67776 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
67777   u8 *z1;
67778   const char *z2;
67779   int i, n;
67780   UNUSED_PARAMETER(argc);
67781   z2 = (char*)sqlite3_value_text(argv[0]);
67782   n = sqlite3_value_bytes(argv[0]);
67783   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
67784   assert( z2==(char*)sqlite3_value_text(argv[0]) );
67785   if( z2 ){
67786     z1 = contextMalloc(context, ((i64)n)+1);
67787     if( z1 ){
67788       memcpy(z1, z2, n+1);
67789       for(i=0; z1[i]; i++){
67790         z1[i] = sqlite3Tolower(z1[i]);
67791       }
67792       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
67793     }
67794   }
67795 }
67796
67797 /*
67798 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
67799 ** All three do the same thing.  They return the first non-NULL
67800 ** argument.
67801 */
67802 static void ifnullFunc(
67803   sqlite3_context *context,
67804   int argc,
67805   sqlite3_value **argv
67806 ){
67807   int i;
67808   for(i=0; i<argc; i++){
67809     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
67810       sqlite3_result_value(context, argv[i]);
67811       break;
67812     }
67813   }
67814 }
67815
67816 /*
67817 ** Implementation of random().  Return a random integer.  
67818 */
67819 static void randomFunc(
67820   sqlite3_context *context,
67821   int NotUsed,
67822   sqlite3_value **NotUsed2
67823 ){
67824   sqlite_int64 r;
67825   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67826   sqlite3_randomness(sizeof(r), &r);
67827   if( (r<<1)==0 ) r = 0;  /* Prevent 0x8000.... as the result so that we */
67828                           /* can always do abs() of the result */
67829   sqlite3_result_int64(context, r);
67830 }
67831
67832 /*
67833 ** Implementation of randomblob(N).  Return a random blob
67834 ** that is N bytes long.
67835 */
67836 static void randomBlob(
67837   sqlite3_context *context,
67838   int argc,
67839   sqlite3_value **argv
67840 ){
67841   int n;
67842   unsigned char *p;
67843   assert( argc==1 );
67844   UNUSED_PARAMETER(argc);
67845   n = sqlite3_value_int(argv[0]);
67846   if( n<1 ){
67847     n = 1;
67848   }
67849   p = contextMalloc(context, n);
67850   if( p ){
67851     sqlite3_randomness(n, p);
67852     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
67853   }
67854 }
67855
67856 /*
67857 ** Implementation of the last_insert_rowid() SQL function.  The return
67858 ** value is the same as the sqlite3_last_insert_rowid() API function.
67859 */
67860 static void last_insert_rowid(
67861   sqlite3_context *context, 
67862   int NotUsed, 
67863   sqlite3_value **NotUsed2
67864 ){
67865   sqlite3 *db = sqlite3_context_db_handle(context);
67866   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67867   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
67868 }
67869
67870 /*
67871 ** Implementation of the changes() SQL function.  The return value is the
67872 ** same as the sqlite3_changes() API function.
67873 */
67874 static void changes(
67875   sqlite3_context *context,
67876   int NotUsed,
67877   sqlite3_value **NotUsed2
67878 ){
67879   sqlite3 *db = sqlite3_context_db_handle(context);
67880   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67881   sqlite3_result_int(context, sqlite3_changes(db));
67882 }
67883
67884 /*
67885 ** Implementation of the total_changes() SQL function.  The return value is
67886 ** the same as the sqlite3_total_changes() API function.
67887 */
67888 static void total_changes(
67889   sqlite3_context *context,
67890   int NotUsed,
67891   sqlite3_value **NotUsed2
67892 ){
67893   sqlite3 *db = sqlite3_context_db_handle(context);
67894   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67895   sqlite3_result_int(context, sqlite3_total_changes(db));
67896 }
67897
67898 /*
67899 ** A structure defining how to do GLOB-style comparisons.
67900 */
67901 struct compareInfo {
67902   u8 matchAll;
67903   u8 matchOne;
67904   u8 matchSet;
67905   u8 noCase;
67906 };
67907
67908 /*
67909 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
67910 ** character is exactly one byte in size.  Also, all characters are
67911 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
67912 ** whereas only characters less than 0x80 do in ASCII.
67913 */
67914 #if defined(SQLITE_EBCDIC)
67915 # define sqlite3Utf8Read(A,B,C)  (*(A++))
67916 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
67917 #else
67918 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
67919 #endif
67920
67921 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
67922 /* The correct SQL-92 behavior is for the LIKE operator to ignore
67923 ** case.  Thus  'a' LIKE 'A' would be true. */
67924 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
67925 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
67926 ** is case sensitive causing 'a' LIKE 'A' to be false */
67927 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
67928
67929 /*
67930 ** Compare two UTF-8 strings for equality where the first string can
67931 ** potentially be a "glob" expression.  Return true (1) if they
67932 ** are the same and false (0) if they are different.
67933 **
67934 ** Globbing rules:
67935 **
67936 **      '*'       Matches any sequence of zero or more characters.
67937 **
67938 **      '?'       Matches exactly one character.
67939 **
67940 **     [...]      Matches one character from the enclosed list of
67941 **                characters.
67942 **
67943 **     [^...]     Matches one character not in the enclosed list.
67944 **
67945 ** With the [...] and [^...] matching, a ']' character can be included
67946 ** in the list by making it the first character after '[' or '^'.  A
67947 ** range of characters can be specified using '-'.  Example:
67948 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
67949 ** it the last character in the list.
67950 **
67951 ** This routine is usually quick, but can be N**2 in the worst case.
67952 **
67953 ** Hints: to match '*' or '?', put them in "[]".  Like this:
67954 **
67955 **         abc[*]xyz        Matches "abc*xyz" only
67956 */
67957 static int patternCompare(
67958   const u8 *zPattern,              /* The glob pattern */
67959   const u8 *zString,               /* The string to compare against the glob */
67960   const struct compareInfo *pInfo, /* Information about how to do the compare */
67961   const int esc                    /* The escape character */
67962 ){
67963   int c, c2;
67964   int invert;
67965   int seen;
67966   u8 matchOne = pInfo->matchOne;
67967   u8 matchAll = pInfo->matchAll;
67968   u8 matchSet = pInfo->matchSet;
67969   u8 noCase = pInfo->noCase; 
67970   int prevEscape = 0;     /* True if the previous character was 'escape' */
67971
67972   while( (c = sqlite3Utf8Read(zPattern,0,&zPattern))!=0 ){
67973     if( !prevEscape && c==matchAll ){
67974       while( (c=sqlite3Utf8Read(zPattern,0,&zPattern)) == matchAll
67975                || c == matchOne ){
67976         if( c==matchOne && sqlite3Utf8Read(zString, 0, &zString)==0 ){
67977           return 0;
67978         }
67979       }
67980       if( c==0 ){
67981         return 1;
67982       }else if( c==esc ){
67983         c = sqlite3Utf8Read(zPattern, 0, &zPattern);
67984         if( c==0 ){
67985           return 0;
67986         }
67987       }else if( c==matchSet ){
67988         assert( esc==0 );         /* This is GLOB, not LIKE */
67989         assert( matchSet<0x80 );  /* '[' is a single-byte character */
67990         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
67991           SQLITE_SKIP_UTF8(zString);
67992         }
67993         return *zString!=0;
67994       }
67995       while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){
67996         if( noCase ){
67997           GlogUpperToLower(c2);
67998           GlogUpperToLower(c);
67999           while( c2 != 0 && c2 != c ){
68000             c2 = sqlite3Utf8Read(zString, 0, &zString);
68001             GlogUpperToLower(c2);
68002           }
68003         }else{
68004           while( c2 != 0 && c2 != c ){
68005             c2 = sqlite3Utf8Read(zString, 0, &zString);
68006           }
68007         }
68008         if( c2==0 ) return 0;
68009         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
68010       }
68011       return 0;
68012     }else if( !prevEscape && c==matchOne ){
68013       if( sqlite3Utf8Read(zString, 0, &zString)==0 ){
68014         return 0;
68015       }
68016     }else if( c==matchSet ){
68017       int prior_c = 0;
68018       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
68019       seen = 0;
68020       invert = 0;
68021       c = sqlite3Utf8Read(zString, 0, &zString);
68022       if( c==0 ) return 0;
68023       c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
68024       if( c2=='^' ){
68025         invert = 1;
68026         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
68027       }
68028       if( c2==']' ){
68029         if( c==']' ) seen = 1;
68030         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
68031       }
68032       while( c2 && c2!=']' ){
68033         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
68034           c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
68035           if( c>=prior_c && c<=c2 ) seen = 1;
68036           prior_c = 0;
68037         }else{
68038           if( c==c2 ){
68039             seen = 1;
68040           }
68041           prior_c = c2;
68042         }
68043         c2 = sqlite3Utf8Read(zPattern, 0, &zPattern);
68044       }
68045       if( c2==0 || (seen ^ invert)==0 ){
68046         return 0;
68047       }
68048     }else if( esc==c && !prevEscape ){
68049       prevEscape = 1;
68050     }else{
68051       c2 = sqlite3Utf8Read(zString, 0, &zString);
68052       if( noCase ){
68053         GlogUpperToLower(c);
68054         GlogUpperToLower(c2);
68055       }
68056       if( c!=c2 ){
68057         return 0;
68058       }
68059       prevEscape = 0;
68060     }
68061   }
68062   return *zString==0;
68063 }
68064
68065 /*
68066 ** Count the number of times that the LIKE operator (or GLOB which is
68067 ** just a variation of LIKE) gets called.  This is used for testing
68068 ** only.
68069 */
68070 #ifdef SQLITE_TEST
68071 SQLITE_API int sqlite3_like_count = 0;
68072 #endif
68073
68074
68075 /*
68076 ** Implementation of the like() SQL function.  This function implements
68077 ** the build-in LIKE operator.  The first argument to the function is the
68078 ** pattern and the second argument is the string.  So, the SQL statements:
68079 **
68080 **       A LIKE B
68081 **
68082 ** is implemented as like(B,A).
68083 **
68084 ** This same function (with a different compareInfo structure) computes
68085 ** the GLOB operator.
68086 */
68087 static void likeFunc(
68088   sqlite3_context *context, 
68089   int argc, 
68090   sqlite3_value **argv
68091 ){
68092   const unsigned char *zA, *zB;
68093   int escape = 0;
68094   sqlite3 *db = sqlite3_context_db_handle(context);
68095
68096   zB = sqlite3_value_text(argv[0]);
68097   zA = sqlite3_value_text(argv[1]);
68098
68099   /* Limit the length of the LIKE or GLOB pattern to avoid problems
68100   ** of deep recursion and N*N behavior in patternCompare().
68101   */
68102   if( sqlite3_value_bytes(argv[0]) >
68103         db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
68104     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
68105     return;
68106   }
68107   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
68108
68109   if( argc==3 ){
68110     /* The escape character string must consist of a single UTF-8 character.
68111     ** Otherwise, return an error.
68112     */
68113     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
68114     if( zEsc==0 ) return;
68115     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
68116       sqlite3_result_error(context, 
68117           "ESCAPE expression must be a single character", -1);
68118       return;
68119     }
68120     escape = sqlite3Utf8Read(zEsc, 0, &zEsc);
68121   }
68122   if( zA && zB ){
68123     struct compareInfo *pInfo = sqlite3_user_data(context);
68124 #ifdef SQLITE_TEST
68125     sqlite3_like_count++;
68126 #endif
68127     
68128     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
68129   }
68130 }
68131
68132 /*
68133 ** Implementation of the NULLIF(x,y) function.  The result is the first
68134 ** argument if the arguments are different.  The result is NULL if the
68135 ** arguments are equal to each other.
68136 */
68137 static void nullifFunc(
68138   sqlite3_context *context,
68139   int NotUsed,
68140   sqlite3_value **argv
68141 ){
68142   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
68143   UNUSED_PARAMETER(NotUsed);
68144   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
68145     sqlite3_result_value(context, argv[0]);
68146   }
68147 }
68148
68149 /*
68150 ** Implementation of the VERSION(*) function.  The result is the version
68151 ** of the SQLite library that is running.
68152 */
68153 static void versionFunc(
68154   sqlite3_context *context,
68155   int NotUsed,
68156   sqlite3_value **NotUsed2
68157 ){
68158   UNUSED_PARAMETER2(NotUsed, NotUsed2);
68159   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
68160 }
68161
68162 /* Array for converting from half-bytes (nybbles) into ASCII hex
68163 ** digits. */
68164 static const char hexdigits[] = {
68165   '0', '1', '2', '3', '4', '5', '6', '7',
68166   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
68167 };
68168
68169 /*
68170 ** EXPERIMENTAL - This is not an official function.  The interface may
68171 ** change.  This function may disappear.  Do not write code that depends
68172 ** on this function.
68173 **
68174 ** Implementation of the QUOTE() function.  This function takes a single
68175 ** argument.  If the argument is numeric, the return value is the same as
68176 ** the argument.  If the argument is NULL, the return value is the string
68177 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
68178 ** single-quote escapes.
68179 */
68180 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
68181   assert( argc==1 );
68182   UNUSED_PARAMETER(argc);
68183   switch( sqlite3_value_type(argv[0]) ){
68184     case SQLITE_INTEGER:
68185     case SQLITE_FLOAT: {
68186       sqlite3_result_value(context, argv[0]);
68187       break;
68188     }
68189     case SQLITE_BLOB: {
68190       char *zText = 0;
68191       char const *zBlob = sqlite3_value_blob(argv[0]);
68192       int nBlob = sqlite3_value_bytes(argv[0]);
68193       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
68194       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
68195       if( zText ){
68196         int i;
68197         for(i=0; i<nBlob; i++){
68198           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
68199           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
68200         }
68201         zText[(nBlob*2)+2] = '\'';
68202         zText[(nBlob*2)+3] = '\0';
68203         zText[0] = 'X';
68204         zText[1] = '\'';
68205         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
68206         sqlite3_free(zText);
68207       }
68208       break;
68209     }
68210     case SQLITE_TEXT: {
68211       int i,j;
68212       u64 n;
68213       const unsigned char *zArg = sqlite3_value_text(argv[0]);
68214       char *z;
68215
68216       if( zArg==0 ) return;
68217       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
68218       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
68219       if( z ){
68220         z[0] = '\'';
68221         for(i=0, j=1; zArg[i]; i++){
68222           z[j++] = zArg[i];
68223           if( zArg[i]=='\'' ){
68224             z[j++] = '\'';
68225           }
68226         }
68227         z[j++] = '\'';
68228         z[j] = 0;
68229         sqlite3_result_text(context, z, j, sqlite3_free);
68230       }
68231       break;
68232     }
68233     default: {
68234       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
68235       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
68236       break;
68237     }
68238   }
68239 }
68240
68241 /*
68242 ** The hex() function.  Interpret the argument as a blob.  Return
68243 ** a hexadecimal rendering as text.
68244 */
68245 static void hexFunc(
68246   sqlite3_context *context,
68247   int argc,
68248   sqlite3_value **argv
68249 ){
68250   int i, n;
68251   const unsigned char *pBlob;
68252   char *zHex, *z;
68253   assert( argc==1 );
68254   UNUSED_PARAMETER(argc);
68255   pBlob = sqlite3_value_blob(argv[0]);
68256   n = sqlite3_value_bytes(argv[0]);
68257   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
68258   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
68259   if( zHex ){
68260     for(i=0; i<n; i++, pBlob++){
68261       unsigned char c = *pBlob;
68262       *(z++) = hexdigits[(c>>4)&0xf];
68263       *(z++) = hexdigits[c&0xf];
68264     }
68265     *z = 0;
68266     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
68267   }
68268 }
68269
68270 /*
68271 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
68272 */
68273 static void zeroblobFunc(
68274   sqlite3_context *context,
68275   int argc,
68276   sqlite3_value **argv
68277 ){
68278   i64 n;
68279   assert( argc==1 );
68280   UNUSED_PARAMETER(argc);
68281   n = sqlite3_value_int64(argv[0]);
68282   if( n>SQLITE_MAX_LENGTH ){
68283     sqlite3_result_error_toobig(context);
68284   }else{
68285     sqlite3_result_zeroblob(context, (int)n);
68286   }
68287 }
68288
68289 /*
68290 ** The replace() function.  Three arguments are all strings: call
68291 ** them A, B, and C. The result is also a string which is derived
68292 ** from A by replacing every occurance of B with C.  The match
68293 ** must be exact.  Collating sequences are not used.
68294 */
68295 static void replaceFunc(
68296   sqlite3_context *context,
68297   int argc,
68298   sqlite3_value **argv
68299 ){
68300   const unsigned char *zStr;        /* The input string A */
68301   const unsigned char *zPattern;    /* The pattern string B */
68302   const unsigned char *zRep;        /* The replacement string C */
68303   unsigned char *zOut;              /* The output */
68304   int nStr;                /* Size of zStr */
68305   int nPattern;            /* Size of zPattern */
68306   int nRep;                /* Size of zRep */
68307   i64 nOut;                /* Maximum size of zOut */
68308   int loopLimit;           /* Last zStr[] that might match zPattern[] */
68309   int i, j;                /* Loop counters */
68310
68311   assert( argc==3 );
68312   UNUSED_PARAMETER(argc);
68313   zStr = sqlite3_value_text(argv[0]);
68314   if( zStr==0 ) return;
68315   nStr = sqlite3_value_bytes(argv[0]);
68316   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
68317   zPattern = sqlite3_value_text(argv[1]);
68318   if( zPattern==0 ){
68319     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
68320             || sqlite3_context_db_handle(context)->mallocFailed );
68321     return;
68322   }
68323   if( zPattern[0]==0 ){
68324     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
68325     sqlite3_result_value(context, argv[0]);
68326     return;
68327   }
68328   nPattern = sqlite3_value_bytes(argv[1]);
68329   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
68330   zRep = sqlite3_value_text(argv[2]);
68331   if( zRep==0 ) return;
68332   nRep = sqlite3_value_bytes(argv[2]);
68333   assert( zRep==sqlite3_value_text(argv[2]) );
68334   nOut = nStr + 1;
68335   assert( nOut<SQLITE_MAX_LENGTH );
68336   zOut = contextMalloc(context, (i64)nOut);
68337   if( zOut==0 ){
68338     return;
68339   }
68340   loopLimit = nStr - nPattern;  
68341   for(i=j=0; i<=loopLimit; i++){
68342     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
68343       zOut[j++] = zStr[i];
68344     }else{
68345       u8 *zOld;
68346       sqlite3 *db = sqlite3_context_db_handle(context);
68347       nOut += nRep - nPattern;
68348       if( nOut>=db->aLimit[SQLITE_LIMIT_LENGTH] ){
68349         sqlite3_result_error_toobig(context);
68350         sqlite3DbFree(db, zOut);
68351         return;
68352       }
68353       zOld = zOut;
68354       zOut = sqlite3_realloc(zOut, (int)nOut);
68355       if( zOut==0 ){
68356         sqlite3_result_error_nomem(context);
68357         sqlite3DbFree(db, zOld);
68358         return;
68359       }
68360       memcpy(&zOut[j], zRep, nRep);
68361       j += nRep;
68362       i += nPattern-1;
68363     }
68364   }
68365   assert( j+nStr-i+1==nOut );
68366   memcpy(&zOut[j], &zStr[i], nStr-i);
68367   j += nStr - i;
68368   assert( j<=nOut );
68369   zOut[j] = 0;
68370   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
68371 }
68372
68373 /*
68374 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
68375 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
68376 */
68377 static void trimFunc(
68378   sqlite3_context *context,
68379   int argc,
68380   sqlite3_value **argv
68381 ){
68382   const unsigned char *zIn;         /* Input string */
68383   const unsigned char *zCharSet;    /* Set of characters to trim */
68384   int nIn;                          /* Number of bytes in input */
68385   int flags;                        /* 1: trimleft  2: trimright  3: trim */
68386   int i;                            /* Loop counter */
68387   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
68388   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
68389   int nChar;                        /* Number of characters in zCharSet */
68390
68391   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
68392     return;
68393   }
68394   zIn = sqlite3_value_text(argv[0]);
68395   if( zIn==0 ) return;
68396   nIn = sqlite3_value_bytes(argv[0]);
68397   assert( zIn==sqlite3_value_text(argv[0]) );
68398   if( argc==1 ){
68399     static const unsigned char lenOne[] = { 1 };
68400     static unsigned char * const azOne[] = { (u8*)" " };
68401     nChar = 1;
68402     aLen = (u8*)lenOne;
68403     azChar = (unsigned char **)azOne;
68404     zCharSet = 0;
68405   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
68406     return;
68407   }else{
68408     const unsigned char *z;
68409     for(z=zCharSet, nChar=0; *z; nChar++){
68410       SQLITE_SKIP_UTF8(z);
68411     }
68412     if( nChar>0 ){
68413       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
68414       if( azChar==0 ){
68415         return;
68416       }
68417       aLen = (unsigned char*)&azChar[nChar];
68418       for(z=zCharSet, nChar=0; *z; nChar++){
68419         azChar[nChar] = (unsigned char *)z;
68420         SQLITE_SKIP_UTF8(z);
68421         aLen[nChar] = (u8)(z - azChar[nChar]);
68422       }
68423     }
68424   }
68425   if( nChar>0 ){
68426     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
68427     if( flags & 1 ){
68428       while( nIn>0 ){
68429         int len = 0;
68430         for(i=0; i<nChar; i++){
68431           len = aLen[i];
68432           if( memcmp(zIn, azChar[i], len)==0 ) break;
68433         }
68434         if( i>=nChar ) break;
68435         zIn += len;
68436         nIn -= len;
68437       }
68438     }
68439     if( flags & 2 ){
68440       while( nIn>0 ){
68441         int len = 0;
68442         for(i=0; i<nChar; i++){
68443           len = aLen[i];
68444           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
68445         }
68446         if( i>=nChar ) break;
68447         nIn -= len;
68448       }
68449     }
68450     if( zCharSet ){
68451       sqlite3_free(azChar);
68452     }
68453   }
68454   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
68455 }
68456
68457
68458 #ifdef SQLITE_SOUNDEX
68459 /*
68460 ** Compute the soundex encoding of a word.
68461 */
68462 static void soundexFunc(
68463   sqlite3_context *context,
68464   int argc,
68465   sqlite3_value **argv
68466 ){
68467   char zResult[8];
68468   const u8 *zIn;
68469   int i, j;
68470   static const unsigned char iCode[] = {
68471     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68472     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68473     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68474     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68475     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
68476     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
68477     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
68478     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
68479   };
68480   assert( argc==1 );
68481   zIn = (u8*)sqlite3_value_text(argv[0]);
68482   if( zIn==0 ) zIn = (u8*)"";
68483   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
68484   if( zIn[i] ){
68485     u8 prevcode = iCode[zIn[i]&0x7f];
68486     zResult[0] = sqlite3Toupper(zIn[i]);
68487     for(j=1; j<4 && zIn[i]; i++){
68488       int code = iCode[zIn[i]&0x7f];
68489       if( code>0 ){
68490         if( code!=prevcode ){
68491           prevcode = code;
68492           zResult[j++] = code + '0';
68493         }
68494       }else{
68495         prevcode = 0;
68496       }
68497     }
68498     while( j<4 ){
68499       zResult[j++] = '0';
68500     }
68501     zResult[j] = 0;
68502     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
68503   }else{
68504     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
68505   }
68506 }
68507 #endif
68508
68509 #ifndef SQLITE_OMIT_LOAD_EXTENSION
68510 /*
68511 ** A function that loads a shared-library extension then returns NULL.
68512 */
68513 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
68514   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
68515   const char *zProc;
68516   sqlite3 *db = sqlite3_context_db_handle(context);
68517   char *zErrMsg = 0;
68518
68519   if( argc==2 ){
68520     zProc = (const char *)sqlite3_value_text(argv[1]);
68521   }else{
68522     zProc = 0;
68523   }
68524   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
68525     sqlite3_result_error(context, zErrMsg, -1);
68526     sqlite3_free(zErrMsg);
68527   }
68528 }
68529 #endif
68530
68531
68532 /*
68533 ** An instance of the following structure holds the context of a
68534 ** sum() or avg() aggregate computation.
68535 */
68536 typedef struct SumCtx SumCtx;
68537 struct SumCtx {
68538   double rSum;      /* Floating point sum */
68539   i64 iSum;         /* Integer sum */   
68540   i64 cnt;          /* Number of elements summed */
68541   u8 overflow;      /* True if integer overflow seen */
68542   u8 approx;        /* True if non-integer value was input to the sum */
68543 };
68544
68545 /*
68546 ** Routines used to compute the sum, average, and total.
68547 **
68548 ** The SUM() function follows the (broken) SQL standard which means
68549 ** that it returns NULL if it sums over no inputs.  TOTAL returns
68550 ** 0.0 in that case.  In addition, TOTAL always returns a float where
68551 ** SUM might return an integer if it never encounters a floating point
68552 ** value.  TOTAL never fails, but SUM might through an exception if
68553 ** it overflows an integer.
68554 */
68555 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
68556   SumCtx *p;
68557   int type;
68558   assert( argc==1 );
68559   UNUSED_PARAMETER(argc);
68560   p = sqlite3_aggregate_context(context, sizeof(*p));
68561   type = sqlite3_value_numeric_type(argv[0]);
68562   if( p && type!=SQLITE_NULL ){
68563     p->cnt++;
68564     if( type==SQLITE_INTEGER ){
68565       i64 v = sqlite3_value_int64(argv[0]);
68566       p->rSum += v;
68567       if( (p->approx|p->overflow)==0 ){
68568         i64 iNewSum = p->iSum + v;
68569         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
68570         int s2 = (int)(v       >> (sizeof(i64)*8-1));
68571         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
68572         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
68573         p->iSum = iNewSum;
68574       }
68575     }else{
68576       p->rSum += sqlite3_value_double(argv[0]);
68577       p->approx = 1;
68578     }
68579   }
68580 }
68581 static void sumFinalize(sqlite3_context *context){
68582   SumCtx *p;
68583   p = sqlite3_aggregate_context(context, 0);
68584   if( p && p->cnt>0 ){
68585     if( p->overflow ){
68586       sqlite3_result_error(context,"integer overflow",-1);
68587     }else if( p->approx ){
68588       sqlite3_result_double(context, p->rSum);
68589     }else{
68590       sqlite3_result_int64(context, p->iSum);
68591     }
68592   }
68593 }
68594 static void avgFinalize(sqlite3_context *context){
68595   SumCtx *p;
68596   p = sqlite3_aggregate_context(context, 0);
68597   if( p && p->cnt>0 ){
68598     sqlite3_result_double(context, p->rSum/(double)p->cnt);
68599   }
68600 }
68601 static void totalFinalize(sqlite3_context *context){
68602   SumCtx *p;
68603   p = sqlite3_aggregate_context(context, 0);
68604   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
68605   sqlite3_result_double(context, p ? p->rSum : (double)0);
68606 }
68607
68608 /*
68609 ** The following structure keeps track of state information for the
68610 ** count() aggregate function.
68611 */
68612 typedef struct CountCtx CountCtx;
68613 struct CountCtx {
68614   i64 n;
68615 };
68616
68617 /*
68618 ** Routines to implement the count() aggregate function.
68619 */
68620 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
68621   CountCtx *p;
68622   p = sqlite3_aggregate_context(context, sizeof(*p));
68623   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
68624     p->n++;
68625   }
68626 }   
68627 static void countFinalize(sqlite3_context *context){
68628   CountCtx *p;
68629   p = sqlite3_aggregate_context(context, 0);
68630   sqlite3_result_int64(context, p ? p->n : 0);
68631 }
68632
68633 /*
68634 ** Routines to implement min() and max() aggregate functions.
68635 */
68636 static void minmaxStep(
68637   sqlite3_context *context, 
68638   int NotUsed, 
68639   sqlite3_value **argv
68640 ){
68641   Mem *pArg  = (Mem *)argv[0];
68642   Mem *pBest;
68643   UNUSED_PARAMETER(NotUsed);
68644
68645   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
68646   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
68647   if( !pBest ) return;
68648
68649   if( pBest->flags ){
68650     int max;
68651     int cmp;
68652     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
68653     /* This step function is used for both the min() and max() aggregates,
68654     ** the only difference between the two being that the sense of the
68655     ** comparison is inverted. For the max() aggregate, the
68656     ** sqlite3_user_data() function returns (void *)-1. For min() it
68657     ** returns (void *)db, where db is the sqlite3* database pointer.
68658     ** Therefore the next statement sets variable 'max' to 1 for the max()
68659     ** aggregate, or 0 for min().
68660     */
68661     max = sqlite3_user_data(context)!=0;
68662     cmp = sqlite3MemCompare(pBest, pArg, pColl);
68663     if( (max && cmp<0) || (!max && cmp>0) ){
68664       sqlite3VdbeMemCopy(pBest, pArg);
68665     }
68666   }else{
68667     sqlite3VdbeMemCopy(pBest, pArg);
68668   }
68669 }
68670 static void minMaxFinalize(sqlite3_context *context){
68671   sqlite3_value *pRes;
68672   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
68673   if( pRes ){
68674     if( pRes->flags ){
68675       sqlite3_result_value(context, pRes);
68676     }
68677     sqlite3VdbeMemRelease(pRes);
68678   }
68679 }
68680
68681 /*
68682 ** group_concat(EXPR, ?SEPARATOR?)
68683 */
68684 static void groupConcatStep(
68685   sqlite3_context *context,
68686   int argc,
68687   sqlite3_value **argv
68688 ){
68689   const char *zVal;
68690   StrAccum *pAccum;
68691   const char *zSep;
68692   int nVal, nSep;
68693   assert( argc==1 || argc==2 );
68694   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
68695   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
68696
68697   if( pAccum ){
68698     sqlite3 *db = sqlite3_context_db_handle(context);
68699     pAccum->useMalloc = 1;
68700     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
68701     if( pAccum->nChar ){
68702       if( argc==2 ){
68703         zSep = (char*)sqlite3_value_text(argv[1]);
68704         nSep = sqlite3_value_bytes(argv[1]);
68705       }else{
68706         zSep = ",";
68707         nSep = 1;
68708       }
68709       sqlite3StrAccumAppend(pAccum, zSep, nSep);
68710     }
68711     zVal = (char*)sqlite3_value_text(argv[0]);
68712     nVal = sqlite3_value_bytes(argv[0]);
68713     sqlite3StrAccumAppend(pAccum, zVal, nVal);
68714   }
68715 }
68716 static void groupConcatFinalize(sqlite3_context *context){
68717   StrAccum *pAccum;
68718   pAccum = sqlite3_aggregate_context(context, 0);
68719   if( pAccum ){
68720     if( pAccum->tooBig ){
68721       sqlite3_result_error_toobig(context);
68722     }else if( pAccum->mallocFailed ){
68723       sqlite3_result_error_nomem(context);
68724     }else{    
68725       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
68726                           sqlite3_free);
68727     }
68728   }
68729 }
68730
68731 /*
68732 ** This function registered all of the above C functions as SQL
68733 ** functions.  This should be the only routine in this file with
68734 ** external linkage.
68735 */
68736 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
68737 #ifndef SQLITE_OMIT_ALTERTABLE
68738   sqlite3AlterFunctions(db);
68739 #endif
68740   if( !db->mallocFailed ){
68741     int rc = sqlite3_overload_function(db, "MATCH", 2);
68742     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
68743     if( rc==SQLITE_NOMEM ){
68744       db->mallocFailed = 1;
68745     }
68746   }
68747 #ifdef SQLITE_SSE
68748   (void)sqlite3SseFunctions(db);
68749 #endif
68750 }
68751
68752 /*
68753 ** Set the LIKEOPT flag on the 2-argument function with the given name.
68754 */
68755 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
68756   FuncDef *pDef;
68757   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
68758                              2, SQLITE_UTF8, 0);
68759   if( pDef ){
68760     pDef->flags = flagVal;
68761   }
68762 }
68763
68764 /*
68765 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
68766 ** parameter determines whether or not the LIKE operator is case
68767 ** sensitive.  GLOB is always case sensitive.
68768 */
68769 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
68770   struct compareInfo *pInfo;
68771   if( caseSensitive ){
68772     pInfo = (struct compareInfo*)&likeInfoAlt;
68773   }else{
68774     pInfo = (struct compareInfo*)&likeInfoNorm;
68775   }
68776   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
68777   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
68778   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
68779       (struct compareInfo*)&globInfo, likeFunc, 0,0);
68780   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
68781   setLikeOptFlag(db, "like", 
68782       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
68783 }
68784
68785 /*
68786 ** pExpr points to an expression which implements a function.  If
68787 ** it is appropriate to apply the LIKE optimization to that function
68788 ** then set aWc[0] through aWc[2] to the wildcard characters and
68789 ** return TRUE.  If the function is not a LIKE-style function then
68790 ** return FALSE.
68791 */
68792 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
68793   FuncDef *pDef;
68794   if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
68795     return 0;
68796   }
68797   if( pExpr->pList->nExpr!=2 ){
68798     return 0;
68799   }
68800   pDef = sqlite3FindFunction(db, (char*)pExpr->token.z, pExpr->token.n, 2,
68801                              SQLITE_UTF8, 0);
68802   if( pDef==0 || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
68803     return 0;
68804   }
68805
68806   /* The memcpy() statement assumes that the wildcard characters are
68807   ** the first three statements in the compareInfo structure.  The
68808   ** asserts() that follow verify that assumption
68809   */
68810   memcpy(aWc, pDef->pUserData, 3);
68811   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
68812   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
68813   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
68814   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
68815   return 1;
68816 }
68817
68818 /*
68819 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
68820 ** to the global function hash table.  This occurs at start-time (as
68821 ** a consequence of calling sqlite3_initialize()).
68822 **
68823 ** After this routine runs
68824 */
68825 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
68826   /*
68827   ** The following array holds FuncDef structures for all of the functions
68828   ** defined in this file.
68829   **
68830   ** The array cannot be constant since changes are made to the
68831   ** FuncDef.pHash elements at start-time.  The elements of this array
68832   ** are read-only after initialization is complete.
68833   */
68834   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
68835     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
68836     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
68837     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
68838     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
68839     FUNCTION(trim,               1, 3, 0, trimFunc         ),
68840     FUNCTION(trim,               2, 3, 0, trimFunc         ),
68841     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
68842     FUNCTION(min,                0, 0, 1, 0                ),
68843     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
68844     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
68845     FUNCTION(max,                0, 1, 1, 0                ),
68846     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
68847     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
68848     FUNCTION(length,             1, 0, 0, lengthFunc       ),
68849     FUNCTION(substr,             2, 0, 0, substrFunc       ),
68850     FUNCTION(substr,             3, 0, 0, substrFunc       ),
68851     FUNCTION(abs,                1, 0, 0, absFunc          ),
68852 #ifndef SQLITE_OMIT_FLOATING_POINT
68853     FUNCTION(round,              1, 0, 0, roundFunc        ),
68854     FUNCTION(round,              2, 0, 0, roundFunc        ),
68855 #endif
68856     FUNCTION(upper,              1, 0, 0, upperFunc        ),
68857     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
68858     FUNCTION(coalesce,           1, 0, 0, 0                ),
68859     FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
68860     FUNCTION(coalesce,           0, 0, 0, 0                ),
68861     FUNCTION(hex,                1, 0, 0, hexFunc          ),
68862     FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
68863     FUNCTION(random,             0, 0, 0, randomFunc       ),
68864     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
68865     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
68866     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
68867     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
68868     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
68869     FUNCTION(changes,            0, 0, 0, changes          ),
68870     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
68871     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
68872     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
68873   #ifdef SQLITE_SOUNDEX
68874     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
68875   #endif
68876   #ifndef SQLITE_OMIT_LOAD_EXTENSION
68877     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
68878     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
68879   #endif
68880     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
68881     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
68882     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
68883     AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
68884     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
68885     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
68886     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
68887   
68888     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
68889   #ifdef SQLITE_CASE_SENSITIVE_LIKE
68890     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
68891     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
68892   #else
68893     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
68894     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
68895   #endif
68896   };
68897
68898   int i;
68899   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
68900   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
68901
68902   for(i=0; i<ArraySize(aBuiltinFunc); i++){
68903     sqlite3FuncDefInsert(pHash, &aFunc[i]);
68904   }
68905   sqlite3RegisterDateTimeFunctions();
68906 }
68907
68908 /************** End of func.c ************************************************/
68909 /************** Begin file insert.c ******************************************/
68910 /*
68911 ** 2001 September 15
68912 **
68913 ** The author disclaims copyright to this source code.  In place of
68914 ** a legal notice, here is a blessing:
68915 **
68916 **    May you do good and not evil.
68917 **    May you find forgiveness for yourself and forgive others.
68918 **    May you share freely, never taking more than you give.
68919 **
68920 *************************************************************************
68921 ** This file contains C code routines that are called by the parser
68922 ** to handle INSERT statements in SQLite.
68923 **
68924 ** $Id: insert.c,v 1.256 2008/12/10 21:19:57 drh Exp $
68925 */
68926
68927 /*
68928 ** Set P4 of the most recently inserted opcode to a column affinity
68929 ** string for index pIdx. A column affinity string has one character
68930 ** for each column in the table, according to the affinity of the column:
68931 **
68932 **  Character      Column affinity
68933 **  ------------------------------
68934 **  'a'            TEXT
68935 **  'b'            NONE
68936 **  'c'            NUMERIC
68937 **  'd'            INTEGER
68938 **  'e'            REAL
68939 **
68940 ** An extra 'b' is appended to the end of the string to cover the
68941 ** rowid that appears as the last column in every index.
68942 */
68943 SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
68944   if( !pIdx->zColAff ){
68945     /* The first time a column affinity string for a particular index is
68946     ** required, it is allocated and populated here. It is then stored as
68947     ** a member of the Index structure for subsequent use.
68948     **
68949     ** The column affinity string will eventually be deleted by
68950     ** sqliteDeleteIndex() when the Index structure itself is cleaned
68951     ** up.
68952     */
68953     int n;
68954     Table *pTab = pIdx->pTable;
68955     sqlite3 *db = sqlite3VdbeDb(v);
68956     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
68957     if( !pIdx->zColAff ){
68958       db->mallocFailed = 1;
68959       return;
68960     }
68961     for(n=0; n<pIdx->nColumn; n++){
68962       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
68963     }
68964     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
68965     pIdx->zColAff[n] = 0;
68966   }
68967  
68968   sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0);
68969 }
68970
68971 /*
68972 ** Set P4 of the most recently inserted opcode to a column affinity
68973 ** string for table pTab. A column affinity string has one character
68974 ** for each column indexed by the index, according to the affinity of the
68975 ** column:
68976 **
68977 **  Character      Column affinity
68978 **  ------------------------------
68979 **  'a'            TEXT
68980 **  'b'            NONE
68981 **  'c'            NUMERIC
68982 **  'd'            INTEGER
68983 **  'e'            REAL
68984 */
68985 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
68986   /* The first time a column affinity string for a particular table
68987   ** is required, it is allocated and populated here. It is then 
68988   ** stored as a member of the Table structure for subsequent use.
68989   **
68990   ** The column affinity string will eventually be deleted by
68991   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
68992   */
68993   if( !pTab->zColAff ){
68994     char *zColAff;
68995     int i;
68996     sqlite3 *db = sqlite3VdbeDb(v);
68997
68998     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
68999     if( !zColAff ){
69000       db->mallocFailed = 1;
69001       return;
69002     }
69003
69004     for(i=0; i<pTab->nCol; i++){
69005       zColAff[i] = pTab->aCol[i].affinity;
69006     }
69007     zColAff[pTab->nCol] = '\0';
69008
69009     pTab->zColAff = zColAff;
69010   }
69011
69012   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
69013 }
69014
69015 /*
69016 ** Return non-zero if the table pTab in database iDb or any of its indices
69017 ** have been opened at any point in the VDBE program beginning at location
69018 ** iStartAddr throught the end of the program.  This is used to see if 
69019 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
69020 ** run without using temporary table for the results of the SELECT. 
69021 */
69022 static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){
69023   int i;
69024   int iEnd = sqlite3VdbeCurrentAddr(v);
69025   for(i=iStartAddr; i<iEnd; i++){
69026     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
69027     assert( pOp!=0 );
69028     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
69029       Index *pIndex;
69030       int tnum = pOp->p2;
69031       if( tnum==pTab->tnum ){
69032         return 1;
69033       }
69034       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
69035         if( tnum==pIndex->tnum ){
69036           return 1;
69037         }
69038       }
69039     }
69040 #ifndef SQLITE_OMIT_VIRTUALTABLE
69041     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){
69042       assert( pOp->p4.pVtab!=0 );
69043       assert( pOp->p4type==P4_VTAB );
69044       return 1;
69045     }
69046 #endif
69047   }
69048   return 0;
69049 }
69050
69051 #ifndef SQLITE_OMIT_AUTOINCREMENT
69052 /*
69053 ** Write out code to initialize the autoincrement logic.  This code
69054 ** looks up the current autoincrement value in the sqlite_sequence
69055 ** table and stores that value in a register.  Code generated by
69056 ** autoIncStep() will keep that register holding the largest
69057 ** rowid value.  Code generated by autoIncEnd() will write the new
69058 ** largest value of the counter back into the sqlite_sequence table.
69059 **
69060 ** This routine returns the index of the mem[] cell that contains
69061 ** the maximum rowid counter.
69062 **
69063 ** Three consecutive registers are allocated by this routine.  The
69064 ** first two hold the name of the target table and the maximum rowid 
69065 ** inserted into the target table, respectively.
69066 ** The third holds the rowid in sqlite_sequence where we will
69067 ** write back the revised maximum rowid.  This routine returns the
69068 ** index of the second of these three registers.
69069 */
69070 static int autoIncBegin(
69071   Parse *pParse,      /* Parsing context */
69072   int iDb,            /* Index of the database holding pTab */
69073   Table *pTab         /* The table we are writing to */
69074 ){
69075   int memId = 0;      /* Register holding maximum rowid */
69076   if( pTab->tabFlags & TF_Autoincrement ){
69077     Vdbe *v = pParse->pVdbe;
69078     Db *pDb = &pParse->db->aDb[iDb];
69079     int iCur = pParse->nTab;
69080     int addr;               /* Address of the top of the loop */
69081     assert( v );
69082     pParse->nMem++;         /* Holds name of table */
69083     memId = ++pParse->nMem;
69084     pParse->nMem++;
69085     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
69086     addr = sqlite3VdbeCurrentAddr(v);
69087     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0);
69088     sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9);
69089     sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId);
69090     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
69091     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
69092     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1);
69093     sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId);
69094     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
69095     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2);
69096     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
69097     sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
69098   }
69099   return memId;
69100 }
69101
69102 /*
69103 ** Update the maximum rowid for an autoincrement calculation.
69104 **
69105 ** This routine should be called when the top of the stack holds a
69106 ** new rowid that is about to be inserted.  If that new rowid is
69107 ** larger than the maximum rowid in the memId memory cell, then the
69108 ** memory cell is updated.  The stack is unchanged.
69109 */
69110 static void autoIncStep(Parse *pParse, int memId, int regRowid){
69111   if( memId>0 ){
69112     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
69113   }
69114 }
69115
69116 /*
69117 ** After doing one or more inserts, the maximum rowid is stored
69118 ** in reg[memId].  Generate code to write this value back into the
69119 ** the sqlite_sequence table.
69120 */
69121 static void autoIncEnd(
69122   Parse *pParse,     /* The parsing context */
69123   int iDb,           /* Index of the database holding pTab */
69124   Table *pTab,       /* Table we are inserting into */
69125   int memId          /* Memory cell holding the maximum rowid */
69126 ){
69127   if( pTab->tabFlags & TF_Autoincrement ){
69128     int iCur = pParse->nTab;
69129     Vdbe *v = pParse->pVdbe;
69130     Db *pDb = &pParse->db->aDb[iDb];
69131     int j1;
69132     int iRec = ++pParse->nMem;    /* Memory cell used for record */
69133
69134     assert( v );
69135     sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
69136     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
69137     sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1);
69138     sqlite3VdbeJumpHere(v, j1);
69139     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
69140     sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1);
69141     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
69142     sqlite3VdbeAddOp1(v, OP_Close, iCur);
69143   }
69144 }
69145 #else
69146 /*
69147 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
69148 ** above are all no-ops
69149 */
69150 # define autoIncBegin(A,B,C) (0)
69151 # define autoIncStep(A,B,C)
69152 # define autoIncEnd(A,B,C,D)
69153 #endif /* SQLITE_OMIT_AUTOINCREMENT */
69154
69155
69156 /* Forward declaration */
69157 static int xferOptimization(
69158   Parse *pParse,        /* Parser context */
69159   Table *pDest,         /* The table we are inserting into */
69160   Select *pSelect,      /* A SELECT statement to use as the data source */
69161   int onError,          /* How to handle constraint errors */
69162   int iDbDest           /* The database of pDest */
69163 );
69164
69165 /*
69166 ** This routine is call to handle SQL of the following forms:
69167 **
69168 **    insert into TABLE (IDLIST) values(EXPRLIST)
69169 **    insert into TABLE (IDLIST) select
69170 **
69171 ** The IDLIST following the table name is always optional.  If omitted,
69172 ** then a list of all columns for the table is substituted.  The IDLIST
69173 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
69174 **
69175 ** The pList parameter holds EXPRLIST in the first form of the INSERT
69176 ** statement above, and pSelect is NULL.  For the second form, pList is
69177 ** NULL and pSelect is a pointer to the select statement used to generate
69178 ** data for the insert.
69179 **
69180 ** The code generated follows one of four templates.  For a simple
69181 ** select with data coming from a VALUES clause, the code executes
69182 ** once straight down through.  Pseudo-code follows (we call this
69183 ** the "1st template"):
69184 **
69185 **         open write cursor to <table> and its indices
69186 **         puts VALUES clause expressions onto the stack
69187 **         write the resulting record into <table>
69188 **         cleanup
69189 **
69190 ** The three remaining templates assume the statement is of the form
69191 **
69192 **   INSERT INTO <table> SELECT ...
69193 **
69194 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
69195 ** in other words if the SELECT pulls all columns from a single table
69196 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
69197 ** if <table2> and <table1> are distinct tables but have identical
69198 ** schemas, including all the same indices, then a special optimization
69199 ** is invoked that copies raw records from <table2> over to <table1>.
69200 ** See the xferOptimization() function for the implementation of this
69201 ** template.  This is the 2nd template.
69202 **
69203 **         open a write cursor to <table>
69204 **         open read cursor on <table2>
69205 **         transfer all records in <table2> over to <table>
69206 **         close cursors
69207 **         foreach index on <table>
69208 **           open a write cursor on the <table> index
69209 **           open a read cursor on the corresponding <table2> index
69210 **           transfer all records from the read to the write cursors
69211 **           close cursors
69212 **         end foreach
69213 **
69214 ** The 3rd template is for when the second template does not apply
69215 ** and the SELECT clause does not read from <table> at any time.
69216 ** The generated code follows this template:
69217 **
69218 **         EOF <- 0
69219 **         X <- A
69220 **         goto B
69221 **      A: setup for the SELECT
69222 **         loop over the rows in the SELECT
69223 **           load values into registers R..R+n
69224 **           yield X
69225 **         end loop
69226 **         cleanup after the SELECT
69227 **         EOF <- 1
69228 **         yield X
69229 **         goto A
69230 **      B: open write cursor to <table> and its indices
69231 **      C: yield X
69232 **         if EOF goto D
69233 **         insert the select result into <table> from R..R+n
69234 **         goto C
69235 **      D: cleanup
69236 **
69237 ** The 4th template is used if the insert statement takes its
69238 ** values from a SELECT but the data is being inserted into a table
69239 ** that is also read as part of the SELECT.  In the third form,
69240 ** we have to use a intermediate table to store the results of
69241 ** the select.  The template is like this:
69242 **
69243 **         EOF <- 0
69244 **         X <- A
69245 **         goto B
69246 **      A: setup for the SELECT
69247 **         loop over the tables in the SELECT
69248 **           load value into register R..R+n
69249 **           yield X
69250 **         end loop
69251 **         cleanup after the SELECT
69252 **         EOF <- 1
69253 **         yield X
69254 **         halt-error
69255 **      B: open temp table
69256 **      L: yield X
69257 **         if EOF goto M
69258 **         insert row from R..R+n into temp table
69259 **         goto L
69260 **      M: open write cursor to <table> and its indices
69261 **         rewind temp table
69262 **      C: loop over rows of intermediate table
69263 **           transfer values form intermediate table into <table>
69264 **         end loop
69265 **      D: cleanup
69266 */
69267 SQLITE_PRIVATE void sqlite3Insert(
69268   Parse *pParse,        /* Parser context */
69269   SrcList *pTabList,    /* Name of table into which we are inserting */
69270   ExprList *pList,      /* List of values to be inserted */
69271   Select *pSelect,      /* A SELECT statement to use as the data source */
69272   IdList *pColumn,      /* Column names corresponding to IDLIST. */
69273   int onError           /* How to handle constraint errors */
69274 ){
69275   sqlite3 *db;          /* The main database structure */
69276   Table *pTab;          /* The table to insert into.  aka TABLE */
69277   char *zTab;           /* Name of the table into which we are inserting */
69278   const char *zDb;      /* Name of the database holding this table */
69279   int i, j, idx;        /* Loop counters */
69280   Vdbe *v;              /* Generate code into this virtual machine */
69281   Index *pIdx;          /* For looping over indices of the table */
69282   int nColumn;          /* Number of columns in the data */
69283   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
69284   int baseCur = 0;      /* VDBE Cursor number for pTab */
69285   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
69286   int endOfLoop;        /* Label for the end of the insertion loop */
69287   int useTempTable = 0; /* Store SELECT results in intermediate table */
69288   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
69289   int addrInsTop = 0;   /* Jump to label "D" */
69290   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
69291   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
69292   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
69293   int newIdx = -1;      /* Cursor for the NEW pseudo-table */
69294   int iDb;              /* Index of database holding TABLE */
69295   Db *pDb;              /* The database containing table being inserted into */
69296   int appendFlag = 0;   /* True if the insert is likely to be an append */
69297
69298   /* Register allocations */
69299   int regFromSelect = 0;/* Base register for data coming from SELECT */
69300   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
69301   int regRowCount = 0;  /* Memory cell used for the row counter */
69302   int regIns;           /* Block of regs holding rowid+data being inserted */
69303   int regRowid;         /* registers holding insert rowid */
69304   int regData;          /* register holding first column to insert */
69305   int regRecord;        /* Holds the assemblied row record */
69306   int regEof = 0;       /* Register recording end of SELECT data */
69307   int *aRegIdx = 0;     /* One register allocated to each index */
69308
69309
69310 #ifndef SQLITE_OMIT_TRIGGER
69311   int isView;                 /* True if attempting to insert into a view */
69312   int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
69313 #endif
69314
69315   db = pParse->db;
69316   memset(&dest, 0, sizeof(dest));
69317   if( pParse->nErr || db->mallocFailed ){
69318     goto insert_cleanup;
69319   }
69320
69321   /* Locate the table into which we will be inserting new information.
69322   */
69323   assert( pTabList->nSrc==1 );
69324   zTab = pTabList->a[0].zName;
69325   if( zTab==0 ) goto insert_cleanup;
69326   pTab = sqlite3SrcListLookup(pParse, pTabList);
69327   if( pTab==0 ){
69328     goto insert_cleanup;
69329   }
69330   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69331   assert( iDb<db->nDb );
69332   pDb = &db->aDb[iDb];
69333   zDb = pDb->zName;
69334   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
69335     goto insert_cleanup;
69336   }
69337
69338   /* Figure out if we have any triggers and if the table being
69339   ** inserted into is a view
69340   */
69341 #ifndef SQLITE_OMIT_TRIGGER
69342   triggers_exist = sqlite3TriggersExist(pTab, TK_INSERT, 0);
69343   isView = pTab->pSelect!=0;
69344 #else
69345 # define triggers_exist 0
69346 # define isView 0
69347 #endif
69348 #ifdef SQLITE_OMIT_VIEW
69349 # undef isView
69350 # define isView 0
69351 #endif
69352
69353   /* Ensure that:
69354   *  (a) the table is not read-only, 
69355   *  (b) that if it is a view then ON INSERT triggers exist
69356   */
69357   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
69358     goto insert_cleanup;
69359   }
69360   assert( pTab!=0 );
69361
69362   /* If pTab is really a view, make sure it has been initialized.
69363   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
69364   ** module table).
69365   */
69366   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
69367     goto insert_cleanup;
69368   }
69369
69370   /* Allocate a VDBE
69371   */
69372   v = sqlite3GetVdbe(pParse);
69373   if( v==0 ) goto insert_cleanup;
69374   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
69375   sqlite3BeginWriteOperation(pParse, pSelect || triggers_exist, iDb);
69376
69377   /* if there are row triggers, allocate a temp table for new.* references. */
69378   if( triggers_exist ){
69379     newIdx = pParse->nTab++;
69380   }
69381
69382 #ifndef SQLITE_OMIT_XFER_OPT
69383   /* If the statement is of the form
69384   **
69385   **       INSERT INTO <table1> SELECT * FROM <table2>;
69386   **
69387   ** Then special optimizations can be applied that make the transfer
69388   ** very fast and which reduce fragmentation of indices.
69389   **
69390   ** This is the 2nd template.
69391   */
69392   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
69393     assert( !triggers_exist );
69394     assert( pList==0 );
69395     goto insert_cleanup;
69396   }
69397 #endif /* SQLITE_OMIT_XFER_OPT */
69398
69399   /* If this is an AUTOINCREMENT table, look up the sequence number in the
69400   ** sqlite_sequence table and store it in memory cell regAutoinc.
69401   */
69402   regAutoinc = autoIncBegin(pParse, iDb, pTab);
69403
69404   /* Figure out how many columns of data are supplied.  If the data
69405   ** is coming from a SELECT statement, then generate a co-routine that
69406   ** produces a single row of the SELECT on each invocation.  The
69407   ** co-routine is the common header to the 3rd and 4th templates.
69408   */
69409   if( pSelect ){
69410     /* Data is coming from a SELECT.  Generate code to implement that SELECT
69411     ** as a co-routine.  The code is common to both the 3rd and 4th
69412     ** templates:
69413     **
69414     **         EOF <- 0
69415     **         X <- A
69416     **         goto B
69417     **      A: setup for the SELECT
69418     **         loop over the tables in the SELECT
69419     **           load value into register R..R+n
69420     **           yield X
69421     **         end loop
69422     **         cleanup after the SELECT
69423     **         EOF <- 1
69424     **         yield X
69425     **         halt-error
69426     **
69427     ** On each invocation of the co-routine, it puts a single row of the
69428     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
69429     ** (These output registers are allocated by sqlite3Select().)  When
69430     ** the SELECT completes, it sets the EOF flag stored in regEof.
69431     */
69432     int rc, j1;
69433
69434     regEof = ++pParse->nMem;
69435     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
69436     VdbeComment((v, "SELECT eof flag"));
69437     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
69438     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
69439     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
69440     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
69441     VdbeComment((v, "Jump over SELECT coroutine"));
69442
69443     /* Resolve the expressions in the SELECT statement and execute it. */
69444     rc = sqlite3Select(pParse, pSelect, &dest);
69445     if( rc || pParse->nErr || db->mallocFailed ){
69446       goto insert_cleanup;
69447     }
69448     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
69449     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
69450     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
69451     VdbeComment((v, "End of SELECT coroutine"));
69452     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
69453
69454     regFromSelect = dest.iMem;
69455     assert( pSelect->pEList );
69456     nColumn = pSelect->pEList->nExpr;
69457     assert( dest.nMem==nColumn );
69458
69459     /* Set useTempTable to TRUE if the result of the SELECT statement
69460     ** should be written into a temporary table (template 4).  Set to
69461     ** FALSE if each* row of the SELECT can be written directly into
69462     ** the destination table (template 3).
69463     **
69464     ** A temp table must be used if the table being updated is also one
69465     ** of the tables being read by the SELECT statement.  Also use a 
69466     ** temp table in the case of row triggers.
69467     */
69468     if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){
69469       useTempTable = 1;
69470     }
69471
69472     if( useTempTable ){
69473       /* Invoke the coroutine to extract information from the SELECT
69474       ** and add it to a transient table srcTab.  The code generated
69475       ** here is from the 4th template:
69476       **
69477       **      B: open temp table
69478       **      L: yield X
69479       **         if EOF goto M
69480       **         insert row from R..R+n into temp table
69481       **         goto L
69482       **      M: ...
69483       */
69484       int regRec;          /* Register to hold packed record */
69485       int regTempRowid;    /* Register to hold temp table ROWID */
69486       int addrTop;         /* Label "L" */
69487       int addrIf;          /* Address of jump to M */
69488
69489       srcTab = pParse->nTab++;
69490       regRec = sqlite3GetTempReg(pParse);
69491       regTempRowid = sqlite3GetTempReg(pParse);
69492       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
69493       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
69494       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
69495       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
69496       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
69497       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
69498       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
69499       sqlite3VdbeJumpHere(v, addrIf);
69500       sqlite3ReleaseTempReg(pParse, regRec);
69501       sqlite3ReleaseTempReg(pParse, regTempRowid);
69502     }
69503   }else{
69504     /* This is the case if the data for the INSERT is coming from a VALUES
69505     ** clause
69506     */
69507     NameContext sNC;
69508     memset(&sNC, 0, sizeof(sNC));
69509     sNC.pParse = pParse;
69510     srcTab = -1;
69511     assert( useTempTable==0 );
69512     nColumn = pList ? pList->nExpr : 0;
69513     for(i=0; i<nColumn; i++){
69514       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
69515         goto insert_cleanup;
69516       }
69517     }
69518   }
69519
69520   /* Make sure the number of columns in the source data matches the number
69521   ** of columns to be inserted into the table.
69522   */
69523   if( IsVirtual(pTab) ){
69524     for(i=0; i<pTab->nCol; i++){
69525       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
69526     }
69527   }
69528   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
69529     sqlite3ErrorMsg(pParse, 
69530        "table %S has %d columns but %d values were supplied",
69531        pTabList, 0, pTab->nCol, nColumn);
69532     goto insert_cleanup;
69533   }
69534   if( pColumn!=0 && nColumn!=pColumn->nId ){
69535     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
69536     goto insert_cleanup;
69537   }
69538
69539   /* If the INSERT statement included an IDLIST term, then make sure
69540   ** all elements of the IDLIST really are columns of the table and 
69541   ** remember the column indices.
69542   **
69543   ** If the table has an INTEGER PRIMARY KEY column and that column
69544   ** is named in the IDLIST, then record in the keyColumn variable
69545   ** the index into IDLIST of the primary key column.  keyColumn is
69546   ** the index of the primary key as it appears in IDLIST, not as
69547   ** is appears in the original table.  (The index of the primary
69548   ** key in the original table is pTab->iPKey.)
69549   */
69550   if( pColumn ){
69551     for(i=0; i<pColumn->nId; i++){
69552       pColumn->a[i].idx = -1;
69553     }
69554     for(i=0; i<pColumn->nId; i++){
69555       for(j=0; j<pTab->nCol; j++){
69556         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
69557           pColumn->a[i].idx = j;
69558           if( j==pTab->iPKey ){
69559             keyColumn = i;
69560           }
69561           break;
69562         }
69563       }
69564       if( j>=pTab->nCol ){
69565         if( sqlite3IsRowid(pColumn->a[i].zName) ){
69566           keyColumn = i;
69567         }else{
69568           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
69569               pTabList, 0, pColumn->a[i].zName);
69570           pParse->nErr++;
69571           goto insert_cleanup;
69572         }
69573       }
69574     }
69575   }
69576
69577   /* If there is no IDLIST term but the table has an integer primary
69578   ** key, the set the keyColumn variable to the primary key column index
69579   ** in the original table definition.
69580   */
69581   if( pColumn==0 && nColumn>0 ){
69582     keyColumn = pTab->iPKey;
69583   }
69584
69585   /* Open the temp table for FOR EACH ROW triggers
69586   */
69587   if( triggers_exist ){
69588     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
69589     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
69590   }
69591     
69592   /* Initialize the count of rows to be inserted
69593   */
69594   if( db->flags & SQLITE_CountRows ){
69595     regRowCount = ++pParse->nMem;
69596     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
69597   }
69598
69599   /* If this is not a view, open the table and and all indices */
69600   if( !isView ){
69601     int nIdx;
69602
69603     baseCur = pParse->nTab;
69604     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
69605     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
69606     if( aRegIdx==0 ){
69607       goto insert_cleanup;
69608     }
69609     for(i=0; i<nIdx; i++){
69610       aRegIdx[i] = ++pParse->nMem;
69611     }
69612   }
69613
69614   /* This is the top of the main insertion loop */
69615   if( useTempTable ){
69616     /* This block codes the top of loop only.  The complete loop is the
69617     ** following pseudocode (template 4):
69618     **
69619     **         rewind temp table
69620     **      C: loop over rows of intermediate table
69621     **           transfer values form intermediate table into <table>
69622     **         end loop
69623     **      D: ...
69624     */
69625     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
69626     addrCont = sqlite3VdbeCurrentAddr(v);
69627   }else if( pSelect ){
69628     /* This block codes the top of loop only.  The complete loop is the
69629     ** following pseudocode (template 3):
69630     **
69631     **      C: yield X
69632     **         if EOF goto D
69633     **         insert the select result into <table> from R..R+n
69634     **         goto C
69635     **      D: ...
69636     */
69637     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
69638     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
69639   }
69640
69641   /* Allocate registers for holding the rowid of the new row,
69642   ** the content of the new row, and the assemblied row record.
69643   */
69644   regRecord = ++pParse->nMem;
69645   regRowid = regIns = pParse->nMem+1;
69646   pParse->nMem += pTab->nCol + 1;
69647   if( IsVirtual(pTab) ){
69648     regRowid++;
69649     pParse->nMem++;
69650   }
69651   regData = regRowid+1;
69652
69653   /* Run the BEFORE and INSTEAD OF triggers, if there are any
69654   */
69655   endOfLoop = sqlite3VdbeMakeLabel(v);
69656   if( triggers_exist & TRIGGER_BEFORE ){
69657     int regTrigRowid;
69658     int regCols;
69659     int regRec;
69660
69661     /* build the NEW.* reference row.  Note that if there is an INTEGER
69662     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
69663     ** translated into a unique ID for the row.  But on a BEFORE trigger,
69664     ** we do not know what the unique ID will be (because the insert has
69665     ** not happened yet) so we substitute a rowid of -1
69666     */
69667     regTrigRowid = sqlite3GetTempReg(pParse);
69668     if( keyColumn<0 ){
69669       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69670     }else if( useTempTable ){
69671       sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
69672     }else{
69673       int j1;
69674       assert( pSelect==0 );  /* Otherwise useTempTable is true */
69675       sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
69676       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
69677       sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69678       sqlite3VdbeJumpHere(v, j1);
69679       sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
69680     }
69681
69682     /* Cannot have triggers on a virtual table. If it were possible,
69683     ** this block would have to account for hidden column.
69684     */
69685     assert(!IsVirtual(pTab));
69686
69687     /* Create the new column data
69688     */
69689     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
69690     for(i=0; i<pTab->nCol; i++){
69691       if( pColumn==0 ){
69692         j = i;
69693       }else{
69694         for(j=0; j<pColumn->nId; j++){
69695           if( pColumn->a[j].idx==i ) break;
69696         }
69697       }
69698       if( pColumn && j>=pColumn->nId ){
69699         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i);
69700       }else if( useTempTable ){
69701         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); 
69702       }else{
69703         assert( pSelect==0 ); /* Otherwise useTempTable is true */
69704         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i);
69705       }
69706     }
69707     regRec = sqlite3GetTempReg(pParse);
69708     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec);
69709
69710     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
69711     ** do not attempt any conversions before assembling the record.
69712     ** If this is a real table, attempt conversions as required by the
69713     ** table column affinities.
69714     */
69715     if( !isView ){
69716       sqlite3TableAffinityStr(v, pTab);
69717     }
69718     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regTrigRowid);
69719     sqlite3ReleaseTempReg(pParse, regRec);
69720     sqlite3ReleaseTempReg(pParse, regTrigRowid);
69721     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
69722
69723     /* Fire BEFORE or INSTEAD OF triggers */
69724     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, 
69725         newIdx, -1, onError, endOfLoop, 0, 0) ){
69726       goto insert_cleanup;
69727     }
69728   }
69729
69730   /* Push the record number for the new entry onto the stack.  The
69731   ** record number is a randomly generate integer created by NewRowid
69732   ** except when the table has an INTEGER PRIMARY KEY column, in which
69733   ** case the record number is the same as that column. 
69734   */
69735   if( !isView ){
69736     if( IsVirtual(pTab) ){
69737       /* The row that the VUpdate opcode will delete: none */
69738       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
69739     }
69740     if( keyColumn>=0 ){
69741       if( useTempTable ){
69742         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
69743       }else if( pSelect ){
69744         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
69745       }else{
69746         VdbeOp *pOp;
69747         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
69748         pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
69749         if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
69750           appendFlag = 1;
69751           pOp->opcode = OP_NewRowid;
69752           pOp->p1 = baseCur;
69753           pOp->p2 = regRowid;
69754           pOp->p3 = regAutoinc;
69755         }
69756       }
69757       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
69758       ** to generate a unique primary key value.
69759       */
69760       if( !appendFlag ){
69761         int j1;
69762         if( !IsVirtual(pTab) ){
69763           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
69764           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
69765           sqlite3VdbeJumpHere(v, j1);
69766         }else{
69767           j1 = sqlite3VdbeCurrentAddr(v);
69768           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
69769         }
69770         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
69771       }
69772     }else if( IsVirtual(pTab) ){
69773       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
69774     }else{
69775       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
69776       appendFlag = 1;
69777     }
69778     autoIncStep(pParse, regAutoinc, regRowid);
69779
69780     /* Push onto the stack, data for all columns of the new entry, beginning
69781     ** with the first column.
69782     */
69783     nHidden = 0;
69784     for(i=0; i<pTab->nCol; i++){
69785       int iRegStore = regRowid+1+i;
69786       if( i==pTab->iPKey ){
69787         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
69788         ** Whenever this column is read, the record number will be substituted
69789         ** in its place.  So will fill this column with a NULL to avoid
69790         ** taking up data space with information that will never be used. */
69791         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
69792         continue;
69793       }
69794       if( pColumn==0 ){
69795         if( IsHiddenColumn(&pTab->aCol[i]) ){
69796           assert( IsVirtual(pTab) );
69797           j = -1;
69798           nHidden++;
69799         }else{
69800           j = i - nHidden;
69801         }
69802       }else{
69803         for(j=0; j<pColumn->nId; j++){
69804           if( pColumn->a[j].idx==i ) break;
69805         }
69806       }
69807       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
69808         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
69809       }else if( useTempTable ){
69810         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
69811       }else if( pSelect ){
69812         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
69813       }else{
69814         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
69815       }
69816     }
69817
69818     /* Generate code to check constraints and generate index keys and
69819     ** do the insertion.
69820     */
69821 #ifndef SQLITE_OMIT_VIRTUALTABLE
69822     if( IsVirtual(pTab) ){
69823       sqlite3VtabMakeWritable(pParse, pTab);
69824       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
69825                      (const char*)pTab->pVtab, P4_VTAB);
69826     }else
69827 #endif
69828     {
69829       sqlite3GenerateConstraintChecks(
69830           pParse,
69831           pTab,
69832           baseCur,
69833           regIns,
69834           aRegIdx,
69835           keyColumn>=0,
69836           0,
69837           onError,
69838           endOfLoop
69839       );
69840       sqlite3CompleteInsertion(
69841           pParse,
69842           pTab,
69843           baseCur,
69844           regIns,
69845           aRegIdx,
69846           0,
69847           (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1,
69848           appendFlag
69849        );
69850     }
69851   }
69852
69853   /* Update the count of rows that are inserted
69854   */
69855   if( (db->flags & SQLITE_CountRows)!=0 ){
69856     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
69857   }
69858
69859   if( triggers_exist ){
69860     /* Code AFTER triggers */
69861     if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab,
69862           newIdx, -1, onError, endOfLoop, 0, 0) ){
69863       goto insert_cleanup;
69864     }
69865   }
69866
69867   /* The bottom of the main insertion loop, if the data source
69868   ** is a SELECT statement.
69869   */
69870   sqlite3VdbeResolveLabel(v, endOfLoop);
69871   if( useTempTable ){
69872     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
69873     sqlite3VdbeJumpHere(v, addrInsTop);
69874     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
69875   }else if( pSelect ){
69876     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
69877     sqlite3VdbeJumpHere(v, addrInsTop);
69878   }
69879
69880   if( !IsVirtual(pTab) && !isView ){
69881     /* Close all tables opened */
69882     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
69883     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
69884       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
69885     }
69886   }
69887
69888   /* Update the sqlite_sequence table by storing the content of the
69889   ** counter value in memory regAutoinc back into the sqlite_sequence
69890   ** table.
69891   */
69892   autoIncEnd(pParse, iDb, pTab, regAutoinc);
69893
69894   /*
69895   ** Return the number of rows inserted. If this routine is 
69896   ** generating code because of a call to sqlite3NestedParse(), do not
69897   ** invoke the callback function.
69898   */
69899   if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){
69900     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
69901     sqlite3VdbeSetNumCols(v, 1);
69902     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
69903   }
69904
69905 insert_cleanup:
69906   sqlite3SrcListDelete(db, pTabList);
69907   sqlite3ExprListDelete(db, pList);
69908   sqlite3SelectDelete(db, pSelect);
69909   sqlite3IdListDelete(db, pColumn);
69910   sqlite3DbFree(db, aRegIdx);
69911 }
69912
69913 /*
69914 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
69915 **
69916 ** The input is a range of consecutive registers as follows:
69917 **
69918 **    1.  The rowid of the row to be updated before the update.  This
69919 **        value is omitted unless we are doing an UPDATE that involves a
69920 **        change to the record number or writing to a virtual table.
69921 **
69922 **    2.  The rowid of the row after the update.
69923 **
69924 **    3.  The data in the first column of the entry after the update.
69925 **
69926 **    i.  Data from middle columns...
69927 **
69928 **    N.  The data in the last column of the entry after the update.
69929 **
69930 ** The regRowid parameter is the index of the register containing (2).
69931 **
69932 ** The old rowid shown as entry (1) above is omitted unless both isUpdate
69933 ** and rowidChng are 1.  isUpdate is true for UPDATEs and false for
69934 ** INSERTs.  RowidChng means that the new rowid is explicitly specified by
69935 ** the update or insert statement.  If rowidChng is false, it means that
69936 ** the rowid is computed automatically in an insert or that the rowid value
69937 ** is not modified by the update.
69938 **
69939 ** The code generated by this routine store new index entries into
69940 ** registers identified by aRegIdx[].  No index entry is created for
69941 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
69942 ** the same as the order of indices on the linked list of indices
69943 ** attached to the table.
69944 **
69945 ** This routine also generates code to check constraints.  NOT NULL,
69946 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
69947 ** then the appropriate action is performed.  There are five possible
69948 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
69949 **
69950 **  Constraint type  Action       What Happens
69951 **  ---------------  ----------   ----------------------------------------
69952 **  any              ROLLBACK     The current transaction is rolled back and
69953 **                                sqlite3_exec() returns immediately with a
69954 **                                return code of SQLITE_CONSTRAINT.
69955 **
69956 **  any              ABORT        Back out changes from the current command
69957 **                                only (do not do a complete rollback) then
69958 **                                cause sqlite3_exec() to return immediately
69959 **                                with SQLITE_CONSTRAINT.
69960 **
69961 **  any              FAIL         Sqlite_exec() returns immediately with a
69962 **                                return code of SQLITE_CONSTRAINT.  The
69963 **                                transaction is not rolled back and any
69964 **                                prior changes are retained.
69965 **
69966 **  any              IGNORE       The record number and data is popped from
69967 **                                the stack and there is an immediate jump
69968 **                                to label ignoreDest.
69969 **
69970 **  NOT NULL         REPLACE      The NULL value is replace by the default
69971 **                                value for that column.  If the default value
69972 **                                is NULL, the action is the same as ABORT.
69973 **
69974 **  UNIQUE           REPLACE      The other row that conflicts with the row
69975 **                                being inserted is removed.
69976 **
69977 **  CHECK            REPLACE      Illegal.  The results in an exception.
69978 **
69979 ** Which action to take is determined by the overrideError parameter.
69980 ** Or if overrideError==OE_Default, then the pParse->onError parameter
69981 ** is used.  Or if pParse->onError==OE_Default then the onError value
69982 ** for the constraint is used.
69983 **
69984 ** The calling routine must open a read/write cursor for pTab with
69985 ** cursor number "baseCur".  All indices of pTab must also have open
69986 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
69987 ** Except, if there is no possibility of a REPLACE action then
69988 ** cursors do not need to be open for indices where aRegIdx[i]==0.
69989 */
69990 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
69991   Parse *pParse,      /* The parser context */
69992   Table *pTab,        /* the table into which we are inserting */
69993   int baseCur,        /* Index of a read/write cursor pointing at pTab */
69994   int regRowid,       /* Index of the range of input registers */
69995   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
69996   int rowidChng,      /* True if the rowid might collide with existing entry */
69997   int isUpdate,       /* True for UPDATE, False for INSERT */
69998   int overrideError,  /* Override onError to this if not OE_Default */
69999   int ignoreDest      /* Jump to this label on an OE_Ignore resolution */
70000 ){
70001   int i;
70002   Vdbe *v;
70003   int nCol;
70004   int onError;
70005   int j1;             /* Addresss of jump instruction */
70006   int j2 = 0, j3;     /* Addresses of jump instructions */
70007   int regData;        /* Register containing first data column */
70008   int iCur;
70009   Index *pIdx;
70010   int seenReplace = 0;
70011   int hasTwoRowids = (isUpdate && rowidChng);
70012
70013   v = sqlite3GetVdbe(pParse);
70014   assert( v!=0 );
70015   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
70016   nCol = pTab->nCol;
70017   regData = regRowid + 1;
70018
70019
70020   /* Test all NOT NULL constraints.
70021   */
70022   for(i=0; i<nCol; i++){
70023     if( i==pTab->iPKey ){
70024       continue;
70025     }
70026     onError = pTab->aCol[i].notNull;
70027     if( onError==OE_None ) continue;
70028     if( overrideError!=OE_Default ){
70029       onError = overrideError;
70030     }else if( onError==OE_Default ){
70031       onError = OE_Abort;
70032     }
70033     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
70034       onError = OE_Abort;
70035     }
70036     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
70037     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
70038         || onError==OE_Ignore || onError==OE_Replace );
70039     switch( onError ){
70040       case OE_Rollback:
70041       case OE_Abort:
70042       case OE_Fail: {
70043         char *zMsg;
70044         sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
70045         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
70046                               pTab->zName, pTab->aCol[i].zName);
70047         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
70048         break;
70049       }
70050       case OE_Ignore: {
70051         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
70052         break;
70053       }
70054       case OE_Replace: {
70055         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
70056         break;
70057       }
70058     }
70059     sqlite3VdbeJumpHere(v, j1);
70060   }
70061
70062   /* Test all CHECK constraints
70063   */
70064 #ifndef SQLITE_OMIT_CHECK
70065   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
70066     int allOk = sqlite3VdbeMakeLabel(v);
70067     pParse->ckBase = regData;
70068     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
70069     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
70070     if( onError==OE_Ignore ){
70071       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
70072     }else{
70073       sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError);
70074     }
70075     sqlite3VdbeResolveLabel(v, allOk);
70076   }
70077 #endif /* !defined(SQLITE_OMIT_CHECK) */
70078
70079   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
70080   ** of the new record does not previously exist.  Except, if this
70081   ** is an UPDATE and the primary key is not changing, that is OK.
70082   */
70083   if( rowidChng ){
70084     onError = pTab->keyConf;
70085     if( overrideError!=OE_Default ){
70086       onError = overrideError;
70087     }else if( onError==OE_Default ){
70088       onError = OE_Abort;
70089     }
70090     
70091     if( onError!=OE_Replace || pTab->pIndex ){
70092       if( isUpdate ){
70093         j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1);
70094       }
70095       j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
70096       switch( onError ){
70097         default: {
70098           onError = OE_Abort;
70099           /* Fall thru into the next case */
70100         }
70101         case OE_Rollback:
70102         case OE_Abort:
70103         case OE_Fail: {
70104           sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
70105                            "PRIMARY KEY must be unique", P4_STATIC);
70106           break;
70107         }
70108         case OE_Replace: {
70109           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
70110           seenReplace = 1;
70111           break;
70112         }
70113         case OE_Ignore: {
70114           assert( seenReplace==0 );
70115           sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
70116           break;
70117         }
70118       }
70119       sqlite3VdbeJumpHere(v, j3);
70120       if( isUpdate ){
70121         sqlite3VdbeJumpHere(v, j2);
70122       }
70123     }
70124   }
70125
70126   /* Test all UNIQUE constraints by creating entries for each UNIQUE
70127   ** index and making sure that duplicate entries do not already exist.
70128   ** Add the new records to the indices as we go.
70129   */
70130   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
70131     int regIdx;
70132     int regR;
70133
70134     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
70135
70136     /* Create a key for accessing the index entry */
70137     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
70138     for(i=0; i<pIdx->nColumn; i++){
70139       int idx = pIdx->aiColumn[i];
70140       if( idx==pTab->iPKey ){
70141         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
70142       }else{
70143         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
70144       }
70145     }
70146     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
70147     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
70148     sqlite3IndexAffinityStr(v, pIdx);
70149     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
70150     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
70151
70152     /* Find out what action to take in case there is an indexing conflict */
70153     onError = pIdx->onError;
70154     if( onError==OE_None ) continue;  /* pIdx is not a UNIQUE index */
70155     if( overrideError!=OE_Default ){
70156       onError = overrideError;
70157     }else if( onError==OE_Default ){
70158       onError = OE_Abort;
70159     }
70160     if( seenReplace ){
70161       if( onError==OE_Ignore ) onError = OE_Replace;
70162       else if( onError==OE_Fail ) onError = OE_Abort;
70163     }
70164     
70165
70166     /* Check to see if the new index entry will be unique */
70167     j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
70168     regR = sqlite3GetTempReg(pParse);
70169     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
70170     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
70171                            regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
70172                            P4_INT32);
70173
70174     /* Generate code that executes if the new index entry is not unique */
70175     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
70176         || onError==OE_Ignore || onError==OE_Replace );
70177     switch( onError ){
70178       case OE_Rollback:
70179       case OE_Abort:
70180       case OE_Fail: {
70181         int j, n1, n2;
70182         char zErrMsg[200];
70183         sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
70184                          pIdx->nColumn>1 ? "columns " : "column ");
70185         n1 = sqlite3Strlen30(zErrMsg);
70186         for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
70187           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
70188           n2 = sqlite3Strlen30(zCol);
70189           if( j>0 ){
70190             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
70191             n1 += 2;
70192           }
70193           if( n1+n2>ArraySize(zErrMsg)-30 ){
70194             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
70195             n1 += 3;
70196             break;
70197           }else{
70198             sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
70199             n1 += n2;
70200           }
70201         }
70202         sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], 
70203             pIdx->nColumn>1 ? " are not unique" : " is not unique");
70204         sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
70205         break;
70206       }
70207       case OE_Ignore: {
70208         assert( seenReplace==0 );
70209         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
70210         break;
70211       }
70212       case OE_Replace: {
70213         sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
70214         seenReplace = 1;
70215         break;
70216       }
70217     }
70218     sqlite3VdbeJumpHere(v, j2);
70219     sqlite3VdbeJumpHere(v, j3);
70220     sqlite3ReleaseTempReg(pParse, regR);
70221   }
70222 }
70223
70224 /*
70225 ** This routine generates code to finish the INSERT or UPDATE operation
70226 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
70227 ** A consecutive range of registers starting at regRowid contains the
70228 ** rowid and the content to be inserted.
70229 **
70230 ** The arguments to this routine should be the same as the first six
70231 ** arguments to sqlite3GenerateConstraintChecks.
70232 */
70233 SQLITE_PRIVATE void sqlite3CompleteInsertion(
70234   Parse *pParse,      /* The parser context */
70235   Table *pTab,        /* the table into which we are inserting */
70236   int baseCur,        /* Index of a read/write cursor pointing at pTab */
70237   int regRowid,       /* Range of content */
70238   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
70239   int isUpdate,       /* True for UPDATE, False for INSERT */
70240   int newIdx,         /* Index of NEW table for triggers.  -1 if none */
70241   int appendBias      /* True if this is likely to be an append */
70242 ){
70243   int i;
70244   Vdbe *v;
70245   int nIdx;
70246   Index *pIdx;
70247   u8 pik_flags;
70248   int regData;
70249   int regRec;
70250
70251   v = sqlite3GetVdbe(pParse);
70252   assert( v!=0 );
70253   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
70254   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
70255   for(i=nIdx-1; i>=0; i--){
70256     if( aRegIdx[i]==0 ) continue;
70257     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
70258   }
70259   regData = regRowid + 1;
70260   regRec = sqlite3GetTempReg(pParse);
70261   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
70262   sqlite3TableAffinityStr(v, pTab);
70263   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
70264 #ifndef SQLITE_OMIT_TRIGGER
70265   if( newIdx>=0 ){
70266     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid);
70267   }
70268 #endif
70269   if( pParse->nested ){
70270     pik_flags = 0;
70271   }else{
70272     pik_flags = OPFLAG_NCHANGE;
70273     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
70274   }
70275   if( appendBias ){
70276     pik_flags |= OPFLAG_APPEND;
70277   }
70278   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
70279   if( !pParse->nested ){
70280     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
70281   }
70282   sqlite3VdbeChangeP5(v, pik_flags);
70283 }
70284
70285 /*
70286 ** Generate code that will open cursors for a table and for all
70287 ** indices of that table.  The "baseCur" parameter is the cursor number used
70288 ** for the table.  Indices are opened on subsequent cursors.
70289 **
70290 ** Return the number of indices on the table.
70291 */
70292 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
70293   Parse *pParse,   /* Parsing context */
70294   Table *pTab,     /* Table to be opened */
70295   int baseCur,     /* Cursor number assigned to the table */
70296   int op           /* OP_OpenRead or OP_OpenWrite */
70297 ){
70298   int i;
70299   int iDb;
70300   Index *pIdx;
70301   Vdbe *v;
70302
70303   if( IsVirtual(pTab) ) return 0;
70304   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70305   v = sqlite3GetVdbe(pParse);
70306   assert( v!=0 );
70307   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
70308   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
70309     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
70310     assert( pIdx->pSchema==pTab->pSchema );
70311     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
70312                       (char*)pKey, P4_KEYINFO_HANDOFF);
70313     VdbeComment((v, "%s", pIdx->zName));
70314   }
70315   if( pParse->nTab<=baseCur+i ){
70316     pParse->nTab = baseCur+i;
70317   }
70318   return i-1;
70319 }
70320
70321
70322 #ifdef SQLITE_TEST
70323 /*
70324 ** The following global variable is incremented whenever the
70325 ** transfer optimization is used.  This is used for testing
70326 ** purposes only - to make sure the transfer optimization really
70327 ** is happening when it is suppose to.
70328 */
70329 SQLITE_API int sqlite3_xferopt_count;
70330 #endif /* SQLITE_TEST */
70331
70332
70333 #ifndef SQLITE_OMIT_XFER_OPT
70334 /*
70335 ** Check to collation names to see if they are compatible.
70336 */
70337 static int xferCompatibleCollation(const char *z1, const char *z2){
70338   if( z1==0 ){
70339     return z2==0;
70340   }
70341   if( z2==0 ){
70342     return 0;
70343   }
70344   return sqlite3StrICmp(z1, z2)==0;
70345 }
70346
70347
70348 /*
70349 ** Check to see if index pSrc is compatible as a source of data
70350 ** for index pDest in an insert transfer optimization.  The rules
70351 ** for a compatible index:
70352 **
70353 **    *   The index is over the same set of columns
70354 **    *   The same DESC and ASC markings occurs on all columns
70355 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
70356 **    *   The same collating sequence on each column
70357 */
70358 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
70359   int i;
70360   assert( pDest && pSrc );
70361   assert( pDest->pTable!=pSrc->pTable );
70362   if( pDest->nColumn!=pSrc->nColumn ){
70363     return 0;   /* Different number of columns */
70364   }
70365   if( pDest->onError!=pSrc->onError ){
70366     return 0;   /* Different conflict resolution strategies */
70367   }
70368   for(i=0; i<pSrc->nColumn; i++){
70369     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
70370       return 0;   /* Different columns indexed */
70371     }
70372     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
70373       return 0;   /* Different sort orders */
70374     }
70375     if( pSrc->azColl[i]!=pDest->azColl[i] ){
70376       return 0;   /* Different collating sequences */
70377     }
70378   }
70379
70380   /* If no test above fails then the indices must be compatible */
70381   return 1;
70382 }
70383
70384 /*
70385 ** Attempt the transfer optimization on INSERTs of the form
70386 **
70387 **     INSERT INTO tab1 SELECT * FROM tab2;
70388 **
70389 ** This optimization is only attempted if
70390 **
70391 **    (1)  tab1 and tab2 have identical schemas including all the
70392 **         same indices and constraints
70393 **
70394 **    (2)  tab1 and tab2 are different tables
70395 **
70396 **    (3)  There must be no triggers on tab1
70397 **
70398 **    (4)  The result set of the SELECT statement is "*"
70399 **
70400 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
70401 **         or LIMIT clause.
70402 **
70403 **    (6)  The SELECT statement is a simple (not a compound) select that
70404 **         contains only tab2 in its FROM clause
70405 **
70406 ** This method for implementing the INSERT transfers raw records from
70407 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
70408 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
70409 ** the resulting tab1 has much less fragmentation.
70410 **
70411 ** This routine returns TRUE if the optimization is attempted.  If any
70412 ** of the conditions above fail so that the optimization should not
70413 ** be attempted, then this routine returns FALSE.
70414 */
70415 static int xferOptimization(
70416   Parse *pParse,        /* Parser context */
70417   Table *pDest,         /* The table we are inserting into */
70418   Select *pSelect,      /* A SELECT statement to use as the data source */
70419   int onError,          /* How to handle constraint errors */
70420   int iDbDest           /* The database of pDest */
70421 ){
70422   ExprList *pEList;                /* The result set of the SELECT */
70423   Table *pSrc;                     /* The table in the FROM clause of SELECT */
70424   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
70425   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
70426   int i;                           /* Loop counter */
70427   int iDbSrc;                      /* The database of pSrc */
70428   int iSrc, iDest;                 /* Cursors from source and destination */
70429   int addr1, addr2;                /* Loop addresses */
70430   int emptyDestTest;               /* Address of test for empty pDest */
70431   int emptySrcTest;                /* Address of test for empty pSrc */
70432   Vdbe *v;                         /* The VDBE we are building */
70433   KeyInfo *pKey;                   /* Key information for an index */
70434   int regAutoinc;                  /* Memory register used by AUTOINC */
70435   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
70436   int regData, regRowid;           /* Registers holding data and rowid */
70437
70438   if( pSelect==0 ){
70439     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
70440   }
70441   if( pDest->pTrigger ){
70442     return 0;   /* tab1 must not have triggers */
70443   }
70444 #ifndef SQLITE_OMIT_VIRTUALTABLE
70445   if( pDest->tabFlags & TF_Virtual ){
70446     return 0;   /* tab1 must not be a virtual table */
70447   }
70448 #endif
70449   if( onError==OE_Default ){
70450     onError = OE_Abort;
70451   }
70452   if( onError!=OE_Abort && onError!=OE_Rollback ){
70453     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
70454   }
70455   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
70456   if( pSelect->pSrc->nSrc!=1 ){
70457     return 0;   /* FROM clause must have exactly one term */
70458   }
70459   if( pSelect->pSrc->a[0].pSelect ){
70460     return 0;   /* FROM clause cannot contain a subquery */
70461   }
70462   if( pSelect->pWhere ){
70463     return 0;   /* SELECT may not have a WHERE clause */
70464   }
70465   if( pSelect->pOrderBy ){
70466     return 0;   /* SELECT may not have an ORDER BY clause */
70467   }
70468   /* Do not need to test for a HAVING clause.  If HAVING is present but
70469   ** there is no ORDER BY, we will get an error. */
70470   if( pSelect->pGroupBy ){
70471     return 0;   /* SELECT may not have a GROUP BY clause */
70472   }
70473   if( pSelect->pLimit ){
70474     return 0;   /* SELECT may not have a LIMIT clause */
70475   }
70476   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
70477   if( pSelect->pPrior ){
70478     return 0;   /* SELECT may not be a compound query */
70479   }
70480   if( pSelect->selFlags & SF_Distinct ){
70481     return 0;   /* SELECT may not be DISTINCT */
70482   }
70483   pEList = pSelect->pEList;
70484   assert( pEList!=0 );
70485   if( pEList->nExpr!=1 ){
70486     return 0;   /* The result set must have exactly one column */
70487   }
70488   assert( pEList->a[0].pExpr );
70489   if( pEList->a[0].pExpr->op!=TK_ALL ){
70490     return 0;   /* The result set must be the special operator "*" */
70491   }
70492
70493   /* At this point we have established that the statement is of the
70494   ** correct syntactic form to participate in this optimization.  Now
70495   ** we have to check the semantics.
70496   */
70497   pItem = pSelect->pSrc->a;
70498   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70499   if( pSrc==0 ){
70500     return 0;   /* FROM clause does not contain a real table */
70501   }
70502   if( pSrc==pDest ){
70503     return 0;   /* tab1 and tab2 may not be the same table */
70504   }
70505 #ifndef SQLITE_OMIT_VIRTUALTABLE
70506   if( pSrc->tabFlags & TF_Virtual ){
70507     return 0;   /* tab2 must not be a virtual table */
70508   }
70509 #endif
70510   if( pSrc->pSelect ){
70511     return 0;   /* tab2 may not be a view */
70512   }
70513   if( pDest->nCol!=pSrc->nCol ){
70514     return 0;   /* Number of columns must be the same in tab1 and tab2 */
70515   }
70516   if( pDest->iPKey!=pSrc->iPKey ){
70517     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
70518   }
70519   for(i=0; i<pDest->nCol; i++){
70520     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
70521       return 0;    /* Affinity must be the same on all columns */
70522     }
70523     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
70524       return 0;    /* Collating sequence must be the same on all columns */
70525     }
70526     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
70527       return 0;    /* tab2 must be NOT NULL if tab1 is */
70528     }
70529   }
70530   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
70531     if( pDestIdx->onError!=OE_None ){
70532       destHasUniqueIdx = 1;
70533     }
70534     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
70535       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
70536     }
70537     if( pSrcIdx==0 ){
70538       return 0;    /* pDestIdx has no corresponding index in pSrc */
70539     }
70540   }
70541 #ifndef SQLITE_OMIT_CHECK
70542   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
70543     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
70544   }
70545 #endif
70546
70547   /* If we get this far, it means either:
70548   **
70549   **    *   We can always do the transfer if the table contains an
70550   **        an integer primary key
70551   **
70552   **    *   We can conditionally do the transfer if the destination
70553   **        table is empty.
70554   */
70555 #ifdef SQLITE_TEST
70556   sqlite3_xferopt_count++;
70557 #endif
70558   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
70559   v = sqlite3GetVdbe(pParse);
70560   sqlite3CodeVerifySchema(pParse, iDbSrc);
70561   iSrc = pParse->nTab++;
70562   iDest = pParse->nTab++;
70563   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
70564   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
70565   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
70566     /* If tables do not have an INTEGER PRIMARY KEY and there
70567     ** are indices to be copied and the destination is not empty,
70568     ** we have to disallow the transfer optimization because the
70569     ** the rowids might change which will mess up indexing.
70570     **
70571     ** Or if the destination has a UNIQUE index and is not empty,
70572     ** we also disallow the transfer optimization because we cannot
70573     ** insure that all entries in the union of DEST and SRC will be
70574     ** unique.
70575     */
70576     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
70577     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
70578     sqlite3VdbeJumpHere(v, addr1);
70579   }else{
70580     emptyDestTest = 0;
70581   }
70582   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
70583   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
70584   regData = sqlite3GetTempReg(pParse);
70585   regRowid = sqlite3GetTempReg(pParse);
70586   if( pDest->iPKey>=0 ){
70587     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
70588     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
70589     sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0,
70590                       "PRIMARY KEY must be unique", P4_STATIC);
70591     sqlite3VdbeJumpHere(v, addr2);
70592     autoIncStep(pParse, regAutoinc, regRowid);
70593   }else if( pDest->pIndex==0 ){
70594     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
70595   }else{
70596     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
70597     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
70598   }
70599   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
70600   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
70601   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
70602   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
70603   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
70604   autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
70605   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
70606     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
70607       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
70608     }
70609     assert( pSrcIdx );
70610     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
70611     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
70612     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
70613     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
70614                       (char*)pKey, P4_KEYINFO_HANDOFF);
70615     VdbeComment((v, "%s", pSrcIdx->zName));
70616     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
70617     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
70618                       (char*)pKey, P4_KEYINFO_HANDOFF);
70619     VdbeComment((v, "%s", pDestIdx->zName));
70620     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
70621     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
70622     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
70623     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
70624     sqlite3VdbeJumpHere(v, addr1);
70625   }
70626   sqlite3VdbeJumpHere(v, emptySrcTest);
70627   sqlite3ReleaseTempReg(pParse, regRowid);
70628   sqlite3ReleaseTempReg(pParse, regData);
70629   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
70630   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
70631   if( emptyDestTest ){
70632     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
70633     sqlite3VdbeJumpHere(v, emptyDestTest);
70634     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
70635     return 0;
70636   }else{
70637     return 1;
70638   }
70639 }
70640 #endif /* SQLITE_OMIT_XFER_OPT */
70641
70642 /* Make sure "isView" gets undefined in case this file becomes part of
70643 ** the amalgamation - so that subsequent files do not see isView as a
70644 ** macro. */
70645 #undef isView
70646
70647 /************** End of insert.c **********************************************/
70648 /************** Begin file legacy.c ******************************************/
70649 /*
70650 ** 2001 September 15
70651 **
70652 ** The author disclaims copyright to this source code.  In place of
70653 ** a legal notice, here is a blessing:
70654 **
70655 **    May you do good and not evil.
70656 **    May you find forgiveness for yourself and forgive others.
70657 **    May you share freely, never taking more than you give.
70658 **
70659 *************************************************************************
70660 ** Main file for the SQLite library.  The routines in this file
70661 ** implement the programmer interface to the library.  Routines in
70662 ** other files are for internal use by SQLite and should not be
70663 ** accessed by users of the library.
70664 **
70665 ** $Id: legacy.c,v 1.31 2009/01/20 16:53:40 danielk1977 Exp $
70666 */
70667
70668
70669 /*
70670 ** Execute SQL code.  Return one of the SQLITE_ success/failure
70671 ** codes.  Also write an error message into memory obtained from
70672 ** malloc() and make *pzErrMsg point to that message.
70673 **
70674 ** If the SQL is a query, then for each row in the query result
70675 ** the xCallback() function is called.  pArg becomes the first
70676 ** argument to xCallback().  If xCallback=NULL then no callback
70677 ** is invoked, even for queries.
70678 */
70679 SQLITE_API int sqlite3_exec(
70680   sqlite3 *db,                /* The database on which the SQL executes */
70681   const char *zSql,           /* The SQL to be executed */
70682   sqlite3_callback xCallback, /* Invoke this callback routine */
70683   void *pArg,                 /* First argument to xCallback() */
70684   char **pzErrMsg             /* Write error messages here */
70685 ){
70686   int rc = SQLITE_OK;
70687   const char *zLeftover;
70688   sqlite3_stmt *pStmt = 0;
70689   char **azCols = 0;
70690
70691   int nRetry = 0;
70692   int nCallback;
70693
70694   if( zSql==0 ) zSql = "";
70695
70696   sqlite3_mutex_enter(db->mutex);
70697   sqlite3Error(db, SQLITE_OK, 0);
70698   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
70699     int nCol;
70700     char **azVals = 0;
70701
70702     pStmt = 0;
70703     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
70704     assert( rc==SQLITE_OK || pStmt==0 );
70705     if( rc!=SQLITE_OK ){
70706       continue;
70707     }
70708     if( !pStmt ){
70709       /* this happens for a comment or white-space */
70710       zSql = zLeftover;
70711       continue;
70712     }
70713
70714     nCallback = 0;
70715     nCol = sqlite3_column_count(pStmt);
70716
70717     while( 1 ){
70718       int i;
70719       rc = sqlite3_step(pStmt);
70720
70721       /* Invoke the callback function if required */
70722       if( xCallback && (SQLITE_ROW==rc || 
70723           (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
70724         if( 0==nCallback ){
70725           if( azCols==0 ){
70726             azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
70727             if( azCols==0 ){
70728               goto exec_out;
70729             }
70730           }
70731           for(i=0; i<nCol; i++){
70732             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
70733             /* sqlite3VdbeSetColName() installs column names as UTF8
70734             ** strings so there is no way for sqlite3_column_name() to fail. */
70735             assert( azCols[i]!=0 );
70736           }
70737           nCallback++;
70738         }
70739         if( rc==SQLITE_ROW ){
70740           azVals = &azCols[nCol];
70741           for(i=0; i<nCol; i++){
70742             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
70743             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
70744               db->mallocFailed = 1;
70745               goto exec_out;
70746             }
70747           }
70748         }
70749         if( xCallback(pArg, nCol, azVals, azCols) ){
70750           rc = SQLITE_ABORT;
70751           sqlite3_finalize(pStmt);
70752           pStmt = 0;
70753           sqlite3Error(db, SQLITE_ABORT, 0);
70754           goto exec_out;
70755         }
70756       }
70757
70758       if( rc!=SQLITE_ROW ){
70759         rc = sqlite3_finalize(pStmt);
70760         pStmt = 0;
70761         if( rc!=SQLITE_SCHEMA ){
70762           nRetry = 0;
70763           zSql = zLeftover;
70764           while( sqlite3Isspace(zSql[0]) ) zSql++;
70765         }
70766         break;
70767       }
70768     }
70769
70770     sqlite3DbFree(db, azCols);
70771     azCols = 0;
70772   }
70773
70774 exec_out:
70775   if( pStmt ) sqlite3_finalize(pStmt);
70776   sqlite3DbFree(db, azCols);
70777
70778   rc = sqlite3ApiExit(db, rc);
70779   if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
70780     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
70781     *pzErrMsg = sqlite3Malloc(nErrMsg);
70782     if( *pzErrMsg ){
70783       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
70784     }
70785   }else if( pzErrMsg ){
70786     *pzErrMsg = 0;
70787   }
70788
70789   assert( (rc&db->errMask)==rc );
70790   sqlite3_mutex_leave(db->mutex);
70791   return rc;
70792 }
70793
70794 /************** End of legacy.c **********************************************/
70795 /************** Begin file loadext.c *****************************************/
70796 /*
70797 ** 2006 June 7
70798 **
70799 ** The author disclaims copyright to this source code.  In place of
70800 ** a legal notice, here is a blessing:
70801 **
70802 **    May you do good and not evil.
70803 **    May you find forgiveness for yourself and forgive others.
70804 **    May you share freely, never taking more than you give.
70805 **
70806 *************************************************************************
70807 ** This file contains code used to dynamically load extensions into
70808 ** the SQLite library.
70809 **
70810 ** $Id: loadext.c,v 1.58 2009/01/20 16:53:40 danielk1977 Exp $
70811 */
70812
70813 #ifndef SQLITE_CORE
70814   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
70815 #endif
70816 /************** Include sqlite3ext.h in the middle of loadext.c **************/
70817 /************** Begin file sqlite3ext.h **************************************/
70818 /*
70819 ** 2006 June 7
70820 **
70821 ** The author disclaims copyright to this source code.  In place of
70822 ** a legal notice, here is a blessing:
70823 **
70824 **    May you do good and not evil.
70825 **    May you find forgiveness for yourself and forgive others.
70826 **    May you share freely, never taking more than you give.
70827 **
70828 *************************************************************************
70829 ** This header file defines the SQLite interface for use by
70830 ** shared libraries that want to be imported as extensions into
70831 ** an SQLite instance.  Shared libraries that intend to be loaded
70832 ** as extensions by SQLite should #include this file instead of 
70833 ** sqlite3.h.
70834 **
70835 ** @(#) $Id: sqlite3ext.h,v 1.25 2008/10/12 00:27:54 shane Exp $
70836 */
70837 #ifndef _SQLITE3EXT_H_
70838 #define _SQLITE3EXT_H_
70839
70840 typedef struct sqlite3_api_routines sqlite3_api_routines;
70841
70842 /*
70843 ** The following structure holds pointers to all of the SQLite API
70844 ** routines.
70845 **
70846 ** WARNING:  In order to maintain backwards compatibility, add new
70847 ** interfaces to the end of this structure only.  If you insert new
70848 ** interfaces in the middle of this structure, then older different
70849 ** versions of SQLite will not be able to load each others' shared
70850 ** libraries!
70851 */
70852 struct sqlite3_api_routines {
70853   void * (*aggregate_context)(sqlite3_context*,int nBytes);
70854   int  (*aggregate_count)(sqlite3_context*);
70855   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
70856   int  (*bind_double)(sqlite3_stmt*,int,double);
70857   int  (*bind_int)(sqlite3_stmt*,int,int);
70858   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
70859   int  (*bind_null)(sqlite3_stmt*,int);
70860   int  (*bind_parameter_count)(sqlite3_stmt*);
70861   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
70862   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
70863   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
70864   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
70865   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
70866   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
70867   int  (*busy_timeout)(sqlite3*,int ms);
70868   int  (*changes)(sqlite3*);
70869   int  (*close)(sqlite3*);
70870   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
70871   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
70872   const void * (*column_blob)(sqlite3_stmt*,int iCol);
70873   int  (*column_bytes)(sqlite3_stmt*,int iCol);
70874   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
70875   int  (*column_count)(sqlite3_stmt*pStmt);
70876   const char * (*column_database_name)(sqlite3_stmt*,int);
70877   const void * (*column_database_name16)(sqlite3_stmt*,int);
70878   const char * (*column_decltype)(sqlite3_stmt*,int i);
70879   const void * (*column_decltype16)(sqlite3_stmt*,int);
70880   double  (*column_double)(sqlite3_stmt*,int iCol);
70881   int  (*column_int)(sqlite3_stmt*,int iCol);
70882   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
70883   const char * (*column_name)(sqlite3_stmt*,int);
70884   const void * (*column_name16)(sqlite3_stmt*,int);
70885   const char * (*column_origin_name)(sqlite3_stmt*,int);
70886   const void * (*column_origin_name16)(sqlite3_stmt*,int);
70887   const char * (*column_table_name)(sqlite3_stmt*,int);
70888   const void * (*column_table_name16)(sqlite3_stmt*,int);
70889   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
70890   const void * (*column_text16)(sqlite3_stmt*,int iCol);
70891   int  (*column_type)(sqlite3_stmt*,int iCol);
70892   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
70893   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
70894   int  (*complete)(const char*sql);
70895   int  (*complete16)(const void*sql);
70896   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
70897   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
70898   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*));
70899   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*));
70900   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
70901   int  (*data_count)(sqlite3_stmt*pStmt);
70902   sqlite3 * (*db_handle)(sqlite3_stmt*);
70903   int (*declare_vtab)(sqlite3*,const char*);
70904   int  (*enable_shared_cache)(int);
70905   int  (*errcode)(sqlite3*db);
70906   const char * (*errmsg)(sqlite3*);
70907   const void * (*errmsg16)(sqlite3*);
70908   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
70909   int  (*expired)(sqlite3_stmt*);
70910   int  (*finalize)(sqlite3_stmt*pStmt);
70911   void  (*free)(void*);
70912   void  (*free_table)(char**result);
70913   int  (*get_autocommit)(sqlite3*);
70914   void * (*get_auxdata)(sqlite3_context*,int);
70915   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
70916   int  (*global_recover)(void);
70917   void  (*interruptx)(sqlite3*);
70918   sqlite_int64  (*last_insert_rowid)(sqlite3*);
70919   const char * (*libversion)(void);
70920   int  (*libversion_number)(void);
70921   void *(*malloc)(int);
70922   char * (*mprintf)(const char*,...);
70923   int  (*open)(const char*,sqlite3**);
70924   int  (*open16)(const void*,sqlite3**);
70925   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
70926   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
70927   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
70928   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
70929   void *(*realloc)(void*,int);
70930   int  (*reset)(sqlite3_stmt*pStmt);
70931   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
70932   void  (*result_double)(sqlite3_context*,double);
70933   void  (*result_error)(sqlite3_context*,const char*,int);
70934   void  (*result_error16)(sqlite3_context*,const void*,int);
70935   void  (*result_int)(sqlite3_context*,int);
70936   void  (*result_int64)(sqlite3_context*,sqlite_int64);
70937   void  (*result_null)(sqlite3_context*);
70938   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
70939   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
70940   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
70941   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
70942   void  (*result_value)(sqlite3_context*,sqlite3_value*);
70943   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
70944   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
70945   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
70946   char * (*snprintf)(int,char*,const char*,...);
70947   int  (*step)(sqlite3_stmt*);
70948   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
70949   void  (*thread_cleanup)(void);
70950   int  (*total_changes)(sqlite3*);
70951   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
70952   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
70953   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
70954   void * (*user_data)(sqlite3_context*);
70955   const void * (*value_blob)(sqlite3_value*);
70956   int  (*value_bytes)(sqlite3_value*);
70957   int  (*value_bytes16)(sqlite3_value*);
70958   double  (*value_double)(sqlite3_value*);
70959   int  (*value_int)(sqlite3_value*);
70960   sqlite_int64  (*value_int64)(sqlite3_value*);
70961   int  (*value_numeric_type)(sqlite3_value*);
70962   const unsigned char * (*value_text)(sqlite3_value*);
70963   const void * (*value_text16)(sqlite3_value*);
70964   const void * (*value_text16be)(sqlite3_value*);
70965   const void * (*value_text16le)(sqlite3_value*);
70966   int  (*value_type)(sqlite3_value*);
70967   char *(*vmprintf)(const char*,va_list);
70968   /* Added ??? */
70969   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
70970   /* Added by 3.3.13 */
70971   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
70972   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
70973   int (*clear_bindings)(sqlite3_stmt*);
70974   /* Added by 3.4.1 */
70975   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
70976   /* Added by 3.5.0 */
70977   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
70978   int (*blob_bytes)(sqlite3_blob*);
70979   int (*blob_close)(sqlite3_blob*);
70980   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
70981   int (*blob_read)(sqlite3_blob*,void*,int,int);
70982   int (*blob_write)(sqlite3_blob*,const void*,int,int);
70983   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
70984   int (*file_control)(sqlite3*,const char*,int,void*);
70985   sqlite3_int64 (*memory_highwater)(int);
70986   sqlite3_int64 (*memory_used)(void);
70987   sqlite3_mutex *(*mutex_alloc)(int);
70988   void (*mutex_enter)(sqlite3_mutex*);
70989   void (*mutex_free)(sqlite3_mutex*);
70990   void (*mutex_leave)(sqlite3_mutex*);
70991   int (*mutex_try)(sqlite3_mutex*);
70992   int (*open_v2)(const char*,sqlite3**,int,const char*);
70993   int (*release_memory)(int);
70994   void (*result_error_nomem)(sqlite3_context*);
70995   void (*result_error_toobig)(sqlite3_context*);
70996   int (*sleep)(int);
70997   void (*soft_heap_limit)(int);
70998   sqlite3_vfs *(*vfs_find)(const char*);
70999   int (*vfs_register)(sqlite3_vfs*,int);
71000   int (*vfs_unregister)(sqlite3_vfs*);
71001   int (*xthreadsafe)(void);
71002   void (*result_zeroblob)(sqlite3_context*,int);
71003   void (*result_error_code)(sqlite3_context*,int);
71004   int (*test_control)(int, ...);
71005   void (*randomness)(int,void*);
71006   sqlite3 *(*context_db_handle)(sqlite3_context*);
71007   int (*extended_result_codes)(sqlite3*,int);
71008   int (*limit)(sqlite3*,int,int);
71009   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
71010   const char *(*sql)(sqlite3_stmt*);
71011   int (*status)(int,int*,int*,int);
71012 };
71013
71014 /*
71015 ** The following macros redefine the API routines so that they are
71016 ** redirected throught the global sqlite3_api structure.
71017 **
71018 ** This header file is also used by the loadext.c source file
71019 ** (part of the main SQLite library - not an extension) so that
71020 ** it can get access to the sqlite3_api_routines structure
71021 ** definition.  But the main library does not want to redefine
71022 ** the API.  So the redefinition macros are only valid if the
71023 ** SQLITE_CORE macros is undefined.
71024 */
71025 #ifndef SQLITE_CORE
71026 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
71027 #ifndef SQLITE_OMIT_DEPRECATED
71028 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
71029 #endif
71030 #define sqlite3_bind_blob              sqlite3_api->bind_blob
71031 #define sqlite3_bind_double            sqlite3_api->bind_double
71032 #define sqlite3_bind_int               sqlite3_api->bind_int
71033 #define sqlite3_bind_int64             sqlite3_api->bind_int64
71034 #define sqlite3_bind_null              sqlite3_api->bind_null
71035 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
71036 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
71037 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
71038 #define sqlite3_bind_text              sqlite3_api->bind_text
71039 #define sqlite3_bind_text16            sqlite3_api->bind_text16
71040 #define sqlite3_bind_value             sqlite3_api->bind_value
71041 #define sqlite3_busy_handler           sqlite3_api->busy_handler
71042 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
71043 #define sqlite3_changes                sqlite3_api->changes
71044 #define sqlite3_close                  sqlite3_api->close
71045 #define sqlite3_collation_needed       sqlite3_api->collation_needed
71046 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
71047 #define sqlite3_column_blob            sqlite3_api->column_blob
71048 #define sqlite3_column_bytes           sqlite3_api->column_bytes
71049 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
71050 #define sqlite3_column_count           sqlite3_api->column_count
71051 #define sqlite3_column_database_name   sqlite3_api->column_database_name
71052 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
71053 #define sqlite3_column_decltype        sqlite3_api->column_decltype
71054 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
71055 #define sqlite3_column_double          sqlite3_api->column_double
71056 #define sqlite3_column_int             sqlite3_api->column_int
71057 #define sqlite3_column_int64           sqlite3_api->column_int64
71058 #define sqlite3_column_name            sqlite3_api->column_name
71059 #define sqlite3_column_name16          sqlite3_api->column_name16
71060 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
71061 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
71062 #define sqlite3_column_table_name      sqlite3_api->column_table_name
71063 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
71064 #define sqlite3_column_text            sqlite3_api->column_text
71065 #define sqlite3_column_text16          sqlite3_api->column_text16
71066 #define sqlite3_column_type            sqlite3_api->column_type
71067 #define sqlite3_column_value           sqlite3_api->column_value
71068 #define sqlite3_commit_hook            sqlite3_api->commit_hook
71069 #define sqlite3_complete               sqlite3_api->complete
71070 #define sqlite3_complete16             sqlite3_api->complete16
71071 #define sqlite3_create_collation       sqlite3_api->create_collation
71072 #define sqlite3_create_collation16     sqlite3_api->create_collation16
71073 #define sqlite3_create_function        sqlite3_api->create_function
71074 #define sqlite3_create_function16      sqlite3_api->create_function16
71075 #define sqlite3_create_module          sqlite3_api->create_module
71076 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
71077 #define sqlite3_data_count             sqlite3_api->data_count
71078 #define sqlite3_db_handle              sqlite3_api->db_handle
71079 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
71080 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
71081 #define sqlite3_errcode                sqlite3_api->errcode
71082 #define sqlite3_errmsg                 sqlite3_api->errmsg
71083 #define sqlite3_errmsg16               sqlite3_api->errmsg16
71084 #define sqlite3_exec                   sqlite3_api->exec
71085 #ifndef SQLITE_OMIT_DEPRECATED
71086 #define sqlite3_expired                sqlite3_api->expired
71087 #endif
71088 #define sqlite3_finalize               sqlite3_api->finalize
71089 #define sqlite3_free                   sqlite3_api->free
71090 #define sqlite3_free_table             sqlite3_api->free_table
71091 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
71092 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
71093 #define sqlite3_get_table              sqlite3_api->get_table
71094 #ifndef SQLITE_OMIT_DEPRECATED
71095 #define sqlite3_global_recover         sqlite3_api->global_recover
71096 #endif
71097 #define sqlite3_interrupt              sqlite3_api->interruptx
71098 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
71099 #define sqlite3_libversion             sqlite3_api->libversion
71100 #define sqlite3_libversion_number      sqlite3_api->libversion_number
71101 #define sqlite3_malloc                 sqlite3_api->malloc
71102 #define sqlite3_mprintf                sqlite3_api->mprintf
71103 #define sqlite3_open                   sqlite3_api->open
71104 #define sqlite3_open16                 sqlite3_api->open16
71105 #define sqlite3_prepare                sqlite3_api->prepare
71106 #define sqlite3_prepare16              sqlite3_api->prepare16
71107 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
71108 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
71109 #define sqlite3_profile                sqlite3_api->profile
71110 #define sqlite3_progress_handler       sqlite3_api->progress_handler
71111 #define sqlite3_realloc                sqlite3_api->realloc
71112 #define sqlite3_reset                  sqlite3_api->reset
71113 #define sqlite3_result_blob            sqlite3_api->result_blob
71114 #define sqlite3_result_double          sqlite3_api->result_double
71115 #define sqlite3_result_error           sqlite3_api->result_error
71116 #define sqlite3_result_error16         sqlite3_api->result_error16
71117 #define sqlite3_result_int             sqlite3_api->result_int
71118 #define sqlite3_result_int64           sqlite3_api->result_int64
71119 #define sqlite3_result_null            sqlite3_api->result_null
71120 #define sqlite3_result_text            sqlite3_api->result_text
71121 #define sqlite3_result_text16          sqlite3_api->result_text16
71122 #define sqlite3_result_text16be        sqlite3_api->result_text16be
71123 #define sqlite3_result_text16le        sqlite3_api->result_text16le
71124 #define sqlite3_result_value           sqlite3_api->result_value
71125 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
71126 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
71127 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
71128 #define sqlite3_snprintf               sqlite3_api->snprintf
71129 #define sqlite3_step                   sqlite3_api->step
71130 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
71131 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
71132 #define sqlite3_total_changes          sqlite3_api->total_changes
71133 #define sqlite3_trace                  sqlite3_api->trace
71134 #ifndef SQLITE_OMIT_DEPRECATED
71135 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
71136 #endif
71137 #define sqlite3_update_hook            sqlite3_api->update_hook
71138 #define sqlite3_user_data              sqlite3_api->user_data
71139 #define sqlite3_value_blob             sqlite3_api->value_blob
71140 #define sqlite3_value_bytes            sqlite3_api->value_bytes
71141 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
71142 #define sqlite3_value_double           sqlite3_api->value_double
71143 #define sqlite3_value_int              sqlite3_api->value_int
71144 #define sqlite3_value_int64            sqlite3_api->value_int64
71145 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
71146 #define sqlite3_value_text             sqlite3_api->value_text
71147 #define sqlite3_value_text16           sqlite3_api->value_text16
71148 #define sqlite3_value_text16be         sqlite3_api->value_text16be
71149 #define sqlite3_value_text16le         sqlite3_api->value_text16le
71150 #define sqlite3_value_type             sqlite3_api->value_type
71151 #define sqlite3_vmprintf               sqlite3_api->vmprintf
71152 #define sqlite3_overload_function      sqlite3_api->overload_function
71153 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
71154 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
71155 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
71156 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
71157 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
71158 #define sqlite3_blob_close             sqlite3_api->blob_close
71159 #define sqlite3_blob_open              sqlite3_api->blob_open
71160 #define sqlite3_blob_read              sqlite3_api->blob_read
71161 #define sqlite3_blob_write             sqlite3_api->blob_write
71162 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
71163 #define sqlite3_file_control           sqlite3_api->file_control
71164 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
71165 #define sqlite3_memory_used            sqlite3_api->memory_used
71166 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
71167 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
71168 #define sqlite3_mutex_free             sqlite3_api->mutex_free
71169 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
71170 #define sqlite3_mutex_try              sqlite3_api->mutex_try
71171 #define sqlite3_open_v2                sqlite3_api->open_v2
71172 #define sqlite3_release_memory         sqlite3_api->release_memory
71173 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
71174 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
71175 #define sqlite3_sleep                  sqlite3_api->sleep
71176 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
71177 #define sqlite3_vfs_find               sqlite3_api->vfs_find
71178 #define sqlite3_vfs_register           sqlite3_api->vfs_register
71179 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
71180 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
71181 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
71182 #define sqlite3_result_error_code      sqlite3_api->result_error_code
71183 #define sqlite3_test_control           sqlite3_api->test_control
71184 #define sqlite3_randomness             sqlite3_api->randomness
71185 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
71186 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
71187 #define sqlite3_limit                  sqlite3_api->limit
71188 #define sqlite3_next_stmt              sqlite3_api->next_stmt
71189 #define sqlite3_sql                    sqlite3_api->sql
71190 #define sqlite3_status                 sqlite3_api->status
71191 #endif /* SQLITE_CORE */
71192
71193 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
71194 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
71195
71196 #endif /* _SQLITE3EXT_H_ */
71197
71198 /************** End of sqlite3ext.h ******************************************/
71199 /************** Continuing where we left off in loadext.c ********************/
71200
71201 #ifndef SQLITE_OMIT_LOAD_EXTENSION
71202
71203 /*
71204 ** Some API routines are omitted when various features are
71205 ** excluded from a build of SQLite.  Substitute a NULL pointer
71206 ** for any missing APIs.
71207 */
71208 #ifndef SQLITE_ENABLE_COLUMN_METADATA
71209 # define sqlite3_column_database_name   0
71210 # define sqlite3_column_database_name16 0
71211 # define sqlite3_column_table_name      0
71212 # define sqlite3_column_table_name16    0
71213 # define sqlite3_column_origin_name     0
71214 # define sqlite3_column_origin_name16   0
71215 # define sqlite3_table_column_metadata  0
71216 #endif
71217
71218 #ifdef SQLITE_OMIT_AUTHORIZATION
71219 # define sqlite3_set_authorizer         0
71220 #endif
71221
71222 #ifdef SQLITE_OMIT_UTF16
71223 # define sqlite3_bind_text16            0
71224 # define sqlite3_collation_needed16     0
71225 # define sqlite3_column_decltype16      0
71226 # define sqlite3_column_name16          0
71227 # define sqlite3_column_text16          0
71228 # define sqlite3_complete16             0
71229 # define sqlite3_create_collation16     0
71230 # define sqlite3_create_function16      0
71231 # define sqlite3_errmsg16               0
71232 # define sqlite3_open16                 0
71233 # define sqlite3_prepare16              0
71234 # define sqlite3_prepare16_v2           0
71235 # define sqlite3_result_error16         0
71236 # define sqlite3_result_text16          0
71237 # define sqlite3_result_text16be        0
71238 # define sqlite3_result_text16le        0
71239 # define sqlite3_value_text16           0
71240 # define sqlite3_value_text16be         0
71241 # define sqlite3_value_text16le         0
71242 # define sqlite3_column_database_name16 0
71243 # define sqlite3_column_table_name16    0
71244 # define sqlite3_column_origin_name16   0
71245 #endif
71246
71247 #ifdef SQLITE_OMIT_COMPLETE
71248 # define sqlite3_complete 0
71249 # define sqlite3_complete16 0
71250 #endif
71251
71252 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
71253 # define sqlite3_progress_handler 0
71254 #endif
71255
71256 #ifdef SQLITE_OMIT_VIRTUALTABLE
71257 # define sqlite3_create_module 0
71258 # define sqlite3_create_module_v2 0
71259 # define sqlite3_declare_vtab 0
71260 #endif
71261
71262 #ifdef SQLITE_OMIT_SHARED_CACHE
71263 # define sqlite3_enable_shared_cache 0
71264 #endif
71265
71266 #ifdef SQLITE_OMIT_TRACE
71267 # define sqlite3_profile       0
71268 # define sqlite3_trace         0
71269 #endif
71270
71271 #ifdef SQLITE_OMIT_GET_TABLE
71272 # define sqlite3_free_table    0
71273 # define sqlite3_get_table     0
71274 #endif
71275
71276 #ifdef SQLITE_OMIT_INCRBLOB
71277 #define sqlite3_bind_zeroblob  0
71278 #define sqlite3_blob_bytes     0
71279 #define sqlite3_blob_close     0
71280 #define sqlite3_blob_open      0
71281 #define sqlite3_blob_read      0
71282 #define sqlite3_blob_write     0
71283 #endif
71284
71285 /*
71286 ** The following structure contains pointers to all SQLite API routines.
71287 ** A pointer to this structure is passed into extensions when they are
71288 ** loaded so that the extension can make calls back into the SQLite
71289 ** library.
71290 **
71291 ** When adding new APIs, add them to the bottom of this structure
71292 ** in order to preserve backwards compatibility.
71293 **
71294 ** Extensions that use newer APIs should first call the
71295 ** sqlite3_libversion_number() to make sure that the API they
71296 ** intend to use is supported by the library.  Extensions should
71297 ** also check to make sure that the pointer to the function is
71298 ** not NULL before calling it.
71299 */
71300 static const sqlite3_api_routines sqlite3Apis = {
71301   sqlite3_aggregate_context,
71302 #ifndef SQLITE_OMIT_DEPRECATED
71303   sqlite3_aggregate_count,
71304 #else
71305   0,
71306 #endif
71307   sqlite3_bind_blob,
71308   sqlite3_bind_double,
71309   sqlite3_bind_int,
71310   sqlite3_bind_int64,
71311   sqlite3_bind_null,
71312   sqlite3_bind_parameter_count,
71313   sqlite3_bind_parameter_index,
71314   sqlite3_bind_parameter_name,
71315   sqlite3_bind_text,
71316   sqlite3_bind_text16,
71317   sqlite3_bind_value,
71318   sqlite3_busy_handler,
71319   sqlite3_busy_timeout,
71320   sqlite3_changes,
71321   sqlite3_close,
71322   sqlite3_collation_needed,
71323   sqlite3_collation_needed16,
71324   sqlite3_column_blob,
71325   sqlite3_column_bytes,
71326   sqlite3_column_bytes16,
71327   sqlite3_column_count,
71328   sqlite3_column_database_name,
71329   sqlite3_column_database_name16,
71330   sqlite3_column_decltype,
71331   sqlite3_column_decltype16,
71332   sqlite3_column_double,
71333   sqlite3_column_int,
71334   sqlite3_column_int64,
71335   sqlite3_column_name,
71336   sqlite3_column_name16,
71337   sqlite3_column_origin_name,
71338   sqlite3_column_origin_name16,
71339   sqlite3_column_table_name,
71340   sqlite3_column_table_name16,
71341   sqlite3_column_text,
71342   sqlite3_column_text16,
71343   sqlite3_column_type,
71344   sqlite3_column_value,
71345   sqlite3_commit_hook,
71346   sqlite3_complete,
71347   sqlite3_complete16,
71348   sqlite3_create_collation,
71349   sqlite3_create_collation16,
71350   sqlite3_create_function,
71351   sqlite3_create_function16,
71352   sqlite3_create_module,
71353   sqlite3_data_count,
71354   sqlite3_db_handle,
71355   sqlite3_declare_vtab,
71356   sqlite3_enable_shared_cache,
71357   sqlite3_errcode,
71358   sqlite3_errmsg,
71359   sqlite3_errmsg16,
71360   sqlite3_exec,
71361 #ifndef SQLITE_OMIT_DEPRECATED
71362   sqlite3_expired,
71363 #else
71364   0,
71365 #endif
71366   sqlite3_finalize,
71367   sqlite3_free,
71368   sqlite3_free_table,
71369   sqlite3_get_autocommit,
71370   sqlite3_get_auxdata,
71371   sqlite3_get_table,
71372   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
71373   sqlite3_interrupt,
71374   sqlite3_last_insert_rowid,
71375   sqlite3_libversion,
71376   sqlite3_libversion_number,
71377   sqlite3_malloc,
71378   sqlite3_mprintf,
71379   sqlite3_open,
71380   sqlite3_open16,
71381   sqlite3_prepare,
71382   sqlite3_prepare16,
71383   sqlite3_profile,
71384   sqlite3_progress_handler,
71385   sqlite3_realloc,
71386   sqlite3_reset,
71387   sqlite3_result_blob,
71388   sqlite3_result_double,
71389   sqlite3_result_error,
71390   sqlite3_result_error16,
71391   sqlite3_result_int,
71392   sqlite3_result_int64,
71393   sqlite3_result_null,
71394   sqlite3_result_text,
71395   sqlite3_result_text16,
71396   sqlite3_result_text16be,
71397   sqlite3_result_text16le,
71398   sqlite3_result_value,
71399   sqlite3_rollback_hook,
71400   sqlite3_set_authorizer,
71401   sqlite3_set_auxdata,
71402   sqlite3_snprintf,
71403   sqlite3_step,
71404   sqlite3_table_column_metadata,
71405 #ifndef SQLITE_OMIT_DEPRECATED
71406   sqlite3_thread_cleanup,
71407 #else
71408   0,
71409 #endif
71410   sqlite3_total_changes,
71411   sqlite3_trace,
71412 #ifndef SQLITE_OMIT_DEPRECATED
71413   sqlite3_transfer_bindings,
71414 #else
71415   0,
71416 #endif
71417   sqlite3_update_hook,
71418   sqlite3_user_data,
71419   sqlite3_value_blob,
71420   sqlite3_value_bytes,
71421   sqlite3_value_bytes16,
71422   sqlite3_value_double,
71423   sqlite3_value_int,
71424   sqlite3_value_int64,
71425   sqlite3_value_numeric_type,
71426   sqlite3_value_text,
71427   sqlite3_value_text16,
71428   sqlite3_value_text16be,
71429   sqlite3_value_text16le,
71430   sqlite3_value_type,
71431   sqlite3_vmprintf,
71432   /*
71433   ** The original API set ends here.  All extensions can call any
71434   ** of the APIs above provided that the pointer is not NULL.  But
71435   ** before calling APIs that follow, extension should check the
71436   ** sqlite3_libversion_number() to make sure they are dealing with
71437   ** a library that is new enough to support that API.
71438   *************************************************************************
71439   */
71440   sqlite3_overload_function,
71441
71442   /*
71443   ** Added after 3.3.13
71444   */
71445   sqlite3_prepare_v2,
71446   sqlite3_prepare16_v2,
71447   sqlite3_clear_bindings,
71448
71449   /*
71450   ** Added for 3.4.1
71451   */
71452   sqlite3_create_module_v2,
71453
71454   /*
71455   ** Added for 3.5.0
71456   */
71457   sqlite3_bind_zeroblob,
71458   sqlite3_blob_bytes,
71459   sqlite3_blob_close,
71460   sqlite3_blob_open,
71461   sqlite3_blob_read,
71462   sqlite3_blob_write,
71463   sqlite3_create_collation_v2,
71464   sqlite3_file_control,
71465   sqlite3_memory_highwater,
71466   sqlite3_memory_used,
71467 #ifdef SQLITE_MUTEX_OMIT
71468   0, 
71469   0, 
71470   0,
71471   0,
71472   0,
71473 #else
71474   sqlite3_mutex_alloc,
71475   sqlite3_mutex_enter,
71476   sqlite3_mutex_free,
71477   sqlite3_mutex_leave,
71478   sqlite3_mutex_try,
71479 #endif
71480   sqlite3_open_v2,
71481   sqlite3_release_memory,
71482   sqlite3_result_error_nomem,
71483   sqlite3_result_error_toobig,
71484   sqlite3_sleep,
71485   sqlite3_soft_heap_limit,
71486   sqlite3_vfs_find,
71487   sqlite3_vfs_register,
71488   sqlite3_vfs_unregister,
71489
71490   /*
71491   ** Added for 3.5.8
71492   */
71493   sqlite3_threadsafe,
71494   sqlite3_result_zeroblob,
71495   sqlite3_result_error_code,
71496   sqlite3_test_control,
71497   sqlite3_randomness,
71498   sqlite3_context_db_handle,
71499
71500   /*
71501   ** Added for 3.6.0
71502   */
71503   sqlite3_extended_result_codes,
71504   sqlite3_limit,
71505   sqlite3_next_stmt,
71506   sqlite3_sql,
71507   sqlite3_status,
71508 };
71509
71510 /*
71511 ** Attempt to load an SQLite extension library contained in the file
71512 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
71513 ** default entry point name (sqlite3_extension_init) is used.  Use
71514 ** of the default name is recommended.
71515 **
71516 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
71517 **
71518 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
71519 ** error message text.  The calling function should free this memory
71520 ** by calling sqlite3DbFree(db, ).
71521 */
71522 static int sqlite3LoadExtension(
71523   sqlite3 *db,          /* Load the extension into this database connection */
71524   const char *zFile,    /* Name of the shared library containing extension */
71525   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
71526   char **pzErrMsg       /* Put error message here if not 0 */
71527 ){
71528   sqlite3_vfs *pVfs = db->pVfs;
71529   void *handle;
71530   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
71531   char *zErrmsg = 0;
71532   void **aHandle;
71533
71534   /* Ticket #1863.  To avoid a creating security problems for older
71535   ** applications that relink against newer versions of SQLite, the
71536   ** ability to run load_extension is turned off by default.  One
71537   ** must call sqlite3_enable_load_extension() to turn on extension
71538   ** loading.  Otherwise you get the following error.
71539   */
71540   if( (db->flags & SQLITE_LoadExtension)==0 ){
71541     if( pzErrMsg ){
71542       *pzErrMsg = sqlite3_mprintf("not authorized");
71543     }
71544     return SQLITE_ERROR;
71545   }
71546
71547   if( zProc==0 ){
71548     zProc = "sqlite3_extension_init";
71549   }
71550
71551   handle = sqlite3OsDlOpen(pVfs, zFile);
71552   if( handle==0 ){
71553     if( pzErrMsg ){
71554       char zErr[256];
71555       zErr[sizeof(zErr)-1] = '\0';
71556       sqlite3_snprintf(sizeof(zErr)-1, zErr, 
71557           "unable to open shared library [%s]", zFile);
71558       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
71559       *pzErrMsg = sqlite3DbStrDup(0, zErr);
71560     }
71561     return SQLITE_ERROR;
71562   }
71563   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
71564                    sqlite3OsDlSym(pVfs, handle, zProc);
71565   if( xInit==0 ){
71566     if( pzErrMsg ){
71567       char zErr[256];
71568       zErr[sizeof(zErr)-1] = '\0';
71569       sqlite3_snprintf(sizeof(zErr)-1, zErr,
71570           "no entry point [%s] in shared library [%s]", zProc,zFile);
71571       sqlite3OsDlError(pVfs, sizeof(zErr)-1, zErr);
71572       *pzErrMsg = sqlite3DbStrDup(0, zErr);
71573       sqlite3OsDlClose(pVfs, handle);
71574     }
71575     return SQLITE_ERROR;
71576   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
71577     if( pzErrMsg ){
71578       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
71579     }
71580     sqlite3_free(zErrmsg);
71581     sqlite3OsDlClose(pVfs, handle);
71582     return SQLITE_ERROR;
71583   }
71584
71585   /* Append the new shared library handle to the db->aExtension array. */
71586   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
71587   if( aHandle==0 ){
71588     return SQLITE_NOMEM;
71589   }
71590   if( db->nExtension>0 ){
71591     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
71592   }
71593   sqlite3DbFree(db, db->aExtension);
71594   db->aExtension = aHandle;
71595
71596   db->aExtension[db->nExtension++] = handle;
71597   return SQLITE_OK;
71598 }
71599 SQLITE_API int sqlite3_load_extension(
71600   sqlite3 *db,          /* Load the extension into this database connection */
71601   const char *zFile,    /* Name of the shared library containing extension */
71602   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
71603   char **pzErrMsg       /* Put error message here if not 0 */
71604 ){
71605   int rc;
71606   sqlite3_mutex_enter(db->mutex);
71607   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
71608   sqlite3_mutex_leave(db->mutex);
71609   return rc;
71610 }
71611
71612 /*
71613 ** Call this routine when the database connection is closing in order
71614 ** to clean up loaded extensions
71615 */
71616 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
71617   int i;
71618   assert( sqlite3_mutex_held(db->mutex) );
71619   for(i=0; i<db->nExtension; i++){
71620     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
71621   }
71622   sqlite3DbFree(db, db->aExtension);
71623 }
71624
71625 /*
71626 ** Enable or disable extension loading.  Extension loading is disabled by
71627 ** default so as not to open security holes in older applications.
71628 */
71629 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
71630   sqlite3_mutex_enter(db->mutex);
71631   if( onoff ){
71632     db->flags |= SQLITE_LoadExtension;
71633   }else{
71634     db->flags &= ~SQLITE_LoadExtension;
71635   }
71636   sqlite3_mutex_leave(db->mutex);
71637   return SQLITE_OK;
71638 }
71639
71640 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
71641
71642 /*
71643 ** The auto-extension code added regardless of whether or not extension
71644 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
71645 ** code if regular extension loading is not available.  This is that
71646 ** dummy pointer.
71647 */
71648 #ifdef SQLITE_OMIT_LOAD_EXTENSION
71649 static const sqlite3_api_routines sqlite3Apis = { 0 };
71650 #endif
71651
71652
71653 /*
71654 ** The following object holds the list of automatically loaded
71655 ** extensions.
71656 **
71657 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
71658 ** mutex must be held while accessing this list.
71659 */
71660 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
71661 static SQLITE_WSD struct sqlite3AutoExtList {
71662   int nExt;              /* Number of entries in aExt[] */          
71663   void (**aExt)(void);   /* Pointers to the extension init functions */
71664 } sqlite3Autoext = { 0, 0 };
71665
71666 /* The "wsdAutoext" macro will resolve to the autoextension
71667 ** state vector.  If writable static data is unsupported on the target,
71668 ** we have to locate the state vector at run-time.  In the more common
71669 ** case where writable static data is supported, wsdStat can refer directly
71670 ** to the "sqlite3Autoext" state vector declared above.
71671 */
71672 #ifdef SQLITE_OMIT_WSD
71673 # define wsdAutoextInit \
71674   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
71675 # define wsdAutoext x[0]
71676 #else
71677 # define wsdAutoextInit
71678 # define wsdAutoext sqlite3Autoext
71679 #endif
71680
71681
71682 /*
71683 ** Register a statically linked extension that is automatically
71684 ** loaded by every new database connection.
71685 */
71686 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
71687   int rc = SQLITE_OK;
71688 #ifndef SQLITE_OMIT_AUTOINIT
71689   rc = sqlite3_initialize();
71690   if( rc ){
71691     return rc;
71692   }else
71693 #endif
71694   {
71695     int i;
71696 #if SQLITE_THREADSAFE
71697     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
71698 #endif
71699     wsdAutoextInit;
71700     sqlite3_mutex_enter(mutex);
71701     for(i=0; i<wsdAutoext.nExt; i++){
71702       if( wsdAutoext.aExt[i]==xInit ) break;
71703     }
71704     if( i==wsdAutoext.nExt ){
71705       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
71706       void (**aNew)(void);
71707       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
71708       if( aNew==0 ){
71709         rc = SQLITE_NOMEM;
71710       }else{
71711         wsdAutoext.aExt = aNew;
71712         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
71713         wsdAutoext.nExt++;
71714       }
71715     }
71716     sqlite3_mutex_leave(mutex);
71717     assert( (rc&0xff)==rc );
71718     return rc;
71719   }
71720 }
71721
71722 /*
71723 ** Reset the automatic extension loading mechanism.
71724 */
71725 SQLITE_API void sqlite3_reset_auto_extension(void){
71726 #ifndef SQLITE_OMIT_AUTOINIT
71727   if( sqlite3_initialize()==SQLITE_OK )
71728 #endif
71729   {
71730 #if SQLITE_THREADSAFE
71731     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
71732 #endif
71733     wsdAutoextInit;
71734     sqlite3_mutex_enter(mutex);
71735     sqlite3_free(wsdAutoext.aExt);
71736     wsdAutoext.aExt = 0;
71737     wsdAutoext.nExt = 0;
71738     sqlite3_mutex_leave(mutex);
71739   }
71740 }
71741
71742 /*
71743 ** Load all automatic extensions.
71744 */
71745 SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
71746   int i;
71747   int go = 1;
71748   int rc = SQLITE_OK;
71749   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
71750
71751   wsdAutoextInit;
71752   if( wsdAutoext.nExt==0 ){
71753     /* Common case: early out without every having to acquire a mutex */
71754     return SQLITE_OK;
71755   }
71756   for(i=0; go; i++){
71757     char *zErrmsg = 0;
71758 #if SQLITE_THREADSAFE
71759     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
71760 #endif
71761     sqlite3_mutex_enter(mutex);
71762     if( i>=wsdAutoext.nExt ){
71763       xInit = 0;
71764       go = 0;
71765     }else{
71766       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
71767               wsdAutoext.aExt[i];
71768     }
71769     sqlite3_mutex_leave(mutex);
71770     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
71771       sqlite3Error(db, SQLITE_ERROR,
71772             "automatic extension loading failed: %s", zErrmsg);
71773       go = 0;
71774       rc = SQLITE_ERROR;
71775       sqlite3_free(zErrmsg);
71776     }
71777   }
71778   return rc;
71779 }
71780
71781 /************** End of loadext.c *********************************************/
71782 /************** Begin file pragma.c ******************************************/
71783 /*
71784 ** 2003 April 6
71785 **
71786 ** The author disclaims copyright to this source code.  In place of
71787 ** a legal notice, here is a blessing:
71788 **
71789 **    May you do good and not evil.
71790 **    May you find forgiveness for yourself and forgive others.
71791 **    May you share freely, never taking more than you give.
71792 **
71793 *************************************************************************
71794 ** This file contains code used to implement the PRAGMA command.
71795 **
71796 ** $Id: pragma.c,v 1.202 2009/01/20 16:53:41 danielk1977 Exp $
71797 */
71798
71799 /* Ignore this whole file if pragmas are disabled
71800 */
71801 #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)
71802
71803 /*
71804 ** Interpret the given string as a safety level.  Return 0 for OFF,
71805 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
71806 ** unrecognized string argument.
71807 **
71808 ** Note that the values returned are one less that the values that
71809 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
71810 ** to support legacy SQL code.  The safety level used to be boolean
71811 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
71812 */
71813 static u8 getSafetyLevel(const char *z){
71814                              /* 123456789 123456789 */
71815   static const char zText[] = "onoffalseyestruefull";
71816   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
71817   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
71818   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
71819   int i, n;
71820   if( sqlite3Isdigit(*z) ){
71821     return (u8)atoi(z);
71822   }
71823   n = sqlite3Strlen30(z);
71824   for(i=0; i<ArraySize(iLength); i++){
71825     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
71826       return iValue[i];
71827     }
71828   }
71829   return 1;
71830 }
71831
71832 /*
71833 ** Interpret the given string as a boolean value.
71834 */
71835 static u8 getBoolean(const char *z){
71836   return getSafetyLevel(z)&1;
71837 }
71838
71839 /*
71840 ** Interpret the given string as a locking mode value.
71841 */
71842 static int getLockingMode(const char *z){
71843   if( z ){
71844     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
71845     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
71846   }
71847   return PAGER_LOCKINGMODE_QUERY;
71848 }
71849
71850 #ifndef SQLITE_OMIT_AUTOVACUUM
71851 /*
71852 ** Interpret the given string as an auto-vacuum mode value.
71853 **
71854 ** The following strings, "none", "full" and "incremental" are 
71855 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
71856 */
71857 static int getAutoVacuum(const char *z){
71858   int i;
71859   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
71860   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
71861   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
71862   i = atoi(z);
71863   return (u8)((i>=0&&i<=2)?i:0);
71864 }
71865 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
71866
71867 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
71868 /*
71869 ** Interpret the given string as a temp db location. Return 1 for file
71870 ** backed temporary databases, 2 for the Red-Black tree in memory database
71871 ** and 0 to use the compile-time default.
71872 */
71873 static int getTempStore(const char *z){
71874   if( z[0]>='0' && z[0]<='2' ){
71875     return z[0] - '0';
71876   }else if( sqlite3StrICmp(z, "file")==0 ){
71877     return 1;
71878   }else if( sqlite3StrICmp(z, "memory")==0 ){
71879     return 2;
71880   }else{
71881     return 0;
71882   }
71883 }
71884 #endif /* SQLITE_PAGER_PRAGMAS */
71885
71886 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
71887 /*
71888 ** Invalidate temp storage, either when the temp storage is changed
71889 ** from default, or when 'file' and the temp_store_directory has changed
71890 */
71891 static int invalidateTempStorage(Parse *pParse){
71892   sqlite3 *db = pParse->db;
71893   if( db->aDb[1].pBt!=0 ){
71894     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
71895       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
71896         "from within a transaction");
71897       return SQLITE_ERROR;
71898     }
71899     sqlite3BtreeClose(db->aDb[1].pBt);
71900     db->aDb[1].pBt = 0;
71901     sqlite3ResetInternalSchema(db, 0);
71902   }
71903   return SQLITE_OK;
71904 }
71905 #endif /* SQLITE_PAGER_PRAGMAS */
71906
71907 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
71908 /*
71909 ** If the TEMP database is open, close it and mark the database schema
71910 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
71911 ** or DEFAULT_TEMP_STORE pragmas.
71912 */
71913 static int changeTempStorage(Parse *pParse, const char *zStorageType){
71914   int ts = getTempStore(zStorageType);
71915   sqlite3 *db = pParse->db;
71916   if( db->temp_store==ts ) return SQLITE_OK;
71917   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
71918     return SQLITE_ERROR;
71919   }
71920   db->temp_store = (u8)ts;
71921   return SQLITE_OK;
71922 }
71923 #endif /* SQLITE_PAGER_PRAGMAS */
71924
71925 /*
71926 ** Generate code to return a single integer value.
71927 */
71928 static void returnSingleInt(Parse *pParse, const char *zLabel, int value){
71929   Vdbe *v = sqlite3GetVdbe(pParse);
71930   int mem = ++pParse->nMem;
71931   sqlite3VdbeAddOp2(v, OP_Integer, value, mem);
71932   if( pParse->explain==0 ){
71933     sqlite3VdbeSetNumCols(v, 1);
71934     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
71935   }
71936   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
71937 }
71938
71939 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
71940 /*
71941 ** Check to see if zRight and zLeft refer to a pragma that queries
71942 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
71943 ** Also, implement the pragma.
71944 */
71945 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
71946   static const struct sPragmaType {
71947     const char *zName;  /* Name of the pragma */
71948     int mask;           /* Mask for the db->flags value */
71949   } aPragma[] = {
71950     { "full_column_names",        SQLITE_FullColNames  },
71951     { "short_column_names",       SQLITE_ShortColNames },
71952     { "count_changes",            SQLITE_CountRows     },
71953     { "empty_result_callbacks",   SQLITE_NullCallback  },
71954     { "legacy_file_format",       SQLITE_LegacyFileFmt },
71955     { "fullfsync",                SQLITE_FullFSync     },
71956 #ifdef SQLITE_DEBUG
71957     { "sql_trace",                SQLITE_SqlTrace      },
71958     { "vdbe_listing",             SQLITE_VdbeListing   },
71959     { "vdbe_trace",               SQLITE_VdbeTrace     },
71960 #endif
71961 #ifndef SQLITE_OMIT_CHECK
71962     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
71963 #endif
71964     /* The following is VERY experimental */
71965     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
71966     { "omit_readlock",            SQLITE_NoReadlock    },
71967
71968     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
71969     ** flag if there are any active statements. */
71970     { "read_uncommitted",         SQLITE_ReadUncommitted },
71971   };
71972   int i;
71973   const struct sPragmaType *p;
71974   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
71975     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
71976       sqlite3 *db = pParse->db;
71977       Vdbe *v;
71978       v = sqlite3GetVdbe(pParse);
71979       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
71980       if( ALWAYS(v) ){
71981         if( zRight==0 ){
71982           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
71983         }else{
71984           if( getBoolean(zRight) ){
71985             db->flags |= p->mask;
71986           }else{
71987             db->flags &= ~p->mask;
71988           }
71989
71990           /* Many of the flag-pragmas modify the code generated by the SQL 
71991           ** compiler (eg. count_changes). So add an opcode to expire all
71992           ** compiled SQL statements after modifying a pragma value.
71993           */
71994           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
71995         }
71996       }
71997
71998       return 1;
71999     }
72000   }
72001   return 0;
72002 }
72003 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
72004
72005 /*
72006 ** Return a human-readable name for a constraint resolution action.
72007 */
72008 static const char *actionName(u8 action){
72009   const char *zName;
72010   switch( action ){
72011     case OE_SetNull:  zName = "SET NULL";            break;
72012     case OE_SetDflt:  zName = "SET DEFAULT";         break;
72013     case OE_Cascade:  zName = "CASCADE";             break;
72014     default:          zName = "RESTRICT";  
72015                       assert( action==OE_Restrict ); break;
72016   }
72017   return zName;
72018 }
72019
72020 /*
72021 ** Process a pragma statement.  
72022 **
72023 ** Pragmas are of this form:
72024 **
72025 **      PRAGMA [database.]id [= value]
72026 **
72027 ** The identifier might also be a string.  The value is a string, and
72028 ** identifier, or a number.  If minusFlag is true, then the value is
72029 ** a number that was preceded by a minus sign.
72030 **
72031 ** If the left side is "database.id" then pId1 is the database name
72032 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
72033 ** id and pId2 is any empty string.
72034 */
72035 SQLITE_PRIVATE void sqlite3Pragma(
72036   Parse *pParse, 
72037   Token *pId1,        /* First part of [database.]id field */
72038   Token *pId2,        /* Second part of [database.]id field, or NULL */
72039   Token *pValue,      /* Token for <value>, or NULL */
72040   int minusFlag       /* True if a '-' sign preceded <value> */
72041 ){
72042   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
72043   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
72044   const char *zDb = 0;   /* The database name */
72045   Token *pId;            /* Pointer to <id> token */
72046   int iDb;               /* Database index for <database> */
72047   sqlite3 *db = pParse->db;
72048   Db *pDb;
72049   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
72050   if( v==0 ) return;
72051   pParse->nMem = 2;
72052
72053   /* Interpret the [database.] part of the pragma statement. iDb is the
72054   ** index of the database this pragma is being applied to in db.aDb[]. */
72055   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
72056   if( iDb<0 ) return;
72057   pDb = &db->aDb[iDb];
72058
72059   /* If the temp database has been explicitly named as part of the 
72060   ** pragma, make sure it is open. 
72061   */
72062   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
72063     return;
72064   }
72065
72066   zLeft = sqlite3NameFromToken(db, pId);
72067   if( !zLeft ) return;
72068   if( minusFlag ){
72069     zRight = sqlite3MPrintf(db, "-%T", pValue);
72070   }else{
72071     zRight = sqlite3NameFromToken(db, pValue);
72072   }
72073
72074   assert( pId2 );
72075   zDb = pId2->n>0 ? pDb->zName : 0;
72076   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
72077     goto pragma_out;
72078   }
72079  
72080 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
72081   /*
72082   **  PRAGMA [database.]default_cache_size
72083   **  PRAGMA [database.]default_cache_size=N
72084   **
72085   ** The first form reports the current persistent setting for the
72086   ** page cache size.  The value returned is the maximum number of
72087   ** pages in the page cache.  The second form sets both the current
72088   ** page cache size value and the persistent page cache size value
72089   ** stored in the database file.
72090   **
72091   ** The default cache size is stored in meta-value 2 of page 1 of the
72092   ** database file.  The cache size is actually the absolute value of
72093   ** this memory location.  The sign of meta-value 2 determines the
72094   ** synchronous setting.  A negative value means synchronous is off
72095   ** and a positive value means synchronous is on.
72096   */
72097   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
72098     static const VdbeOpList getCacheSize[] = {
72099       { OP_ReadCookie,  0, 1,        2},  /* 0 */
72100       { OP_IfPos,       1, 6,        0},
72101       { OP_Integer,     0, 2,        0},
72102       { OP_Subtract,    1, 2,        1},
72103       { OP_IfPos,       1, 6,        0},
72104       { OP_Integer,     0, 1,        0},  /* 5 */
72105       { OP_ResultRow,   1, 1,        0},
72106     };
72107     int addr;
72108     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72109     sqlite3VdbeUsesBtree(v, iDb);
72110     if( !zRight ){
72111       sqlite3VdbeSetNumCols(v, 1);
72112       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
72113       pParse->nMem += 2;
72114       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
72115       sqlite3VdbeChangeP1(v, addr, iDb);
72116       sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE);
72117     }else{
72118       int size = atoi(zRight);
72119       if( size<0 ) size = -size;
72120       sqlite3BeginWriteOperation(pParse, 0, iDb);
72121       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
72122       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2);
72123       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
72124       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
72125       sqlite3VdbeJumpHere(v, addr);
72126       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1);
72127       pDb->pSchema->cache_size = size;
72128       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
72129     }
72130   }else
72131
72132   /*
72133   **  PRAGMA [database.]page_size
72134   **  PRAGMA [database.]page_size=N
72135   **
72136   ** The first form reports the current setting for the
72137   ** database page size in bytes.  The second form sets the
72138   ** database page size value.  The value can only be set if
72139   ** the database has not yet been created.
72140   */
72141   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
72142     Btree *pBt = pDb->pBt;
72143     assert( pBt!=0 );
72144     if( !zRight ){
72145       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
72146       returnSingleInt(pParse, "page_size", size);
72147     }else{
72148       /* Malloc may fail when setting the page-size, as there is an internal
72149       ** buffer that the pager module resizes using sqlite3_realloc().
72150       */
72151       db->nextPagesize = atoi(zRight);
72152       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){
72153         db->mallocFailed = 1;
72154       }
72155     }
72156   }else
72157
72158   /*
72159   **  PRAGMA [database.]max_page_count
72160   **  PRAGMA [database.]max_page_count=N
72161   **
72162   ** The first form reports the current setting for the
72163   ** maximum number of pages in the database file.  The 
72164   ** second form attempts to change this setting.  Both
72165   ** forms return the current setting.
72166   */
72167   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
72168     Btree *pBt = pDb->pBt;
72169     int newMax = 0;
72170     assert( pBt!=0 );
72171     if( zRight ){
72172       newMax = atoi(zRight);
72173     }
72174     if( ALWAYS(pBt) ){
72175       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
72176     }
72177     returnSingleInt(pParse, "max_page_count", newMax);
72178   }else
72179
72180   /*
72181   **  PRAGMA [database.]page_count
72182   **
72183   ** Return the number of pages in the specified database.
72184   */
72185   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
72186     int iReg;
72187     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72188     sqlite3CodeVerifySchema(pParse, iDb);
72189     iReg = ++pParse->nMem;
72190     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
72191     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
72192     sqlite3VdbeSetNumCols(v, 1);
72193     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
72194   }else
72195
72196   /*
72197   **  PRAGMA [database.]locking_mode
72198   **  PRAGMA [database.]locking_mode = (normal|exclusive)
72199   */
72200   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
72201     const char *zRet = "normal";
72202     int eMode = getLockingMode(zRight);
72203
72204     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
72205       /* Simple "PRAGMA locking_mode;" statement. This is a query for
72206       ** the current default locking mode (which may be different to
72207       ** the locking-mode of the main database).
72208       */
72209       eMode = db->dfltLockMode;
72210     }else{
72211       Pager *pPager;
72212       if( pId2->n==0 ){
72213         /* This indicates that no database name was specified as part
72214         ** of the PRAGMA command. In this case the locking-mode must be
72215         ** set on all attached databases, as well as the main db file.
72216         **
72217         ** Also, the sqlite3.dfltLockMode variable is set so that
72218         ** any subsequently attached databases also use the specified
72219         ** locking mode.
72220         */
72221         int ii;
72222         assert(pDb==&db->aDb[0]);
72223         for(ii=2; ii<db->nDb; ii++){
72224           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
72225           sqlite3PagerLockingMode(pPager, eMode);
72226         }
72227         db->dfltLockMode = (u8)eMode;
72228       }
72229       pPager = sqlite3BtreePager(pDb->pBt);
72230       eMode = sqlite3PagerLockingMode(pPager, eMode);
72231     }
72232
72233     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
72234     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
72235       zRet = "exclusive";
72236     }
72237     sqlite3VdbeSetNumCols(v, 1);
72238     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
72239     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
72240     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
72241   }else
72242
72243   /*
72244   **  PRAGMA [database.]journal_mode
72245   **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
72246   */
72247   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
72248     int eMode;
72249     static char * const azModeName[] = {
72250       "delete", "persist", "off", "truncate", "memory"
72251     };
72252
72253     if( zRight==0 ){
72254       eMode = PAGER_JOURNALMODE_QUERY;
72255     }else{
72256       int n = sqlite3Strlen30(zRight);
72257       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
72258       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
72259         eMode--;
72260       }
72261     }
72262     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
72263       /* Simple "PRAGMA journal_mode;" statement. This is a query for
72264       ** the current default journal mode (which may be different to
72265       ** the journal-mode of the main database).
72266       */
72267       eMode = db->dfltJournalMode;
72268     }else{
72269       Pager *pPager;
72270       if( pId2->n==0 ){
72271         /* This indicates that no database name was specified as part
72272         ** of the PRAGMA command. In this case the journal-mode must be
72273         ** set on all attached databases, as well as the main db file.
72274         **
72275         ** Also, the sqlite3.dfltJournalMode variable is set so that
72276         ** any subsequently attached databases also use the specified
72277         ** journal mode.
72278         */
72279         int ii;
72280         assert(pDb==&db->aDb[0]);
72281         for(ii=1; ii<db->nDb; ii++){
72282           if( db->aDb[ii].pBt ){
72283             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
72284             sqlite3PagerJournalMode(pPager, eMode);
72285           }
72286         }
72287         db->dfltJournalMode = (u8)eMode;
72288       }
72289       pPager = sqlite3BtreePager(pDb->pBt);
72290       eMode = sqlite3PagerJournalMode(pPager, eMode);
72291     }
72292     assert( eMode==PAGER_JOURNALMODE_DELETE
72293               || eMode==PAGER_JOURNALMODE_TRUNCATE
72294               || eMode==PAGER_JOURNALMODE_PERSIST
72295               || eMode==PAGER_JOURNALMODE_OFF
72296               || eMode==PAGER_JOURNALMODE_MEMORY );
72297     sqlite3VdbeSetNumCols(v, 1);
72298     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
72299     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
72300            azModeName[eMode], P4_STATIC);
72301     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
72302   }else
72303
72304   /*
72305   **  PRAGMA [database.]journal_size_limit
72306   **  PRAGMA [database.]journal_size_limit=N
72307   **
72308   ** Get or set the size limit on rollback journal files.
72309   */
72310   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
72311     Pager *pPager = sqlite3BtreePager(pDb->pBt);
72312     i64 iLimit = -2;
72313     if( zRight ){
72314       int iLimit32 = atoi(zRight);
72315       if( iLimit32<-1 ){
72316         iLimit32 = -1;
72317       }
72318       iLimit = iLimit32;
72319     }
72320     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
72321     returnSingleInt(pParse, "journal_size_limit", (int)iLimit);
72322   }else
72323
72324 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
72325
72326   /*
72327   **  PRAGMA [database.]auto_vacuum
72328   **  PRAGMA [database.]auto_vacuum=N
72329   **
72330   ** Get or set the value of the database 'auto-vacuum' parameter.
72331   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
72332   */
72333 #ifndef SQLITE_OMIT_AUTOVACUUM
72334   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
72335     Btree *pBt = pDb->pBt;
72336     assert( pBt!=0 );
72337     if( sqlite3ReadSchema(pParse) ){
72338       goto pragma_out;
72339     }
72340     if( !zRight ){
72341       int auto_vacuum;
72342       if( ALWAYS(pBt) ){
72343          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
72344       }else{
72345          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
72346       }
72347       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
72348     }else{
72349       int eAuto = getAutoVacuum(zRight);
72350       assert( eAuto>=0 && eAuto<=2 );
72351       db->nextAutovac = (u8)eAuto;
72352       if( ALWAYS(eAuto>=0) ){
72353         /* Call SetAutoVacuum() to set initialize the internal auto and
72354         ** incr-vacuum flags. This is required in case this connection
72355         ** creates the database file. It is important that it is created
72356         ** as an auto-vacuum capable db.
72357         */
72358         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
72359         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
72360           /* When setting the auto_vacuum mode to either "full" or 
72361           ** "incremental", write the value of meta[6] in the database
72362           ** file. Before writing to meta[6], check that meta[3] indicates
72363           ** that this really is an auto-vacuum capable database.
72364           */
72365           static const VdbeOpList setMeta6[] = {
72366             { OP_Transaction,    0,               1,        0},    /* 0 */
72367             { OP_ReadCookie,     0,               1,        3},    /* 1 */
72368             { OP_If,             1,               0,        0},    /* 2 */
72369             { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
72370             { OP_Integer,        0,               1,        0},    /* 4 */
72371             { OP_SetCookie,      0,               6,        1},    /* 5 */
72372           };
72373           int iAddr;
72374           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
72375           sqlite3VdbeChangeP1(v, iAddr, iDb);
72376           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
72377           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
72378           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
72379           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
72380           sqlite3VdbeUsesBtree(v, iDb);
72381         }
72382       }
72383     }
72384   }else
72385 #endif
72386
72387   /*
72388   **  PRAGMA [database.]incremental_vacuum(N)
72389   **
72390   ** Do N steps of incremental vacuuming on a database.
72391   */
72392 #ifndef SQLITE_OMIT_AUTOVACUUM
72393   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
72394     int iLimit, addr;
72395     if( sqlite3ReadSchema(pParse) ){
72396       goto pragma_out;
72397     }
72398     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
72399       iLimit = 0x7fffffff;
72400     }
72401     sqlite3BeginWriteOperation(pParse, 0, iDb);
72402     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
72403     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
72404     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
72405     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
72406     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
72407     sqlite3VdbeJumpHere(v, addr);
72408   }else
72409 #endif
72410
72411 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
72412   /*
72413   **  PRAGMA [database.]cache_size
72414   **  PRAGMA [database.]cache_size=N
72415   **
72416   ** The first form reports the current local setting for the
72417   ** page cache size.  The local setting can be different from
72418   ** the persistent cache size value that is stored in the database
72419   ** file itself.  The value returned is the maximum number of
72420   ** pages in the page cache.  The second form sets the local
72421   ** page cache size value.  It does not change the persistent
72422   ** cache size stored on the disk so the cache size will revert
72423   ** to its default value when the database is closed and reopened.
72424   ** N should be a positive integer.
72425   */
72426   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
72427     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72428     if( !zRight ){
72429       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
72430     }else{
72431       int size = atoi(zRight);
72432       if( size<0 ) size = -size;
72433       pDb->pSchema->cache_size = size;
72434       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
72435     }
72436   }else
72437
72438   /*
72439   **   PRAGMA temp_store
72440   **   PRAGMA temp_store = "default"|"memory"|"file"
72441   **
72442   ** Return or set the local value of the temp_store flag.  Changing
72443   ** the local value does not make changes to the disk file and the default
72444   ** value will be restored the next time the database is opened.
72445   **
72446   ** Note that it is possible for the library compile-time options to
72447   ** override this setting
72448   */
72449   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
72450     if( !zRight ){
72451       returnSingleInt(pParse, "temp_store", db->temp_store);
72452     }else{
72453       changeTempStorage(pParse, zRight);
72454     }
72455   }else
72456
72457   /*
72458   **   PRAGMA temp_store_directory
72459   **   PRAGMA temp_store_directory = ""|"directory_name"
72460   **
72461   ** Return or set the local value of the temp_store_directory flag.  Changing
72462   ** the value sets a specific directory to be used for temporary files.
72463   ** Setting to a null string reverts to the default temporary directory search.
72464   ** If temporary directory is changed, then invalidateTempStorage.
72465   **
72466   */
72467   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
72468     if( !zRight ){
72469       if( sqlite3_temp_directory ){
72470         sqlite3VdbeSetNumCols(v, 1);
72471         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
72472             "temp_store_directory", SQLITE_STATIC);
72473         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
72474         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
72475       }
72476     }else{
72477 #ifndef SQLITE_OMIT_WSD
72478       if( zRight[0] ){
72479         int rc;
72480         int res;
72481         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
72482         if( rc!=SQLITE_OK || res==0 ){
72483           sqlite3ErrorMsg(pParse, "not a writable directory");
72484           goto pragma_out;
72485         }
72486       }
72487       if( SQLITE_TEMP_STORE==0
72488        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
72489        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
72490       ){
72491         invalidateTempStorage(pParse);
72492       }
72493       sqlite3_free(sqlite3_temp_directory);
72494       if( zRight[0] ){
72495         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
72496       }else{
72497         sqlite3_temp_directory = 0;
72498       }
72499 #endif /* SQLITE_OMIT_WSD */
72500     }
72501   }else
72502
72503 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
72504 #  if defined(__APPLE__)
72505 #    define SQLITE_ENABLE_LOCKING_STYLE 1
72506 #  else
72507 #    define SQLITE_ENABLE_LOCKING_STYLE 0
72508 #  endif
72509 #endif
72510 #if SQLITE_ENABLE_LOCKING_STYLE
72511   /*
72512    **   PRAGMA [database.]lock_proxy_file
72513    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
72514    **
72515    ** Return or set the value of the lock_proxy_file flag.  Changing
72516    ** the value sets a specific file to be used for database access locks.
72517    **
72518    */
72519   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
72520     if( !zRight ){
72521       Pager *pPager = sqlite3BtreePager(pDb->pBt);
72522       char *proxy_file_path = NULL;
72523       sqlite3_file *pFile = sqlite3PagerFile(pPager);
72524       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
72525                            &proxy_file_path);
72526       
72527       if( proxy_file_path ){
72528         sqlite3VdbeSetNumCols(v, 1);
72529         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
72530                               "lock_proxy_file", SQLITE_STATIC);
72531         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
72532         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
72533       }
72534     }else{
72535       Pager *pPager = sqlite3BtreePager(pDb->pBt);
72536       sqlite3_file *pFile = sqlite3PagerFile(pPager);
72537       int res;
72538       if( zRight[0] ){
72539         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
72540                                      zRight);
72541       } else {
72542         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
72543                                      NULL);
72544       }
72545       if( res!=SQLITE_OK ){
72546         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
72547         goto pragma_out;
72548       }
72549     }
72550   }else
72551 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
72552     
72553   /*
72554   **   PRAGMA [database.]synchronous
72555   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
72556   **
72557   ** Return or set the local value of the synchronous flag.  Changing
72558   ** the local value does not make changes to the disk file and the
72559   ** default value will be restored the next time the database is
72560   ** opened.
72561   */
72562   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
72563     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72564     if( !zRight ){
72565       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
72566     }else{
72567       if( !db->autoCommit ){
72568         sqlite3ErrorMsg(pParse, 
72569             "Safety level may not be changed inside a transaction");
72570       }else{
72571         pDb->safety_level = getSafetyLevel(zRight)+1;
72572       }
72573     }
72574   }else
72575 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
72576
72577 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
72578   if( flagPragma(pParse, zLeft, zRight) ){
72579     /* The flagPragma() subroutine also generates any necessary code
72580     ** there is nothing more to do here */
72581   }else
72582 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
72583
72584 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
72585   /*
72586   **   PRAGMA table_info(<table>)
72587   **
72588   ** Return a single row for each column of the named table. The columns of
72589   ** the returned data set are:
72590   **
72591   ** cid:        Column id (numbered from left to right, starting at 0)
72592   ** name:       Column name
72593   ** type:       Column declaration type.
72594   ** notnull:    True if 'NOT NULL' is part of column declaration
72595   ** dflt_value: The default value for the column, if any.
72596   */
72597   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
72598     Table *pTab;
72599     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72600     pTab = sqlite3FindTable(db, zRight, zDb);
72601     if( pTab ){
72602       int i;
72603       int nHidden = 0;
72604       Column *pCol;
72605       sqlite3VdbeSetNumCols(v, 6);
72606       pParse->nMem = 6;
72607       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
72608       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
72609       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
72610       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
72611       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
72612       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
72613       sqlite3ViewGetColumnNames(pParse, pTab);
72614       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
72615         const Token *pDflt;
72616         if( IsHiddenColumn(pCol) ){
72617           nHidden++;
72618           continue;
72619         }
72620         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
72621         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
72622         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
72623            pCol->zType ? pCol->zType : "", 0);
72624         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
72625         if( pCol->pDflt ){
72626           pDflt = &pCol->pDflt->span;
72627           assert( pDflt->z );
72628           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n);
72629         }else{
72630           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
72631         }
72632         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
72633         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
72634       }
72635     }
72636   }else
72637
72638   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
72639     Index *pIdx;
72640     Table *pTab;
72641     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72642     pIdx = sqlite3FindIndex(db, zRight, zDb);
72643     if( pIdx ){
72644       int i;
72645       pTab = pIdx->pTable;
72646       sqlite3VdbeSetNumCols(v, 3);
72647       pParse->nMem = 3;
72648       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
72649       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
72650       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
72651       for(i=0; i<pIdx->nColumn; i++){
72652         int cnum = pIdx->aiColumn[i];
72653         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
72654         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
72655         assert( pTab->nCol>cnum );
72656         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
72657         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
72658       }
72659     }
72660   }else
72661
72662   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
72663     Index *pIdx;
72664     Table *pTab;
72665     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72666     pTab = sqlite3FindTable(db, zRight, zDb);
72667     if( pTab ){
72668       v = sqlite3GetVdbe(pParse);
72669       pIdx = pTab->pIndex;
72670       if( pIdx ){
72671         int i = 0; 
72672         sqlite3VdbeSetNumCols(v, 3);
72673         pParse->nMem = 3;
72674         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
72675         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
72676         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
72677         while(pIdx){
72678           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
72679           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
72680           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
72681           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
72682           ++i;
72683           pIdx = pIdx->pNext;
72684         }
72685       }
72686     }
72687   }else
72688
72689   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
72690     int i;
72691     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72692     sqlite3VdbeSetNumCols(v, 3);
72693     pParse->nMem = 3;
72694     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
72695     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
72696     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
72697     for(i=0; i<db->nDb; i++){
72698       if( db->aDb[i].pBt==0 ) continue;
72699       assert( db->aDb[i].zName!=0 );
72700       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
72701       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
72702       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
72703            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
72704       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
72705     }
72706   }else
72707
72708   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
72709     int i = 0;
72710     HashElem *p;
72711     sqlite3VdbeSetNumCols(v, 2);
72712     pParse->nMem = 2;
72713     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
72714     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
72715     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
72716       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
72717       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
72718       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
72719       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
72720     }
72721   }else
72722 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
72723
72724 #ifndef SQLITE_OMIT_FOREIGN_KEY
72725   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
72726     FKey *pFK;
72727     Table *pTab;
72728     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72729     pTab = sqlite3FindTable(db, zRight, zDb);
72730     if( pTab ){
72731       v = sqlite3GetVdbe(pParse);
72732       pFK = pTab->pFKey;
72733       if( pFK ){
72734         int i = 0; 
72735         sqlite3VdbeSetNumCols(v, 8);
72736         pParse->nMem = 8;
72737         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
72738         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
72739         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
72740         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
72741         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
72742         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
72743         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
72744         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
72745         while(pFK){
72746           int j;
72747           for(j=0; j<pFK->nCol; j++){
72748             char *zCol = pFK->aCol[j].zCol;
72749             char *zOnUpdate = (char *)actionName(pFK->updateConf);
72750             char *zOnDelete = (char *)actionName(pFK->deleteConf);
72751             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
72752             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
72753             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
72754             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
72755                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
72756             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
72757             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
72758             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
72759             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
72760             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
72761           }
72762           ++i;
72763           pFK = pFK->pNextFrom;
72764         }
72765       }
72766     }
72767   }else
72768 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
72769
72770 #ifndef NDEBUG
72771   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
72772     if( zRight ){
72773       if( getBoolean(zRight) ){
72774         sqlite3ParserTrace(stderr, "parser: ");
72775       }else{
72776         sqlite3ParserTrace(0, 0);
72777       }
72778     }
72779   }else
72780 #endif
72781
72782   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
72783   ** used will be case sensitive or not depending on the RHS.
72784   */
72785   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
72786     if( zRight ){
72787       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
72788     }
72789   }else
72790
72791 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
72792 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
72793 #endif
72794
72795 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
72796   /* Pragma "quick_check" is an experimental reduced version of 
72797   ** integrity_check designed to detect most database corruption
72798   ** without most of the overhead of a full integrity-check.
72799   */
72800   if( sqlite3StrICmp(zLeft, "integrity_check")==0
72801    || sqlite3StrICmp(zLeft, "quick_check")==0 
72802   ){
72803     int i, j, addr, mxErr;
72804
72805     /* Code that appears at the end of the integrity check.  If no error
72806     ** messages have been generated, output OK.  Otherwise output the
72807     ** error message
72808     */
72809     static const VdbeOpList endCode[] = {
72810       { OP_AddImm,      1, 0,        0},    /* 0 */
72811       { OP_IfNeg,       1, 0,        0},    /* 1 */
72812       { OP_String8,     0, 3,        0},    /* 2 */
72813       { OP_ResultRow,   3, 1,        0},
72814     };
72815
72816     int isQuick = (zLeft[0]=='q');
72817
72818     /* Initialize the VDBE program */
72819     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
72820     pParse->nMem = 6;
72821     sqlite3VdbeSetNumCols(v, 1);
72822     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
72823
72824     /* Set the maximum error count */
72825     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
72826     if( zRight ){
72827       mxErr = atoi(zRight);
72828       if( mxErr<=0 ){
72829         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
72830       }
72831     }
72832     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
72833
72834     /* Do an integrity check on each database file */
72835     for(i=0; i<db->nDb; i++){
72836       HashElem *x;
72837       Hash *pTbls;
72838       int cnt = 0;
72839
72840       if( OMIT_TEMPDB && i==1 ) continue;
72841
72842       sqlite3CodeVerifySchema(pParse, i);
72843       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
72844       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
72845       sqlite3VdbeJumpHere(v, addr);
72846
72847       /* Do an integrity check of the B-Tree
72848       **
72849       ** Begin by filling registers 2, 3, ... with the root pages numbers
72850       ** for all tables and indices in the database.
72851       */
72852       pTbls = &db->aDb[i].pSchema->tblHash;
72853       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
72854         Table *pTab = sqliteHashData(x);
72855         Index *pIdx;
72856         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
72857         cnt++;
72858         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72859           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
72860           cnt++;
72861         }
72862       }
72863       if( cnt==0 ) continue;
72864
72865       /* Make sure sufficient number of registers have been allocated */
72866       if( pParse->nMem < cnt+4 ){
72867         pParse->nMem = cnt+4;
72868       }
72869
72870       /* Do the b-tree integrity checks */
72871       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
72872       sqlite3VdbeChangeP5(v, (u8)i);
72873       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
72874       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
72875          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
72876          P4_DYNAMIC);
72877       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
72878       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
72879       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
72880       sqlite3VdbeJumpHere(v, addr);
72881
72882       /* Make sure all the indices are constructed correctly.
72883       */
72884       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
72885         Table *pTab = sqliteHashData(x);
72886         Index *pIdx;
72887         int loopTop;
72888
72889         if( pTab->pIndex==0 ) continue;
72890         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
72891         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
72892         sqlite3VdbeJumpHere(v, addr);
72893         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
72894         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
72895         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
72896         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
72897         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
72898           int jmp2;
72899           static const VdbeOpList idxErr[] = {
72900             { OP_AddImm,      1, -1,  0},
72901             { OP_String8,     0,  3,  0},    /* 1 */
72902             { OP_Rowid,       1,  4,  0},
72903             { OP_String8,     0,  5,  0},    /* 3 */
72904             { OP_String8,     0,  6,  0},    /* 4 */
72905             { OP_Concat,      4,  3,  3},
72906             { OP_Concat,      5,  3,  3},
72907             { OP_Concat,      6,  3,  3},
72908             { OP_ResultRow,   3,  1,  0},
72909             { OP_IfPos,       1,  0,  0},    /* 9 */
72910             { OP_Halt,        0,  0,  0},
72911           };
72912           sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1);
72913           jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3);
72914           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
72915           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
72916           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
72917           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
72918           sqlite3VdbeJumpHere(v, addr+9);
72919           sqlite3VdbeJumpHere(v, jmp2);
72920         }
72921         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
72922         sqlite3VdbeJumpHere(v, loopTop);
72923         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
72924           static const VdbeOpList cntIdx[] = {
72925              { OP_Integer,      0,  3,  0},
72926              { OP_Rewind,       0,  0,  0},  /* 1 */
72927              { OP_AddImm,       3,  1,  0},
72928              { OP_Next,         0,  0,  0},  /* 3 */
72929              { OP_Eq,           2,  0,  3},  /* 4 */
72930              { OP_AddImm,       1, -1,  0},
72931              { OP_String8,      0,  2,  0},  /* 6 */
72932              { OP_String8,      0,  3,  0},  /* 7 */
72933              { OP_Concat,       3,  2,  2},
72934              { OP_ResultRow,    2,  1,  0},
72935           };
72936           if( pIdx->tnum==0 ) continue;
72937           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
72938           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
72939           sqlite3VdbeJumpHere(v, addr);
72940           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
72941           sqlite3VdbeChangeP1(v, addr+1, j+2);
72942           sqlite3VdbeChangeP2(v, addr+1, addr+4);
72943           sqlite3VdbeChangeP1(v, addr+3, j+2);
72944           sqlite3VdbeChangeP2(v, addr+3, addr+2);
72945           sqlite3VdbeJumpHere(v, addr+4);
72946           sqlite3VdbeChangeP4(v, addr+6, 
72947                      "wrong # of entries in index ", P4_STATIC);
72948           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
72949         }
72950       } 
72951     }
72952     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
72953     sqlite3VdbeChangeP2(v, addr, -mxErr);
72954     sqlite3VdbeJumpHere(v, addr+1);
72955     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
72956   }else
72957 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
72958
72959 #ifndef SQLITE_OMIT_UTF16
72960   /*
72961   **   PRAGMA encoding
72962   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
72963   **
72964   ** In its first form, this pragma returns the encoding of the main
72965   ** database. If the database is not initialized, it is initialized now.
72966   **
72967   ** The second form of this pragma is a no-op if the main database file
72968   ** has not already been initialized. In this case it sets the default
72969   ** encoding that will be used for the main database file if a new file
72970   ** is created. If an existing main database file is opened, then the
72971   ** default text encoding for the existing database is used.
72972   ** 
72973   ** In all cases new databases created using the ATTACH command are
72974   ** created to use the same default text encoding as the main database. If
72975   ** the main database has not been initialized and/or created when ATTACH
72976   ** is executed, this is done before the ATTACH operation.
72977   **
72978   ** In the second form this pragma sets the text encoding to be used in
72979   ** new database files created using this database handle. It is only
72980   ** useful if invoked immediately after the main database i
72981   */
72982   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
72983     static const struct EncName {
72984       char *zName;
72985       u8 enc;
72986     } encnames[] = {
72987       { "UTF8",     SQLITE_UTF8        },
72988       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
72989       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
72990       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
72991       { "UTF16le",  SQLITE_UTF16LE     },
72992       { "UTF16be",  SQLITE_UTF16BE     },
72993       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
72994       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
72995       { 0, 0 }
72996     };
72997     const struct EncName *pEnc;
72998     if( !zRight ){    /* "PRAGMA encoding" */
72999       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
73000       sqlite3VdbeSetNumCols(v, 1);
73001       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
73002       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
73003       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
73004       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
73005       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
73006       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
73007       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
73008     }else{                        /* "PRAGMA encoding = XXX" */
73009       /* Only change the value of sqlite.enc if the database handle is not
73010       ** initialized. If the main database exists, the new sqlite.enc value
73011       ** will be overwritten when the schema is next loaded. If it does not
73012       ** already exists, it will be created to use the new encoding value.
73013       */
73014       if( 
73015         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
73016         DbHasProperty(db, 0, DB_Empty) 
73017       ){
73018         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
73019           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
73020             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
73021             break;
73022           }
73023         }
73024         if( !pEnc->zName ){
73025           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
73026         }
73027       }
73028     }
73029   }else
73030 #endif /* SQLITE_OMIT_UTF16 */
73031
73032 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
73033   /*
73034   **   PRAGMA [database.]schema_version
73035   **   PRAGMA [database.]schema_version = <integer>
73036   **
73037   **   PRAGMA [database.]user_version
73038   **   PRAGMA [database.]user_version = <integer>
73039   **
73040   ** The pragma's schema_version and user_version are used to set or get
73041   ** the value of the schema-version and user-version, respectively. Both
73042   ** the schema-version and the user-version are 32-bit signed integers
73043   ** stored in the database header.
73044   **
73045   ** The schema-cookie is usually only manipulated internally by SQLite. It
73046   ** is incremented by SQLite whenever the database schema is modified (by
73047   ** creating or dropping a table or index). The schema version is used by
73048   ** SQLite each time a query is executed to ensure that the internal cache
73049   ** of the schema used when compiling the SQL query matches the schema of
73050   ** the database against which the compiled query is actually executed.
73051   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
73052   ** the schema-version is potentially dangerous and may lead to program
73053   ** crashes or database corruption. Use with caution!
73054   **
73055   ** The user-version is not used internally by SQLite. It may be used by
73056   ** applications for any purpose.
73057   */
73058   if( sqlite3StrICmp(zLeft, "schema_version")==0 
73059    || sqlite3StrICmp(zLeft, "user_version")==0 
73060    || sqlite3StrICmp(zLeft, "freelist_count")==0 
73061   ){
73062     int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
73063     sqlite3VdbeUsesBtree(v, iDb);
73064     switch( zLeft[0] ){
73065       case 's': case 'S':
73066         iCookie = 0;
73067         break;
73068       case 'f': case 'F':
73069         iCookie = 1;
73070         iDb = (-1*(iDb+1));
73071         assert(iDb<=0);
73072         break;
73073       default:
73074         iCookie = 5;
73075         break;
73076     }
73077
73078     if( zRight && iDb>=0 ){
73079       /* Write the specified cookie value */
73080       static const VdbeOpList setCookie[] = {
73081         { OP_Transaction,    0,  1,  0},    /* 0 */
73082         { OP_Integer,        0,  1,  0},    /* 1 */
73083         { OP_SetCookie,      0,  0,  1},    /* 2 */
73084       };
73085       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
73086       sqlite3VdbeChangeP1(v, addr, iDb);
73087       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
73088       sqlite3VdbeChangeP1(v, addr+2, iDb);
73089       sqlite3VdbeChangeP2(v, addr+2, iCookie);
73090     }else{
73091       /* Read the specified cookie value */
73092       static const VdbeOpList readCookie[] = {
73093         { OP_ReadCookie,      0,  1,  0},    /* 0 */
73094         { OP_ResultRow,       1,  1,  0}
73095       };
73096       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
73097       sqlite3VdbeChangeP1(v, addr, iDb);
73098       sqlite3VdbeChangeP3(v, addr, iCookie);
73099       sqlite3VdbeSetNumCols(v, 1);
73100       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
73101     }
73102   }else
73103 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
73104
73105 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
73106   /*
73107   ** Report the current state of file logs for all databases
73108   */
73109   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
73110     static const char *const azLockName[] = {
73111       "unlocked", "shared", "reserved", "pending", "exclusive"
73112     };
73113     int i;
73114     sqlite3VdbeSetNumCols(v, 2);
73115     pParse->nMem = 2;
73116     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
73117     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
73118     for(i=0; i<db->nDb; i++){
73119       Btree *pBt;
73120       Pager *pPager;
73121       const char *zState = "unknown";
73122       int j;
73123       if( db->aDb[i].zName==0 ) continue;
73124       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
73125       pBt = db->aDb[i].pBt;
73126       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
73127         zState = "closed";
73128       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
73129                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
73130          zState = azLockName[j];
73131       }
73132       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
73133       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
73134     }
73135
73136   }else
73137 #endif
73138
73139 #ifdef SQLITE_SSE
73140   /*
73141   ** Check to see if the sqlite_statements table exists.  Create it
73142   ** if it does not.
73143   */
73144   if( sqlite3StrICmp(zLeft, "create_sqlite_statement_table")==0 ){
73145     extern int sqlite3CreateStatementsTable(Parse*);
73146     sqlite3CreateStatementsTable(pParse);
73147   }else
73148 #endif
73149
73150 #if SQLITE_HAS_CODEC
73151   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
73152     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
73153   }else
73154   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
73155     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
73156   }else
73157   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
73158                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
73159     int i, h1, h2;
73160     char zKey[40];
73161     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
73162       h1 += 9*(1&(h1>>6));
73163       h2 += 9*(1&(h2>>6));
73164       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
73165     }
73166     if( (zLeft[3] & 0xf)==0xb ){
73167       sqlite3_key(db, zKey, i/2);
73168     }else{
73169       sqlite3_rekey(db, zKey, i/2);
73170     }
73171   }else
73172 #endif
73173 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
73174   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
73175 #if SQLITE_HAS_CODEC
73176     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
73177       extern void sqlite3_activate_see(const char*);
73178       sqlite3_activate_see(&zRight[4]);
73179     }
73180 #endif
73181 #ifdef SQLITE_ENABLE_CEROD
73182     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
73183       extern void sqlite3_activate_cerod(const char*);
73184       sqlite3_activate_cerod(&zRight[6]);
73185     }
73186 #endif
73187   }else
73188 #endif
73189
73190  
73191   {/* Empty ELSE clause */}
73192
73193   /* Code an OP_Expire at the end of each PRAGMA program to cause
73194   ** the VDBE implementing the pragma to expire. Most (all?) pragmas
73195   ** are only valid for a single execution.
73196   */
73197   sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
73198
73199   /*
73200   ** Reset the safety level, in case the fullfsync flag or synchronous
73201   ** setting changed.
73202   */
73203 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
73204   if( db->autoCommit ){
73205     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
73206                (db->flags&SQLITE_FullFSync)!=0);
73207   }
73208 #endif
73209 pragma_out:
73210   sqlite3DbFree(db, zLeft);
73211   sqlite3DbFree(db, zRight);
73212 }
73213
73214 #endif /* SQLITE_OMIT_PRAGMA || SQLITE_OMIT_PARSER */
73215
73216 /************** End of pragma.c **********************************************/
73217 /************** Begin file prepare.c *****************************************/
73218 /*
73219 ** 2005 May 25
73220 **
73221 ** The author disclaims copyright to this source code.  In place of
73222 ** a legal notice, here is a blessing:
73223 **
73224 **    May you do good and not evil.
73225 **    May you find forgiveness for yourself and forgive others.
73226 **    May you share freely, never taking more than you give.
73227 **
73228 *************************************************************************
73229 ** This file contains the implementation of the sqlite3_prepare()
73230 ** interface, and routines that contribute to loading the database schema
73231 ** from disk.
73232 **
73233 ** $Id: prepare.c,v 1.105 2009/01/20 16:53:41 danielk1977 Exp $
73234 */
73235
73236 /*
73237 ** Fill the InitData structure with an error message that indicates
73238 ** that the database is corrupt.
73239 */
73240 static void corruptSchema(
73241   InitData *pData,     /* Initialization context */
73242   const char *zObj,    /* Object being parsed at the point of error */
73243   const char *zExtra   /* Error information */
73244 ){
73245   sqlite3 *db = pData->db;
73246   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
73247     if( zObj==0 ) zObj = "?";
73248     sqlite3SetString(pData->pzErrMsg, pData->db,
73249        "malformed database schema (%s)", zObj);
73250     if( zExtra && zExtra[0] ){
73251       *pData->pzErrMsg = sqlite3MAppendf(pData->db, *pData->pzErrMsg, "%s - %s",
73252                                   *pData->pzErrMsg, zExtra);
73253     }
73254   }
73255   pData->rc = SQLITE_CORRUPT;
73256 }
73257
73258 /*
73259 ** This is the callback routine for the code that initializes the
73260 ** database.  See sqlite3Init() below for additional information.
73261 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
73262 **
73263 ** Each callback contains the following information:
73264 **
73265 **     argv[0] = name of thing being created
73266 **     argv[1] = root page number for table or index. 0 for trigger or view.
73267 **     argv[2] = SQL text for the CREATE statement.
73268 **
73269 */
73270 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
73271   InitData *pData = (InitData*)pInit;
73272   sqlite3 *db = pData->db;
73273   int iDb = pData->iDb;
73274
73275   assert( argc==3 );
73276   UNUSED_PARAMETER2(NotUsed, argc);
73277   assert( sqlite3_mutex_held(db->mutex) );
73278   DbClearProperty(db, iDb, DB_Empty);
73279   if( db->mallocFailed ){
73280     corruptSchema(pData, argv[0], 0);
73281     return SQLITE_NOMEM;
73282   }
73283
73284   assert( iDb>=0 && iDb<db->nDb );
73285   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
73286   if( argv[1]==0 ){
73287     corruptSchema(pData, argv[0], 0);
73288   }else if( argv[2] && argv[2][0] ){
73289     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
73290     ** But because db->init.busy is set to 1, no VDBE code is generated
73291     ** or executed.  All the parser does is build the internal data
73292     ** structures that describe the table, index, or view.
73293     */
73294     char *zErr;
73295     int rc;
73296     u8 lookasideEnabled;
73297     assert( db->init.busy );
73298     db->init.iDb = iDb;
73299     db->init.newTnum = atoi(argv[1]);
73300     lookasideEnabled = db->lookaside.bEnabled;
73301     db->lookaside.bEnabled = 0;
73302     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
73303     db->init.iDb = 0;
73304     db->lookaside.bEnabled = lookasideEnabled;
73305     assert( rc!=SQLITE_OK || zErr==0 );
73306     if( SQLITE_OK!=rc ){
73307       pData->rc = rc;
73308       if( rc==SQLITE_NOMEM ){
73309         db->mallocFailed = 1;
73310       }else if( rc!=SQLITE_INTERRUPT ){
73311         corruptSchema(pData, argv[0], zErr);
73312       }
73313       sqlite3DbFree(db, zErr);
73314     }
73315   }else if( argv[0]==0 ){
73316     corruptSchema(pData, 0, 0);
73317   }else{
73318     /* If the SQL column is blank it means this is an index that
73319     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
73320     ** constraint for a CREATE TABLE.  The index should have already
73321     ** been created when we processed the CREATE TABLE.  All we have
73322     ** to do here is record the root page number for that index.
73323     */
73324     Index *pIndex;
73325     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
73326     if( pIndex==0 || pIndex->tnum!=0 ){
73327       /* This can occur if there exists an index on a TEMP table which
73328       ** has the same name as another index on a permanent index.  Since
73329       ** the permanent table is hidden by the TEMP table, we can also
73330       ** safely ignore the index on the permanent table.
73331       */
73332       /* Do Nothing */;
73333     }else{
73334       pIndex->tnum = atoi(argv[1]);
73335     }
73336   }
73337   return 0;
73338 }
73339
73340 /*
73341 ** Attempt to read the database schema and initialize internal
73342 ** data structures for a single database file.  The index of the
73343 ** database file is given by iDb.  iDb==0 is used for the main
73344 ** database.  iDb==1 should never be used.  iDb>=2 is used for
73345 ** auxiliary databases.  Return one of the SQLITE_ error codes to
73346 ** indicate success or failure.
73347 */
73348 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
73349   int rc;
73350   BtCursor *curMain;
73351   int size;
73352   Table *pTab;
73353   Db *pDb;
73354   char const *azArg[4];
73355   int meta[10];
73356   InitData initData;
73357   char const *zMasterSchema;
73358   char const *zMasterName = SCHEMA_TABLE(iDb);
73359
73360   /*
73361   ** The master database table has a structure like this
73362   */
73363   static const char master_schema[] = 
73364      "CREATE TABLE sqlite_master(\n"
73365      "  type text,\n"
73366      "  name text,\n"
73367      "  tbl_name text,\n"
73368      "  rootpage integer,\n"
73369      "  sql text\n"
73370      ")"
73371   ;
73372 #ifndef SQLITE_OMIT_TEMPDB
73373   static const char temp_master_schema[] = 
73374      "CREATE TEMP TABLE sqlite_temp_master(\n"
73375      "  type text,\n"
73376      "  name text,\n"
73377      "  tbl_name text,\n"
73378      "  rootpage integer,\n"
73379      "  sql text\n"
73380      ")"
73381   ;
73382 #else
73383   #define temp_master_schema 0
73384 #endif
73385
73386   assert( iDb>=0 && iDb<db->nDb );
73387   assert( db->aDb[iDb].pSchema );
73388   assert( sqlite3_mutex_held(db->mutex) );
73389   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
73390
73391   /* zMasterSchema and zInitScript are set to point at the master schema
73392   ** and initialisation script appropriate for the database being
73393   ** initialised. zMasterName is the name of the master table.
73394   */
73395   if( !OMIT_TEMPDB && iDb==1 ){
73396     zMasterSchema = temp_master_schema;
73397   }else{
73398     zMasterSchema = master_schema;
73399   }
73400   zMasterName = SCHEMA_TABLE(iDb);
73401
73402   /* Construct the schema tables.  */
73403   azArg[0] = zMasterName;
73404   azArg[1] = "1";
73405   azArg[2] = zMasterSchema;
73406   azArg[3] = 0;
73407   initData.db = db;
73408   initData.iDb = iDb;
73409   initData.rc = SQLITE_OK;
73410   initData.pzErrMsg = pzErrMsg;
73411   (void)sqlite3SafetyOff(db);
73412   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
73413   (void)sqlite3SafetyOn(db);
73414   if( initData.rc ){
73415     rc = initData.rc;
73416     goto error_out;
73417   }
73418   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
73419   if( pTab ){
73420     pTab->tabFlags |= TF_Readonly;
73421   }
73422
73423   /* Create a cursor to hold the database open
73424   */
73425   pDb = &db->aDb[iDb];
73426   if( pDb->pBt==0 ){
73427     if( !OMIT_TEMPDB && iDb==1 ){
73428       DbSetProperty(db, 1, DB_SchemaLoaded);
73429     }
73430     return SQLITE_OK;
73431   }
73432   curMain = sqlite3MallocZero(sqlite3BtreeCursorSize());
73433   if( !curMain ){
73434     rc = SQLITE_NOMEM;
73435     goto error_out;
73436   }
73437   sqlite3BtreeEnter(pDb->pBt);
73438   rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
73439   if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
73440     sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73441     goto initone_error_out;
73442   }
73443
73444   /* Get the database meta information.
73445   **
73446   ** Meta values are as follows:
73447   **    meta[0]   Schema cookie.  Changes with each schema change.
73448   **    meta[1]   File format of schema layer.
73449   **    meta[2]   Size of the page cache.
73450   **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
73451   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
73452   **    meta[5]   The user cookie. Used by the application.
73453   **    meta[6]   Incremental-vacuum flag.
73454   **    meta[7]
73455   **    meta[8]
73456   **    meta[9]
73457   **
73458   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
73459   ** the possible values of meta[4].
73460   */
73461   if( rc==SQLITE_OK ){
73462     int i;
73463     for(i=0; i<ArraySize(meta); i++){
73464       rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
73465       if( rc ){
73466         sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73467         goto initone_error_out;
73468       }
73469     }
73470   }else{
73471     memset(meta, 0, sizeof(meta));
73472   }
73473   pDb->pSchema->schema_cookie = meta[0];
73474
73475   /* If opening a non-empty database, check the text encoding. For the
73476   ** main database, set sqlite3.enc to the encoding of the main database.
73477   ** For an attached db, it is an error if the encoding is not the same
73478   ** as sqlite3.enc.
73479   */
73480   if( meta[4] ){  /* text encoding */
73481     if( iDb==0 ){
73482       /* If opening the main database, set ENC(db). */
73483       ENC(db) = (u8)meta[4];
73484       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
73485     }else{
73486       /* If opening an attached database, the encoding much match ENC(db) */
73487       if( meta[4]!=ENC(db) ){
73488         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
73489             " text encoding as main database");
73490         rc = SQLITE_ERROR;
73491         goto initone_error_out;
73492       }
73493     }
73494   }else{
73495     DbSetProperty(db, iDb, DB_Empty);
73496   }
73497   pDb->pSchema->enc = ENC(db);
73498
73499   if( pDb->pSchema->cache_size==0 ){
73500     size = meta[2];
73501     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
73502     if( size<0 ) size = -size;
73503     pDb->pSchema->cache_size = size;
73504     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
73505   }
73506
73507   /*
73508   ** file_format==1    Version 3.0.0.
73509   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
73510   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
73511   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
73512   */
73513   pDb->pSchema->file_format = (u8)meta[1];
73514   if( pDb->pSchema->file_format==0 ){
73515     pDb->pSchema->file_format = 1;
73516   }
73517   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
73518     sqlite3SetString(pzErrMsg, db, "unsupported file format");
73519     rc = SQLITE_ERROR;
73520     goto initone_error_out;
73521   }
73522
73523   /* Ticket #2804:  When we open a database in the newer file format,
73524   ** clear the legacy_file_format pragma flag so that a VACUUM will
73525   ** not downgrade the database and thus invalidate any descending
73526   ** indices that the user might have created.
73527   */
73528   if( iDb==0 && meta[1]>=4 ){
73529     db->flags &= ~SQLITE_LegacyFileFmt;
73530   }
73531
73532   /* Read the schema information out of the schema tables
73533   */
73534   assert( db->init.busy );
73535   if( rc==SQLITE_EMPTY ){
73536     /* For an empty database, there is nothing to read */
73537     rc = SQLITE_OK;
73538   }else{
73539     char *zSql;
73540     zSql = sqlite3MPrintf(db, 
73541         "SELECT name, rootpage, sql FROM '%q'.%s",
73542         db->aDb[iDb].zName, zMasterName);
73543     (void)sqlite3SafetyOff(db);
73544 #ifndef SQLITE_OMIT_AUTHORIZATION
73545     {
73546       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
73547       xAuth = db->xAuth;
73548       db->xAuth = 0;
73549 #endif
73550       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
73551 #ifndef SQLITE_OMIT_AUTHORIZATION
73552       db->xAuth = xAuth;
73553     }
73554 #endif
73555     if( rc==SQLITE_OK ) rc = initData.rc;
73556     (void)sqlite3SafetyOn(db);
73557     sqlite3DbFree(db, zSql);
73558 #ifndef SQLITE_OMIT_ANALYZE
73559     if( rc==SQLITE_OK ){
73560       sqlite3AnalysisLoad(db, iDb);
73561     }
73562 #endif
73563   }
73564   if( db->mallocFailed ){
73565     rc = SQLITE_NOMEM;
73566     sqlite3ResetInternalSchema(db, 0);
73567   }
73568   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
73569     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
73570     ** the schema loaded, even if errors occured. In this situation the 
73571     ** current sqlite3_prepare() operation will fail, but the following one
73572     ** will attempt to compile the supplied statement against whatever subset
73573     ** of the schema was loaded before the error occured. The primary
73574     ** purpose of this is to allow access to the sqlite_master table
73575     ** even when its contents have been corrupted.
73576     */
73577     DbSetProperty(db, iDb, DB_SchemaLoaded);
73578     rc = SQLITE_OK;
73579   }
73580
73581   /* Jump here for an error that occurs after successfully allocating
73582   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
73583   ** before that point, jump to error_out.
73584   */
73585 initone_error_out:
73586   sqlite3BtreeCloseCursor(curMain);
73587   sqlite3_free(curMain);
73588   sqlite3BtreeLeave(pDb->pBt);
73589
73590 error_out:
73591   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
73592     db->mallocFailed = 1;
73593   }
73594   return rc;
73595 }
73596
73597 /*
73598 ** Initialize all database files - the main database file, the file
73599 ** used to store temporary tables, and any additional database files
73600 ** created using ATTACH statements.  Return a success code.  If an
73601 ** error occurs, write an error message into *pzErrMsg.
73602 **
73603 ** After a database is initialized, the DB_SchemaLoaded bit is set
73604 ** bit is set in the flags field of the Db structure. If the database
73605 ** file was of zero-length, then the DB_Empty flag is also set.
73606 */
73607 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
73608   int i, rc;
73609   int commit_internal = !(db->flags&SQLITE_InternChanges);
73610   
73611   assert( sqlite3_mutex_held(db->mutex) );
73612   if( db->init.busy ) return SQLITE_OK;
73613   rc = SQLITE_OK;
73614   db->init.busy = 1;
73615   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
73616     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
73617     rc = sqlite3InitOne(db, i, pzErrMsg);
73618     if( rc ){
73619       sqlite3ResetInternalSchema(db, i);
73620     }
73621   }
73622
73623   /* Once all the other databases have been initialised, load the schema
73624   ** for the TEMP database. This is loaded last, as the TEMP database
73625   ** schema may contain references to objects in other databases.
73626   */
73627 #ifndef SQLITE_OMIT_TEMPDB
73628   if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
73629     rc = sqlite3InitOne(db, 1, pzErrMsg);
73630     if( rc ){
73631       sqlite3ResetInternalSchema(db, 1);
73632     }
73633   }
73634 #endif
73635
73636   db->init.busy = 0;
73637   if( rc==SQLITE_OK && commit_internal ){
73638     sqlite3CommitInternalChanges(db);
73639   }
73640
73641   return rc; 
73642 }
73643
73644 /*
73645 ** This routine is a no-op if the database schema is already initialised.
73646 ** Otherwise, the schema is loaded. An error code is returned.
73647 */
73648 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
73649   int rc = SQLITE_OK;
73650   sqlite3 *db = pParse->db;
73651   assert( sqlite3_mutex_held(db->mutex) );
73652   if( !db->init.busy ){
73653     rc = sqlite3Init(db, &pParse->zErrMsg);
73654   }
73655   if( rc!=SQLITE_OK ){
73656     pParse->rc = rc;
73657     pParse->nErr++;
73658   }
73659   return rc;
73660 }
73661
73662
73663 /*
73664 ** Check schema cookies in all databases.  If any cookie is out
73665 ** of date, return 0.  If all schema cookies are current, return 1.
73666 */
73667 static int schemaIsValid(sqlite3 *db){
73668   int iDb;
73669   int rc;
73670   BtCursor *curTemp;
73671   int cookie;
73672   int allOk = 1;
73673
73674   curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize());
73675   if( curTemp ){
73676     assert( sqlite3_mutex_held(db->mutex) );
73677     for(iDb=0; allOk && iDb<db->nDb; iDb++){
73678       Btree *pBt;
73679       pBt = db->aDb[iDb].pBt;
73680       if( pBt==0 ) continue;
73681       memset(curTemp, 0, sqlite3BtreeCursorSize());
73682       rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp);
73683       if( rc==SQLITE_OK ){
73684         rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie);
73685         if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){
73686           allOk = 0;
73687         }
73688         sqlite3BtreeCloseCursor(curTemp);
73689       }
73690       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
73691         db->mallocFailed = 1;
73692       }
73693     }
73694     sqlite3_free(curTemp);
73695   }else{
73696     allOk = 0;
73697     db->mallocFailed = 1;
73698   }
73699
73700   return allOk;
73701 }
73702
73703 /*
73704 ** Convert a schema pointer into the iDb index that indicates
73705 ** which database file in db->aDb[] the schema refers to.
73706 **
73707 ** If the same database is attached more than once, the first
73708 ** attached database is returned.
73709 */
73710 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
73711   int i = -1000000;
73712
73713   /* If pSchema is NULL, then return -1000000. This happens when code in 
73714   ** expr.c is trying to resolve a reference to a transient table (i.e. one
73715   ** created by a sub-select). In this case the return value of this 
73716   ** function should never be used.
73717   **
73718   ** We return -1000000 instead of the more usual -1 simply because using
73719   ** -1000000 as the incorrect index into db->aDb[] is much 
73720   ** more likely to cause a segfault than -1 (of course there are assert()
73721   ** statements too, but it never hurts to play the odds).
73722   */
73723   assert( sqlite3_mutex_held(db->mutex) );
73724   if( pSchema ){
73725     for(i=0; ALWAYS(i<db->nDb); i++){
73726       if( db->aDb[i].pSchema==pSchema ){
73727         break;
73728       }
73729     }
73730     assert( i>=0 && i<db->nDb );
73731   }
73732   return i;
73733 }
73734
73735 /*
73736 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
73737 */
73738 static int sqlite3Prepare(
73739   sqlite3 *db,              /* Database handle. */
73740   const char *zSql,         /* UTF-8 encoded SQL statement. */
73741   int nBytes,               /* Length of zSql in bytes. */
73742   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
73743   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
73744   const char **pzTail       /* OUT: End of parsed string */
73745 ){
73746   Parse sParse;
73747   char *zErrMsg = 0;
73748   int rc = SQLITE_OK;
73749   int i;
73750
73751   assert( ppStmt );
73752   *ppStmt = 0;
73753   if( sqlite3SafetyOn(db) ){
73754     return SQLITE_MISUSE;
73755   }
73756   assert( !db->mallocFailed );
73757   assert( sqlite3_mutex_held(db->mutex) );
73758
73759   /* If any attached database schemas are locked, do not proceed with
73760   ** compilation. Instead return SQLITE_LOCKED immediately.
73761   */
73762   for(i=0; i<db->nDb; i++) {
73763     Btree *pBt = db->aDb[i].pBt;
73764     if( pBt ){
73765       rc = sqlite3BtreeSchemaLocked(pBt);
73766       if( rc ){
73767         const char *zDb = db->aDb[i].zName;
73768         sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb);
73769         (void)sqlite3SafetyOff(db);
73770         return sqlite3ApiExit(db, SQLITE_LOCKED);
73771       }
73772     }
73773   }
73774   
73775   memset(&sParse, 0, sizeof(sParse));
73776   sParse.db = db;
73777   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
73778     char *zSqlCopy;
73779     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
73780     if( nBytes>mxLen ){
73781       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
73782       (void)sqlite3SafetyOff(db);
73783       return sqlite3ApiExit(db, SQLITE_TOOBIG);
73784     }
73785     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
73786     if( zSqlCopy ){
73787       sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
73788       sqlite3DbFree(db, zSqlCopy);
73789       sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
73790     }else{
73791       sParse.zTail = &zSql[nBytes];
73792     }
73793   }else{
73794     sqlite3RunParser(&sParse, zSql, &zErrMsg);
73795   }
73796
73797   if( db->mallocFailed ){
73798     sParse.rc = SQLITE_NOMEM;
73799   }
73800   if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
73801   if( sParse.checkSchema && !schemaIsValid(db) ){
73802     sParse.rc = SQLITE_SCHEMA;
73803   }
73804   if( sParse.rc==SQLITE_SCHEMA ){
73805     sqlite3ResetInternalSchema(db, 0);
73806   }
73807   if( db->mallocFailed ){
73808     sParse.rc = SQLITE_NOMEM;
73809   }
73810   if( pzTail ){
73811     *pzTail = sParse.zTail;
73812   }
73813   rc = sParse.rc;
73814
73815 #ifndef SQLITE_OMIT_EXPLAIN
73816   if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
73817     if( sParse.explain==2 ){
73818       sqlite3VdbeSetNumCols(sParse.pVdbe, 3);
73819       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", SQLITE_STATIC);
73820       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", SQLITE_STATIC);
73821       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", SQLITE_STATIC);
73822     }else{
73823       sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
73824       sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", SQLITE_STATIC);
73825       sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", SQLITE_STATIC);
73826       sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", SQLITE_STATIC);
73827       sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", SQLITE_STATIC);
73828       sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", SQLITE_STATIC);
73829       sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", SQLITE_STATIC);
73830       sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", SQLITE_STATIC);
73831       sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment", SQLITE_STATIC);
73832     }
73833   }
73834 #endif
73835
73836   if( sqlite3SafetyOff(db) ){
73837     rc = SQLITE_MISUSE;
73838   }
73839
73840   if( saveSqlFlag ){
73841     sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail - zSql));
73842   }
73843   if( rc!=SQLITE_OK || db->mallocFailed ){
73844     sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
73845     assert(!(*ppStmt));
73846   }else{
73847     *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
73848   }
73849
73850   if( zErrMsg ){
73851     sqlite3Error(db, rc, "%s", zErrMsg);
73852     sqlite3DbFree(db, zErrMsg);
73853   }else{
73854     sqlite3Error(db, rc, 0);
73855   }
73856
73857   rc = sqlite3ApiExit(db, rc);
73858   assert( (rc&db->errMask)==rc );
73859   return rc;
73860 }
73861 static int sqlite3LockAndPrepare(
73862   sqlite3 *db,              /* Database handle. */
73863   const char *zSql,         /* UTF-8 encoded SQL statement. */
73864   int nBytes,               /* Length of zSql in bytes. */
73865   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
73866   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
73867   const char **pzTail       /* OUT: End of parsed string */
73868 ){
73869   int rc;
73870   if( !sqlite3SafetyCheckOk(db) ){
73871     return SQLITE_MISUSE;
73872   }
73873   sqlite3_mutex_enter(db->mutex);
73874   sqlite3BtreeEnterAll(db);
73875   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail);
73876   sqlite3BtreeLeaveAll(db);
73877   sqlite3_mutex_leave(db->mutex);
73878   return rc;
73879 }
73880
73881 /*
73882 ** Rerun the compilation of a statement after a schema change.
73883 ** Return true if the statement was recompiled successfully.
73884 ** Return false if there is an error of some kind.
73885 */
73886 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
73887   int rc;
73888   sqlite3_stmt *pNew;
73889   const char *zSql;
73890   sqlite3 *db;
73891
73892   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
73893   zSql = sqlite3_sql((sqlite3_stmt *)p);
73894   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
73895   db = sqlite3VdbeDb(p);
73896   assert( sqlite3_mutex_held(db->mutex) );
73897   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0);
73898   if( rc ){
73899     if( rc==SQLITE_NOMEM ){
73900       db->mallocFailed = 1;
73901     }
73902     assert( pNew==0 );
73903     return 0;
73904   }else{
73905     assert( pNew!=0 );
73906   }
73907   sqlite3VdbeSwap((Vdbe*)pNew, p);
73908   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
73909   sqlite3VdbeResetStepResult((Vdbe*)pNew);
73910   sqlite3VdbeFinalize((Vdbe*)pNew);
73911   return 1;
73912 }
73913
73914
73915 /*
73916 ** Two versions of the official API.  Legacy and new use.  In the legacy
73917 ** version, the original SQL text is not saved in the prepared statement
73918 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
73919 ** sqlite3_step().  In the new version, the original SQL text is retained
73920 ** and the statement is automatically recompiled if an schema change
73921 ** occurs.
73922 */
73923 SQLITE_API int sqlite3_prepare(
73924   sqlite3 *db,              /* Database handle. */
73925   const char *zSql,         /* UTF-8 encoded SQL statement. */
73926   int nBytes,               /* Length of zSql in bytes. */
73927   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
73928   const char **pzTail       /* OUT: End of parsed string */
73929 ){
73930   int rc;
73931   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail);
73932   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
73933   return rc;
73934 }
73935 SQLITE_API int sqlite3_prepare_v2(
73936   sqlite3 *db,              /* Database handle. */
73937   const char *zSql,         /* UTF-8 encoded SQL statement. */
73938   int nBytes,               /* Length of zSql in bytes. */
73939   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
73940   const char **pzTail       /* OUT: End of parsed string */
73941 ){
73942   int rc;
73943   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail);
73944   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
73945   return rc;
73946 }
73947
73948
73949 #ifndef SQLITE_OMIT_UTF16
73950 /*
73951 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
73952 */
73953 static int sqlite3Prepare16(
73954   sqlite3 *db,              /* Database handle. */ 
73955   const void *zSql,         /* UTF-8 encoded SQL statement. */
73956   int nBytes,               /* Length of zSql in bytes. */
73957   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
73958   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
73959   const void **pzTail       /* OUT: End of parsed string */
73960 ){
73961   /* This function currently works by first transforming the UTF-16
73962   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
73963   ** tricky bit is figuring out the pointer to return in *pzTail.
73964   */
73965   char *zSql8;
73966   const char *zTail8 = 0;
73967   int rc = SQLITE_OK;
73968
73969   if( !sqlite3SafetyCheckOk(db) ){
73970     return SQLITE_MISUSE;
73971   }
73972   sqlite3_mutex_enter(db->mutex);
73973   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
73974   if( zSql8 ){
73975     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, ppStmt, &zTail8);
73976   }
73977
73978   if( zTail8 && pzTail ){
73979     /* If sqlite3_prepare returns a tail pointer, we calculate the
73980     ** equivalent pointer into the UTF-16 string by counting the unicode
73981     ** characters between zSql8 and zTail8, and then returning a pointer
73982     ** the same number of characters into the UTF-16 string.
73983     */
73984     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
73985     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
73986   }
73987   sqlite3DbFree(db, zSql8); 
73988   rc = sqlite3ApiExit(db, rc);
73989   sqlite3_mutex_leave(db->mutex);
73990   return rc;
73991 }
73992
73993 /*
73994 ** Two versions of the official API.  Legacy and new use.  In the legacy
73995 ** version, the original SQL text is not saved in the prepared statement
73996 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
73997 ** sqlite3_step().  In the new version, the original SQL text is retained
73998 ** and the statement is automatically recompiled if an schema change
73999 ** occurs.
74000 */
74001 SQLITE_API int sqlite3_prepare16(
74002   sqlite3 *db,              /* Database handle. */ 
74003   const void *zSql,         /* UTF-8 encoded SQL statement. */
74004   int nBytes,               /* Length of zSql in bytes. */
74005   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
74006   const void **pzTail       /* OUT: End of parsed string */
74007 ){
74008   int rc;
74009   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
74010   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
74011   return rc;
74012 }
74013 SQLITE_API int sqlite3_prepare16_v2(
74014   sqlite3 *db,              /* Database handle. */ 
74015   const void *zSql,         /* UTF-8 encoded SQL statement. */
74016   int nBytes,               /* Length of zSql in bytes. */
74017   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
74018   const void **pzTail       /* OUT: End of parsed string */
74019 ){
74020   int rc;
74021   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
74022   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
74023   return rc;
74024 }
74025
74026 #endif /* SQLITE_OMIT_UTF16 */
74027
74028 /************** End of prepare.c *********************************************/
74029 /************** Begin file select.c ******************************************/
74030 /*
74031 ** 2001 September 15
74032 **
74033 ** The author disclaims copyright to this source code.  In place of
74034 ** a legal notice, here is a blessing:
74035 **
74036 **    May you do good and not evil.
74037 **    May you find forgiveness for yourself and forgive others.
74038 **    May you share freely, never taking more than you give.
74039 **
74040 *************************************************************************
74041 ** This file contains C code routines that are called by the parser
74042 ** to handle SELECT statements in SQLite.
74043 **
74044 ** $Id: select.c,v 1.499 2009/02/09 13:19:28 drh Exp $
74045 */
74046
74047
74048 /*
74049 ** Delete all the content of a Select structure but do not deallocate
74050 ** the select structure itself.
74051 */
74052 static void clearSelect(sqlite3 *db, Select *p){
74053   sqlite3ExprListDelete(db, p->pEList);
74054   sqlite3SrcListDelete(db, p->pSrc);
74055   sqlite3ExprDelete(db, p->pWhere);
74056   sqlite3ExprListDelete(db, p->pGroupBy);
74057   sqlite3ExprDelete(db, p->pHaving);
74058   sqlite3ExprListDelete(db, p->pOrderBy);
74059   sqlite3SelectDelete(db, p->pPrior);
74060   sqlite3ExprDelete(db, p->pLimit);
74061   sqlite3ExprDelete(db, p->pOffset);
74062 }
74063
74064 /*
74065 ** Initialize a SelectDest structure.
74066 */
74067 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
74068   pDest->eDest = (u8)eDest;
74069   pDest->iParm = iParm;
74070   pDest->affinity = 0;
74071   pDest->iMem = 0;
74072   pDest->nMem = 0;
74073 }
74074
74075
74076 /*
74077 ** Allocate a new Select structure and return a pointer to that
74078 ** structure.
74079 */
74080 SQLITE_PRIVATE Select *sqlite3SelectNew(
74081   Parse *pParse,        /* Parsing context */
74082   ExprList *pEList,     /* which columns to include in the result */
74083   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
74084   Expr *pWhere,         /* the WHERE clause */
74085   ExprList *pGroupBy,   /* the GROUP BY clause */
74086   Expr *pHaving,        /* the HAVING clause */
74087   ExprList *pOrderBy,   /* the ORDER BY clause */
74088   int isDistinct,       /* true if the DISTINCT keyword is present */
74089   Expr *pLimit,         /* LIMIT value.  NULL means not used */
74090   Expr *pOffset         /* OFFSET value.  NULL means no offset */
74091 ){
74092   Select *pNew;
74093   Select standin;
74094   sqlite3 *db = pParse->db;
74095   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
74096   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
74097   if( pNew==0 ){
74098     pNew = &standin;
74099     memset(pNew, 0, sizeof(*pNew));
74100   }
74101   if( pEList==0 ){
74102     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
74103   }
74104   pNew->pEList = pEList;
74105   pNew->pSrc = pSrc;
74106   pNew->pWhere = pWhere;
74107   pNew->pGroupBy = pGroupBy;
74108   pNew->pHaving = pHaving;
74109   pNew->pOrderBy = pOrderBy;
74110   pNew->selFlags = isDistinct ? SF_Distinct : 0;
74111   pNew->op = TK_SELECT;
74112   pNew->pLimit = pLimit;
74113   pNew->pOffset = pOffset;
74114   pNew->addrOpenEphm[0] = -1;
74115   pNew->addrOpenEphm[1] = -1;
74116   pNew->addrOpenEphm[2] = -1;
74117   if( db->mallocFailed ) {
74118     clearSelect(db, pNew);
74119     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
74120     pNew = 0;
74121   }
74122   return pNew;
74123 }
74124
74125 /*
74126 ** Delete the given Select structure and all of its substructures.
74127 */
74128 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
74129   if( p ){
74130     clearSelect(db, p);
74131     sqlite3DbFree(db, p);
74132   }
74133 }
74134
74135 /*
74136 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
74137 ** type of join.  Return an integer constant that expresses that type
74138 ** in terms of the following bit values:
74139 **
74140 **     JT_INNER
74141 **     JT_CROSS
74142 **     JT_OUTER
74143 **     JT_NATURAL
74144 **     JT_LEFT
74145 **     JT_RIGHT
74146 **
74147 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
74148 **
74149 ** If an illegal or unsupported join type is seen, then still return
74150 ** a join type, but put an error in the pParse structure.
74151 */
74152 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
74153   int jointype = 0;
74154   Token *apAll[3];
74155   Token *p;
74156   static const struct {
74157     const char zKeyword[8];
74158     u8 nChar;
74159     u8 code;
74160   } keywords[] = {
74161     { "natural", 7, JT_NATURAL },
74162     { "left",    4, JT_LEFT|JT_OUTER },
74163     { "right",   5, JT_RIGHT|JT_OUTER },
74164     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
74165     { "outer",   5, JT_OUTER },
74166     { "inner",   5, JT_INNER },
74167     { "cross",   5, JT_INNER|JT_CROSS },
74168   };
74169   int i, j;
74170   apAll[0] = pA;
74171   apAll[1] = pB;
74172   apAll[2] = pC;
74173   for(i=0; i<3 && apAll[i]; i++){
74174     p = apAll[i];
74175     for(j=0; j<ArraySize(keywords); j++){
74176       if( p->n==keywords[j].nChar 
74177           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
74178         jointype |= keywords[j].code;
74179         break;
74180       }
74181     }
74182     if( j>=ArraySize(keywords) ){
74183       jointype |= JT_ERROR;
74184       break;
74185     }
74186   }
74187   if(
74188      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
74189      (jointype & JT_ERROR)!=0
74190   ){
74191     const char *zSp = " ";
74192     assert( pB!=0 );
74193     if( pC==0 ){ zSp++; }
74194     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
74195        "%T %T%s%T", pA, pB, zSp, pC);
74196     jointype = JT_INNER;
74197   }else if( jointype & JT_RIGHT ){
74198     sqlite3ErrorMsg(pParse, 
74199       "RIGHT and FULL OUTER JOINs are not currently supported");
74200     jointype = JT_INNER;
74201   }
74202   return jointype;
74203 }
74204
74205 /*
74206 ** Return the index of a column in a table.  Return -1 if the column
74207 ** is not contained in the table.
74208 */
74209 static int columnIndex(Table *pTab, const char *zCol){
74210   int i;
74211   for(i=0; i<pTab->nCol; i++){
74212     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
74213   }
74214   return -1;
74215 }
74216
74217 /*
74218 ** Set the value of a token to a '\000'-terminated string.
74219 */
74220 static void setToken(Token *p, const char *z){
74221   p->z = (u8*)z;
74222   p->n = z ? sqlite3Strlen30(z) : 0;
74223   p->dyn = 0;
74224 }
74225
74226 /*
74227 ** Set the token to the double-quoted and escaped version of the string pointed
74228 ** to by z. For example;
74229 **
74230 **    {a"bc}  ->  {"a""bc"}
74231 */
74232 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
74233
74234   /* Check if the string appears to be quoted using "..." or `...`
74235   ** or [...] or '...' or if the string contains any " characters.  
74236   ** If it does, then record a version of the string with the special
74237   ** characters escaped.
74238   */
74239   const char *z2 = z;
74240   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
74241     while( *z2 ){
74242       if( *z2=='"' ) break;
74243       z2++;
74244     }
74245   }
74246
74247   if( *z2 ){
74248     /* String contains " characters - copy and quote the string. */
74249     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
74250     if( p->z ){
74251       p->n = sqlite3Strlen30((char *)p->z);
74252       p->dyn = 1;
74253     }
74254   }else{
74255     /* String contains no " characters - copy the pointer. */
74256     p->z = (u8*)z;
74257     p->n = (int)(z2 - z);
74258     p->dyn = 0;
74259   }
74260 }
74261
74262 /*
74263 ** Create an expression node for an identifier with the name of zName
74264 */
74265 SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
74266   Token dummy;
74267   setToken(&dummy, zName);
74268   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
74269 }
74270
74271 /*
74272 ** Add a term to the WHERE expression in *ppExpr that requires the
74273 ** zCol column to be equal in the two tables pTab1 and pTab2.
74274 */
74275 static void addWhereTerm(
74276   Parse *pParse,           /* Parsing context */
74277   const char *zCol,        /* Name of the column */
74278   const Table *pTab1,      /* First table */
74279   const char *zAlias1,     /* Alias for first table.  May be NULL */
74280   const Table *pTab2,      /* Second table */
74281   const char *zAlias2,     /* Alias for second table.  May be NULL */
74282   int iRightJoinTable,     /* VDBE cursor for the right table */
74283   Expr **ppExpr,           /* Add the equality term to this expression */
74284   int isOuterJoin          /* True if dealing with an OUTER join */
74285 ){
74286   Expr *pE1a, *pE1b, *pE1c;
74287   Expr *pE2a, *pE2b, *pE2c;
74288   Expr *pE;
74289
74290   pE1a = sqlite3CreateIdExpr(pParse, zCol);
74291   pE2a = sqlite3CreateIdExpr(pParse, zCol);
74292   if( zAlias1==0 ){
74293     zAlias1 = pTab1->zName;
74294   }
74295   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
74296   if( zAlias2==0 ){
74297     zAlias2 = pTab2->zName;
74298   }
74299   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
74300   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
74301   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
74302   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
74303   if( pE && isOuterJoin ){
74304     ExprSetProperty(pE, EP_FromJoin);
74305     pE->iRightJoinTable = iRightJoinTable;
74306   }
74307   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
74308 }
74309
74310 /*
74311 ** Set the EP_FromJoin property on all terms of the given expression.
74312 ** And set the Expr.iRightJoinTable to iTable for every term in the
74313 ** expression.
74314 **
74315 ** The EP_FromJoin property is used on terms of an expression to tell
74316 ** the LEFT OUTER JOIN processing logic that this term is part of the
74317 ** join restriction specified in the ON or USING clause and not a part
74318 ** of the more general WHERE clause.  These terms are moved over to the
74319 ** WHERE clause during join processing but we need to remember that they
74320 ** originated in the ON or USING clause.
74321 **
74322 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
74323 ** expression depends on table iRightJoinTable even if that table is not
74324 ** explicitly mentioned in the expression.  That information is needed
74325 ** for cases like this:
74326 **
74327 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
74328 **
74329 ** The where clause needs to defer the handling of the t1.x=5
74330 ** term until after the t2 loop of the join.  In that way, a
74331 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
74332 ** defer the handling of t1.x=5, it will be processed immediately
74333 ** after the t1 loop and rows with t1.x!=5 will never appear in
74334 ** the output, which is incorrect.
74335 */
74336 static void setJoinExpr(Expr *p, int iTable){
74337   while( p ){
74338     ExprSetProperty(p, EP_FromJoin);
74339     p->iRightJoinTable = iTable;
74340     setJoinExpr(p->pLeft, iTable);
74341     p = p->pRight;
74342   } 
74343 }
74344
74345 /*
74346 ** This routine processes the join information for a SELECT statement.
74347 ** ON and USING clauses are converted into extra terms of the WHERE clause.
74348 ** NATURAL joins also create extra WHERE clause terms.
74349 **
74350 ** The terms of a FROM clause are contained in the Select.pSrc structure.
74351 ** The left most table is the first entry in Select.pSrc.  The right-most
74352 ** table is the last entry.  The join operator is held in the entry to
74353 ** the left.  Thus entry 0 contains the join operator for the join between
74354 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
74355 ** also attached to the left entry.
74356 **
74357 ** This routine returns the number of errors encountered.
74358 */
74359 static int sqliteProcessJoin(Parse *pParse, Select *p){
74360   SrcList *pSrc;                  /* All tables in the FROM clause */
74361   int i, j;                       /* Loop counters */
74362   struct SrcList_item *pLeft;     /* Left table being joined */
74363   struct SrcList_item *pRight;    /* Right table being joined */
74364
74365   pSrc = p->pSrc;
74366   pLeft = &pSrc->a[0];
74367   pRight = &pLeft[1];
74368   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
74369     Table *pLeftTab = pLeft->pTab;
74370     Table *pRightTab = pRight->pTab;
74371     int isOuter;
74372
74373     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
74374     isOuter = (pRight->jointype & JT_OUTER)!=0;
74375
74376     /* When the NATURAL keyword is present, add WHERE clause terms for
74377     ** every column that the two tables have in common.
74378     */
74379     if( pRight->jointype & JT_NATURAL ){
74380       if( pRight->pOn || pRight->pUsing ){
74381         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
74382            "an ON or USING clause", 0);
74383         return 1;
74384       }
74385       for(j=0; j<pLeftTab->nCol; j++){
74386         char *zName = pLeftTab->aCol[j].zName;
74387         if( columnIndex(pRightTab, zName)>=0 ){
74388           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
74389                               pRightTab, pRight->zAlias,
74390                               pRight->iCursor, &p->pWhere, isOuter);
74391           
74392         }
74393       }
74394     }
74395
74396     /* Disallow both ON and USING clauses in the same join
74397     */
74398     if( pRight->pOn && pRight->pUsing ){
74399       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
74400         "clauses in the same join");
74401       return 1;
74402     }
74403
74404     /* Add the ON clause to the end of the WHERE clause, connected by
74405     ** an AND operator.
74406     */
74407     if( pRight->pOn ){
74408       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
74409       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
74410       pRight->pOn = 0;
74411     }
74412
74413     /* Create extra terms on the WHERE clause for each column named
74414     ** in the USING clause.  Example: If the two tables to be joined are 
74415     ** A and B and the USING clause names X, Y, and Z, then add this
74416     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
74417     ** Report an error if any column mentioned in the USING clause is
74418     ** not contained in both tables to be joined.
74419     */
74420     if( pRight->pUsing ){
74421       IdList *pList = pRight->pUsing;
74422       for(j=0; j<pList->nId; j++){
74423         char *zName = pList->a[j].zName;
74424         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
74425           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
74426             "not present in both tables", zName);
74427           return 1;
74428         }
74429         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
74430                             pRightTab, pRight->zAlias,
74431                             pRight->iCursor, &p->pWhere, isOuter);
74432       }
74433     }
74434   }
74435   return 0;
74436 }
74437
74438 /*
74439 ** Insert code into "v" that will push the record on the top of the
74440 ** stack into the sorter.
74441 */
74442 static void pushOntoSorter(
74443   Parse *pParse,         /* Parser context */
74444   ExprList *pOrderBy,    /* The ORDER BY clause */
74445   Select *pSelect,       /* The whole SELECT statement */
74446   int regData            /* Register holding data to be sorted */
74447 ){
74448   Vdbe *v = pParse->pVdbe;
74449   int nExpr = pOrderBy->nExpr;
74450   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
74451   int regRecord = sqlite3GetTempReg(pParse);
74452   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
74453   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
74454   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
74455   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
74456   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
74457   sqlite3ReleaseTempReg(pParse, regRecord);
74458   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
74459   if( pSelect->iLimit ){
74460     int addr1, addr2;
74461     int iLimit;
74462     if( pSelect->iOffset ){
74463       iLimit = pSelect->iOffset+1;
74464     }else{
74465       iLimit = pSelect->iLimit;
74466     }
74467     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
74468     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
74469     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
74470     sqlite3VdbeJumpHere(v, addr1);
74471     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
74472     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
74473     sqlite3VdbeJumpHere(v, addr2);
74474     pSelect->iLimit = 0;
74475   }
74476 }
74477
74478 /*
74479 ** Add code to implement the OFFSET
74480 */
74481 static void codeOffset(
74482   Vdbe *v,          /* Generate code into this VM */
74483   Select *p,        /* The SELECT statement being coded */
74484   int iContinue     /* Jump here to skip the current record */
74485 ){
74486   if( p->iOffset && iContinue!=0 ){
74487     int addr;
74488     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
74489     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
74490     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
74491     VdbeComment((v, "skip OFFSET records"));
74492     sqlite3VdbeJumpHere(v, addr);
74493   }
74494 }
74495
74496 /*
74497 ** Add code that will check to make sure the N registers starting at iMem
74498 ** form a distinct entry.  iTab is a sorting index that holds previously
74499 ** seen combinations of the N values.  A new entry is made in iTab
74500 ** if the current N values are new.
74501 **
74502 ** A jump to addrRepeat is made and the N+1 values are popped from the
74503 ** stack if the top N elements are not distinct.
74504 */
74505 static void codeDistinct(
74506   Parse *pParse,     /* Parsing and code generating context */
74507   int iTab,          /* A sorting index used to test for distinctness */
74508   int addrRepeat,    /* Jump to here if not distinct */
74509   int N,             /* Number of elements */
74510   int iMem           /* First element */
74511 ){
74512   Vdbe *v;
74513   int r1;
74514
74515   v = pParse->pVdbe;
74516   r1 = sqlite3GetTempReg(pParse);
74517   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
74518   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
74519   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
74520   sqlite3ReleaseTempReg(pParse, r1);
74521 }
74522
74523 /*
74524 ** Generate an error message when a SELECT is used within a subexpression
74525 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
74526 ** column.  We do this in a subroutine because the error occurs in multiple
74527 ** places.
74528 */
74529 static int checkForMultiColumnSelectError(
74530   Parse *pParse,       /* Parse context. */
74531   SelectDest *pDest,   /* Destination of SELECT results */
74532   int nExpr            /* Number of result columns returned by SELECT */
74533 ){
74534   int eDest = pDest->eDest;
74535   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
74536     sqlite3ErrorMsg(pParse, "only a single result allowed for "
74537        "a SELECT that is part of an expression");
74538     return 1;
74539   }else{
74540     return 0;
74541   }
74542 }
74543
74544 /*
74545 ** This routine generates the code for the inside of the inner loop
74546 ** of a SELECT.
74547 **
74548 ** If srcTab and nColumn are both zero, then the pEList expressions
74549 ** are evaluated in order to get the data for this row.  If nColumn>0
74550 ** then data is pulled from srcTab and pEList is used only to get the
74551 ** datatypes for each column.
74552 */
74553 static void selectInnerLoop(
74554   Parse *pParse,          /* The parser context */
74555   Select *p,              /* The complete select statement being coded */
74556   ExprList *pEList,       /* List of values being extracted */
74557   int srcTab,             /* Pull data from this table */
74558   int nColumn,            /* Number of columns in the source table */
74559   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
74560   int distinct,           /* If >=0, make sure results are distinct */
74561   SelectDest *pDest,      /* How to dispose of the results */
74562   int iContinue,          /* Jump here to continue with next row */
74563   int iBreak              /* Jump here to break out of the inner loop */
74564 ){
74565   Vdbe *v = pParse->pVdbe;
74566   int i;
74567   int hasDistinct;        /* True if the DISTINCT keyword is present */
74568   int regResult;              /* Start of memory holding result set */
74569   int eDest = pDest->eDest;   /* How to dispose of results */
74570   int iParm = pDest->iParm;   /* First argument to disposal method */
74571   int nResultCol;             /* Number of result columns */
74572
74573   assert( v );
74574   if( NEVER(v==0) ) return;
74575   assert( pEList!=0 );
74576   hasDistinct = distinct>=0;
74577   if( pOrderBy==0 && !hasDistinct ){
74578     codeOffset(v, p, iContinue);
74579   }
74580
74581   /* Pull the requested columns.
74582   */
74583   if( nColumn>0 ){
74584     nResultCol = nColumn;
74585   }else{
74586     nResultCol = pEList->nExpr;
74587   }
74588   if( pDest->iMem==0 ){
74589     pDest->iMem = pParse->nMem+1;
74590     pDest->nMem = nResultCol;
74591     pParse->nMem += nResultCol;
74592   }else{ 
74593     assert( pDest->nMem==nResultCol );
74594   }
74595   regResult = pDest->iMem;
74596   if( nColumn>0 ){
74597     for(i=0; i<nColumn; i++){
74598       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
74599     }
74600   }else if( eDest!=SRT_Exists ){
74601     /* If the destination is an EXISTS(...) expression, the actual
74602     ** values returned by the SELECT are not required.
74603     */
74604     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
74605   }
74606   nColumn = nResultCol;
74607
74608   /* If the DISTINCT keyword was present on the SELECT statement
74609   ** and this row has been seen before, then do not make this row
74610   ** part of the result.
74611   */
74612   if( hasDistinct ){
74613     assert( pEList!=0 );
74614     assert( pEList->nExpr==nColumn );
74615     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
74616     if( pOrderBy==0 ){
74617       codeOffset(v, p, iContinue);
74618     }
74619   }
74620
74621   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
74622     return;
74623   }
74624
74625   switch( eDest ){
74626     /* In this mode, write each query result to the key of the temporary
74627     ** table iParm.
74628     */
74629 #ifndef SQLITE_OMIT_COMPOUND_SELECT
74630     case SRT_Union: {
74631       int r1;
74632       r1 = sqlite3GetTempReg(pParse);
74633       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
74634       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
74635       sqlite3ReleaseTempReg(pParse, r1);
74636       break;
74637     }
74638
74639     /* Construct a record from the query result, but instead of
74640     ** saving that record, use it as a key to delete elements from
74641     ** the temporary table iParm.
74642     */
74643     case SRT_Except: {
74644       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
74645       break;
74646     }
74647 #endif
74648
74649     /* Store the result as data using a unique key.
74650     */
74651     case SRT_Table:
74652     case SRT_EphemTab: {
74653       int r1 = sqlite3GetTempReg(pParse);
74654       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
74655       if( pOrderBy ){
74656         pushOntoSorter(pParse, pOrderBy, p, r1);
74657       }else{
74658         int r2 = sqlite3GetTempReg(pParse);
74659         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
74660         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
74661         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74662         sqlite3ReleaseTempReg(pParse, r2);
74663       }
74664       sqlite3ReleaseTempReg(pParse, r1);
74665       break;
74666     }
74667
74668 #ifndef SQLITE_OMIT_SUBQUERY
74669     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
74670     ** then there should be a single item on the stack.  Write this
74671     ** item into the set table with bogus data.
74672     */
74673     case SRT_Set: {
74674       assert( nColumn==1 );
74675       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
74676       if( pOrderBy ){
74677         /* At first glance you would think we could optimize out the
74678         ** ORDER BY in this case since the order of entries in the set
74679         ** does not matter.  But there might be a LIMIT clause, in which
74680         ** case the order does matter */
74681         pushOntoSorter(pParse, pOrderBy, p, regResult);
74682       }else{
74683         int r1 = sqlite3GetTempReg(pParse);
74684         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
74685         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
74686         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
74687         sqlite3ReleaseTempReg(pParse, r1);
74688       }
74689       break;
74690     }
74691
74692     /* If any row exist in the result set, record that fact and abort.
74693     */
74694     case SRT_Exists: {
74695       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
74696       /* The LIMIT clause will terminate the loop for us */
74697       break;
74698     }
74699
74700     /* If this is a scalar select that is part of an expression, then
74701     ** store the results in the appropriate memory cell and break out
74702     ** of the scan loop.
74703     */
74704     case SRT_Mem: {
74705       assert( nColumn==1 );
74706       if( pOrderBy ){
74707         pushOntoSorter(pParse, pOrderBy, p, regResult);
74708       }else{
74709         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
74710         /* The LIMIT clause will jump out of the loop for us */
74711       }
74712       break;
74713     }
74714 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
74715
74716     /* Send the data to the callback function or to a subroutine.  In the
74717     ** case of a subroutine, the subroutine itself is responsible for
74718     ** popping the data from the stack.
74719     */
74720     case SRT_Coroutine:
74721     case SRT_Output: {
74722       if( pOrderBy ){
74723         int r1 = sqlite3GetTempReg(pParse);
74724         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
74725         pushOntoSorter(pParse, pOrderBy, p, r1);
74726         sqlite3ReleaseTempReg(pParse, r1);
74727       }else if( eDest==SRT_Coroutine ){
74728         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
74729       }else{
74730         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
74731         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
74732       }
74733       break;
74734     }
74735
74736 #if !defined(SQLITE_OMIT_TRIGGER)
74737     /* Discard the results.  This is used for SELECT statements inside
74738     ** the body of a TRIGGER.  The purpose of such selects is to call
74739     ** user-defined functions that have side effects.  We do not care
74740     ** about the actual results of the select.
74741     */
74742     default: {
74743       assert( eDest==SRT_Discard );
74744       break;
74745     }
74746 #endif
74747   }
74748
74749   /* Jump to the end of the loop if the LIMIT is reached.
74750   */
74751   if( p->iLimit ){
74752     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
74753                             ** pushOntoSorter() would have cleared p->iLimit */
74754     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
74755     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
74756   }
74757 }
74758
74759 /*
74760 ** Given an expression list, generate a KeyInfo structure that records
74761 ** the collating sequence for each expression in that expression list.
74762 **
74763 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
74764 ** KeyInfo structure is appropriate for initializing a virtual index to
74765 ** implement that clause.  If the ExprList is the result set of a SELECT
74766 ** then the KeyInfo structure is appropriate for initializing a virtual
74767 ** index to implement a DISTINCT test.
74768 **
74769 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
74770 ** function is responsible for seeing that this structure is eventually
74771 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
74772 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
74773 */
74774 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
74775   sqlite3 *db = pParse->db;
74776   int nExpr;
74777   KeyInfo *pInfo;
74778   struct ExprList_item *pItem;
74779   int i;
74780
74781   nExpr = pList->nExpr;
74782   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
74783   if( pInfo ){
74784     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
74785     pInfo->nField = (u16)nExpr;
74786     pInfo->enc = ENC(db);
74787     pInfo->db = db;
74788     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
74789       CollSeq *pColl;
74790       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
74791       if( !pColl ){
74792         pColl = db->pDfltColl;
74793       }
74794       pInfo->aColl[i] = pColl;
74795       pInfo->aSortOrder[i] = pItem->sortOrder;
74796     }
74797   }
74798   return pInfo;
74799 }
74800
74801
74802 /*
74803 ** If the inner loop was generated using a non-null pOrderBy argument,
74804 ** then the results were placed in a sorter.  After the loop is terminated
74805 ** we need to run the sorter and output the results.  The following
74806 ** routine generates the code needed to do that.
74807 */
74808 static void generateSortTail(
74809   Parse *pParse,    /* Parsing context */
74810   Select *p,        /* The SELECT statement */
74811   Vdbe *v,          /* Generate code into this VDBE */
74812   int nColumn,      /* Number of columns of data */
74813   SelectDest *pDest /* Write the sorted results here */
74814 ){
74815   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
74816   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
74817   int addr;
74818   int iTab;
74819   int pseudoTab = 0;
74820   ExprList *pOrderBy = p->pOrderBy;
74821
74822   int eDest = pDest->eDest;
74823   int iParm = pDest->iParm;
74824
74825   int regRow;
74826   int regRowid;
74827
74828   iTab = pOrderBy->iECursor;
74829   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
74830     pseudoTab = pParse->nTab++;
74831     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
74832     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
74833   }
74834   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
74835   codeOffset(v, p, addrContinue);
74836   regRow = sqlite3GetTempReg(pParse);
74837   regRowid = sqlite3GetTempReg(pParse);
74838   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
74839   switch( eDest ){
74840     case SRT_Table:
74841     case SRT_EphemTab: {
74842       testcase( eDest==SRT_Table );
74843       testcase( eDest==SRT_EphemTab );
74844       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
74845       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
74846       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74847       break;
74848     }
74849 #ifndef SQLITE_OMIT_SUBQUERY
74850     case SRT_Set: {
74851       assert( nColumn==1 );
74852       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
74853       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
74854       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
74855       break;
74856     }
74857     case SRT_Mem: {
74858       assert( nColumn==1 );
74859       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
74860       /* The LIMIT clause will terminate the loop for us */
74861       break;
74862     }
74863 #endif
74864     case SRT_Output:
74865     case SRT_Coroutine: {
74866       int i;
74867       testcase( eDest==SRT_Output );
74868       testcase( eDest==SRT_Coroutine );
74869       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
74870       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
74871       for(i=0; i<nColumn; i++){
74872         assert( regRow!=pDest->iMem+i );
74873         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
74874       }
74875       if( eDest==SRT_Output ){
74876         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
74877         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
74878       }else{
74879         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
74880       }
74881       break;
74882     }
74883     default: {
74884       /* Do nothing */
74885       break;
74886     }
74887   }
74888   sqlite3ReleaseTempReg(pParse, regRow);
74889   sqlite3ReleaseTempReg(pParse, regRowid);
74890
74891   /* LIMIT has been implemented by the pushOntoSorter() routine.
74892   */
74893   assert( p->iLimit==0 );
74894
74895   /* The bottom of the loop
74896   */
74897   sqlite3VdbeResolveLabel(v, addrContinue);
74898   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
74899   sqlite3VdbeResolveLabel(v, addrBreak);
74900   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
74901     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
74902   }
74903 }
74904
74905 /*
74906 ** Return a pointer to a string containing the 'declaration type' of the
74907 ** expression pExpr. The string may be treated as static by the caller.
74908 **
74909 ** The declaration type is the exact datatype definition extracted from the
74910 ** original CREATE TABLE statement if the expression is a column. The
74911 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
74912 ** is considered a column can be complex in the presence of subqueries. The
74913 ** result-set expression in all of the following SELECT statements is 
74914 ** considered a column by this function.
74915 **
74916 **   SELECT col FROM tbl;
74917 **   SELECT (SELECT col FROM tbl;
74918 **   SELECT (SELECT col FROM tbl);
74919 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
74920 ** 
74921 ** The declaration type for any expression other than a column is NULL.
74922 */
74923 static const char *columnType(
74924   NameContext *pNC, 
74925   Expr *pExpr,
74926   const char **pzOriginDb,
74927   const char **pzOriginTab,
74928   const char **pzOriginCol
74929 ){
74930   char const *zType = 0;
74931   char const *zOriginDb = 0;
74932   char const *zOriginTab = 0;
74933   char const *zOriginCol = 0;
74934   int j;
74935   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
74936
74937   switch( pExpr->op ){
74938     case TK_AGG_COLUMN:
74939     case TK_COLUMN: {
74940       /* The expression is a column. Locate the table the column is being
74941       ** extracted from in NameContext.pSrcList. This table may be real
74942       ** database table or a subquery.
74943       */
74944       Table *pTab = 0;            /* Table structure column is extracted from */
74945       Select *pS = 0;             /* Select the column is extracted from */
74946       int iCol = pExpr->iColumn;  /* Index of column in pTab */
74947       while( pNC && !pTab ){
74948         SrcList *pTabList = pNC->pSrcList;
74949         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
74950         if( j<pTabList->nSrc ){
74951           pTab = pTabList->a[j].pTab;
74952           pS = pTabList->a[j].pSelect;
74953         }else{
74954           pNC = pNC->pNext;
74955         }
74956       }
74957
74958       if( pTab==0 ){
74959         /* FIX ME:
74960         ** This can occurs if you have something like "SELECT new.x;" inside
74961         ** a trigger.  In other words, if you reference the special "new"
74962         ** table in the result set of a select.  We do not have a good way
74963         ** to find the actual table type, so call it "TEXT".  This is really
74964         ** something of a bug, but I do not know how to fix it.
74965         **
74966         ** This code does not produce the correct answer - it just prevents
74967         ** a segfault.  See ticket #1229.
74968         */
74969         zType = "TEXT";
74970         break;
74971       }
74972
74973       assert( pTab );
74974       if( pS ){
74975         /* The "table" is actually a sub-select or a view in the FROM clause
74976         ** of the SELECT statement. Return the declaration type and origin
74977         ** data for the result-set column of the sub-select.
74978         */
74979         if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
74980           /* If iCol is less than zero, then the expression requests the
74981           ** rowid of the sub-select or view. This expression is legal (see 
74982           ** test case misc2.2.2) - it always evaluates to NULL.
74983           */
74984           NameContext sNC;
74985           Expr *p = pS->pEList->a[iCol].pExpr;
74986           sNC.pSrcList = pS->pSrc;
74987           sNC.pNext = 0;
74988           sNC.pParse = pNC->pParse;
74989           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
74990         }
74991       }else if( ALWAYS(pTab->pSchema) ){
74992         /* A real table */
74993         assert( !pS );
74994         if( iCol<0 ) iCol = pTab->iPKey;
74995         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
74996         if( iCol<0 ){
74997           zType = "INTEGER";
74998           zOriginCol = "rowid";
74999         }else{
75000           zType = pTab->aCol[iCol].zType;
75001           zOriginCol = pTab->aCol[iCol].zName;
75002         }
75003         zOriginTab = pTab->zName;
75004         if( pNC->pParse ){
75005           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
75006           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
75007         }
75008       }
75009       break;
75010     }
75011 #ifndef SQLITE_OMIT_SUBQUERY
75012     case TK_SELECT: {
75013       /* The expression is a sub-select. Return the declaration type and
75014       ** origin info for the single column in the result set of the SELECT
75015       ** statement.
75016       */
75017       NameContext sNC;
75018       Select *pS = pExpr->pSelect;
75019       Expr *p = pS->pEList->a[0].pExpr;
75020       sNC.pSrcList = pS->pSrc;
75021       sNC.pNext = pNC;
75022       sNC.pParse = pNC->pParse;
75023       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
75024       break;
75025     }
75026 #endif
75027   }
75028   
75029   if( pzOriginDb ){
75030     assert( pzOriginTab && pzOriginCol );
75031     *pzOriginDb = zOriginDb;
75032     *pzOriginTab = zOriginTab;
75033     *pzOriginCol = zOriginCol;
75034   }
75035   return zType;
75036 }
75037
75038 /*
75039 ** Generate code that will tell the VDBE the declaration types of columns
75040 ** in the result set.
75041 */
75042 static void generateColumnTypes(
75043   Parse *pParse,      /* Parser context */
75044   SrcList *pTabList,  /* List of tables */
75045   ExprList *pEList    /* Expressions defining the result set */
75046 ){
75047 #ifndef SQLITE_OMIT_DECLTYPE
75048   Vdbe *v = pParse->pVdbe;
75049   int i;
75050   NameContext sNC;
75051   sNC.pSrcList = pTabList;
75052   sNC.pParse = pParse;
75053   for(i=0; i<pEList->nExpr; i++){
75054     Expr *p = pEList->a[i].pExpr;
75055     const char *zType;
75056 #ifdef SQLITE_ENABLE_COLUMN_METADATA
75057     const char *zOrigDb = 0;
75058     const char *zOrigTab = 0;
75059     const char *zOrigCol = 0;
75060     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
75061
75062     /* The vdbe must make its own copy of the column-type and other 
75063     ** column specific strings, in case the schema is reset before this
75064     ** virtual machine is deleted.
75065     */
75066     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
75067     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
75068     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
75069 #else
75070     zType = columnType(&sNC, p, 0, 0, 0);
75071 #endif
75072     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
75073   }
75074 #endif /* SQLITE_OMIT_DECLTYPE */
75075 }
75076
75077 /*
75078 ** Generate code that will tell the VDBE the names of columns
75079 ** in the result set.  This information is used to provide the
75080 ** azCol[] values in the callback.
75081 */
75082 static void generateColumnNames(
75083   Parse *pParse,      /* Parser context */
75084   SrcList *pTabList,  /* List of tables */
75085   ExprList *pEList    /* Expressions defining the result set */
75086 ){
75087   Vdbe *v = pParse->pVdbe;
75088   int i, j;
75089   sqlite3 *db = pParse->db;
75090   int fullNames, shortNames;
75091
75092 #ifndef SQLITE_OMIT_EXPLAIN
75093   /* If this is an EXPLAIN, skip this step */
75094   if( pParse->explain ){
75095     return;
75096   }
75097 #endif
75098
75099   assert( v!=0 );
75100   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
75101   pParse->colNamesSet = 1;
75102   fullNames = (db->flags & SQLITE_FullColNames)!=0;
75103   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
75104   sqlite3VdbeSetNumCols(v, pEList->nExpr);
75105   for(i=0; i<pEList->nExpr; i++){
75106     Expr *p;
75107     p = pEList->a[i].pExpr;
75108     if( p==0 ) continue;
75109     if( pEList->a[i].zName ){
75110       char *zName = pEList->a[i].zName;
75111       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
75112     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
75113       Table *pTab;
75114       char *zCol;
75115       int iCol = p->iColumn;
75116       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
75117         if( pTabList->a[j].iCursor==p->iTable ) break;
75118       }
75119       assert( j<pTabList->nSrc );
75120       pTab = pTabList->a[j].pTab;
75121       if( iCol<0 ) iCol = pTab->iPKey;
75122       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
75123       if( iCol<0 ){
75124         zCol = "rowid";
75125       }else{
75126         zCol = pTab->aCol[iCol].zName;
75127       }
75128       if( !shortNames && !fullNames ){
75129         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
75130             sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
75131       }else if( fullNames ){
75132         char *zName = 0;
75133         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
75134         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
75135       }else{
75136         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
75137       }
75138     }else{
75139       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
75140           sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
75141     }
75142   }
75143   generateColumnTypes(pParse, pTabList, pEList);
75144 }
75145
75146 #ifndef SQLITE_OMIT_COMPOUND_SELECT
75147 /*
75148 ** Name of the connection operator, used for error messages.
75149 */
75150 static const char *selectOpName(int id){
75151   char *z;
75152   switch( id ){
75153     case TK_ALL:       z = "UNION ALL";   break;
75154     case TK_INTERSECT: z = "INTERSECT";   break;
75155     case TK_EXCEPT:    z = "EXCEPT";      break;
75156     default:           z = "UNION";       break;
75157   }
75158   return z;
75159 }
75160 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
75161
75162 /*
75163 ** Given a an expression list (which is really the list of expressions
75164 ** that form the result set of a SELECT statement) compute appropriate
75165 ** column names for a table that would hold the expression list.
75166 **
75167 ** All column names will be unique.
75168 **
75169 ** Only the column names are computed.  Column.zType, Column.zColl,
75170 ** and other fields of Column are zeroed.
75171 **
75172 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
75173 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
75174 */
75175 static int selectColumnsFromExprList(
75176   Parse *pParse,          /* Parsing context */
75177   ExprList *pEList,       /* Expr list from which to derive column names */
75178   int *pnCol,             /* Write the number of columns here */
75179   Column **paCol          /* Write the new column list here */
75180 ){
75181   sqlite3 *db = pParse->db;   /* Database connection */
75182   int i, j;                   /* Loop counters */
75183   int cnt;                    /* Index added to make the name unique */
75184   Column *aCol, *pCol;        /* For looping over result columns */
75185   int nCol;                   /* Number of columns in the result set */
75186   Expr *p;                    /* Expression for a single result column */
75187   char *zName;                /* Column name */
75188   int nName;                  /* Size of name in zName[] */
75189
75190   *pnCol = nCol = pEList->nExpr;
75191   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
75192   if( aCol==0 ) return SQLITE_NOMEM;
75193   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
75194     /* Get an appropriate name for the column
75195     */
75196     p = pEList->a[i].pExpr;
75197     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
75198     if( (zName = pEList->a[i].zName)!=0 ){
75199       /* If the column contains an "AS <name>" phrase, use <name> as the name */
75200       zName = sqlite3DbStrDup(db, zName);
75201     }else{
75202       Expr *pColExpr = p;  /* The expression that is the result column name */
75203       Table *pTab;         /* Table associated with this expression */
75204       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
75205       if( pColExpr->op==TK_COLUMN && (pTab = pColExpr->pTab)!=0 ){
75206         /* For columns use the column name name */
75207         int iCol = pColExpr->iColumn;
75208         if( iCol<0 ) iCol = pTab->iPKey;
75209         zName = sqlite3MPrintf(db, "%s",
75210                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
75211       }else{
75212         /* Use the original text of the column expression as its name */
75213         Token *pToken = (pColExpr->span.z?&pColExpr->span:&pColExpr->token);
75214         zName = sqlite3MPrintf(db, "%T", pToken);
75215       }
75216     }
75217     if( db->mallocFailed ){
75218       sqlite3DbFree(db, zName);
75219       break;
75220     }
75221     sqlite3Dequote(zName);
75222
75223     /* Make sure the column name is unique.  If the name is not unique,
75224     ** append a integer to the name so that it becomes unique.
75225     */
75226     nName = sqlite3Strlen30(zName);
75227     for(j=cnt=0; j<i; j++){
75228       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
75229         char *zNewName;
75230         zName[nName] = 0;
75231         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
75232         sqlite3DbFree(db, zName);
75233         zName = zNewName;
75234         j = -1;
75235         if( zName==0 ) break;
75236       }
75237     }
75238     pCol->zName = zName;
75239   }
75240   if( db->mallocFailed ){
75241     for(j=0; j<i; j++){
75242       sqlite3DbFree(db, aCol[j].zName);
75243     }
75244     sqlite3DbFree(db, aCol);
75245     *paCol = 0;
75246     *pnCol = 0;
75247     return SQLITE_NOMEM;
75248   }
75249   return SQLITE_OK;
75250 }
75251
75252 /*
75253 ** Add type and collation information to a column list based on
75254 ** a SELECT statement.
75255 ** 
75256 ** The column list presumably came from selectColumnNamesFromExprList().
75257 ** The column list has only names, not types or collations.  This
75258 ** routine goes through and adds the types and collations.
75259 **
75260 ** This routine requires that all indentifiers in the SELECT
75261 ** statement be resolved.
75262 */
75263 static void selectAddColumnTypeAndCollation(
75264   Parse *pParse,        /* Parsing contexts */
75265   int nCol,             /* Number of columns */
75266   Column *aCol,         /* List of columns */
75267   Select *pSelect       /* SELECT used to determine types and collations */
75268 ){
75269   sqlite3 *db = pParse->db;
75270   NameContext sNC;
75271   Column *pCol;
75272   CollSeq *pColl;
75273   int i;
75274   Expr *p;
75275   struct ExprList_item *a;
75276
75277   assert( pSelect!=0 );
75278   assert( (pSelect->selFlags & SF_Resolved)!=0 );
75279   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
75280   if( db->mallocFailed ) return;
75281   memset(&sNC, 0, sizeof(sNC));
75282   sNC.pSrcList = pSelect->pSrc;
75283   a = pSelect->pEList->a;
75284   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
75285     p = a[i].pExpr;
75286     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
75287     pCol->affinity = sqlite3ExprAffinity(p);
75288     pColl = sqlite3ExprCollSeq(pParse, p);
75289     if( pColl ){
75290       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
75291     }
75292   }
75293 }
75294
75295 /*
75296 ** Given a SELECT statement, generate a Table structure that describes
75297 ** the result set of that SELECT.
75298 */
75299 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
75300   Table *pTab;
75301   sqlite3 *db = pParse->db;
75302   int savedFlags;
75303
75304   savedFlags = db->flags;
75305   db->flags &= ~SQLITE_FullColNames;
75306   db->flags |= SQLITE_ShortColNames;
75307   sqlite3SelectPrep(pParse, pSelect, 0);
75308   if( pParse->nErr ) return 0;
75309   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
75310   db->flags = savedFlags;
75311   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
75312   if( pTab==0 ){
75313     return 0;
75314   }
75315   pTab->db = db;
75316   pTab->nRef = 1;
75317   pTab->zName = 0;
75318   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
75319   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
75320   pTab->iPKey = -1;
75321   if( db->mallocFailed ){
75322     sqlite3DeleteTable(pTab);
75323     return 0;
75324   }
75325   return pTab;
75326 }
75327
75328 /*
75329 ** Get a VDBE for the given parser context.  Create a new one if necessary.
75330 ** If an error occurs, return NULL and leave a message in pParse.
75331 */
75332 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
75333   Vdbe *v = pParse->pVdbe;
75334   if( v==0 ){
75335     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
75336 #ifndef SQLITE_OMIT_TRACE
75337     if( v ){
75338       sqlite3VdbeAddOp0(v, OP_Trace);
75339     }
75340 #endif
75341   }
75342   return v;
75343 }
75344
75345
75346 /*
75347 ** Compute the iLimit and iOffset fields of the SELECT based on the
75348 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
75349 ** that appear in the original SQL statement after the LIMIT and OFFSET
75350 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
75351 ** are the integer memory register numbers for counters used to compute 
75352 ** the limit and offset.  If there is no limit and/or offset, then 
75353 ** iLimit and iOffset are negative.
75354 **
75355 ** This routine changes the values of iLimit and iOffset only if
75356 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
75357 ** iOffset should have been preset to appropriate default values
75358 ** (usually but not always -1) prior to calling this routine.
75359 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
75360 ** redefined.  The UNION ALL operator uses this property to force
75361 ** the reuse of the same limit and offset registers across multiple
75362 ** SELECT statements.
75363 */
75364 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
75365   Vdbe *v = 0;
75366   int iLimit = 0;
75367   int iOffset;
75368   int addr1;
75369   if( p->iLimit ) return;
75370
75371   /* 
75372   ** "LIMIT -1" always shows all rows.  There is some
75373   ** contraversy about what the correct behavior should be.
75374   ** The current implementation interprets "LIMIT 0" to mean
75375   ** no rows.
75376   */
75377   if( p->pLimit ){
75378     p->iLimit = iLimit = ++pParse->nMem;
75379     v = sqlite3GetVdbe(pParse);
75380     if( v==0 ) return;
75381     sqlite3ExprCode(pParse, p->pLimit, iLimit);
75382     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
75383     VdbeComment((v, "LIMIT counter"));
75384     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
75385   }
75386   if( p->pOffset ){
75387     p->iOffset = iOffset = ++pParse->nMem;
75388     if( p->pLimit ){
75389       pParse->nMem++;   /* Allocate an extra register for limit+offset */
75390     }
75391     v = sqlite3GetVdbe(pParse);
75392     if( v==0 ) return;
75393     sqlite3ExprCode(pParse, p->pOffset, iOffset);
75394     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
75395     VdbeComment((v, "OFFSET counter"));
75396     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
75397     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
75398     sqlite3VdbeJumpHere(v, addr1);
75399     if( p->pLimit ){
75400       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
75401       VdbeComment((v, "LIMIT+OFFSET"));
75402       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
75403       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
75404       sqlite3VdbeJumpHere(v, addr1);
75405     }
75406   }
75407 }
75408
75409 #ifndef SQLITE_OMIT_COMPOUND_SELECT
75410 /*
75411 ** Return the appropriate collating sequence for the iCol-th column of
75412 ** the result set for the compound-select statement "p".  Return NULL if
75413 ** the column has no default collating sequence.
75414 **
75415 ** The collating sequence for the compound select is taken from the
75416 ** left-most term of the select that has a collating sequence.
75417 */
75418 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
75419   CollSeq *pRet;
75420   if( p->pPrior ){
75421     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
75422   }else{
75423     pRet = 0;
75424   }
75425   if( pRet==0 ){
75426     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
75427   }
75428   return pRet;
75429 }
75430 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
75431
75432 /* Forward reference */
75433 static int multiSelectOrderBy(
75434   Parse *pParse,        /* Parsing context */
75435   Select *p,            /* The right-most of SELECTs to be coded */
75436   SelectDest *pDest     /* What to do with query results */
75437 );
75438
75439
75440 #ifndef SQLITE_OMIT_COMPOUND_SELECT
75441 /*
75442 ** This routine is called to process a compound query form from
75443 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
75444 ** INTERSECT
75445 **
75446 ** "p" points to the right-most of the two queries.  the query on the
75447 ** left is p->pPrior.  The left query could also be a compound query
75448 ** in which case this routine will be called recursively. 
75449 **
75450 ** The results of the total query are to be written into a destination
75451 ** of type eDest with parameter iParm.
75452 **
75453 ** Example 1:  Consider a three-way compound SQL statement.
75454 **
75455 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
75456 **
75457 ** This statement is parsed up as follows:
75458 **
75459 **     SELECT c FROM t3
75460 **      |
75461 **      `----->  SELECT b FROM t2
75462 **                |
75463 **                `------>  SELECT a FROM t1
75464 **
75465 ** The arrows in the diagram above represent the Select.pPrior pointer.
75466 ** So if this routine is called with p equal to the t3 query, then
75467 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
75468 **
75469 ** Notice that because of the way SQLite parses compound SELECTs, the
75470 ** individual selects always group from left to right.
75471 */
75472 static int multiSelect(
75473   Parse *pParse,        /* Parsing context */
75474   Select *p,            /* The right-most of SELECTs to be coded */
75475   SelectDest *pDest     /* What to do with query results */
75476 ){
75477   int rc = SQLITE_OK;   /* Success code from a subroutine */
75478   Select *pPrior;       /* Another SELECT immediately to our left */
75479   Vdbe *v;              /* Generate code to this VDBE */
75480   SelectDest dest;      /* Alternative data destination */
75481   Select *pDelete = 0;  /* Chain of simple selects to delete */
75482   sqlite3 *db;          /* Database connection */
75483
75484   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
75485   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
75486   */
75487   assert( p && p->pPrior );  /* Calling function guarantees this much */
75488   db = pParse->db;
75489   pPrior = p->pPrior;
75490   assert( pPrior->pRightmost!=pPrior );
75491   assert( pPrior->pRightmost==p->pRightmost );
75492   dest = *pDest;
75493   if( pPrior->pOrderBy ){
75494     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
75495       selectOpName(p->op));
75496     rc = 1;
75497     goto multi_select_end;
75498   }
75499   if( pPrior->pLimit ){
75500     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
75501       selectOpName(p->op));
75502     rc = 1;
75503     goto multi_select_end;
75504   }
75505
75506   v = sqlite3GetVdbe(pParse);
75507   assert( v!=0 );  /* The VDBE already created by calling function */
75508
75509   /* Create the destination temporary table if necessary
75510   */
75511   if( dest.eDest==SRT_EphemTab ){
75512     assert( p->pEList );
75513     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
75514     dest.eDest = SRT_Table;
75515   }
75516
75517   /* Make sure all SELECTs in the statement have the same number of elements
75518   ** in their result sets.
75519   */
75520   assert( p->pEList && pPrior->pEList );
75521   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
75522     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
75523       " do not have the same number of result columns", selectOpName(p->op));
75524     rc = 1;
75525     goto multi_select_end;
75526   }
75527
75528   /* Compound SELECTs that have an ORDER BY clause are handled separately.
75529   */
75530   if( p->pOrderBy ){
75531     return multiSelectOrderBy(pParse, p, pDest);
75532   }
75533
75534   /* Generate code for the left and right SELECT statements.
75535   */
75536   switch( p->op ){
75537     case TK_ALL: {
75538       int addr = 0;
75539       assert( !pPrior->pLimit );
75540       pPrior->pLimit = p->pLimit;
75541       pPrior->pOffset = p->pOffset;
75542       rc = sqlite3Select(pParse, pPrior, &dest);
75543       p->pLimit = 0;
75544       p->pOffset = 0;
75545       if( rc ){
75546         goto multi_select_end;
75547       }
75548       p->pPrior = 0;
75549       p->iLimit = pPrior->iLimit;
75550       p->iOffset = pPrior->iOffset;
75551       if( p->iLimit ){
75552         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
75553         VdbeComment((v, "Jump ahead if LIMIT reached"));
75554       }
75555       rc = sqlite3Select(pParse, p, &dest);
75556       pDelete = p->pPrior;
75557       p->pPrior = pPrior;
75558       if( rc ){
75559         goto multi_select_end;
75560       }
75561       if( addr ){
75562         sqlite3VdbeJumpHere(v, addr);
75563       }
75564       break;
75565     }
75566     case TK_EXCEPT:
75567     case TK_UNION: {
75568       int unionTab;    /* Cursor number of the temporary table holding result */
75569       u8 op = 0;       /* One of the SRT_ operations to apply to self */
75570       int priorOp;     /* The SRT_ operation to apply to prior selects */
75571       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
75572       int addr;
75573       SelectDest uniondest;
75574
75575       priorOp = SRT_Union;
75576       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
75577         /* We can reuse a temporary table generated by a SELECT to our
75578         ** right.
75579         */
75580         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
75581                                      ** of a 3-way or more compound */
75582         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
75583         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
75584         unionTab = dest.iParm;
75585       }else{
75586         /* We will need to create our own temporary table to hold the
75587         ** intermediate results.
75588         */
75589         unionTab = pParse->nTab++;
75590         assert( p->pOrderBy==0 );
75591         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
75592         assert( p->addrOpenEphm[0] == -1 );
75593         p->addrOpenEphm[0] = addr;
75594         p->pRightmost->selFlags |= SF_UsesEphemeral;
75595         assert( p->pEList );
75596       }
75597
75598       /* Code the SELECT statements to our left
75599       */
75600       assert( !pPrior->pOrderBy );
75601       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
75602       rc = sqlite3Select(pParse, pPrior, &uniondest);
75603       if( rc ){
75604         goto multi_select_end;
75605       }
75606
75607       /* Code the current SELECT statement
75608       */
75609       if( p->op==TK_EXCEPT ){
75610         op = SRT_Except;
75611       }else{
75612         assert( p->op==TK_UNION );
75613         op = SRT_Union;
75614       }
75615       p->pPrior = 0;
75616       pLimit = p->pLimit;
75617       p->pLimit = 0;
75618       pOffset = p->pOffset;
75619       p->pOffset = 0;
75620       uniondest.eDest = op;
75621       rc = sqlite3Select(pParse, p, &uniondest);
75622       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
75623       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
75624       sqlite3ExprListDelete(db, p->pOrderBy);
75625       pDelete = p->pPrior;
75626       p->pPrior = pPrior;
75627       p->pOrderBy = 0;
75628       sqlite3ExprDelete(db, p->pLimit);
75629       p->pLimit = pLimit;
75630       p->pOffset = pOffset;
75631       p->iLimit = 0;
75632       p->iOffset = 0;
75633       if( rc ){
75634         goto multi_select_end;
75635       }
75636
75637
75638       /* Convert the data in the temporary table into whatever form
75639       ** it is that we currently need.
75640       */      
75641       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
75642         int iCont, iBreak, iStart;
75643         assert( p->pEList );
75644         if( dest.eDest==SRT_Output ){
75645           Select *pFirst = p;
75646           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
75647           generateColumnNames(pParse, 0, pFirst->pEList);
75648         }
75649         iBreak = sqlite3VdbeMakeLabel(v);
75650         iCont = sqlite3VdbeMakeLabel(v);
75651         computeLimitRegisters(pParse, p, iBreak);
75652         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
75653         iStart = sqlite3VdbeCurrentAddr(v);
75654         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
75655                         0, -1, &dest, iCont, iBreak);
75656         sqlite3VdbeResolveLabel(v, iCont);
75657         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
75658         sqlite3VdbeResolveLabel(v, iBreak);
75659         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
75660       }
75661       break;
75662     }
75663     case TK_INTERSECT: {
75664       int tab1, tab2;
75665       int iCont, iBreak, iStart;
75666       Expr *pLimit, *pOffset;
75667       int addr;
75668       SelectDest intersectdest;
75669       int r1;
75670
75671       /* INTERSECT is different from the others since it requires
75672       ** two temporary tables.  Hence it has its own case.  Begin
75673       ** by allocating the tables we will need.
75674       */
75675       tab1 = pParse->nTab++;
75676       tab2 = pParse->nTab++;
75677       assert( p->pOrderBy==0 );
75678
75679       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
75680       assert( p->addrOpenEphm[0] == -1 );
75681       p->addrOpenEphm[0] = addr;
75682       p->pRightmost->selFlags |= SF_UsesEphemeral;
75683       assert( p->pEList );
75684
75685       /* Code the SELECTs to our left into temporary table "tab1".
75686       */
75687       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
75688       rc = sqlite3Select(pParse, pPrior, &intersectdest);
75689       if( rc ){
75690         goto multi_select_end;
75691       }
75692
75693       /* Code the current SELECT into temporary table "tab2"
75694       */
75695       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
75696       assert( p->addrOpenEphm[1] == -1 );
75697       p->addrOpenEphm[1] = addr;
75698       p->pPrior = 0;
75699       pLimit = p->pLimit;
75700       p->pLimit = 0;
75701       pOffset = p->pOffset;
75702       p->pOffset = 0;
75703       intersectdest.iParm = tab2;
75704       rc = sqlite3Select(pParse, p, &intersectdest);
75705       pDelete = p->pPrior;
75706       p->pPrior = pPrior;
75707       sqlite3ExprDelete(db, p->pLimit);
75708       p->pLimit = pLimit;
75709       p->pOffset = pOffset;
75710       if( rc ){
75711         goto multi_select_end;
75712       }
75713
75714       /* Generate code to take the intersection of the two temporary
75715       ** tables.
75716       */
75717       assert( p->pEList );
75718       if( dest.eDest==SRT_Output ){
75719         Select *pFirst = p;
75720         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
75721         generateColumnNames(pParse, 0, pFirst->pEList);
75722       }
75723       iBreak = sqlite3VdbeMakeLabel(v);
75724       iCont = sqlite3VdbeMakeLabel(v);
75725       computeLimitRegisters(pParse, p, iBreak);
75726       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
75727       r1 = sqlite3GetTempReg(pParse);
75728       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
75729       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
75730       sqlite3ReleaseTempReg(pParse, r1);
75731       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
75732                       0, -1, &dest, iCont, iBreak);
75733       sqlite3VdbeResolveLabel(v, iCont);
75734       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
75735       sqlite3VdbeResolveLabel(v, iBreak);
75736       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
75737       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
75738       break;
75739     }
75740   }
75741
75742   /* Compute collating sequences used by 
75743   ** temporary tables needed to implement the compound select.
75744   ** Attach the KeyInfo structure to all temporary tables.
75745   **
75746   ** This section is run by the right-most SELECT statement only.
75747   ** SELECT statements to the left always skip this part.  The right-most
75748   ** SELECT might also skip this part if it has no ORDER BY clause and
75749   ** no temp tables are required.
75750   */
75751   if( p->selFlags & SF_UsesEphemeral ){
75752     int i;                        /* Loop counter */
75753     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
75754     Select *pLoop;                /* For looping through SELECT statements */
75755     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
75756     int nCol;                     /* Number of columns in result set */
75757
75758     assert( p->pRightmost==p );
75759     nCol = p->pEList->nExpr;
75760     pKeyInfo = sqlite3DbMallocZero(db,
75761                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
75762     if( !pKeyInfo ){
75763       rc = SQLITE_NOMEM;
75764       goto multi_select_end;
75765     }
75766
75767     pKeyInfo->enc = ENC(db);
75768     pKeyInfo->nField = (u16)nCol;
75769
75770     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
75771       *apColl = multiSelectCollSeq(pParse, p, i);
75772       if( 0==*apColl ){
75773         *apColl = db->pDfltColl;
75774       }
75775     }
75776
75777     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
75778       for(i=0; i<2; i++){
75779         int addr = pLoop->addrOpenEphm[i];
75780         if( addr<0 ){
75781           /* If [0] is unused then [1] is also unused.  So we can
75782           ** always safely abort as soon as the first unused slot is found */
75783           assert( pLoop->addrOpenEphm[1]<0 );
75784           break;
75785         }
75786         sqlite3VdbeChangeP2(v, addr, nCol);
75787         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
75788         pLoop->addrOpenEphm[i] = -1;
75789       }
75790     }
75791     sqlite3DbFree(db, pKeyInfo);
75792   }
75793
75794 multi_select_end:
75795   pDest->iMem = dest.iMem;
75796   pDest->nMem = dest.nMem;
75797   sqlite3SelectDelete(db, pDelete);
75798   return rc;
75799 }
75800 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
75801
75802 /*
75803 ** Code an output subroutine for a coroutine implementation of a
75804 ** SELECT statment.
75805 **
75806 ** The data to be output is contained in pIn->iMem.  There are
75807 ** pIn->nMem columns to be output.  pDest is where the output should
75808 ** be sent.
75809 **
75810 ** regReturn is the number of the register holding the subroutine
75811 ** return address.
75812 **
75813 ** If regPrev>0 then it is a the first register in a vector that
75814 ** records the previous output.  mem[regPrev] is a flag that is false
75815 ** if there has been no previous output.  If regPrev>0 then code is
75816 ** generated to suppress duplicates.  pKeyInfo is used for comparing
75817 ** keys.
75818 **
75819 ** If the LIMIT found in p->iLimit is reached, jump immediately to
75820 ** iBreak.
75821 */
75822 static int generateOutputSubroutine(
75823   Parse *pParse,          /* Parsing context */
75824   Select *p,              /* The SELECT statement */
75825   SelectDest *pIn,        /* Coroutine supplying data */
75826   SelectDest *pDest,      /* Where to send the data */
75827   int regReturn,          /* The return address register */
75828   int regPrev,            /* Previous result register.  No uniqueness if 0 */
75829   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
75830   int p4type,             /* The p4 type for pKeyInfo */
75831   int iBreak              /* Jump here if we hit the LIMIT */
75832 ){
75833   Vdbe *v = pParse->pVdbe;
75834   int iContinue;
75835   int addr;
75836
75837   addr = sqlite3VdbeCurrentAddr(v);
75838   iContinue = sqlite3VdbeMakeLabel(v);
75839
75840   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
75841   */
75842   if( regPrev ){
75843     int j1, j2;
75844     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
75845     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
75846                               (char*)pKeyInfo, p4type);
75847     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
75848     sqlite3VdbeJumpHere(v, j1);
75849     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
75850     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
75851   }
75852   if( pParse->db->mallocFailed ) return 0;
75853
75854   /* Suppress the the first OFFSET entries if there is an OFFSET clause
75855   */
75856   codeOffset(v, p, iContinue);
75857
75858   switch( pDest->eDest ){
75859     /* Store the result as data using a unique key.
75860     */
75861     case SRT_Table:
75862     case SRT_EphemTab: {
75863       int r1 = sqlite3GetTempReg(pParse);
75864       int r2 = sqlite3GetTempReg(pParse);
75865       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
75866       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
75867       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
75868       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75869       sqlite3ReleaseTempReg(pParse, r2);
75870       sqlite3ReleaseTempReg(pParse, r1);
75871       break;
75872     }
75873
75874 #ifndef SQLITE_OMIT_SUBQUERY
75875     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
75876     ** then there should be a single item on the stack.  Write this
75877     ** item into the set table with bogus data.
75878     */
75879     case SRT_Set: {
75880       int r1;
75881       assert( pIn->nMem==1 );
75882       p->affinity = 
75883          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
75884       r1 = sqlite3GetTempReg(pParse);
75885       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
75886       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
75887       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
75888       sqlite3ReleaseTempReg(pParse, r1);
75889       break;
75890     }
75891
75892 #if 0  /* Never occurs on an ORDER BY query */
75893     /* If any row exist in the result set, record that fact and abort.
75894     */
75895     case SRT_Exists: {
75896       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
75897       /* The LIMIT clause will terminate the loop for us */
75898       break;
75899     }
75900 #endif
75901
75902     /* If this is a scalar select that is part of an expression, then
75903     ** store the results in the appropriate memory cell and break out
75904     ** of the scan loop.
75905     */
75906     case SRT_Mem: {
75907       assert( pIn->nMem==1 );
75908       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
75909       /* The LIMIT clause will jump out of the loop for us */
75910       break;
75911     }
75912 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
75913
75914     /* The results are stored in a sequence of registers
75915     ** starting at pDest->iMem.  Then the co-routine yields.
75916     */
75917     case SRT_Coroutine: {
75918       if( pDest->iMem==0 ){
75919         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
75920         pDest->nMem = pIn->nMem;
75921       }
75922       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
75923       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
75924       break;
75925     }
75926
75927     /* Results are stored in a sequence of registers.  Then the
75928     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
75929     ** the next row of result.
75930     */
75931     case SRT_Output: {
75932       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
75933       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
75934       break;
75935     }
75936
75937 #if !defined(SQLITE_OMIT_TRIGGER)
75938     /* Discard the results.  This is used for SELECT statements inside
75939     ** the body of a TRIGGER.  The purpose of such selects is to call
75940     ** user-defined functions that have side effects.  We do not care
75941     ** about the actual results of the select.
75942     */
75943     default: {
75944       break;
75945     }
75946 #endif
75947   }
75948
75949   /* Jump to the end of the loop if the LIMIT is reached.
75950   */
75951   if( p->iLimit ){
75952     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
75953     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
75954   }
75955
75956   /* Generate the subroutine return
75957   */
75958   sqlite3VdbeResolveLabel(v, iContinue);
75959   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
75960
75961   return addr;
75962 }
75963
75964 /*
75965 ** Alternative compound select code generator for cases when there
75966 ** is an ORDER BY clause.
75967 **
75968 ** We assume a query of the following form:
75969 **
75970 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
75971 **
75972 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
75973 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
75974 ** co-routines.  Then run the co-routines in parallel and merge the results
75975 ** into the output.  In addition to the two coroutines (called selectA and
75976 ** selectB) there are 7 subroutines:
75977 **
75978 **    outA:    Move the output of the selectA coroutine into the output
75979 **             of the compound query.
75980 **
75981 **    outB:    Move the output of the selectB coroutine into the output
75982 **             of the compound query.  (Only generated for UNION and
75983 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
75984 **             appears only in B.)
75985 **
75986 **    AltB:    Called when there is data from both coroutines and A<B.
75987 **
75988 **    AeqB:    Called when there is data from both coroutines and A==B.
75989 **
75990 **    AgtB:    Called when there is data from both coroutines and A>B.
75991 **
75992 **    EofA:    Called when data is exhausted from selectA.
75993 **
75994 **    EofB:    Called when data is exhausted from selectB.
75995 **
75996 ** The implementation of the latter five subroutines depend on which 
75997 ** <operator> is used:
75998 **
75999 **
76000 **             UNION ALL         UNION            EXCEPT          INTERSECT
76001 **          -------------  -----------------  --------------  -----------------
76002 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
76003 **
76004 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
76005 **
76006 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
76007 **
76008 **   EofA:   outB, nextB      outB, nextB          halt             halt
76009 **
76010 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
76011 **
76012 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
76013 ** causes an immediate jump to EofA and an EOF on B following nextB causes
76014 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
76015 ** following nextX causes a jump to the end of the select processing.
76016 **
76017 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
76018 ** within the output subroutine.  The regPrev register set holds the previously
76019 ** output value.  A comparison is made against this value and the output
76020 ** is skipped if the next results would be the same as the previous.
76021 **
76022 ** The implementation plan is to implement the two coroutines and seven
76023 ** subroutines first, then put the control logic at the bottom.  Like this:
76024 **
76025 **          goto Init
76026 **     coA: coroutine for left query (A)
76027 **     coB: coroutine for right query (B)
76028 **    outA: output one row of A
76029 **    outB: output one row of B (UNION and UNION ALL only)
76030 **    EofA: ...
76031 **    EofB: ...
76032 **    AltB: ...
76033 **    AeqB: ...
76034 **    AgtB: ...
76035 **    Init: initialize coroutine registers
76036 **          yield coA
76037 **          if eof(A) goto EofA
76038 **          yield coB
76039 **          if eof(B) goto EofB
76040 **    Cmpr: Compare A, B
76041 **          Jump AltB, AeqB, AgtB
76042 **     End: ...
76043 **
76044 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
76045 ** actually called using Gosub and they do not Return.  EofA and EofB loop
76046 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
76047 ** and AgtB jump to either L2 or to one of EofA or EofB.
76048 */
76049 #ifndef SQLITE_OMIT_COMPOUND_SELECT
76050 static int multiSelectOrderBy(
76051   Parse *pParse,        /* Parsing context */
76052   Select *p,            /* The right-most of SELECTs to be coded */
76053   SelectDest *pDest     /* What to do with query results */
76054 ){
76055   int i, j;             /* Loop counters */
76056   Select *pPrior;       /* Another SELECT immediately to our left */
76057   Vdbe *v;              /* Generate code to this VDBE */
76058   SelectDest destA;     /* Destination for coroutine A */
76059   SelectDest destB;     /* Destination for coroutine B */
76060   int regAddrA;         /* Address register for select-A coroutine */
76061   int regEofA;          /* Flag to indicate when select-A is complete */
76062   int regAddrB;         /* Address register for select-B coroutine */
76063   int regEofB;          /* Flag to indicate when select-B is complete */
76064   int addrSelectA;      /* Address of the select-A coroutine */
76065   int addrSelectB;      /* Address of the select-B coroutine */
76066   int regOutA;          /* Address register for the output-A subroutine */
76067   int regOutB;          /* Address register for the output-B subroutine */
76068   int addrOutA;         /* Address of the output-A subroutine */
76069   int addrOutB = 0;     /* Address of the output-B subroutine */
76070   int addrEofA;         /* Address of the select-A-exhausted subroutine */
76071   int addrEofB;         /* Address of the select-B-exhausted subroutine */
76072   int addrAltB;         /* Address of the A<B subroutine */
76073   int addrAeqB;         /* Address of the A==B subroutine */
76074   int addrAgtB;         /* Address of the A>B subroutine */
76075   int regLimitA;        /* Limit register for select-A */
76076   int regLimitB;        /* Limit register for select-A */
76077   int regPrev;          /* A range of registers to hold previous output */
76078   int savedLimit;       /* Saved value of p->iLimit */
76079   int savedOffset;      /* Saved value of p->iOffset */
76080   int labelCmpr;        /* Label for the start of the merge algorithm */
76081   int labelEnd;         /* Label for the end of the overall SELECT stmt */
76082   int j1;               /* Jump instructions that get retargetted */
76083   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
76084   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
76085   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
76086   sqlite3 *db;          /* Database connection */
76087   ExprList *pOrderBy;   /* The ORDER BY clause */
76088   int nOrderBy;         /* Number of terms in the ORDER BY clause */
76089   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
76090
76091   assert( p->pOrderBy!=0 );
76092   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
76093   db = pParse->db;
76094   v = pParse->pVdbe;
76095   if( v==0 ) return SQLITE_NOMEM;
76096   labelEnd = sqlite3VdbeMakeLabel(v);
76097   labelCmpr = sqlite3VdbeMakeLabel(v);
76098
76099
76100   /* Patch up the ORDER BY clause
76101   */
76102   op = p->op;  
76103   pPrior = p->pPrior;
76104   assert( pPrior->pOrderBy==0 );
76105   pOrderBy = p->pOrderBy;
76106   assert( pOrderBy );
76107   nOrderBy = pOrderBy->nExpr;
76108
76109   /* For operators other than UNION ALL we have to make sure that
76110   ** the ORDER BY clause covers every term of the result set.  Add
76111   ** terms to the ORDER BY clause as necessary.
76112   */
76113   if( op!=TK_ALL ){
76114     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
76115       struct ExprList_item *pItem;
76116       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
76117         assert( pItem->iCol>0 );
76118         if( pItem->iCol==i ) break;
76119       }
76120       if( j==nOrderBy ){
76121         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
76122         if( pNew==0 ) return SQLITE_NOMEM;
76123         pNew->flags |= EP_IntValue;
76124         pNew->iTable = i;
76125         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
76126         pOrderBy->a[nOrderBy++].iCol = (u16)i;
76127       }
76128     }
76129   }
76130
76131   /* Compute the comparison permutation and keyinfo that is used with
76132   ** the permutation in order to comparisons to determine if the next
76133   ** row of results comes from selectA or selectB.  Also add explicit
76134   ** collations to the ORDER BY clause terms so that when the subqueries
76135   ** to the right and the left are evaluated, they use the correct
76136   ** collation.
76137   */
76138   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
76139   if( aPermute ){
76140     struct ExprList_item *pItem;
76141     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
76142       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
76143       aPermute[i] = pItem->iCol - 1;
76144     }
76145     pKeyMerge =
76146       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
76147     if( pKeyMerge ){
76148       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
76149       pKeyMerge->nField = (u16)nOrderBy;
76150       pKeyMerge->enc = ENC(db);
76151       for(i=0; i<nOrderBy; i++){
76152         CollSeq *pColl;
76153         Expr *pTerm = pOrderBy->a[i].pExpr;
76154         if( pTerm->flags & EP_ExpCollate ){
76155           pColl = pTerm->pColl;
76156         }else{
76157           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
76158           pTerm->flags |= EP_ExpCollate;
76159           pTerm->pColl = pColl;
76160         }
76161         pKeyMerge->aColl[i] = pColl;
76162         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
76163       }
76164     }
76165   }else{
76166     pKeyMerge = 0;
76167   }
76168
76169   /* Reattach the ORDER BY clause to the query.
76170   */
76171   p->pOrderBy = pOrderBy;
76172   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
76173
76174   /* Allocate a range of temporary registers and the KeyInfo needed
76175   ** for the logic that removes duplicate result rows when the
76176   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
76177   */
76178   if( op==TK_ALL ){
76179     regPrev = 0;
76180   }else{
76181     int nExpr = p->pEList->nExpr;
76182     assert( nOrderBy>=nExpr || db->mallocFailed );
76183     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
76184     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
76185     pKeyDup = sqlite3DbMallocZero(db,
76186                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
76187     if( pKeyDup ){
76188       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
76189       pKeyDup->nField = (u16)nExpr;
76190       pKeyDup->enc = ENC(db);
76191       for(i=0; i<nExpr; i++){
76192         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
76193         pKeyDup->aSortOrder[i] = 0;
76194       }
76195     }
76196   }
76197  
76198   /* Separate the left and the right query from one another
76199   */
76200   p->pPrior = 0;
76201   pPrior->pRightmost = 0;
76202   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
76203   if( pPrior->pPrior==0 ){
76204     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
76205   }
76206
76207   /* Compute the limit registers */
76208   computeLimitRegisters(pParse, p, labelEnd);
76209   if( p->iLimit && op==TK_ALL ){
76210     regLimitA = ++pParse->nMem;
76211     regLimitB = ++pParse->nMem;
76212     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
76213                                   regLimitA);
76214     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
76215   }else{
76216     regLimitA = regLimitB = 0;
76217   }
76218   sqlite3ExprDelete(db, p->pLimit);
76219   p->pLimit = 0;
76220   sqlite3ExprDelete(db, p->pOffset);
76221   p->pOffset = 0;
76222
76223   regAddrA = ++pParse->nMem;
76224   regEofA = ++pParse->nMem;
76225   regAddrB = ++pParse->nMem;
76226   regEofB = ++pParse->nMem;
76227   regOutA = ++pParse->nMem;
76228   regOutB = ++pParse->nMem;
76229   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
76230   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
76231
76232   /* Jump past the various subroutines and coroutines to the main
76233   ** merge loop
76234   */
76235   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
76236   addrSelectA = sqlite3VdbeCurrentAddr(v);
76237
76238
76239   /* Generate a coroutine to evaluate the SELECT statement to the
76240   ** left of the compound operator - the "A" select.
76241   */
76242   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
76243   pPrior->iLimit = regLimitA;
76244   sqlite3Select(pParse, pPrior, &destA);
76245   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
76246   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
76247   VdbeNoopComment((v, "End coroutine for left SELECT"));
76248
76249   /* Generate a coroutine to evaluate the SELECT statement on 
76250   ** the right - the "B" select
76251   */
76252   addrSelectB = sqlite3VdbeCurrentAddr(v);
76253   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
76254   savedLimit = p->iLimit;
76255   savedOffset = p->iOffset;
76256   p->iLimit = regLimitB;
76257   p->iOffset = 0;  
76258   sqlite3Select(pParse, p, &destB);
76259   p->iLimit = savedLimit;
76260   p->iOffset = savedOffset;
76261   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
76262   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
76263   VdbeNoopComment((v, "End coroutine for right SELECT"));
76264
76265   /* Generate a subroutine that outputs the current row of the A
76266   ** select as the next output row of the compound select.
76267   */
76268   VdbeNoopComment((v, "Output routine for A"));
76269   addrOutA = generateOutputSubroutine(pParse,
76270                  p, &destA, pDest, regOutA,
76271                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
76272   
76273   /* Generate a subroutine that outputs the current row of the B
76274   ** select as the next output row of the compound select.
76275   */
76276   if( op==TK_ALL || op==TK_UNION ){
76277     VdbeNoopComment((v, "Output routine for B"));
76278     addrOutB = generateOutputSubroutine(pParse,
76279                  p, &destB, pDest, regOutB,
76280                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
76281   }
76282
76283   /* Generate a subroutine to run when the results from select A
76284   ** are exhausted and only data in select B remains.
76285   */
76286   VdbeNoopComment((v, "eof-A subroutine"));
76287   if( op==TK_EXCEPT || op==TK_INTERSECT ){
76288     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
76289   }else{  
76290     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
76291     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
76292     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
76293     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
76294   }
76295
76296   /* Generate a subroutine to run when the results from select B
76297   ** are exhausted and only data in select A remains.
76298   */
76299   if( op==TK_INTERSECT ){
76300     addrEofB = addrEofA;
76301   }else{  
76302     VdbeNoopComment((v, "eof-B subroutine"));
76303     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
76304     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
76305     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
76306     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
76307   }
76308
76309   /* Generate code to handle the case of A<B
76310   */
76311   VdbeNoopComment((v, "A-lt-B subroutine"));
76312   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
76313   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
76314   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
76315   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
76316
76317   /* Generate code to handle the case of A==B
76318   */
76319   if( op==TK_ALL ){
76320     addrAeqB = addrAltB;
76321   }else if( op==TK_INTERSECT ){
76322     addrAeqB = addrAltB;
76323     addrAltB++;
76324   }else{
76325     VdbeNoopComment((v, "A-eq-B subroutine"));
76326     addrAeqB =
76327     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
76328     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
76329     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
76330   }
76331
76332   /* Generate code to handle the case of A>B
76333   */
76334   VdbeNoopComment((v, "A-gt-B subroutine"));
76335   addrAgtB = sqlite3VdbeCurrentAddr(v);
76336   if( op==TK_ALL || op==TK_UNION ){
76337     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
76338   }
76339   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
76340   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
76341   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
76342
76343   /* This code runs once to initialize everything.
76344   */
76345   sqlite3VdbeJumpHere(v, j1);
76346   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
76347   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
76348   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
76349   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
76350   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
76351   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
76352
76353   /* Implement the main merge loop
76354   */
76355   sqlite3VdbeResolveLabel(v, labelCmpr);
76356   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
76357   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
76358                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
76359   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
76360
76361   /* Release temporary registers
76362   */
76363   if( regPrev ){
76364     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
76365   }
76366
76367   /* Jump to the this point in order to terminate the query.
76368   */
76369   sqlite3VdbeResolveLabel(v, labelEnd);
76370
76371   /* Set the number of output columns
76372   */
76373   if( pDest->eDest==SRT_Output ){
76374     Select *pFirst = pPrior;
76375     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
76376     generateColumnNames(pParse, 0, pFirst->pEList);
76377   }
76378
76379   /* Reassembly the compound query so that it will be freed correctly
76380   ** by the calling function */
76381   if( p->pPrior ){
76382     sqlite3SelectDelete(db, p->pPrior);
76383   }
76384   p->pPrior = pPrior;
76385
76386   /*** TBD:  Insert subroutine calls to close cursors on incomplete
76387   **** subqueries ****/
76388   return SQLITE_OK;
76389 }
76390 #endif
76391
76392 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
76393 /* Forward Declarations */
76394 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
76395 static void substSelect(sqlite3*, Select *, int, ExprList *);
76396
76397 /*
76398 ** Scan through the expression pExpr.  Replace every reference to
76399 ** a column in table number iTable with a copy of the iColumn-th
76400 ** entry in pEList.  (But leave references to the ROWID column 
76401 ** unchanged.)
76402 **
76403 ** This routine is part of the flattening procedure.  A subquery
76404 ** whose result set is defined by pEList appears as entry in the
76405 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
76406 ** FORM clause entry is iTable.  This routine make the necessary 
76407 ** changes to pExpr so that it refers directly to the source table
76408 ** of the subquery rather the result set of the subquery.
76409 */
76410 static void substExpr(
76411   sqlite3 *db,        /* Report malloc errors to this connection */
76412   Expr *pExpr,        /* Expr in which substitution occurs */
76413   int iTable,         /* Table to be substituted */
76414   ExprList *pEList    /* Substitute expressions */
76415 ){
76416   if( pExpr==0 ) return;
76417   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
76418     if( pExpr->iColumn<0 ){
76419       pExpr->op = TK_NULL;
76420     }else{
76421       Expr *pNew;
76422       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
76423       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
76424       pNew = pEList->a[pExpr->iColumn].pExpr;
76425       assert( pNew!=0 );
76426       pExpr->op = pNew->op;
76427       assert( pExpr->pLeft==0 );
76428       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
76429       assert( pExpr->pRight==0 );
76430       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
76431       assert( pExpr->pList==0 );
76432       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
76433       pExpr->iTable = pNew->iTable;
76434       pExpr->pTab = pNew->pTab;
76435       pExpr->iColumn = pNew->iColumn;
76436       pExpr->iAgg = pNew->iAgg;
76437       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
76438       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
76439       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
76440       pExpr->flags = pNew->flags;
76441       pExpr->pAggInfo = pNew->pAggInfo;
76442       pNew->pAggInfo = 0;
76443     }
76444   }else{
76445     substExpr(db, pExpr->pLeft, iTable, pEList);
76446     substExpr(db, pExpr->pRight, iTable, pEList);
76447     substSelect(db, pExpr->pSelect, iTable, pEList);
76448     substExprList(db, pExpr->pList, iTable, pEList);
76449   }
76450 }
76451 static void substExprList(
76452   sqlite3 *db,         /* Report malloc errors here */
76453   ExprList *pList,     /* List to scan and in which to make substitutes */
76454   int iTable,          /* Table to be substituted */
76455   ExprList *pEList     /* Substitute values */
76456 ){
76457   int i;
76458   if( pList==0 ) return;
76459   for(i=0; i<pList->nExpr; i++){
76460     substExpr(db, pList->a[i].pExpr, iTable, pEList);
76461   }
76462 }
76463 static void substSelect(
76464   sqlite3 *db,         /* Report malloc errors here */
76465   Select *p,           /* SELECT statement in which to make substitutions */
76466   int iTable,          /* Table to be replaced */
76467   ExprList *pEList     /* Substitute values */
76468 ){
76469   SrcList *pSrc;
76470   struct SrcList_item *pItem;
76471   int i;
76472   if( !p ) return;
76473   substExprList(db, p->pEList, iTable, pEList);
76474   substExprList(db, p->pGroupBy, iTable, pEList);
76475   substExprList(db, p->pOrderBy, iTable, pEList);
76476   substExpr(db, p->pHaving, iTable, pEList);
76477   substExpr(db, p->pWhere, iTable, pEList);
76478   substSelect(db, p->pPrior, iTable, pEList);
76479   pSrc = p->pSrc;
76480   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
76481   if( ALWAYS(pSrc) ){
76482     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
76483       substSelect(db, pItem->pSelect, iTable, pEList);
76484     }
76485   }
76486 }
76487 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
76488
76489 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
76490 /*
76491 ** This routine attempts to flatten subqueries in order to speed
76492 ** execution.  It returns 1 if it makes changes and 0 if no flattening
76493 ** occurs.
76494 **
76495 ** To understand the concept of flattening, consider the following
76496 ** query:
76497 **
76498 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
76499 **
76500 ** The default way of implementing this query is to execute the
76501 ** subquery first and store the results in a temporary table, then
76502 ** run the outer query on that temporary table.  This requires two
76503 ** passes over the data.  Furthermore, because the temporary table
76504 ** has no indices, the WHERE clause on the outer query cannot be
76505 ** optimized.
76506 **
76507 ** This routine attempts to rewrite queries such as the above into
76508 ** a single flat select, like this:
76509 **
76510 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
76511 **
76512 ** The code generated for this simpification gives the same result
76513 ** but only has to scan the data once.  And because indices might 
76514 ** exist on the table t1, a complete scan of the data might be
76515 ** avoided.
76516 **
76517 ** Flattening is only attempted if all of the following are true:
76518 **
76519 **   (1)  The subquery and the outer query do not both use aggregates.
76520 **
76521 **   (2)  The subquery is not an aggregate or the outer query is not a join.
76522 **
76523 **   (3)  The subquery is not the right operand of a left outer join
76524 **        (Originally ticket #306.  Strenghtened by ticket #3300)
76525 **
76526 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
76527 **
76528 **   (5)  The subquery is not DISTINCT or the outer query does not use
76529 **        aggregates.
76530 **
76531 **   (6)  The subquery does not use aggregates or the outer query is not
76532 **        DISTINCT.
76533 **
76534 **   (7)  The subquery has a FROM clause.
76535 **
76536 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
76537 **
76538 **   (9)  The subquery does not use LIMIT or the outer query does not use
76539 **        aggregates.
76540 **
76541 **  (10)  The subquery does not use aggregates or the outer query does not
76542 **        use LIMIT.
76543 **
76544 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
76545 **
76546 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
76547 **        a separate restriction deriving from ticket #350.
76548 **
76549 **  (13)  The subquery and outer query do not both use LIMIT
76550 **
76551 **  (14)  The subquery does not use OFFSET
76552 **
76553 **  (15)  The outer query is not part of a compound select or the
76554 **        subquery does not have both an ORDER BY and a LIMIT clause.
76555 **        (See ticket #2339)
76556 **
76557 **  (16)  The outer query is not an aggregate or the subquery does
76558 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
76559 **        until we introduced the group_concat() function.  
76560 **
76561 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
76562 **        compound clause made up entirely of non-aggregate queries, and 
76563 **        the parent query:
76564 **
76565 **          * is not itself part of a compound select,
76566 **          * is not an aggregate or DISTINCT query, and
76567 **          * has no other tables or sub-selects in the FROM clause.
76568 **
76569 **        The parent and sub-query may contain WHERE clauses. Subject to
76570 **        rules (11), (13) and (14), they may also contain ORDER BY,
76571 **        LIMIT and OFFSET clauses.
76572 **
76573 **  (18)  If the sub-query is a compound select, then all terms of the
76574 **        ORDER by clause of the parent must be simple references to 
76575 **        columns of the sub-query.
76576 **
76577 **  (19)  The subquery does not use LIMIT or the outer query does not
76578 **        have a WHERE clause.
76579 **
76580 ** In this routine, the "p" parameter is a pointer to the outer query.
76581 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
76582 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
76583 **
76584 ** If flattening is not attempted, this routine is a no-op and returns 0.
76585 ** If flattening is attempted this routine returns 1.
76586 **
76587 ** All of the expression analysis must occur on both the outer query and
76588 ** the subquery before this routine runs.
76589 */
76590 static int flattenSubquery(
76591   Parse *pParse,       /* Parsing context */
76592   Select *p,           /* The parent or outer SELECT statement */
76593   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
76594   int isAgg,           /* True if outer SELECT uses aggregate functions */
76595   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
76596 ){
76597   const char *zSavedAuthContext = pParse->zAuthContext;
76598   Select *pParent;
76599   Select *pSub;       /* The inner query or "subquery" */
76600   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
76601   SrcList *pSrc;      /* The FROM clause of the outer query */
76602   SrcList *pSubSrc;   /* The FROM clause of the subquery */
76603   ExprList *pList;    /* The result set of the outer query */
76604   int iParent;        /* VDBE cursor number of the pSub result set temp table */
76605   int i;              /* Loop counter */
76606   Expr *pWhere;                    /* The WHERE clause */
76607   struct SrcList_item *pSubitem;   /* The subquery */
76608   sqlite3 *db = pParse->db;
76609
76610   /* Check to see if flattening is permitted.  Return 0 if not.
76611   */
76612   assert( p!=0 );
76613   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
76614   pSrc = p->pSrc;
76615   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
76616   pSubitem = &pSrc->a[iFrom];
76617   iParent = pSubitem->iCursor;
76618   pSub = pSubitem->pSelect;
76619   assert( pSub!=0 );
76620   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
76621   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
76622   pSubSrc = pSub->pSrc;
76623   assert( pSubSrc );
76624   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
76625   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
76626   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
76627   ** became arbitrary expressions, we were forced to add restrictions (13)
76628   ** and (14). */
76629   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
76630   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
76631   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
76632     return 0;                                            /* Restriction (15) */
76633   }
76634   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
76635   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
76636          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
76637      return 0;       
76638   }
76639   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
76640      return 0;         /* Restriction (6)  */
76641   }
76642   if( p->pOrderBy && pSub->pOrderBy ){
76643      return 0;                                           /* Restriction (11) */
76644   }
76645   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
76646   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
76647
76648   /* OBSOLETE COMMENT 1:
76649   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
76650   ** not used as the right operand of an outer join.  Examples of why this
76651   ** is not allowed:
76652   **
76653   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
76654   **
76655   ** If we flatten the above, we would get
76656   **
76657   **         (t1 LEFT OUTER JOIN t2) JOIN t3
76658   **
76659   ** which is not at all the same thing.
76660   **
76661   ** OBSOLETE COMMENT 2:
76662   ** Restriction 12:  If the subquery is the right operand of a left outer
76663   ** join, make sure the subquery has no WHERE clause.
76664   ** An examples of why this is not allowed:
76665   **
76666   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
76667   **
76668   ** If we flatten the above, we would get
76669   **
76670   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
76671   **
76672   ** But the t2.x>0 test will always fail on a NULL row of t2, which
76673   ** effectively converts the OUTER JOIN into an INNER JOIN.
76674   **
76675   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
76676   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
76677   ** is fraught with danger.  Best to avoid the whole thing.  If the
76678   ** subquery is the right term of a LEFT JOIN, then do not flatten.
76679   */
76680   if( (pSubitem->jointype & JT_OUTER)!=0 ){
76681     return 0;
76682   }
76683
76684   /* Restriction 17: If the sub-query is a compound SELECT, then it must
76685   ** use only the UNION ALL operator. And none of the simple select queries
76686   ** that make up the compound SELECT are allowed to be aggregate or distinct
76687   ** queries.
76688   */
76689   if( pSub->pPrior ){
76690     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
76691       return 0;
76692     }
76693     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
76694       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
76695        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
76696        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
76697       ){
76698         return 0;
76699       }
76700     }
76701
76702     /* Restriction 18. */
76703     if( p->pOrderBy ){
76704       int ii;
76705       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
76706         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
76707       }
76708     }
76709   }
76710
76711   /***** If we reach this point, flattening is permitted. *****/
76712
76713   /* Authorize the subquery */
76714   pParse->zAuthContext = pSubitem->zName;
76715   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
76716   pParse->zAuthContext = zSavedAuthContext;
76717
76718   /* If the sub-query is a compound SELECT statement, then (by restrictions
76719   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
76720   ** be of the form:
76721   **
76722   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
76723   **
76724   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
76725   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
76726   ** OFFSET clauses and joins them to the left-hand-side of the original
76727   ** using UNION ALL operators. In this case N is the number of simple
76728   ** select statements in the compound sub-query.
76729   **
76730   ** Example:
76731   **
76732   **     SELECT a+1 FROM (
76733   **        SELECT x FROM tab
76734   **        UNION ALL
76735   **        SELECT y FROM tab
76736   **        UNION ALL
76737   **        SELECT abs(z*2) FROM tab2
76738   **     ) WHERE a!=5 ORDER BY 1
76739   **
76740   ** Transformed into:
76741   **
76742   **     SELECT x+1 FROM tab WHERE x+1!=5
76743   **     UNION ALL
76744   **     SELECT y+1 FROM tab WHERE y+1!=5
76745   **     UNION ALL
76746   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
76747   **     ORDER BY 1
76748   **
76749   ** We call this the "compound-subquery flattening".
76750   */
76751   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
76752     Select *pNew;
76753     ExprList *pOrderBy = p->pOrderBy;
76754     Expr *pLimit = p->pLimit;
76755     Select *pPrior = p->pPrior;
76756     p->pOrderBy = 0;
76757     p->pSrc = 0;
76758     p->pPrior = 0;
76759     p->pLimit = 0;
76760     pNew = sqlite3SelectDup(db, p);
76761     p->pLimit = pLimit;
76762     p->pOrderBy = pOrderBy;
76763     p->pSrc = pSrc;
76764     p->op = TK_ALL;
76765     p->pRightmost = 0;
76766     if( pNew==0 ){
76767       pNew = pPrior;
76768     }else{
76769       pNew->pPrior = pPrior;
76770       pNew->pRightmost = 0;
76771     }
76772     p->pPrior = pNew;
76773     if( db->mallocFailed ) return 1;
76774   }
76775
76776   /* Begin flattening the iFrom-th entry of the FROM clause 
76777   ** in the outer query.
76778   */
76779   pSub = pSub1 = pSubitem->pSelect;
76780
76781   /* Delete the transient table structure associated with the
76782   ** subquery
76783   */
76784   sqlite3DbFree(db, pSubitem->zDatabase);
76785   sqlite3DbFree(db, pSubitem->zName);
76786   sqlite3DbFree(db, pSubitem->zAlias);
76787   pSubitem->zDatabase = 0;
76788   pSubitem->zName = 0;
76789   pSubitem->zAlias = 0;
76790   pSubitem->pSelect = 0;
76791
76792   /* Defer deleting the Table object associated with the
76793   ** subquery until code generation is
76794   ** complete, since there may still exist Expr.pTab entries that
76795   ** refer to the subquery even after flattening.  Ticket #3346.
76796   */
76797   if( pSubitem->pTab!=0 ){
76798     Table *pTabToDel = pSubitem->pTab;
76799     if( pTabToDel->nRef==1 ){
76800       pTabToDel->pNextZombie = pParse->pZombieTab;
76801       pParse->pZombieTab = pTabToDel;
76802     }else{
76803       pTabToDel->nRef--;
76804     }
76805     pSubitem->pTab = 0;
76806   }
76807
76808   /* The following loop runs once for each term in a compound-subquery
76809   ** flattening (as described above).  If we are doing a different kind
76810   ** of flattening - a flattening other than a compound-subquery flattening -
76811   ** then this loop only runs once.
76812   **
76813   ** This loop moves all of the FROM elements of the subquery into the
76814   ** the FROM clause of the outer query.  Before doing this, remember
76815   ** the cursor number for the original outer query FROM element in
76816   ** iParent.  The iParent cursor will never be used.  Subsequent code
76817   ** will scan expressions looking for iParent references and replace
76818   ** those references with expressions that resolve to the subquery FROM
76819   ** elements we are now copying in.
76820   */
76821   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
76822     int nSubSrc;
76823     u8 jointype = 0;
76824     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
76825     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
76826     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
76827
76828     if( pSrc ){
76829       assert( pParent==p );  /* First time through the loop */
76830       jointype = pSubitem->jointype;
76831     }else{
76832       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
76833       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
76834       if( pSrc==0 ){
76835         assert( db->mallocFailed );
76836         break;
76837       }
76838     }
76839
76840     /* The subquery uses a single slot of the FROM clause of the outer
76841     ** query.  If the subquery has more than one element in its FROM clause,
76842     ** then expand the outer query to make space for it to hold all elements
76843     ** of the subquery.
76844     **
76845     ** Example:
76846     **
76847     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
76848     **
76849     ** The outer query has 3 slots in its FROM clause.  One slot of the
76850     ** outer query (the middle slot) is used by the subquery.  The next
76851     ** block of code will expand the out query to 4 slots.  The middle
76852     ** slot is expanded to two slots in order to make space for the
76853     ** two elements in the FROM clause of the subquery.
76854     */
76855     if( nSubSrc>1 ){
76856       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
76857       if( db->mallocFailed ){
76858         break;
76859       }
76860     }
76861
76862     /* Transfer the FROM clause terms from the subquery into the
76863     ** outer query.
76864     */
76865     for(i=0; i<nSubSrc; i++){
76866       pSrc->a[i+iFrom] = pSubSrc->a[i];
76867       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
76868     }
76869     pSrc->a[iFrom].jointype = jointype;
76870   
76871     /* Now begin substituting subquery result set expressions for 
76872     ** references to the iParent in the outer query.
76873     ** 
76874     ** Example:
76875     **
76876     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
76877     **   \                     \_____________ subquery __________/          /
76878     **    \_____________________ outer query ______________________________/
76879     **
76880     ** We look at every expression in the outer query and every place we see
76881     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
76882     */
76883     pList = pParent->pEList;
76884     for(i=0; i<pList->nExpr; i++){
76885       Expr *pExpr;
76886       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
76887         pList->a[i].zName = 
76888                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
76889       }
76890     }
76891     substExprList(db, pParent->pEList, iParent, pSub->pEList);
76892     if( isAgg ){
76893       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
76894       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
76895     }
76896     if( pSub->pOrderBy ){
76897       assert( pParent->pOrderBy==0 );
76898       pParent->pOrderBy = pSub->pOrderBy;
76899       pSub->pOrderBy = 0;
76900     }else if( pParent->pOrderBy ){
76901       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
76902     }
76903     if( pSub->pWhere ){
76904       pWhere = sqlite3ExprDup(db, pSub->pWhere);
76905     }else{
76906       pWhere = 0;
76907     }
76908     if( subqueryIsAgg ){
76909       assert( pParent->pHaving==0 );
76910       pParent->pHaving = pParent->pWhere;
76911       pParent->pWhere = pWhere;
76912       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
76913       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
76914                                   sqlite3ExprDup(db, pSub->pHaving));
76915       assert( pParent->pGroupBy==0 );
76916       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
76917     }else{
76918       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
76919       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
76920     }
76921   
76922     /* The flattened query is distinct if either the inner or the
76923     ** outer query is distinct. 
76924     */
76925     pParent->selFlags |= pSub->selFlags & SF_Distinct;
76926   
76927     /*
76928     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
76929     **
76930     ** One is tempted to try to add a and b to combine the limits.  But this
76931     ** does not work if either limit is negative.
76932     */
76933     if( pSub->pLimit ){
76934       pParent->pLimit = pSub->pLimit;
76935       pSub->pLimit = 0;
76936     }
76937   }
76938
76939   /* Finially, delete what is left of the subquery and return
76940   ** success.
76941   */
76942   sqlite3SelectDelete(db, pSub1);
76943
76944   return 1;
76945 }
76946 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
76947
76948 /*
76949 ** Analyze the SELECT statement passed as an argument to see if it
76950 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
76951 ** it is, or 0 otherwise. At present, a query is considered to be
76952 ** a min()/max() query if:
76953 **
76954 **   1. There is a single object in the FROM clause.
76955 **
76956 **   2. There is a single expression in the result set, and it is
76957 **      either min(x) or max(x), where x is a column reference.
76958 */
76959 static u8 minMaxQuery(Select *p){
76960   Expr *pExpr;
76961   ExprList *pEList = p->pEList;
76962
76963   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
76964   pExpr = pEList->a[0].pExpr;
76965   pEList = pExpr->pList;
76966   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
76967   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
76968   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
76969   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
76970     return WHERE_ORDERBY_MIN;
76971   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
76972     return WHERE_ORDERBY_MAX;
76973   }
76974   return WHERE_ORDERBY_NORMAL;
76975 }
76976
76977 /*
76978 ** If the source-list item passed as an argument was augmented with an
76979 ** INDEXED BY clause, then try to locate the specified index. If there
76980 ** was such a clause and the named index cannot be found, return 
76981 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
76982 ** pFrom->pIndex and return SQLITE_OK.
76983 */
76984 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
76985   if( pFrom->pTab && pFrom->zIndex ){
76986     Table *pTab = pFrom->pTab;
76987     char *zIndex = pFrom->zIndex;
76988     Index *pIdx;
76989     for(pIdx=pTab->pIndex; 
76990         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
76991         pIdx=pIdx->pNext
76992     );
76993     if( !pIdx ){
76994       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
76995       return SQLITE_ERROR;
76996     }
76997     pFrom->pIndex = pIdx;
76998   }
76999   return SQLITE_OK;
77000 }
77001
77002 /*
77003 ** This routine is a Walker callback for "expanding" a SELECT statement.
77004 ** "Expanding" means to do the following:
77005 **
77006 **    (1)  Make sure VDBE cursor numbers have been assigned to every
77007 **         element of the FROM clause.
77008 **
77009 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
77010 **         defines FROM clause.  When views appear in the FROM clause,
77011 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
77012 **         that implements the view.  A copy is made of the view's SELECT
77013 **         statement so that we can freely modify or delete that statement
77014 **         without worrying about messing up the presistent representation
77015 **         of the view.
77016 **
77017 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
77018 **         on joins and the ON and USING clause of joins.
77019 **
77020 **    (4)  Scan the list of columns in the result set (pEList) looking
77021 **         for instances of the "*" operator or the TABLE.* operator.
77022 **         If found, expand each "*" to be every column in every table
77023 **         and TABLE.* to be every column in TABLE.
77024 **
77025 */
77026 static int selectExpander(Walker *pWalker, Select *p){
77027   Parse *pParse = pWalker->pParse;
77028   int i, j, k;
77029   SrcList *pTabList;
77030   ExprList *pEList;
77031   struct SrcList_item *pFrom;
77032   sqlite3 *db = pParse->db;
77033
77034   if( db->mallocFailed  ){
77035     return WRC_Abort;
77036   }
77037   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
77038     return WRC_Prune;
77039   }
77040   p->selFlags |= SF_Expanded;
77041   pTabList = p->pSrc;
77042   pEList = p->pEList;
77043
77044   /* Make sure cursor numbers have been assigned to all entries in
77045   ** the FROM clause of the SELECT statement.
77046   */
77047   sqlite3SrcListAssignCursors(pParse, pTabList);
77048
77049   /* Look up every table named in the FROM clause of the select.  If
77050   ** an entry of the FROM clause is a subquery instead of a table or view,
77051   ** then create a transient table structure to describe the subquery.
77052   */
77053   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
77054     Table *pTab;
77055     if( pFrom->pTab!=0 ){
77056       /* This statement has already been prepared.  There is no need
77057       ** to go further. */
77058       assert( i==0 );
77059       return WRC_Prune;
77060     }
77061     if( pFrom->zName==0 ){
77062 #ifndef SQLITE_OMIT_SUBQUERY
77063       Select *pSel = pFrom->pSelect;
77064       /* A sub-query in the FROM clause of a SELECT */
77065       assert( pSel!=0 );
77066       assert( pFrom->pTab==0 );
77067       sqlite3WalkSelect(pWalker, pSel);
77068       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
77069       if( pTab==0 ) return WRC_Abort;
77070       pTab->db = db;
77071       pTab->nRef = 1;
77072       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
77073       while( pSel->pPrior ){ pSel = pSel->pPrior; }
77074       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
77075       pTab->iPKey = -1;
77076       pTab->tabFlags |= TF_Ephemeral;
77077 #endif
77078     }else{
77079       /* An ordinary table or view name in the FROM clause */
77080       assert( pFrom->pTab==0 );
77081       pFrom->pTab = pTab = 
77082         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
77083       if( pTab==0 ) return WRC_Abort;
77084       pTab->nRef++;
77085 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
77086       if( pTab->pSelect || IsVirtual(pTab) ){
77087         /* We reach here if the named table is a really a view */
77088         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
77089
77090         /* If pFrom->pSelect!=0 it means we are dealing with a
77091         ** view within a view.  The SELECT structure has already been
77092         ** copied by the outer view so we can skip the copy step here
77093         ** in the inner view.
77094         */
77095         if( pFrom->pSelect==0 ){
77096           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
77097           sqlite3WalkSelect(pWalker, pFrom->pSelect);
77098         }
77099       }
77100 #endif
77101     }
77102
77103     /* Locate the index named by the INDEXED BY clause, if any. */
77104     if( sqlite3IndexedByLookup(pParse, pFrom) ){
77105       return WRC_Abort;
77106     }
77107   }
77108
77109   /* Process NATURAL keywords, and ON and USING clauses of joins.
77110   */
77111   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
77112     return WRC_Abort;
77113   }
77114
77115   /* For every "*" that occurs in the column list, insert the names of
77116   ** all columns in all tables.  And for every TABLE.* insert the names
77117   ** of all columns in TABLE.  The parser inserted a special expression
77118   ** with the TK_ALL operator for each "*" that it found in the column list.
77119   ** The following code just has to locate the TK_ALL expressions and expand
77120   ** each one to the list of all columns in all tables.
77121   **
77122   ** The first loop just checks to see if there are any "*" operators
77123   ** that need expanding.
77124   */
77125   for(k=0; k<pEList->nExpr; k++){
77126     Expr *pE = pEList->a[k].pExpr;
77127     if( pE->op==TK_ALL ) break;
77128     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
77129          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
77130   }
77131   if( k<pEList->nExpr ){
77132     /*
77133     ** If we get here it means the result set contains one or more "*"
77134     ** operators that need to be expanded.  Loop through each expression
77135     ** in the result set and expand them one by one.
77136     */
77137     struct ExprList_item *a = pEList->a;
77138     ExprList *pNew = 0;
77139     int flags = pParse->db->flags;
77140     int longNames = (flags & SQLITE_FullColNames)!=0
77141                       && (flags & SQLITE_ShortColNames)==0;
77142
77143     for(k=0; k<pEList->nExpr; k++){
77144       Expr *pE = a[k].pExpr;
77145       if( pE->op!=TK_ALL &&
77146            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
77147         /* This particular expression does not need to be expanded.
77148         */
77149         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
77150         if( pNew ){
77151           pNew->a[pNew->nExpr-1].zName = a[k].zName;
77152         }
77153         a[k].pExpr = 0;
77154         a[k].zName = 0;
77155       }else{
77156         /* This expression is a "*" or a "TABLE.*" and needs to be
77157         ** expanded. */
77158         int tableSeen = 0;      /* Set to 1 when TABLE matches */
77159         char *zTName;            /* text of name of TABLE */
77160         if( pE->op==TK_DOT && pE->pLeft ){
77161           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
77162         }else{
77163           zTName = 0;
77164         }
77165         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
77166           Table *pTab = pFrom->pTab;
77167           char *zTabName = pFrom->zAlias;
77168           if( zTabName==0 || zTabName[0]==0 ){ 
77169             zTabName = pTab->zName;
77170           }
77171           if( db->mallocFailed ) break;
77172           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
77173             continue;
77174           }
77175           tableSeen = 1;
77176           for(j=0; j<pTab->nCol; j++){
77177             Expr *pExpr, *pRight;
77178             char *zName = pTab->aCol[j].zName;
77179
77180             /* If a column is marked as 'hidden' (currently only possible
77181             ** for virtual tables), do not include it in the expanded
77182             ** result-set list.
77183             */
77184             if( IsHiddenColumn(&pTab->aCol[j]) ){
77185               assert(IsVirtual(pTab));
77186               continue;
77187             }
77188
77189             if( i>0 && zTName==0 ){
77190               struct SrcList_item *pLeft = &pTabList->a[i-1];
77191               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
77192                         columnIndex(pLeft->pTab, zName)>=0 ){
77193                 /* In a NATURAL join, omit the join columns from the 
77194                 ** table on the right */
77195                 continue;
77196               }
77197               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
77198                 /* In a join with a USING clause, omit columns in the
77199                 ** using clause from the table on the right. */
77200                 continue;
77201               }
77202             }
77203             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
77204             if( pRight==0 ) break;
77205             setQuotedToken(pParse, &pRight->token, zName);
77206             if( longNames || pTabList->nSrc>1 ){
77207               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
77208               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
77209               if( pExpr==0 ) break;
77210               setQuotedToken(pParse, &pLeft->token, zTabName);
77211               setToken(&pExpr->span, 
77212                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
77213               pExpr->span.dyn = 1;
77214               pExpr->token.z = 0;
77215               pExpr->token.n = 0;
77216               pExpr->token.dyn = 0;
77217             }else{
77218               pExpr = pRight;
77219               pExpr->span = pExpr->token;
77220               pExpr->span.dyn = 0;
77221             }
77222             if( longNames ){
77223               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
77224             }else{
77225               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
77226             }
77227           }
77228         }
77229         if( !tableSeen ){
77230           if( zTName ){
77231             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
77232           }else{
77233             sqlite3ErrorMsg(pParse, "no tables specified");
77234           }
77235         }
77236         sqlite3DbFree(db, zTName);
77237       }
77238     }
77239     sqlite3ExprListDelete(db, pEList);
77240     p->pEList = pNew;
77241   }
77242 #if SQLITE_MAX_COLUMN
77243   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77244     sqlite3ErrorMsg(pParse, "too many columns in result set");
77245   }
77246 #endif
77247   return WRC_Continue;
77248 }
77249
77250 /*
77251 ** No-op routine for the parse-tree walker.
77252 **
77253 ** When this routine is the Walker.xExprCallback then expression trees
77254 ** are walked without any actions being taken at each node.  Presumably,
77255 ** when this routine is used for Walker.xExprCallback then 
77256 ** Walker.xSelectCallback is set to do something useful for every 
77257 ** subquery in the parser tree.
77258 */
77259 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
77260   UNUSED_PARAMETER2(NotUsed, NotUsed2);
77261   return WRC_Continue;
77262 }
77263
77264 /*
77265 ** This routine "expands" a SELECT statement and all of its subqueries.
77266 ** For additional information on what it means to "expand" a SELECT
77267 ** statement, see the comment on the selectExpand worker callback above.
77268 **
77269 ** Expanding a SELECT statement is the first step in processing a
77270 ** SELECT statement.  The SELECT statement must be expanded before
77271 ** name resolution is performed.
77272 **
77273 ** If anything goes wrong, an error message is written into pParse.
77274 ** The calling function can detect the problem by looking at pParse->nErr
77275 ** and/or pParse->db->mallocFailed.
77276 */
77277 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
77278   Walker w;
77279   w.xSelectCallback = selectExpander;
77280   w.xExprCallback = exprWalkNoop;
77281   w.pParse = pParse;
77282   sqlite3WalkSelect(&w, pSelect);
77283 }
77284
77285
77286 #ifndef SQLITE_OMIT_SUBQUERY
77287 /*
77288 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
77289 ** interface.
77290 **
77291 ** For each FROM-clause subquery, add Column.zType and Column.zColl
77292 ** information to the Table structure that represents the result set
77293 ** of that subquery.
77294 **
77295 ** The Table structure that represents the result set was constructed
77296 ** by selectExpander() but the type and collation information was omitted
77297 ** at that point because identifiers had not yet been resolved.  This
77298 ** routine is called after identifier resolution.
77299 */
77300 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
77301   Parse *pParse;
77302   int i;
77303   SrcList *pTabList;
77304   struct SrcList_item *pFrom;
77305
77306   assert( p->selFlags & SF_Resolved );
77307   if( (p->selFlags & SF_HasTypeInfo)==0 ){
77308     p->selFlags |= SF_HasTypeInfo;
77309     pParse = pWalker->pParse;
77310     pTabList = p->pSrc;
77311     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
77312       Table *pTab = pFrom->pTab;
77313       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
77314         /* A sub-query in the FROM clause of a SELECT */
77315         Select *pSel = pFrom->pSelect;
77316         assert( pSel );
77317         while( pSel->pPrior ) pSel = pSel->pPrior;
77318         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
77319       }
77320     }
77321   }
77322   return WRC_Continue;
77323 }
77324 #endif
77325
77326
77327 /*
77328 ** This routine adds datatype and collating sequence information to
77329 ** the Table structures of all FROM-clause subqueries in a
77330 ** SELECT statement.
77331 **
77332 ** Use this routine after name resolution.
77333 */
77334 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
77335 #ifndef SQLITE_OMIT_SUBQUERY
77336   Walker w;
77337   w.xSelectCallback = selectAddSubqueryTypeInfo;
77338   w.xExprCallback = exprWalkNoop;
77339   w.pParse = pParse;
77340   sqlite3WalkSelect(&w, pSelect);
77341 #endif
77342 }
77343
77344
77345 /*
77346 ** This routine sets of a SELECT statement for processing.  The
77347 ** following is accomplished:
77348 **
77349 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
77350 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
77351 **     *  ON and USING clauses are shifted into WHERE statements
77352 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
77353 **     *  Identifiers in expression are matched to tables.
77354 **
77355 ** This routine acts recursively on all subqueries within the SELECT.
77356 */
77357 SQLITE_PRIVATE void sqlite3SelectPrep(
77358   Parse *pParse,         /* The parser context */
77359   Select *p,             /* The SELECT statement being coded. */
77360   NameContext *pOuterNC  /* Name context for container */
77361 ){
77362   sqlite3 *db;
77363   if( p==0 ) return;
77364   db = pParse->db;
77365   if( p->selFlags & SF_HasTypeInfo ) return;
77366   if( pParse->nErr || db->mallocFailed ) return;
77367   sqlite3SelectExpand(pParse, p);
77368   if( pParse->nErr || db->mallocFailed ) return;
77369   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
77370   if( pParse->nErr || db->mallocFailed ) return;
77371   sqlite3SelectAddTypeInfo(pParse, p);
77372 }
77373
77374 /*
77375 ** Reset the aggregate accumulator.
77376 **
77377 ** The aggregate accumulator is a set of memory cells that hold
77378 ** intermediate results while calculating an aggregate.  This
77379 ** routine simply stores NULLs in all of those memory cells.
77380 */
77381 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
77382   Vdbe *v = pParse->pVdbe;
77383   int i;
77384   struct AggInfo_func *pFunc;
77385   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
77386     return;
77387   }
77388   for(i=0; i<pAggInfo->nColumn; i++){
77389     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
77390   }
77391   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
77392     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
77393     if( pFunc->iDistinct>=0 ){
77394       Expr *pE = pFunc->pExpr;
77395       if( pE->pList==0 || pE->pList->nExpr!=1 ){
77396         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
77397            "argument");
77398         pFunc->iDistinct = -1;
77399       }else{
77400         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
77401         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
77402                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
77403       }
77404     }
77405   }
77406 }
77407
77408 /*
77409 ** Invoke the OP_AggFinalize opcode for every aggregate function
77410 ** in the AggInfo structure.
77411 */
77412 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
77413   Vdbe *v = pParse->pVdbe;
77414   int i;
77415   struct AggInfo_func *pF;
77416   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
77417     ExprList *pList = pF->pExpr->pList;
77418     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
77419                       (void*)pF->pFunc, P4_FUNCDEF);
77420   }
77421 }
77422
77423 /*
77424 ** Update the accumulator memory cells for an aggregate based on
77425 ** the current cursor position.
77426 */
77427 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
77428   Vdbe *v = pParse->pVdbe;
77429   int i;
77430   struct AggInfo_func *pF;
77431   struct AggInfo_col *pC;
77432
77433   pAggInfo->directMode = 1;
77434   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
77435     int nArg;
77436     int addrNext = 0;
77437     int regAgg;
77438     ExprList *pList = pF->pExpr->pList;
77439     if( pList ){
77440       nArg = pList->nExpr;
77441       regAgg = sqlite3GetTempRange(pParse, nArg);
77442       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
77443     }else{
77444       nArg = 0;
77445       regAgg = 0;
77446     }
77447     if( pF->iDistinct>=0 ){
77448       addrNext = sqlite3VdbeMakeLabel(v);
77449       assert( nArg==1 );
77450       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
77451     }
77452     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
77453       CollSeq *pColl = 0;
77454       struct ExprList_item *pItem;
77455       int j;
77456       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
77457       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
77458         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
77459       }
77460       if( !pColl ){
77461         pColl = pParse->db->pDfltColl;
77462       }
77463       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77464     }
77465     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
77466                       (void*)pF->pFunc, P4_FUNCDEF);
77467     sqlite3VdbeChangeP5(v, (u8)nArg);
77468     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
77469     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
77470     if( addrNext ){
77471       sqlite3VdbeResolveLabel(v, addrNext);
77472     }
77473   }
77474   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
77475     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
77476   }
77477   pAggInfo->directMode = 0;
77478 }
77479
77480 /*
77481 ** Generate code for the SELECT statement given in the p argument.  
77482 **
77483 ** The results are distributed in various ways depending on the
77484 ** contents of the SelectDest structure pointed to by argument pDest
77485 ** as follows:
77486 **
77487 **     pDest->eDest    Result
77488 **     ------------    -------------------------------------------
77489 **     SRT_Output      Generate a row of output (using the OP_ResultRow
77490 **                     opcode) for each row in the result set.
77491 **
77492 **     SRT_Mem         Only valid if the result is a single column.
77493 **                     Store the first column of the first result row
77494 **                     in register pDest->iParm then abandon the rest
77495 **                     of the query.  This destination implies "LIMIT 1".
77496 **
77497 **     SRT_Set         The result must be a single column.  Store each
77498 **                     row of result as the key in table pDest->iParm. 
77499 **                     Apply the affinity pDest->affinity before storing
77500 **                     results.  Used to implement "IN (SELECT ...)".
77501 **
77502 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
77503 **
77504 **     SRT_Except      Remove results from the temporary table pDest->iParm.
77505 **
77506 **     SRT_Table       Store results in temporary table pDest->iParm.
77507 **                     This is like SRT_EphemTab except that the table
77508 **                     is assumed to already be open.
77509 **
77510 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
77511 **                     the result there. The cursor is left open after
77512 **                     returning.  This is like SRT_Table except that
77513 **                     this destination uses OP_OpenEphemeral to create
77514 **                     the table first.
77515 **
77516 **     SRT_Coroutine   Generate a co-routine that returns a new row of
77517 **                     results each time it is invoked.  The entry point
77518 **                     of the co-routine is stored in register pDest->iParm.
77519 **
77520 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
77521 **                     set is not empty.
77522 **
77523 **     SRT_Discard     Throw the results away.  This is used by SELECT
77524 **                     statements within triggers whose only purpose is
77525 **                     the side-effects of functions.
77526 **
77527 ** This routine returns the number of errors.  If any errors are
77528 ** encountered, then an appropriate error message is left in
77529 ** pParse->zErrMsg.
77530 **
77531 ** This routine does NOT free the Select structure passed in.  The
77532 ** calling function needs to do that.
77533 */
77534 SQLITE_PRIVATE int sqlite3Select(
77535   Parse *pParse,         /* The parser context */
77536   Select *p,             /* The SELECT statement being coded. */
77537   SelectDest *pDest      /* What to do with the query results */
77538 ){
77539   int i, j;              /* Loop counters */
77540   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
77541   Vdbe *v;               /* The virtual machine under construction */
77542   int isAgg;             /* True for select lists like "count(*)" */
77543   ExprList *pEList;      /* List of columns to extract. */
77544   SrcList *pTabList;     /* List of tables to select from */
77545   Expr *pWhere;          /* The WHERE clause.  May be NULL */
77546   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
77547   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
77548   Expr *pHaving;         /* The HAVING clause.  May be NULL */
77549   int isDistinct;        /* True if the DISTINCT keyword is present */
77550   int distinct;          /* Table to use for the distinct set */
77551   int rc = 1;            /* Value to return from this function */
77552   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
77553   AggInfo sAggInfo;      /* Information used by aggregate queries */
77554   int iEnd;              /* Address of the end of the query */
77555   sqlite3 *db;           /* The database connection */
77556
77557   db = pParse->db;
77558   if( p==0 || db->mallocFailed || pParse->nErr ){
77559     return 1;
77560   }
77561   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
77562   memset(&sAggInfo, 0, sizeof(sAggInfo));
77563
77564   pOrderBy = p->pOrderBy;
77565   if( IgnorableOrderby(pDest) ){
77566     p->pOrderBy = 0;
77567
77568     /* In these cases the DISTINCT operator makes no difference to the
77569     ** results, so remove it if it were specified.
77570     */
77571     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
77572            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
77573     p->selFlags &= ~SF_Distinct;
77574   }
77575   sqlite3SelectPrep(pParse, p, 0);
77576   pTabList = p->pSrc;
77577   pEList = p->pEList;
77578   if( pParse->nErr || db->mallocFailed ){
77579     goto select_end;
77580   }
77581   p->pOrderBy = pOrderBy;
77582   isAgg = (p->selFlags & SF_Aggregate)!=0;
77583   if( pEList==0 ) goto select_end;
77584
77585   /* 
77586   ** Do not even attempt to generate any code if we have already seen
77587   ** errors before this routine starts.
77588   */
77589   if( pParse->nErr>0 ) goto select_end;
77590
77591   /* ORDER BY is ignored for some destinations.
77592   */
77593   if( IgnorableOrderby(pDest) ){
77594     pOrderBy = 0;
77595   }
77596
77597   /* Begin generating code.
77598   */
77599   v = sqlite3GetVdbe(pParse);
77600   if( v==0 ) goto select_end;
77601
77602   /* Generate code for all sub-queries in the FROM clause
77603   */
77604 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
77605   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
77606     struct SrcList_item *pItem = &pTabList->a[i];
77607     SelectDest dest;
77608     Select *pSub = pItem->pSelect;
77609     int isAggSub;
77610
77611     if( pSub==0 || pItem->isPopulated ) continue;
77612
77613     /* Increment Parse.nHeight by the height of the largest expression
77614     ** tree refered to by this, the parent select. The child select
77615     ** may contain expression trees of at most
77616     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
77617     ** more conservative than necessary, but much easier than enforcing
77618     ** an exact limit.
77619     */
77620     pParse->nHeight += sqlite3SelectExprHeight(p);
77621
77622     /* Check to see if the subquery can be absorbed into the parent. */
77623     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
77624     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
77625       if( isAggSub ){
77626         isAgg = 1;
77627         p->selFlags |= SF_Aggregate;
77628       }
77629       i = -1;
77630     }else{
77631       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
77632       assert( pItem->isPopulated==0 );
77633       sqlite3Select(pParse, pSub, &dest);
77634       pItem->isPopulated = 1;
77635     }
77636     if( pParse->nErr || db->mallocFailed ){
77637       goto select_end;
77638     }
77639     pParse->nHeight -= sqlite3SelectExprHeight(p);
77640     pTabList = p->pSrc;
77641     if( !IgnorableOrderby(pDest) ){
77642       pOrderBy = p->pOrderBy;
77643     }
77644   }
77645   pEList = p->pEList;
77646 #endif
77647   pWhere = p->pWhere;
77648   pGroupBy = p->pGroupBy;
77649   pHaving = p->pHaving;
77650   isDistinct = (p->selFlags & SF_Distinct)!=0;
77651
77652 #ifndef SQLITE_OMIT_COMPOUND_SELECT
77653   /* If there is are a sequence of queries, do the earlier ones first.
77654   */
77655   if( p->pPrior ){
77656     if( p->pRightmost==0 ){
77657       Select *pLoop, *pRight = 0;
77658       int cnt = 0;
77659       int mxSelect;
77660       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
77661         pLoop->pRightmost = p;
77662         pLoop->pNext = pRight;
77663         pRight = pLoop;
77664       }
77665       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
77666       if( mxSelect && cnt>mxSelect ){
77667         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
77668         return 1;
77669       }
77670     }
77671     return multiSelect(pParse, p, pDest);
77672   }
77673 #endif
77674
77675   /* If writing to memory or generating a set
77676   ** only a single column may be output.
77677   */
77678 #ifndef SQLITE_OMIT_SUBQUERY
77679   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
77680     goto select_end;
77681   }
77682 #endif
77683
77684   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
77685   ** GROUP BY might use an index, DISTINCT never does.
77686   */
77687   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
77688     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
77689     pGroupBy = p->pGroupBy;
77690     p->selFlags &= ~SF_Distinct;
77691     isDistinct = 0;
77692   }
77693
77694   /* If there is an ORDER BY clause, then this sorting
77695   ** index might end up being unused if the data can be 
77696   ** extracted in pre-sorted order.  If that is the case, then the
77697   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
77698   ** we figure out that the sorting index is not needed.  The addrSortIndex
77699   ** variable is used to facilitate that change.
77700   */
77701   if( pOrderBy ){
77702     KeyInfo *pKeyInfo;
77703     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
77704     pOrderBy->iECursor = pParse->nTab++;
77705     p->addrOpenEphm[2] = addrSortIndex =
77706       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
77707                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
77708                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
77709   }else{
77710     addrSortIndex = -1;
77711   }
77712
77713   /* If the output is destined for a temporary table, open that table.
77714   */
77715   if( pDest->eDest==SRT_EphemTab ){
77716     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
77717   }
77718
77719   /* Set the limiter.
77720   */
77721   iEnd = sqlite3VdbeMakeLabel(v);
77722   computeLimitRegisters(pParse, p, iEnd);
77723
77724   /* Open a virtual index to use for the distinct set.
77725   */
77726   if( isDistinct ){
77727     KeyInfo *pKeyInfo;
77728     assert( isAgg || pGroupBy );
77729     distinct = pParse->nTab++;
77730     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
77731     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
77732                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
77733   }else{
77734     distinct = -1;
77735   }
77736
77737   /* Aggregate and non-aggregate queries are handled differently */
77738   if( !isAgg && pGroupBy==0 ){
77739     /* This case is for non-aggregate queries
77740     ** Begin the database scan
77741     */
77742     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0, 0);
77743     if( pWInfo==0 ) goto select_end;
77744
77745     /* If sorting index that was created by a prior OP_OpenEphemeral 
77746     ** instruction ended up not being needed, then change the OP_OpenEphemeral
77747     ** into an OP_Noop.
77748     */
77749     if( addrSortIndex>=0 && pOrderBy==0 ){
77750       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
77751       p->addrOpenEphm[2] = -1;
77752     }
77753
77754     /* Use the standard inner loop
77755     */
77756     assert(!isDistinct);
77757     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
77758                     pWInfo->iContinue, pWInfo->iBreak);
77759
77760     /* End the database scan loop.
77761     */
77762     sqlite3WhereEnd(pWInfo);
77763   }else{
77764     /* This is the processing for aggregate queries */
77765     NameContext sNC;    /* Name context for processing aggregate information */
77766     int iAMem;          /* First Mem address for storing current GROUP BY */
77767     int iBMem;          /* First Mem address for previous GROUP BY */
77768     int iUseFlag;       /* Mem address holding flag indicating that at least
77769                         ** one row of the input to the aggregator has been
77770                         ** processed */
77771     int iAbortFlag;     /* Mem address which causes query abort if positive */
77772     int groupBySort;    /* Rows come from source in GROUP BY order */
77773     int addrEnd;        /* End of processing for this SELECT */
77774
77775     /* Remove any and all aliases between the result set and the
77776     ** GROUP BY clause.
77777     */
77778     if( pGroupBy ){
77779       int k;                        /* Loop counter */
77780       struct ExprList_item *pItem;  /* For looping over expression in a list */
77781
77782       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
77783         pItem->iAlias = 0;
77784       }
77785       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
77786         pItem->iAlias = 0;
77787       }
77788     }
77789
77790  
77791     /* Create a label to jump to when we want to abort the query */
77792     addrEnd = sqlite3VdbeMakeLabel(v);
77793
77794     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
77795     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
77796     ** SELECT statement.
77797     */
77798     memset(&sNC, 0, sizeof(sNC));
77799     sNC.pParse = pParse;
77800     sNC.pSrcList = pTabList;
77801     sNC.pAggInfo = &sAggInfo;
77802     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
77803     sAggInfo.pGroupBy = pGroupBy;
77804     sqlite3ExprAnalyzeAggList(&sNC, pEList);
77805     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
77806     if( pHaving ){
77807       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
77808     }
77809     sAggInfo.nAccumulator = sAggInfo.nColumn;
77810     for(i=0; i<sAggInfo.nFunc; i++){
77811       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
77812     }
77813     if( db->mallocFailed ) goto select_end;
77814
77815     /* Processing for aggregates with GROUP BY is very different and
77816     ** much more complex than aggregates without a GROUP BY.
77817     */
77818     if( pGroupBy ){
77819       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
77820       int j1;             /* A-vs-B comparision jump */
77821       int addrOutputRow;  /* Start of subroutine that outputs a result row */
77822       int regOutputRow;   /* Return address register for output subroutine */
77823       int addrSetAbort;   /* Set the abort flag and return */
77824       int addrTopOfLoop;  /* Top of the input loop */
77825       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
77826       int addrReset;      /* Subroutine for resetting the accumulator */
77827       int regReset;       /* Return address register for reset subroutine */
77828
77829       /* If there is a GROUP BY clause we might need a sorting index to
77830       ** implement it.  Allocate that sorting index now.  If it turns out
77831       ** that we do not need it after all, the OpenEphemeral instruction
77832       ** will be converted into a Noop.  
77833       */
77834       sAggInfo.sortingIdx = pParse->nTab++;
77835       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
77836       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
77837           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
77838           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
77839
77840       /* Initialize memory locations used by GROUP BY aggregate processing
77841       */
77842       iUseFlag = ++pParse->nMem;
77843       iAbortFlag = ++pParse->nMem;
77844       regOutputRow = ++pParse->nMem;
77845       addrOutputRow = sqlite3VdbeMakeLabel(v);
77846       regReset = ++pParse->nMem;
77847       addrReset = sqlite3VdbeMakeLabel(v);
77848       iAMem = pParse->nMem + 1;
77849       pParse->nMem += pGroupBy->nExpr;
77850       iBMem = pParse->nMem + 1;
77851       pParse->nMem += pGroupBy->nExpr;
77852       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
77853       VdbeComment((v, "clear abort flag"));
77854       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
77855       VdbeComment((v, "indicate accumulator empty"));
77856
77857       /* Begin a loop that will extract all source rows in GROUP BY order.
77858       ** This might involve two separate loops with an OP_Sort in between, or
77859       ** it might be a single loop that uses an index to extract information
77860       ** in the right order to begin with.
77861       */
77862       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
77863       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
77864       if( pWInfo==0 ) goto select_end;
77865       if( pGroupBy==0 ){
77866         /* The optimizer is able to deliver rows in group by order so
77867         ** we do not have to sort.  The OP_OpenEphemeral table will be
77868         ** cancelled later because we still need to use the pKeyInfo
77869         */
77870         pGroupBy = p->pGroupBy;
77871         groupBySort = 0;
77872       }else{
77873         /* Rows are coming out in undetermined order.  We have to push
77874         ** each row into a sorting index, terminate the first loop,
77875         ** then loop over the sorting index in order to get the output
77876         ** in sorted order
77877         */
77878         int regBase;
77879         int regRecord;
77880         int nCol;
77881         int nGroupBy;
77882
77883         groupBySort = 1;
77884         nGroupBy = pGroupBy->nExpr;
77885         nCol = nGroupBy + 1;
77886         j = nGroupBy+1;
77887         for(i=0; i<sAggInfo.nColumn; i++){
77888           if( sAggInfo.aCol[i].iSorterColumn>=j ){
77889             nCol++;
77890             j++;
77891           }
77892         }
77893         regBase = sqlite3GetTempRange(pParse, nCol);
77894         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
77895         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
77896         j = nGroupBy+1;
77897         for(i=0; i<sAggInfo.nColumn; i++){
77898           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
77899           if( pCol->iSorterColumn>=j ){
77900             int r1 = j + regBase;
77901             int r2;
77902
77903             r2 = sqlite3ExprCodeGetColumn(pParse, 
77904                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
77905             if( r1!=r2 ){
77906               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
77907             }
77908             j++;
77909           }
77910         }
77911         regRecord = sqlite3GetTempReg(pParse);
77912         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
77913         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
77914         sqlite3ReleaseTempReg(pParse, regRecord);
77915         sqlite3ReleaseTempRange(pParse, regBase, nCol);
77916         sqlite3WhereEnd(pWInfo);
77917         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
77918         VdbeComment((v, "GROUP BY sort"));
77919         sAggInfo.useSortingIdx = 1;
77920       }
77921
77922       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
77923       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
77924       ** Then compare the current GROUP BY terms against the GROUP BY terms
77925       ** from the previous row currently stored in a0, a1, a2...
77926       */
77927       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
77928       for(j=0; j<pGroupBy->nExpr; j++){
77929         if( groupBySort ){
77930           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
77931         }else{
77932           sAggInfo.directMode = 1;
77933           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
77934         }
77935       }
77936       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
77937                           (char*)pKeyInfo, P4_KEYINFO);
77938       j1 = sqlite3VdbeCurrentAddr(v);
77939       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
77940
77941       /* Generate code that runs whenever the GROUP BY changes.
77942       ** Changes in the GROUP BY are detected by the previous code
77943       ** block.  If there were no changes, this block is skipped.
77944       **
77945       ** This code copies current group by terms in b0,b1,b2,...
77946       ** over to a0,a1,a2.  It then calls the output subroutine
77947       ** and resets the aggregate accumulator registers in preparation
77948       ** for the next GROUP BY batch.
77949       */
77950       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
77951       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
77952       VdbeComment((v, "output one row"));
77953       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
77954       VdbeComment((v, "check abort flag"));
77955       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
77956       VdbeComment((v, "reset accumulator"));
77957
77958       /* Update the aggregate accumulators based on the content of
77959       ** the current row
77960       */
77961       sqlite3VdbeJumpHere(v, j1);
77962       updateAccumulator(pParse, &sAggInfo);
77963       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
77964       VdbeComment((v, "indicate data in accumulator"));
77965
77966       /* End of the loop
77967       */
77968       if( groupBySort ){
77969         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
77970       }else{
77971         sqlite3WhereEnd(pWInfo);
77972         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
77973       }
77974
77975       /* Output the final row of result
77976       */
77977       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
77978       VdbeComment((v, "output final row"));
77979
77980       /* Jump over the subroutines
77981       */
77982       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
77983
77984       /* Generate a subroutine that outputs a single row of the result
77985       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
77986       ** is less than or equal to zero, the subroutine is a no-op.  If
77987       ** the processing calls for the query to abort, this subroutine
77988       ** increments the iAbortFlag memory location before returning in
77989       ** order to signal the caller to abort.
77990       */
77991       addrSetAbort = sqlite3VdbeCurrentAddr(v);
77992       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
77993       VdbeComment((v, "set abort flag"));
77994       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
77995       sqlite3VdbeResolveLabel(v, addrOutputRow);
77996       addrOutputRow = sqlite3VdbeCurrentAddr(v);
77997       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
77998       VdbeComment((v, "Groupby result generator entry point"));
77999       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
78000       finalizeAggFunctions(pParse, &sAggInfo);
78001       if( pHaving ){
78002         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
78003       }
78004       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
78005                       distinct, pDest,
78006                       addrOutputRow+1, addrSetAbort);
78007       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
78008       VdbeComment((v, "end groupby result generator"));
78009
78010       /* Generate a subroutine that will reset the group-by accumulator
78011       */
78012       sqlite3VdbeResolveLabel(v, addrReset);
78013       resetAccumulator(pParse, &sAggInfo);
78014       sqlite3VdbeAddOp1(v, OP_Return, regReset);
78015      
78016     } /* endif pGroupBy */
78017     else {
78018       ExprList *pMinMax = 0;
78019       ExprList *pDel = 0;
78020       u8 flag;
78021
78022       /* Check if the query is of one of the following forms:
78023       **
78024       **   SELECT min(x) FROM ...
78025       **   SELECT max(x) FROM ...
78026       **
78027       ** If it is, then ask the code in where.c to attempt to sort results
78028       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
78029       ** If where.c is able to produce results sorted in this order, then
78030       ** add vdbe code to break out of the processing loop after the 
78031       ** first iteration (since the first iteration of the loop is 
78032       ** guaranteed to operate on the row with the minimum or maximum 
78033       ** value of x, the only row required).
78034       **
78035       ** A special flag must be passed to sqlite3WhereBegin() to slightly
78036       ** modify behaviour as follows:
78037       **
78038       **   + If the query is a "SELECT min(x)", then the loop coded by
78039       **     where.c should not iterate over any values with a NULL value
78040       **     for x.
78041       **
78042       **   + The optimizer code in where.c (the thing that decides which
78043       **     index or indices to use) should place a different priority on 
78044       **     satisfying the 'ORDER BY' clause than it does in other cases.
78045       **     Refer to code and comments in where.c for details.
78046       */
78047       flag = minMaxQuery(p);
78048       if( flag ){
78049         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
78050         if( pMinMax && !db->mallocFailed ){
78051           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
78052           pMinMax->a[0].pExpr->op = TK_COLUMN;
78053         }
78054       }
78055
78056       /* This case runs if the aggregate has no GROUP BY clause.  The
78057       ** processing is much simpler since there is only a single row
78058       ** of output.
78059       */
78060       resetAccumulator(pParse, &sAggInfo);
78061       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag, 0);
78062       if( pWInfo==0 ){
78063         sqlite3ExprListDelete(db, pDel);
78064         goto select_end;
78065       }
78066       updateAccumulator(pParse, &sAggInfo);
78067       if( !pMinMax && flag ){
78068         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
78069         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
78070       }
78071       sqlite3WhereEnd(pWInfo);
78072       finalizeAggFunctions(pParse, &sAggInfo);
78073       pOrderBy = 0;
78074       if( pHaving ){
78075         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
78076       }
78077       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
78078                       pDest, addrEnd, addrEnd);
78079
78080       sqlite3ExprListDelete(db, pDel);
78081     }
78082     sqlite3VdbeResolveLabel(v, addrEnd);
78083     
78084   } /* endif aggregate query */
78085
78086   /* If there is an ORDER BY clause, then we need to sort the results
78087   ** and send them to the callback one by one.
78088   */
78089   if( pOrderBy ){
78090     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
78091   }
78092
78093   /* Jump here to skip this query
78094   */
78095   sqlite3VdbeResolveLabel(v, iEnd);
78096
78097   /* The SELECT was successfully coded.   Set the return code to 0
78098   ** to indicate no errors.
78099   */
78100   rc = 0;
78101
78102   /* Control jumps to here if an error is encountered above, or upon
78103   ** successful coding of the SELECT.
78104   */
78105 select_end:
78106
78107   /* Identify column names if results of the SELECT are to be output.
78108   */
78109   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
78110     generateColumnNames(pParse, pTabList, pEList);
78111   }
78112
78113   sqlite3DbFree(db, sAggInfo.aCol);
78114   sqlite3DbFree(db, sAggInfo.aFunc);
78115   return rc;
78116 }
78117
78118 #if defined(SQLITE_DEBUG)
78119 /*
78120 *******************************************************************************
78121 ** The following code is used for testing and debugging only.  The code
78122 ** that follows does not appear in normal builds.
78123 **
78124 ** These routines are used to print out the content of all or part of a 
78125 ** parse structures such as Select or Expr.  Such printouts are useful
78126 ** for helping to understand what is happening inside the code generator
78127 ** during the execution of complex SELECT statements.
78128 **
78129 ** These routine are not called anywhere from within the normal
78130 ** code base.  Then are intended to be called from within the debugger
78131 ** or from temporary "printf" statements inserted for debugging.
78132 */
78133 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
78134   if( p->token.z && p->token.n>0 ){
78135     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
78136   }else{
78137     sqlite3DebugPrintf("(%d", p->op);
78138   }
78139   if( p->pLeft ){
78140     sqlite3DebugPrintf(" ");
78141     sqlite3PrintExpr(p->pLeft);
78142   }
78143   if( p->pRight ){
78144     sqlite3DebugPrintf(" ");
78145     sqlite3PrintExpr(p->pRight);
78146   }
78147   sqlite3DebugPrintf(")");
78148 }
78149 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
78150   int i;
78151   for(i=0; i<pList->nExpr; i++){
78152     sqlite3PrintExpr(pList->a[i].pExpr);
78153     if( i<pList->nExpr-1 ){
78154       sqlite3DebugPrintf(", ");
78155     }
78156   }
78157 }
78158 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
78159   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
78160   sqlite3PrintExprList(p->pEList);
78161   sqlite3DebugPrintf("\n");
78162   if( p->pSrc ){
78163     char *zPrefix;
78164     int i;
78165     zPrefix = "FROM";
78166     for(i=0; i<p->pSrc->nSrc; i++){
78167       struct SrcList_item *pItem = &p->pSrc->a[i];
78168       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
78169       zPrefix = "";
78170       if( pItem->pSelect ){
78171         sqlite3DebugPrintf("(\n");
78172         sqlite3PrintSelect(pItem->pSelect, indent+10);
78173         sqlite3DebugPrintf("%*s)", indent+8, "");
78174       }else if( pItem->zName ){
78175         sqlite3DebugPrintf("%s", pItem->zName);
78176       }
78177       if( pItem->pTab ){
78178         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
78179       }
78180       if( pItem->zAlias ){
78181         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
78182       }
78183       if( i<p->pSrc->nSrc-1 ){
78184         sqlite3DebugPrintf(",");
78185       }
78186       sqlite3DebugPrintf("\n");
78187     }
78188   }
78189   if( p->pWhere ){
78190     sqlite3DebugPrintf("%*s WHERE ", indent, "");
78191     sqlite3PrintExpr(p->pWhere);
78192     sqlite3DebugPrintf("\n");
78193   }
78194   if( p->pGroupBy ){
78195     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
78196     sqlite3PrintExprList(p->pGroupBy);
78197     sqlite3DebugPrintf("\n");
78198   }
78199   if( p->pHaving ){
78200     sqlite3DebugPrintf("%*s HAVING ", indent, "");
78201     sqlite3PrintExpr(p->pHaving);
78202     sqlite3DebugPrintf("\n");
78203   }
78204   if( p->pOrderBy ){
78205     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
78206     sqlite3PrintExprList(p->pOrderBy);
78207     sqlite3DebugPrintf("\n");
78208   }
78209 }
78210 /* End of the structure debug printing code
78211 *****************************************************************************/
78212 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
78213
78214 /************** End of select.c **********************************************/
78215 /************** Begin file table.c *******************************************/
78216 /*
78217 ** 2001 September 15
78218 **
78219 ** The author disclaims copyright to this source code.  In place of
78220 ** a legal notice, here is a blessing:
78221 **
78222 **    May you do good and not evil.
78223 **    May you find forgiveness for yourself and forgive others.
78224 **    May you share freely, never taking more than you give.
78225 **
78226 *************************************************************************
78227 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
78228 ** interface routines.  These are just wrappers around the main
78229 ** interface routine of sqlite3_exec().
78230 **
78231 ** These routines are in a separate files so that they will not be linked
78232 ** if they are not used.
78233 **
78234 ** $Id: table.c,v 1.39 2009/01/19 20:49:10 drh Exp $
78235 */
78236
78237 #ifndef SQLITE_OMIT_GET_TABLE
78238
78239 /*
78240 ** This structure is used to pass data from sqlite3_get_table() through
78241 ** to the callback function is uses to build the result.
78242 */
78243 typedef struct TabResult {
78244   char **azResult;
78245   char *zErrMsg;
78246   int nResult;
78247   int nAlloc;
78248   int nRow;
78249   int nColumn;
78250   int nData;
78251   int rc;
78252 } TabResult;
78253
78254 /*
78255 ** This routine is called once for each row in the result table.  Its job
78256 ** is to fill in the TabResult structure appropriately, allocating new
78257 ** memory as necessary.
78258 */
78259 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
78260   TabResult *p = (TabResult*)pArg;
78261   int need;
78262   int i;
78263   char *z;
78264
78265   /* Make sure there is enough space in p->azResult to hold everything
78266   ** we need to remember from this invocation of the callback.
78267   */
78268   if( p->nRow==0 && argv!=0 ){
78269     need = nCol*2;
78270   }else{
78271     need = nCol;
78272   }
78273   if( p->nData + need >= p->nAlloc ){
78274     char **azNew;
78275     p->nAlloc = p->nAlloc*2 + need + 1;
78276     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
78277     if( azNew==0 ) goto malloc_failed;
78278     p->azResult = azNew;
78279   }
78280
78281   /* If this is the first row, then generate an extra row containing
78282   ** the names of all columns.
78283   */
78284   if( p->nRow==0 ){
78285     p->nColumn = nCol;
78286     for(i=0; i<nCol; i++){
78287       z = sqlite3_mprintf("%s", colv[i]);
78288       if( z==0 ) goto malloc_failed;
78289       p->azResult[p->nData++] = z;
78290     }
78291   }else if( p->nColumn!=nCol ){
78292     sqlite3_free(p->zErrMsg);
78293     p->zErrMsg = sqlite3_mprintf(
78294        "sqlite3_get_table() called with two or more incompatible queries"
78295     );
78296     p->rc = SQLITE_ERROR;
78297     return 1;
78298   }
78299
78300   /* Copy over the row data
78301   */
78302   if( argv!=0 ){
78303     for(i=0; i<nCol; i++){
78304       if( argv[i]==0 ){
78305         z = 0;
78306       }else{
78307         int n = sqlite3Strlen30(argv[i])+1;
78308         z = sqlite3_malloc( n );
78309         if( z==0 ) goto malloc_failed;
78310         memcpy(z, argv[i], n);
78311       }
78312       p->azResult[p->nData++] = z;
78313     }
78314     p->nRow++;
78315   }
78316   return 0;
78317
78318 malloc_failed:
78319   p->rc = SQLITE_NOMEM;
78320   return 1;
78321 }
78322
78323 /*
78324 ** Query the database.  But instead of invoking a callback for each row,
78325 ** malloc() for space to hold the result and return the entire results
78326 ** at the conclusion of the call.
78327 **
78328 ** The result that is written to ***pazResult is held in memory obtained
78329 ** from malloc().  But the caller cannot free this memory directly.  
78330 ** Instead, the entire table should be passed to sqlite3_free_table() when
78331 ** the calling procedure is finished using it.
78332 */
78333 SQLITE_API int sqlite3_get_table(
78334   sqlite3 *db,                /* The database on which the SQL executes */
78335   const char *zSql,           /* The SQL to be executed */
78336   char ***pazResult,          /* Write the result table here */
78337   int *pnRow,                 /* Write the number of rows in the result here */
78338   int *pnColumn,              /* Write the number of columns of result here */
78339   char **pzErrMsg             /* Write error messages here */
78340 ){
78341   int rc;
78342   TabResult res;
78343
78344   *pazResult = 0;
78345   if( pnColumn ) *pnColumn = 0;
78346   if( pnRow ) *pnRow = 0;
78347   if( pzErrMsg ) *pzErrMsg = 0;
78348   res.zErrMsg = 0;
78349   res.nResult = 0;
78350   res.nRow = 0;
78351   res.nColumn = 0;
78352   res.nData = 1;
78353   res.nAlloc = 20;
78354   res.rc = SQLITE_OK;
78355   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
78356   if( res.azResult==0 ){
78357      db->errCode = SQLITE_NOMEM;
78358      return SQLITE_NOMEM;
78359   }
78360   res.azResult[0] = 0;
78361   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
78362   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
78363   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
78364   if( (rc&0xff)==SQLITE_ABORT ){
78365     sqlite3_free_table(&res.azResult[1]);
78366     if( res.zErrMsg ){
78367       if( pzErrMsg ){
78368         sqlite3_free(*pzErrMsg);
78369         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
78370       }
78371       sqlite3_free(res.zErrMsg);
78372     }
78373     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
78374     return res.rc;
78375   }
78376   sqlite3_free(res.zErrMsg);
78377   if( rc!=SQLITE_OK ){
78378     sqlite3_free_table(&res.azResult[1]);
78379     return rc;
78380   }
78381   if( res.nAlloc>res.nData ){
78382     char **azNew;
78383     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
78384     if( azNew==0 ){
78385       sqlite3_free_table(&res.azResult[1]);
78386       db->errCode = SQLITE_NOMEM;
78387       return SQLITE_NOMEM;
78388     }
78389     res.nAlloc = res.nData+1;
78390     res.azResult = azNew;
78391   }
78392   *pazResult = &res.azResult[1];
78393   if( pnColumn ) *pnColumn = res.nColumn;
78394   if( pnRow ) *pnRow = res.nRow;
78395   return rc;
78396 }
78397
78398 /*
78399 ** This routine frees the space the sqlite3_get_table() malloced.
78400 */
78401 SQLITE_API void sqlite3_free_table(
78402   char **azResult            /* Result returned from from sqlite3_get_table() */
78403 ){
78404   if( azResult ){
78405     int i, n;
78406     azResult--;
78407     assert( azResult!=0 );
78408     n = SQLITE_PTR_TO_INT(azResult[0]);
78409     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
78410     sqlite3_free(azResult);
78411   }
78412 }
78413
78414 #endif /* SQLITE_OMIT_GET_TABLE */
78415
78416 /************** End of table.c ***********************************************/
78417 /************** Begin file trigger.c *****************************************/
78418 /*
78419 **
78420 ** The author disclaims copyright to this source code.  In place of
78421 ** a legal notice, here is a blessing:
78422 **
78423 **    May you do good and not evil.
78424 **    May you find forgiveness for yourself and forgive others.
78425 **    May you share freely, never taking more than you give.
78426 **
78427 *************************************************************************
78428 **
78429 **
78430 ** $Id: trigger.c,v 1.133 2008/12/26 07:56:39 danielk1977 Exp $
78431 */
78432
78433 #ifndef SQLITE_OMIT_TRIGGER
78434 /*
78435 ** Delete a linked list of TriggerStep structures.
78436 */
78437 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
78438   while( pTriggerStep ){
78439     TriggerStep * pTmp = pTriggerStep;
78440     pTriggerStep = pTriggerStep->pNext;
78441
78442     if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
78443     sqlite3ExprDelete(db, pTmp->pWhere);
78444     sqlite3ExprListDelete(db, pTmp->pExprList);
78445     sqlite3SelectDelete(db, pTmp->pSelect);
78446     sqlite3IdListDelete(db, pTmp->pIdList);
78447
78448     sqlite3DbFree(db, pTmp);
78449   }
78450 }
78451
78452 /*
78453 ** This is called by the parser when it sees a CREATE TRIGGER statement
78454 ** up to the point of the BEGIN before the trigger actions.  A Trigger
78455 ** structure is generated based on the information available and stored
78456 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
78457 ** sqlite3FinishTrigger() function is called to complete the trigger
78458 ** construction process.
78459 */
78460 SQLITE_PRIVATE void sqlite3BeginTrigger(
78461   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
78462   Token *pName1,      /* The name of the trigger */
78463   Token *pName2,      /* The name of the trigger */
78464   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
78465   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
78466   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
78467   SrcList *pTableName,/* The name of the table/view the trigger applies to */
78468   Expr *pWhen,        /* WHEN clause */
78469   int isTemp,         /* True if the TEMPORARY keyword is present */
78470   int noErr           /* Suppress errors if the trigger already exists */
78471 ){
78472   Trigger *pTrigger = 0;
78473   Table *pTab;
78474   char *zName = 0;        /* Name of the trigger */
78475   sqlite3 *db = pParse->db;
78476   int iDb;                /* The database to store the trigger in */
78477   Token *pName;           /* The unqualified db name */
78478   DbFixer sFix;
78479   int iTabDb;
78480
78481   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
78482   assert( pName2!=0 );
78483   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
78484   assert( op>0 && op<0xff );
78485   if( isTemp ){
78486     /* If TEMP was specified, then the trigger name may not be qualified. */
78487     if( pName2->n>0 ){
78488       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
78489       goto trigger_cleanup;
78490     }
78491     iDb = 1;
78492     pName = pName1;
78493   }else{
78494     /* Figure out the db that the the trigger will be created in */
78495     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78496     if( iDb<0 ){
78497       goto trigger_cleanup;
78498     }
78499   }
78500
78501   /* If the trigger name was unqualified, and the table is a temp table,
78502   ** then set iDb to 1 to create the trigger in the temporary database.
78503   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
78504   ** exist, the error is caught by the block below.
78505   */
78506   if( !pTableName || db->mallocFailed ){
78507     goto trigger_cleanup;
78508   }
78509   pTab = sqlite3SrcListLookup(pParse, pTableName);
78510   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
78511     iDb = 1;
78512   }
78513
78514   /* Ensure the table name matches database name and that the table exists */
78515   if( db->mallocFailed ) goto trigger_cleanup;
78516   assert( pTableName->nSrc==1 );
78517   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
78518       sqlite3FixSrcList(&sFix, pTableName) ){
78519     goto trigger_cleanup;
78520   }
78521   pTab = sqlite3SrcListLookup(pParse, pTableName);
78522   if( !pTab ){
78523     /* The table does not exist. */
78524     goto trigger_cleanup;
78525   }
78526   if( IsVirtual(pTab) ){
78527     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
78528     goto trigger_cleanup;
78529   }
78530
78531   /* Check that the trigger name is not reserved and that no trigger of the
78532   ** specified name exists */
78533   zName = sqlite3NameFromToken(db, pName);
78534   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
78535     goto trigger_cleanup;
78536   }
78537   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
78538                       zName, sqlite3Strlen30(zName)) ){
78539     if( !noErr ){
78540       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
78541     }
78542     goto trigger_cleanup;
78543   }
78544
78545   /* Do not create a trigger on a system table */
78546   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
78547     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
78548     pParse->nErr++;
78549     goto trigger_cleanup;
78550   }
78551
78552   /* INSTEAD of triggers are only for views and views only support INSTEAD
78553   ** of triggers.
78554   */
78555   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
78556     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
78557         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
78558     goto trigger_cleanup;
78559   }
78560   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
78561     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
78562         " trigger on table: %S", pTableName, 0);
78563     goto trigger_cleanup;
78564   }
78565   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78566
78567 #ifndef SQLITE_OMIT_AUTHORIZATION
78568   {
78569     int code = SQLITE_CREATE_TRIGGER;
78570     const char *zDb = db->aDb[iTabDb].zName;
78571     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
78572     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
78573     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
78574       goto trigger_cleanup;
78575     }
78576     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
78577       goto trigger_cleanup;
78578     }
78579   }
78580 #endif
78581
78582   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
78583   ** cannot appear on views.  So we might as well translate every
78584   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
78585   ** elsewhere.
78586   */
78587   if (tr_tm == TK_INSTEAD){
78588     tr_tm = TK_BEFORE;
78589   }
78590
78591   /* Build the Trigger object */
78592   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
78593   if( pTrigger==0 ) goto trigger_cleanup;
78594   pTrigger->name = zName;
78595   zName = 0;
78596   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
78597   pTrigger->pSchema = db->aDb[iDb].pSchema;
78598   pTrigger->pTabSchema = pTab->pSchema;
78599   pTrigger->op = (u8)op;
78600   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
78601   pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
78602   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
78603   sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
78604   assert( pParse->pNewTrigger==0 );
78605   pParse->pNewTrigger = pTrigger;
78606
78607 trigger_cleanup:
78608   sqlite3DbFree(db, zName);
78609   sqlite3SrcListDelete(db, pTableName);
78610   sqlite3IdListDelete(db, pColumns);
78611   sqlite3ExprDelete(db, pWhen);
78612   if( !pParse->pNewTrigger ){
78613     sqlite3DeleteTrigger(db, pTrigger);
78614   }else{
78615     assert( pParse->pNewTrigger==pTrigger );
78616   }
78617 }
78618
78619 /*
78620 ** This routine is called after all of the trigger actions have been parsed
78621 ** in order to complete the process of building the trigger.
78622 */
78623 SQLITE_PRIVATE void sqlite3FinishTrigger(
78624   Parse *pParse,          /* Parser context */
78625   TriggerStep *pStepList, /* The triggered program */
78626   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
78627 ){
78628   Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
78629   sqlite3 *db = pParse->db;  /* The database */
78630   DbFixer sFix;
78631   int iDb;                   /* Database containing the trigger */
78632
78633   pTrig = pParse->pNewTrigger;
78634   pParse->pNewTrigger = 0;
78635   if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
78636   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78637   pTrig->step_list = pStepList;
78638   while( pStepList ){
78639     pStepList->pTrig = pTrig;
78640     pStepList = pStepList->pNext;
78641   }
78642   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken) 
78643           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
78644     goto triggerfinish_cleanup;
78645   }
78646
78647   /* if we are not initializing, and this trigger is not on a TEMP table, 
78648   ** build the sqlite_master entry
78649   */
78650   if( !db->init.busy ){
78651     Vdbe *v;
78652     char *z;
78653
78654     /* Make an entry in the sqlite_master table */
78655     v = sqlite3GetVdbe(pParse);
78656     if( v==0 ) goto triggerfinish_cleanup;
78657     sqlite3BeginWriteOperation(pParse, 0, iDb);
78658     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
78659     sqlite3NestedParse(pParse,
78660        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
78661        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
78662        pTrig->table, z);
78663     sqlite3DbFree(db, z);
78664     sqlite3ChangeCookie(pParse, iDb);
78665     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
78666         db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
78667     );
78668   }
78669
78670   if( db->init.busy ){
78671     int n;
78672     Table *pTab;
78673     Trigger *pDel;
78674     pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash, 
78675                      pTrig->name, sqlite3Strlen30(pTrig->name), pTrig);
78676     if( pDel ){
78677       assert( pDel==pTrig );
78678       db->mallocFailed = 1;
78679       goto triggerfinish_cleanup;
78680     }
78681     n = sqlite3Strlen30(pTrig->table) + 1;
78682     pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
78683     assert( pTab!=0 );
78684     pTrig->pNext = pTab->pTrigger;
78685     pTab->pTrigger = pTrig;
78686     pTrig = 0;
78687   }
78688
78689 triggerfinish_cleanup:
78690   sqlite3DeleteTrigger(db, pTrig);
78691   assert( !pParse->pNewTrigger );
78692   sqlite3DeleteTriggerStep(db, pStepList);
78693 }
78694
78695 /*
78696 ** Make a copy of all components of the given trigger step.  This has
78697 ** the effect of copying all Expr.token.z values into memory obtained
78698 ** from sqlite3_malloc().  As initially created, the Expr.token.z values
78699 ** all point to the input string that was fed to the parser.  But that
78700 ** string is ephemeral - it will go away as soon as the sqlite3_exec()
78701 ** call that started the parser exits.  This routine makes a persistent
78702 ** copy of all the Expr.token.z strings so that the TriggerStep structure
78703 ** will be valid even after the sqlite3_exec() call returns.
78704 */
78705 static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
78706   if( p->target.z ){
78707     p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
78708     p->target.dyn = 1;
78709   }
78710   if( p->pSelect ){
78711     Select *pNew = sqlite3SelectDup(db, p->pSelect);
78712     sqlite3SelectDelete(db, p->pSelect);
78713     p->pSelect = pNew;
78714   }
78715   if( p->pWhere ){
78716     Expr *pNew = sqlite3ExprDup(db, p->pWhere);
78717     sqlite3ExprDelete(db, p->pWhere);
78718     p->pWhere = pNew;
78719   }
78720   if( p->pExprList ){
78721     ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
78722     sqlite3ExprListDelete(db, p->pExprList);
78723     p->pExprList = pNew;
78724   }
78725   if( p->pIdList ){
78726     IdList *pNew = sqlite3IdListDup(db, p->pIdList);
78727     sqlite3IdListDelete(db, p->pIdList);
78728     p->pIdList = pNew;
78729   }
78730 }
78731
78732 /*
78733 ** Turn a SELECT statement (that the pSelect parameter points to) into
78734 ** a trigger step.  Return a pointer to a TriggerStep structure.
78735 **
78736 ** The parser calls this routine when it finds a SELECT statement in
78737 ** body of a TRIGGER.  
78738 */
78739 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
78740   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
78741   if( pTriggerStep==0 ) {
78742     sqlite3SelectDelete(db, pSelect);
78743     return 0;
78744   }
78745
78746   pTriggerStep->op = TK_SELECT;
78747   pTriggerStep->pSelect = pSelect;
78748   pTriggerStep->orconf = OE_Default;
78749   sqlitePersistTriggerStep(db, pTriggerStep);
78750
78751   return pTriggerStep;
78752 }
78753
78754 /*
78755 ** Build a trigger step out of an INSERT statement.  Return a pointer
78756 ** to the new trigger step.
78757 **
78758 ** The parser calls this routine when it sees an INSERT inside the
78759 ** body of a trigger.
78760 */
78761 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
78762   sqlite3 *db,        /* The database connection */
78763   Token *pTableName,  /* Name of the table into which we insert */
78764   IdList *pColumn,    /* List of columns in pTableName to insert into */
78765   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
78766   Select *pSelect,    /* A SELECT statement that supplies values */
78767   int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
78768 ){
78769   TriggerStep *pTriggerStep;
78770
78771   assert(pEList == 0 || pSelect == 0);
78772   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
78773
78774   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
78775   if( pTriggerStep ){
78776     pTriggerStep->op = TK_INSERT;
78777     pTriggerStep->pSelect = pSelect;
78778     pTriggerStep->target  = *pTableName;
78779     pTriggerStep->pIdList = pColumn;
78780     pTriggerStep->pExprList = pEList;
78781     pTriggerStep->orconf = orconf;
78782     sqlitePersistTriggerStep(db, pTriggerStep);
78783   }else{
78784     sqlite3IdListDelete(db, pColumn);
78785     sqlite3ExprListDelete(db, pEList);
78786     sqlite3SelectDelete(db, pSelect);
78787   }
78788
78789   return pTriggerStep;
78790 }
78791
78792 /*
78793 ** Construct a trigger step that implements an UPDATE statement and return
78794 ** a pointer to that trigger step.  The parser calls this routine when it
78795 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
78796 */
78797 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
78798   sqlite3 *db,         /* The database connection */
78799   Token *pTableName,   /* Name of the table to be updated */
78800   ExprList *pEList,    /* The SET clause: list of column and new values */
78801   Expr *pWhere,        /* The WHERE clause */
78802   int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
78803 ){
78804   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
78805   if( pTriggerStep==0 ){
78806      sqlite3ExprListDelete(db, pEList);
78807      sqlite3ExprDelete(db, pWhere);
78808      return 0;
78809   }
78810
78811   pTriggerStep->op = TK_UPDATE;
78812   pTriggerStep->target  = *pTableName;
78813   pTriggerStep->pExprList = pEList;
78814   pTriggerStep->pWhere = pWhere;
78815   pTriggerStep->orconf = orconf;
78816   sqlitePersistTriggerStep(db, pTriggerStep);
78817
78818   return pTriggerStep;
78819 }
78820
78821 /*
78822 ** Construct a trigger step that implements a DELETE statement and return
78823 ** a pointer to that trigger step.  The parser calls this routine when it
78824 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
78825 */
78826 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
78827   sqlite3 *db,            /* Database connection */
78828   Token *pTableName,      /* The table from which rows are deleted */
78829   Expr *pWhere            /* The WHERE clause */
78830 ){
78831   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
78832   if( pTriggerStep==0 ){
78833     sqlite3ExprDelete(db, pWhere);
78834     return 0;
78835   }
78836
78837   pTriggerStep->op = TK_DELETE;
78838   pTriggerStep->target  = *pTableName;
78839   pTriggerStep->pWhere = pWhere;
78840   pTriggerStep->orconf = OE_Default;
78841   sqlitePersistTriggerStep(db, pTriggerStep);
78842
78843   return pTriggerStep;
78844 }
78845
78846 /* 
78847 ** Recursively delete a Trigger structure
78848 */
78849 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
78850   if( pTrigger==0 ) return;
78851   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
78852   sqlite3DbFree(db, pTrigger->name);
78853   sqlite3DbFree(db, pTrigger->table);
78854   sqlite3ExprDelete(db, pTrigger->pWhen);
78855   sqlite3IdListDelete(db, pTrigger->pColumns);
78856   if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
78857   sqlite3DbFree(db, pTrigger);
78858 }
78859
78860 /*
78861 ** This function is called to drop a trigger from the database schema. 
78862 **
78863 ** This may be called directly from the parser and therefore identifies
78864 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
78865 ** same job as this routine except it takes a pointer to the trigger
78866 ** instead of the trigger name.
78867 **/
78868 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
78869   Trigger *pTrigger = 0;
78870   int i;
78871   const char *zDb;
78872   const char *zName;
78873   int nName;
78874   sqlite3 *db = pParse->db;
78875
78876   if( db->mallocFailed ) goto drop_trigger_cleanup;
78877   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78878     goto drop_trigger_cleanup;
78879   }
78880
78881   assert( pName->nSrc==1 );
78882   zDb = pName->a[0].zDatabase;
78883   zName = pName->a[0].zName;
78884   nName = sqlite3Strlen30(zName);
78885   for(i=OMIT_TEMPDB; i<db->nDb; i++){
78886     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
78887     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
78888     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
78889     if( pTrigger ) break;
78890   }
78891   if( !pTrigger ){
78892     if( !noErr ){
78893       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
78894     }
78895     goto drop_trigger_cleanup;
78896   }
78897   sqlite3DropTriggerPtr(pParse, pTrigger);
78898
78899 drop_trigger_cleanup:
78900   sqlite3SrcListDelete(db, pName);
78901 }
78902
78903 /*
78904 ** Return a pointer to the Table structure for the table that a trigger
78905 ** is set on.
78906 */
78907 static Table *tableOfTrigger(Trigger *pTrigger){
78908   int n = sqlite3Strlen30(pTrigger->table) + 1;
78909   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
78910 }
78911
78912
78913 /*
78914 ** Drop a trigger given a pointer to that trigger. 
78915 */
78916 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
78917   Table   *pTable;
78918   Vdbe *v;
78919   sqlite3 *db = pParse->db;
78920   int iDb;
78921
78922   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
78923   assert( iDb>=0 && iDb<db->nDb );
78924   pTable = tableOfTrigger(pTrigger);
78925   assert( pTable );
78926   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
78927 #ifndef SQLITE_OMIT_AUTHORIZATION
78928   {
78929     int code = SQLITE_DROP_TRIGGER;
78930     const char *zDb = db->aDb[iDb].zName;
78931     const char *zTab = SCHEMA_TABLE(iDb);
78932     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
78933     if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
78934       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
78935       return;
78936     }
78937   }
78938 #endif
78939
78940   /* Generate code to destroy the database record of the trigger.
78941   */
78942   assert( pTable!=0 );
78943   if( (v = sqlite3GetVdbe(pParse))!=0 ){
78944     int base;
78945     static const VdbeOpList dropTrigger[] = {
78946       { OP_Rewind,     0, ADDR(9),  0},
78947       { OP_String8,    0, 1,        0}, /* 1 */
78948       { OP_Column,     0, 1,        2},
78949       { OP_Ne,         2, ADDR(8),  1},
78950       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
78951       { OP_Column,     0, 0,        2},
78952       { OP_Ne,         2, ADDR(8),  1},
78953       { OP_Delete,     0, 0,        0},
78954       { OP_Next,       0, ADDR(1),  0}, /* 8 */
78955     };
78956
78957     sqlite3BeginWriteOperation(pParse, 0, iDb);
78958     sqlite3OpenMasterTable(pParse, iDb);
78959     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
78960     sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
78961     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
78962     sqlite3ChangeCookie(pParse, iDb);
78963     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
78964     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
78965   }
78966 }
78967
78968 /*
78969 ** Remove a trigger from the hash tables of the sqlite* pointer.
78970 */
78971 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
78972   Trigger *pTrigger;
78973   int nName = sqlite3Strlen30(zName);
78974   pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
78975                                zName, nName, 0);
78976   if( pTrigger ){
78977     Table *pTable = tableOfTrigger(pTrigger);
78978     assert( pTable!=0 );
78979     if( pTable->pTrigger == pTrigger ){
78980       pTable->pTrigger = pTrigger->pNext;
78981     }else{
78982       Trigger *cc = pTable->pTrigger;
78983       while( cc ){ 
78984         if( cc->pNext == pTrigger ){
78985           cc->pNext = cc->pNext->pNext;
78986           break;
78987         }
78988         cc = cc->pNext;
78989       }
78990       assert(cc);
78991     }
78992     sqlite3DeleteTrigger(db, pTrigger);
78993     db->flags |= SQLITE_InternChanges;
78994   }
78995 }
78996
78997 /*
78998 ** pEList is the SET clause of an UPDATE statement.  Each entry
78999 ** in pEList is of the format <id>=<expr>.  If any of the entries
79000 ** in pEList have an <id> which matches an identifier in pIdList,
79001 ** then return TRUE.  If pIdList==NULL, then it is considered a
79002 ** wildcard that matches anything.  Likewise if pEList==NULL then
79003 ** it matches anything so always return true.  Return false only
79004 ** if there is no match.
79005 */
79006 static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
79007   int e;
79008   if( !pIdList || !pEList ) return 1;
79009   for(e=0; e<pEList->nExpr; e++){
79010     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
79011   }
79012   return 0; 
79013 }
79014
79015 /*
79016 ** Return a bit vector to indicate what kind of triggers exist for operation
79017 ** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
79018 ** that are being updated.  Triggers only match if the ON clause of the
79019 ** trigger definition overlaps the set of columns being updated.
79020 **
79021 ** The returned bit vector is some combination of TRIGGER_BEFORE and
79022 ** TRIGGER_AFTER.
79023 */
79024 SQLITE_PRIVATE int sqlite3TriggersExist(
79025   Table *pTab,            /* The table the contains the triggers */
79026   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
79027   ExprList *pChanges      /* Columns that change in an UPDATE statement */
79028 ){
79029   Trigger *pTrigger;
79030   int mask = 0;
79031
79032   pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
79033   while( pTrigger ){
79034     if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
79035       mask |= pTrigger->tr_tm;
79036     }
79037     pTrigger = pTrigger->pNext;
79038   }
79039   return mask;
79040 }
79041
79042 /*
79043 ** Convert the pStep->target token into a SrcList and return a pointer
79044 ** to that SrcList.
79045 **
79046 ** This routine adds a specific database name, if needed, to the target when
79047 ** forming the SrcList.  This prevents a trigger in one database from
79048 ** referring to a target in another database.  An exception is when the
79049 ** trigger is in TEMP in which case it can refer to any other database it
79050 ** wants.
79051 */
79052 static SrcList *targetSrcList(
79053   Parse *pParse,       /* The parsing context */
79054   TriggerStep *pStep   /* The trigger containing the target token */
79055 ){
79056   Token sDb;           /* Dummy database name token */
79057   int iDb;             /* Index of the database to use */
79058   SrcList *pSrc;       /* SrcList to be returned */
79059
79060   iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
79061   if( iDb==0 || iDb>=2 ){
79062     assert( iDb<pParse->db->nDb );
79063     sDb.z = (u8*)pParse->db->aDb[iDb].zName;
79064     sDb.n = sqlite3Strlen30((char*)sDb.z);
79065     pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
79066   } else {
79067     pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
79068   }
79069   return pSrc;
79070 }
79071
79072 /*
79073 ** Generate VDBE code for zero or more statements inside the body of a
79074 ** trigger.  
79075 */
79076 static int codeTriggerProgram(
79077   Parse *pParse,            /* The parser context */
79078   TriggerStep *pStepList,   /* List of statements inside the trigger body */
79079   int orconfin              /* Conflict algorithm. (OE_Abort, etc) */  
79080 ){
79081   TriggerStep * pTriggerStep = pStepList;
79082   int orconf;
79083   Vdbe *v = pParse->pVdbe;
79084   sqlite3 *db = pParse->db;
79085
79086   assert( pTriggerStep!=0 );
79087   assert( v!=0 );
79088   sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
79089   VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
79090   while( pTriggerStep ){
79091     sqlite3ExprClearColumnCache(pParse, -1);
79092     orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
79093     pParse->trigStack->orconf = orconf;
79094     switch( pTriggerStep->op ){
79095       case TK_SELECT: {
79096         Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
79097         if( ss ){
79098           SelectDest dest;
79099
79100           sqlite3SelectDestInit(&dest, SRT_Discard, 0);
79101           sqlite3Select(pParse, ss, &dest);
79102           sqlite3SelectDelete(db, ss);
79103         }
79104         break;
79105       }
79106       case TK_UPDATE: {
79107         SrcList *pSrc;
79108         pSrc = targetSrcList(pParse, pTriggerStep);
79109         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
79110         sqlite3Update(pParse, pSrc,
79111                 sqlite3ExprListDup(db, pTriggerStep->pExprList), 
79112                 sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
79113         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
79114         break;
79115       }
79116       case TK_INSERT: {
79117         SrcList *pSrc;
79118         pSrc = targetSrcList(pParse, pTriggerStep);
79119         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
79120         sqlite3Insert(pParse, pSrc,
79121           sqlite3ExprListDup(db, pTriggerStep->pExprList), 
79122           sqlite3SelectDup(db, pTriggerStep->pSelect), 
79123           sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
79124         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
79125         break;
79126       }
79127       case TK_DELETE: {
79128         SrcList *pSrc;
79129         sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
79130         pSrc = targetSrcList(pParse, pTriggerStep);
79131         sqlite3DeleteFrom(pParse, pSrc, 
79132                           sqlite3ExprDup(db, pTriggerStep->pWhere));
79133         sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
79134         break;
79135       }
79136       default:
79137         assert(0);
79138     } 
79139     pTriggerStep = pTriggerStep->pNext;
79140   }
79141   sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
79142   VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
79143
79144   return 0;
79145 }
79146
79147 /*
79148 ** This is called to code FOR EACH ROW triggers.
79149 **
79150 ** When the code that this function generates is executed, the following 
79151 ** must be true:
79152 **
79153 ** 1. No cursors may be open in the main database.  (But newIdx and oldIdx
79154 **    can be indices of cursors in temporary tables.  See below.)
79155 **
79156 ** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
79157 **    a temporary vdbe cursor (index newIdx) must be open and pointing at
79158 **    a row containing values to be substituted for new.* expressions in the
79159 **    trigger program(s).
79160 **
79161 ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
79162 **    a temporary vdbe cursor (index oldIdx) must be open and pointing at
79163 **    a row containing values to be substituted for old.* expressions in the
79164 **    trigger program(s).
79165 **
79166 ** If they are not NULL, the piOldColMask and piNewColMask output variables
79167 ** are set to values that describe the columns used by the trigger program
79168 ** in the OLD.* and NEW.* tables respectively. If column N of the 
79169 ** pseudo-table is read at least once, the corresponding bit of the output
79170 ** mask is set. If a column with an index greater than 32 is read, the
79171 ** output mask is set to the special value 0xffffffff.
79172 **
79173 */
79174 SQLITE_PRIVATE int sqlite3CodeRowTrigger(
79175   Parse *pParse,       /* Parse context */
79176   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
79177   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
79178   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
79179   Table *pTab,         /* The table to code triggers from */
79180   int newIdx,          /* The indice of the "new" row to access */
79181   int oldIdx,          /* The indice of the "old" row to access */
79182   int orconf,          /* ON CONFLICT policy */
79183   int ignoreJump,      /* Instruction to jump to for RAISE(IGNORE) */
79184   u32 *piOldColMask,   /* OUT: Mask of columns used from the OLD.* table */
79185   u32 *piNewColMask    /* OUT: Mask of columns used from the NEW.* table */
79186 ){
79187   Trigger *p;
79188   sqlite3 *db = pParse->db;
79189   TriggerStack trigStackEntry;
79190
79191   trigStackEntry.oldColMask = 0;
79192   trigStackEntry.newColMask = 0;
79193
79194   assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
79195   assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
79196
79197   assert(newIdx != -1 || oldIdx != -1);
79198
79199   for(p=pTab->pTrigger; p; p=p->pNext){
79200     int fire_this = 0;
79201
79202     /* Determine whether we should code this trigger */
79203     if( 
79204       p->op==op && 
79205       p->tr_tm==tr_tm && 
79206       (p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
79207       (op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
79208     ){
79209       TriggerStack *pS;      /* Pointer to trigger-stack entry */
79210       for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
79211       if( !pS ){
79212         fire_this = 1;
79213       }
79214 #if 0    /* Give no warning for recursive triggers.  Just do not do them */
79215       else{
79216         sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
79217             p->name);
79218         return SQLITE_ERROR;
79219       }
79220 #endif
79221     }
79222  
79223     if( fire_this ){
79224       int endTrigger;
79225       Expr * whenExpr;
79226       AuthContext sContext;
79227       NameContext sNC;
79228
79229 #ifndef SQLITE_OMIT_TRACE
79230       sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
79231                         sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
79232                         P4_DYNAMIC);
79233 #endif
79234       memset(&sNC, 0, sizeof(sNC));
79235       sNC.pParse = pParse;
79236
79237       /* Push an entry on to the trigger stack */
79238       trigStackEntry.pTrigger = p;
79239       trigStackEntry.newIdx = newIdx;
79240       trigStackEntry.oldIdx = oldIdx;
79241       trigStackEntry.pTab = pTab;
79242       trigStackEntry.pNext = pParse->trigStack;
79243       trigStackEntry.ignoreJump = ignoreJump;
79244       pParse->trigStack = &trigStackEntry;
79245       sqlite3AuthContextPush(pParse, &sContext, p->name);
79246
79247       /* code the WHEN clause */
79248       endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
79249       whenExpr = sqlite3ExprDup(db, p->pWhen);
79250       if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
79251         pParse->trigStack = trigStackEntry.pNext;
79252         sqlite3ExprDelete(db, whenExpr);
79253         return 1;
79254       }
79255       sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
79256       sqlite3ExprDelete(db, whenExpr);
79257
79258       codeTriggerProgram(pParse, p->step_list, orconf); 
79259
79260       /* Pop the entry off the trigger stack */
79261       pParse->trigStack = trigStackEntry.pNext;
79262       sqlite3AuthContextPop(&sContext);
79263
79264       sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
79265     }
79266   }
79267   if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
79268   if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
79269   return 0;
79270 }
79271 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
79272
79273 /************** End of trigger.c *********************************************/
79274 /************** Begin file update.c ******************************************/
79275 /*
79276 ** 2001 September 15
79277 **
79278 ** The author disclaims copyright to this source code.  In place of
79279 ** a legal notice, here is a blessing:
79280 **
79281 **    May you do good and not evil.
79282 **    May you find forgiveness for yourself and forgive others.
79283 **    May you share freely, never taking more than you give.
79284 **
79285 *************************************************************************
79286 ** This file contains C code routines that are called by the parser
79287 ** to handle UPDATE statements.
79288 **
79289 ** $Id: update.c,v 1.191 2008/12/23 23:56:22 drh Exp $
79290 */
79291
79292 #ifndef SQLITE_OMIT_VIRTUALTABLE
79293 /* Forward declaration */
79294 static void updateVirtualTable(
79295   Parse *pParse,       /* The parsing context */
79296   SrcList *pSrc,       /* The virtual table to be modified */
79297   Table *pTab,         /* The virtual table */
79298   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
79299   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
79300   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
79301   Expr *pWhere         /* WHERE clause of the UPDATE statement */
79302 );
79303 #endif /* SQLITE_OMIT_VIRTUALTABLE */
79304
79305 /*
79306 ** The most recently coded instruction was an OP_Column to retrieve the
79307 ** i-th column of table pTab. This routine sets the P4 parameter of the 
79308 ** OP_Column to the default value, if any.
79309 **
79310 ** The default value of a column is specified by a DEFAULT clause in the 
79311 ** column definition. This was either supplied by the user when the table
79312 ** was created, or added later to the table definition by an ALTER TABLE
79313 ** command. If the latter, then the row-records in the table btree on disk
79314 ** may not contain a value for the column and the default value, taken
79315 ** from the P4 parameter of the OP_Column instruction, is returned instead.
79316 ** If the former, then all row-records are guaranteed to include a value
79317 ** for the column and the P4 value is not required.
79318 **
79319 ** Column definitions created by an ALTER TABLE command may only have 
79320 ** literal default values specified: a number, null or a string. (If a more
79321 ** complicated default expression value was provided, it is evaluated 
79322 ** when the ALTER TABLE is executed and one of the literal values written
79323 ** into the sqlite_master table.)
79324 **
79325 ** Therefore, the P4 parameter is only required if the default value for
79326 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
79327 ** function is capable of transforming these types of expressions into
79328 ** sqlite3_value objects.
79329 */
79330 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
79331   if( pTab && !pTab->pSelect ){
79332     sqlite3_value *pValue;
79333     u8 enc = ENC(sqlite3VdbeDb(v));
79334     Column *pCol = &pTab->aCol[i];
79335     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
79336     assert( i<pTab->nCol );
79337     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
79338                          pCol->affinity, &pValue);
79339     if( pValue ){
79340       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
79341     }
79342   }
79343 }
79344
79345 /*
79346 ** Process an UPDATE statement.
79347 **
79348 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
79349 **          \_______/ \________/     \______/       \________________/
79350 *            onError   pTabList      pChanges             pWhere
79351 */
79352 SQLITE_PRIVATE void sqlite3Update(
79353   Parse *pParse,         /* The parser context */
79354   SrcList *pTabList,     /* The table in which we should change things */
79355   ExprList *pChanges,    /* Things to be changed */
79356   Expr *pWhere,          /* The WHERE clause.  May be null */
79357   int onError            /* How to handle constraint errors */
79358 ){
79359   int i, j;              /* Loop counters */
79360   Table *pTab;           /* The table to be updated */
79361   int addr = 0;          /* VDBE instruction address of the start of the loop */
79362   WhereInfo *pWInfo;     /* Information about the WHERE clause */
79363   Vdbe *v;               /* The virtual database engine */
79364   Index *pIdx;           /* For looping over indices */
79365   int nIdx;              /* Number of indices that need updating */
79366   int iCur;              /* VDBE Cursor number of pTab */
79367   sqlite3 *db;           /* The database structure */
79368   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
79369   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
79370                          ** an expression for the i-th column of the table.
79371                          ** aXRef[i]==-1 if the i-th column is not changed. */
79372   int chngRowid;         /* True if the record number is being changed */
79373   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
79374   int openAll = 0;       /* True if all indices need to be opened */
79375   AuthContext sContext;  /* The authorization context */
79376   NameContext sNC;       /* The name-context to resolve expressions in */
79377   int iDb;               /* Database containing the table being updated */
79378   int j1;                /* Addresses of jump instructions */
79379   int okOnePass;         /* True for one-pass algorithm without the FIFO */
79380
79381 #ifndef SQLITE_OMIT_TRIGGER
79382   int isView;                  /* Trying to update a view */
79383   int triggers_exist = 0;      /* True if any row triggers exist */
79384 #endif
79385   int iBeginAfterTrigger = 0;  /* Address of after trigger program */
79386   int iEndAfterTrigger = 0;    /* Exit of after trigger program */
79387   int iBeginBeforeTrigger = 0; /* Address of before trigger program */
79388   int iEndBeforeTrigger = 0;   /* Exit of before trigger program */
79389   u32 old_col_mask = 0;        /* Mask of OLD.* columns in use */
79390   u32 new_col_mask = 0;        /* Mask of NEW.* columns in use */
79391
79392   int newIdx      = -1;  /* index of trigger "new" temp table       */
79393   int oldIdx      = -1;  /* index of trigger "old" temp table       */
79394
79395   /* Register Allocations */
79396   int regRowCount = 0;   /* A count of rows changed */
79397   int regOldRowid;       /* The old rowid */
79398   int regNewRowid;       /* The new rowid */
79399   int regData;           /* New data for the row */
79400   int regRowSet = 0;     /* Rowset of rows to be updated */
79401
79402   sContext.pParse = 0;
79403   db = pParse->db;
79404   if( pParse->nErr || db->mallocFailed ){
79405     goto update_cleanup;
79406   }
79407   assert( pTabList->nSrc==1 );
79408
79409   /* Locate the table which we want to update. 
79410   */
79411   pTab = sqlite3SrcListLookup(pParse, pTabList);
79412   if( pTab==0 ) goto update_cleanup;
79413   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79414
79415   /* Figure out if we have any triggers and if the table being
79416   ** updated is a view
79417   */
79418 #ifndef SQLITE_OMIT_TRIGGER
79419   triggers_exist = sqlite3TriggersExist(pTab, TK_UPDATE, pChanges);
79420   isView = pTab->pSelect!=0;
79421 #else
79422 # define triggers_exist 0
79423 # define isView 0
79424 #endif
79425 #ifdef SQLITE_OMIT_VIEW
79426 # undef isView
79427 # define isView 0
79428 #endif
79429
79430   if( sqlite3IsReadOnly(pParse, pTab, triggers_exist) ){
79431     goto update_cleanup;
79432   }
79433   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79434     goto update_cleanup;
79435   }
79436   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
79437   if( aXRef==0 ) goto update_cleanup;
79438   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
79439
79440   /* If there are FOR EACH ROW triggers, allocate cursors for the
79441   ** special OLD and NEW tables
79442   */
79443   if( triggers_exist ){
79444     newIdx = pParse->nTab++;
79445     oldIdx = pParse->nTab++;
79446   }
79447
79448   /* Allocate a cursors for the main database table and for all indices.
79449   ** The index cursors might not be used, but if they are used they
79450   ** need to occur right after the database cursor.  So go ahead and
79451   ** allocate enough space, just in case.
79452   */
79453   pTabList->a[0].iCursor = iCur = pParse->nTab++;
79454   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79455     pParse->nTab++;
79456   }
79457
79458   /* Initialize the name-context */
79459   memset(&sNC, 0, sizeof(sNC));
79460   sNC.pParse = pParse;
79461   sNC.pSrcList = pTabList;
79462
79463   /* Resolve the column names in all the expressions of the
79464   ** of the UPDATE statement.  Also find the column index
79465   ** for each column to be updated in the pChanges array.  For each
79466   ** column to be updated, make sure we have authorization to change
79467   ** that column.
79468   */
79469   chngRowid = 0;
79470   for(i=0; i<pChanges->nExpr; i++){
79471     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
79472       goto update_cleanup;
79473     }
79474     for(j=0; j<pTab->nCol; j++){
79475       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
79476         if( j==pTab->iPKey ){
79477           chngRowid = 1;
79478           pRowidExpr = pChanges->a[i].pExpr;
79479         }
79480         aXRef[j] = i;
79481         break;
79482       }
79483     }
79484     if( j>=pTab->nCol ){
79485       if( sqlite3IsRowid(pChanges->a[i].zName) ){
79486         chngRowid = 1;
79487         pRowidExpr = pChanges->a[i].pExpr;
79488       }else{
79489         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
79490         goto update_cleanup;
79491       }
79492     }
79493 #ifndef SQLITE_OMIT_AUTHORIZATION
79494     {
79495       int rc;
79496       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
79497                            pTab->aCol[j].zName, db->aDb[iDb].zName);
79498       if( rc==SQLITE_DENY ){
79499         goto update_cleanup;
79500       }else if( rc==SQLITE_IGNORE ){
79501         aXRef[j] = -1;
79502       }
79503     }
79504 #endif
79505   }
79506
79507   /* Allocate memory for the array aRegIdx[].  There is one entry in the
79508   ** array for each index associated with table being updated.  Fill in
79509   ** the value with a register number for indices that are to be used
79510   ** and with zero for unused indices.
79511   */
79512   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
79513   if( nIdx>0 ){
79514     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
79515     if( aRegIdx==0 ) goto update_cleanup;
79516   }
79517   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
79518     int reg;
79519     if( chngRowid ){
79520       reg = ++pParse->nMem;
79521     }else{
79522       reg = 0;
79523       for(i=0; i<pIdx->nColumn; i++){
79524         if( aXRef[pIdx->aiColumn[i]]>=0 ){
79525           reg = ++pParse->nMem;
79526           break;
79527         }
79528       }
79529     }
79530     aRegIdx[j] = reg;
79531   }
79532
79533   /* Allocate a block of register used to store the change record
79534   ** sent to sqlite3GenerateConstraintChecks().  There are either
79535   ** one or two registers for holding the rowid.  One rowid register
79536   ** is used if chngRowid is false and two are used if chngRowid is
79537   ** true.  Following these are pTab->nCol register holding column
79538   ** data.
79539   */
79540   regOldRowid = regNewRowid = pParse->nMem + 1;
79541   pParse->nMem += pTab->nCol + 1;
79542   if( chngRowid ){
79543     regNewRowid++;
79544     pParse->nMem++;
79545   }
79546   regData = regNewRowid+1;
79547  
79548
79549   /* Begin generating code.
79550   */
79551   v = sqlite3GetVdbe(pParse);
79552   if( v==0 ) goto update_cleanup;
79553   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
79554   sqlite3BeginWriteOperation(pParse, 1, iDb);
79555
79556 #ifndef SQLITE_OMIT_VIRTUALTABLE
79557   /* Virtual tables must be handled separately */
79558   if( IsVirtual(pTab) ){
79559     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
79560                        pWhere);
79561     pWhere = 0;
79562     pTabList = 0;
79563     goto update_cleanup;
79564   }
79565 #endif
79566
79567   /* Start the view context
79568   */
79569   if( isView ){
79570     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
79571   }
79572
79573   /* Generate the code for triggers.
79574   */
79575   if( triggers_exist ){
79576     int iGoto;
79577
79578     /* Create pseudo-tables for NEW and OLD
79579     */
79580     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
79581     sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0);
79582     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol);
79583     sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0);
79584
79585     iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
79586     addr = sqlite3VdbeMakeLabel(v);
79587     iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v);
79588     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab,
79589           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
79590       goto update_cleanup;
79591     }
79592     iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
79593     iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v);
79594     if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, 
79595           newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){
79596       goto update_cleanup;
79597     }
79598     iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
79599     sqlite3VdbeJumpHere(v, iGoto);
79600   }
79601
79602   /* If we are trying to update a view, realize that view into
79603   ** a ephemeral table.
79604   */
79605 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
79606   if( isView ){
79607     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
79608   }
79609 #endif
79610
79611   /* Resolve the column names in all the expressions in the
79612   ** WHERE clause.
79613   */
79614   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
79615     goto update_cleanup;
79616   }
79617
79618   /* Begin the database scan
79619   */
79620   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
79621   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
79622                              WHERE_ONEPASS_DESIRED, 0);
79623   if( pWInfo==0 ) goto update_cleanup;
79624   okOnePass = pWInfo->okOnePass;
79625
79626   /* Remember the rowid of every item to be updated.
79627   */
79628   sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
79629   if( !okOnePass ){
79630     regRowSet = ++pParse->nMem;
79631     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
79632   }
79633
79634   /* End the database scan loop.
79635   */
79636   sqlite3WhereEnd(pWInfo);
79637
79638   /* Initialize the count of updated rows
79639   */
79640   if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
79641     regRowCount = ++pParse->nMem;
79642     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
79643   }
79644
79645   if( !isView && !IsVirtual(pTab) ){
79646     /* 
79647     ** Open every index that needs updating.  Note that if any
79648     ** index could potentially invoke a REPLACE conflict resolution 
79649     ** action, then we need to open all indices because we might need
79650     ** to be deleting some records.
79651     */
79652     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
79653     if( onError==OE_Replace ){
79654       openAll = 1;
79655     }else{
79656       openAll = 0;
79657       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79658         if( pIdx->onError==OE_Replace ){
79659           openAll = 1;
79660           break;
79661         }
79662       }
79663     }
79664     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
79665       if( openAll || aRegIdx[i]>0 ){
79666         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79667         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
79668                        (char*)pKey, P4_KEYINFO_HANDOFF);
79669         assert( pParse->nTab>iCur+i+1 );
79670       }
79671     }
79672   }
79673   
79674   /* Jump back to this point if a trigger encounters an IGNORE constraint. */
79675   if( triggers_exist ){
79676     sqlite3VdbeResolveLabel(v, addr);
79677   }
79678
79679   /* Top of the update loop */
79680   if( okOnePass ){
79681     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
79682     addr = sqlite3VdbeAddOp0(v, OP_Goto);
79683     sqlite3VdbeJumpHere(v, a1);
79684   }else{
79685     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
79686   }
79687
79688   if( triggers_exist ){
79689     int regRowid;
79690     int regRow;
79691     int regCols;
79692
79693     /* Make cursor iCur point to the record that is being updated.
79694     */
79695     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
79696
79697     /* Generate the OLD table
79698     */
79699     regRowid = sqlite3GetTempReg(pParse);
79700     regRow = sqlite3GetTempReg(pParse);
79701     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
79702     if( !old_col_mask ){
79703       sqlite3VdbeAddOp2(v, OP_Null, 0, regRow);
79704     }else{
79705       sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow);
79706     }
79707     sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid);
79708
79709     /* Generate the NEW table
79710     */
79711     if( chngRowid ){
79712       sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid);
79713       sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
79714     }else{
79715       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid);
79716     }
79717     regCols = sqlite3GetTempRange(pParse, pTab->nCol);
79718     for(i=0; i<pTab->nCol; i++){
79719       if( i==pTab->iPKey ){
79720         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
79721         continue;
79722       }
79723       j = aXRef[i];
79724       if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
79725         if( j<0 ){
79726           sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
79727           sqlite3ColumnDefault(v, pTab, i);
79728         }else{
79729           sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
79730         }
79731       }else{
79732         sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
79733       }
79734     }
79735     sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow);
79736     if( !isView ){
79737       sqlite3TableAffinityStr(v, pTab);
79738       sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol);
79739     }
79740     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol);
79741     /* if( pParse->nErr ) goto update_cleanup; */
79742     sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid);
79743     sqlite3ReleaseTempReg(pParse, regRowid);
79744     sqlite3ReleaseTempReg(pParse, regRow);
79745
79746     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
79747     sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
79748   }
79749
79750   if( !isView && !IsVirtual(pTab) ){
79751     /* Loop over every record that needs updating.  We have to load
79752     ** the old data for each record to be updated because some columns
79753     ** might not change and we will need to copy the old value.
79754     ** Also, the old data is needed to delete the old index entries.
79755     ** So make the cursor point at the old record.
79756     */
79757     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
79758
79759     /* If the record number will change, push the record number as it
79760     ** will be after the update. (The old record number is currently
79761     ** on top of the stack.)
79762     */
79763     if( chngRowid ){
79764       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
79765       sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
79766     }
79767
79768     /* Compute new data for this record.  
79769     */
79770     for(i=0; i<pTab->nCol; i++){
79771       if( i==pTab->iPKey ){
79772         sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i);
79773         continue;
79774       }
79775       j = aXRef[i];
79776       if( j<0 ){
79777         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i);
79778         sqlite3ColumnDefault(v, pTab, i);
79779       }else{
79780         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i);
79781       }
79782     }
79783
79784     /* Do constraint checks
79785     */
79786     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
79787                                     aRegIdx, chngRowid, 1,
79788                                     onError, addr);
79789
79790     /* Delete the old indices for the current record.
79791     */
79792     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
79793     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
79794
79795     /* If changing the record number, delete the old record.
79796     */
79797     if( chngRowid ){
79798       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
79799     }
79800     sqlite3VdbeJumpHere(v, j1);
79801
79802     /* Create the new index entries and the new record.
79803     */
79804     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, 
79805                              aRegIdx, 1, -1, 0);
79806   }
79807
79808   /* Increment the row counter 
79809   */
79810   if( db->flags & SQLITE_CountRows && !pParse->trigStack){
79811     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
79812   }
79813
79814   /* If there are triggers, close all the cursors after each iteration
79815   ** through the loop.  The fire the after triggers.
79816   */
79817   if( triggers_exist ){
79818     sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger);
79819     sqlite3VdbeJumpHere(v, iEndAfterTrigger);
79820   }
79821
79822   /* Repeat the above with the next record to be updated, until
79823   ** all record selected by the WHERE clause have been updated.
79824   */
79825   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
79826   sqlite3VdbeJumpHere(v, addr);
79827
79828   /* Close all tables */
79829   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
79830     if( openAll || aRegIdx[i]>0 ){
79831       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
79832     }
79833   }
79834   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
79835   if( triggers_exist ){
79836     sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0);
79837     sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0);
79838   }
79839
79840   /*
79841   ** Return the number of rows that were changed. If this routine is 
79842   ** generating code because of a call to sqlite3NestedParse(), do not
79843   ** invoke the callback function.
79844   */
79845   if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){
79846     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
79847     sqlite3VdbeSetNumCols(v, 1);
79848     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
79849   }
79850
79851 update_cleanup:
79852   sqlite3AuthContextPop(&sContext);
79853   sqlite3DbFree(db, aRegIdx);
79854   sqlite3DbFree(db, aXRef);
79855   sqlite3SrcListDelete(db, pTabList);
79856   sqlite3ExprListDelete(db, pChanges);
79857   sqlite3ExprDelete(db, pWhere);
79858   return;
79859 }
79860
79861 #ifndef SQLITE_OMIT_VIRTUALTABLE
79862 /*
79863 ** Generate code for an UPDATE of a virtual table.
79864 **
79865 ** The strategy is that we create an ephemerial table that contains
79866 ** for each row to be changed:
79867 **
79868 **   (A)  The original rowid of that row.
79869 **   (B)  The revised rowid for the row. (note1)
79870 **   (C)  The content of every column in the row.
79871 **
79872 ** Then we loop over this ephemeral table and for each row in
79873 ** the ephermeral table call VUpdate.
79874 **
79875 ** When finished, drop the ephemeral table.
79876 **
79877 ** (note1) Actually, if we know in advance that (A) is always the same
79878 ** as (B) we only store (A), then duplicate (A) when pulling
79879 ** it out of the ephemeral table before calling VUpdate.
79880 */
79881 static void updateVirtualTable(
79882   Parse *pParse,       /* The parsing context */
79883   SrcList *pSrc,       /* The virtual table to be modified */
79884   Table *pTab,         /* The virtual table */
79885   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
79886   Expr *pRowid,        /* Expression used to recompute the rowid */
79887   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
79888   Expr *pWhere         /* WHERE clause of the UPDATE statement */
79889 ){
79890   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
79891   ExprList *pEList = 0;     /* The result set of the SELECT statement */
79892   Select *pSelect = 0;      /* The SELECT statement */
79893   Expr *pExpr;              /* Temporary expression */
79894   int ephemTab;             /* Table holding the result of the SELECT */
79895   int i;                    /* Loop counter */
79896   int addr;                 /* Address of top of loop */
79897   int iReg;                 /* First register in set passed to OP_VUpdate */
79898   sqlite3 *db = pParse->db; /* Database connection */
79899   const char *pVtab = (const char*)pTab->pVtab;
79900   SelectDest dest;
79901
79902   /* Construct the SELECT statement that will find the new values for
79903   ** all updated rows. 
79904   */
79905   pEList = sqlite3ExprListAppend(pParse, 0, 
79906                                  sqlite3CreateIdExpr(pParse, "_rowid_"), 0);
79907   if( pRowid ){
79908     pEList = sqlite3ExprListAppend(pParse, pEList,
79909                                    sqlite3ExprDup(db, pRowid), 0);
79910   }
79911   assert( pTab->iPKey<0 );
79912   for(i=0; i<pTab->nCol; i++){
79913     if( aXRef[i]>=0 ){
79914       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr);
79915     }else{
79916       pExpr = sqlite3CreateIdExpr(pParse, pTab->aCol[i].zName);
79917     }
79918     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr, 0);
79919   }
79920   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
79921   
79922   /* Create the ephemeral table into which the update results will
79923   ** be stored.
79924   */
79925   assert( v );
79926   ephemTab = pParse->nTab++;
79927   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
79928
79929   /* fill the ephemeral table 
79930   */
79931   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
79932   sqlite3Select(pParse, pSelect, &dest);
79933
79934   /* Generate code to scan the ephemeral table and call VUpdate. */
79935   iReg = ++pParse->nMem;
79936   pParse->nMem += pTab->nCol+1;
79937   sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
79938   addr = sqlite3VdbeCurrentAddr(v);
79939   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
79940   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
79941   for(i=0; i<pTab->nCol; i++){
79942     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
79943   }
79944   sqlite3VtabMakeWritable(pParse, pTab);
79945   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB);
79946   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr);
79947   sqlite3VdbeJumpHere(v, addr-1);
79948   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
79949
79950   /* Cleanup */
79951   sqlite3SelectDelete(db, pSelect);  
79952 }
79953 #endif /* SQLITE_OMIT_VIRTUALTABLE */
79954
79955 /* Make sure "isView" gets undefined in case this file becomes part of
79956 ** the amalgamation - so that subsequent files do not see isView as a
79957 ** macro. */
79958 #undef isView
79959
79960 /************** End of update.c **********************************************/
79961 /************** Begin file vacuum.c ******************************************/
79962 /*
79963 ** 2003 April 6
79964 **
79965 ** The author disclaims copyright to this source code.  In place of
79966 ** a legal notice, here is a blessing:
79967 **
79968 **    May you do good and not evil.
79969 **    May you find forgiveness for yourself and forgive others.
79970 **    May you share freely, never taking more than you give.
79971 **
79972 *************************************************************************
79973 ** This file contains code used to implement the VACUUM command.
79974 **
79975 ** Most of the code in this file may be omitted by defining the
79976 ** SQLITE_OMIT_VACUUM macro.
79977 **
79978 ** $Id: vacuum.c,v 1.86 2009/02/03 16:51:25 danielk1977 Exp $
79979 */
79980
79981 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
79982 /*
79983 ** Execute zSql on database db. Return an error code.
79984 */
79985 static int execSql(sqlite3 *db, const char *zSql){
79986   sqlite3_stmt *pStmt;
79987   if( !zSql ){
79988     return SQLITE_NOMEM;
79989   }
79990   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
79991     return sqlite3_errcode(db);
79992   }
79993   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
79994   return sqlite3_finalize(pStmt);
79995 }
79996
79997 /*
79998 ** Execute zSql on database db. The statement returns exactly
79999 ** one column. Execute this as SQL on the same database.
80000 */
80001 static int execExecSql(sqlite3 *db, const char *zSql){
80002   sqlite3_stmt *pStmt;
80003   int rc;
80004
80005   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
80006   if( rc!=SQLITE_OK ) return rc;
80007
80008   while( SQLITE_ROW==sqlite3_step(pStmt) ){
80009     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
80010     if( rc!=SQLITE_OK ){
80011       sqlite3_finalize(pStmt);
80012       return rc;
80013     }
80014   }
80015
80016   return sqlite3_finalize(pStmt);
80017 }
80018
80019 /*
80020 ** The non-standard VACUUM command is used to clean up the database,
80021 ** collapse free space, etc.  It is modelled after the VACUUM command
80022 ** in PostgreSQL.
80023 **
80024 ** In version 1.0.x of SQLite, the VACUUM command would call
80025 ** gdbm_reorganize() on all the database tables.  But beginning
80026 ** with 2.0.0, SQLite no longer uses GDBM so this command has
80027 ** become a no-op.
80028 */
80029 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
80030   Vdbe *v = sqlite3GetVdbe(pParse);
80031   if( v ){
80032     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
80033   }
80034   return;
80035 }
80036
80037 /*
80038 ** This routine implements the OP_Vacuum opcode of the VDBE.
80039 */
80040 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
80041   int rc = SQLITE_OK;     /* Return code from service routines */
80042   Btree *pMain;           /* The database being vacuumed */
80043   Pager *pMainPager;      /* Pager for database being vacuumed */
80044   Btree *pTemp;           /* The temporary database we vacuum into */
80045   char *zSql = 0;         /* SQL statements */
80046   int saved_flags;        /* Saved value of the db->flags */
80047   int saved_nChange;      /* Saved value of db->nChange */
80048   int saved_nTotalChange; /* Saved value of db->nTotalChange */
80049   Db *pDb = 0;            /* Database to detach at end of vacuum */
80050   int isMemDb;            /* True is vacuuming a :memory: database */
80051   int nRes;
80052
80053   if( !db->autoCommit ){
80054     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
80055     return SQLITE_ERROR;
80056   }
80057
80058   /* Save the current value of the write-schema flag before setting it. */
80059   saved_flags = db->flags;
80060   saved_nChange = db->nChange;
80061   saved_nTotalChange = db->nTotalChange;
80062   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
80063
80064   pMain = db->aDb[0].pBt;
80065   pMainPager = sqlite3BtreePager(pMain);
80066   isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;
80067
80068   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
80069   ** can be set to 'off' for this file, as it is not recovered if a crash
80070   ** occurs anyway. The integrity of the database is maintained by a
80071   ** (possibly synchronous) transaction opened on the main database before
80072   ** sqlite3BtreeCopyFile() is called.
80073   **
80074   ** An optimisation would be to use a non-journaled pager.
80075   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
80076   ** that actually made the VACUUM run slower.  Very little journalling
80077   ** actually occurs when doing a vacuum since the vacuum_db is initially
80078   ** empty.  Only the journal header is written.  Apparently it takes more
80079   ** time to parse and run the PRAGMA to turn journalling off than it does
80080   ** to write the journal header file.
80081   */
80082   zSql = "ATTACH '' AS vacuum_db;";
80083   rc = execSql(db, zSql);
80084   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80085   pDb = &db->aDb[db->nDb-1];
80086   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
80087   pTemp = db->aDb[db->nDb-1].pBt;
80088
80089   nRes = sqlite3BtreeGetReserve(pMain);
80090
80091   /* A VACUUM cannot change the pagesize of an encrypted database. */
80092 #ifdef SQLITE_HAS_CODEC
80093   if( db->nextPagesize ){
80094     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80095     int nKey;
80096     char *zKey;
80097     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80098     if( nKey ) db->nextPagesize = 0;
80099   }
80100 #endif
80101
80102   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
80103    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes))
80104    || db->mallocFailed 
80105   ){
80106     rc = SQLITE_NOMEM;
80107     goto end_of_vacuum;
80108   }
80109   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
80110   if( rc!=SQLITE_OK ){
80111     goto end_of_vacuum;
80112   }
80113
80114 #ifndef SQLITE_OMIT_AUTOVACUUM
80115   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
80116                                            sqlite3BtreeGetAutoVacuum(pMain));
80117 #endif
80118
80119   /* Begin a transaction */
80120   rc = execSql(db, "BEGIN EXCLUSIVE;");
80121   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80122
80123   /* Query the schema of the main database. Create a mirror schema
80124   ** in the temporary database.
80125   */
80126   rc = execExecSql(db, 
80127       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
80128       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
80129       "   AND rootpage>0"
80130   );
80131   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80132   rc = execExecSql(db, 
80133       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
80134       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
80135   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80136   rc = execExecSql(db, 
80137       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
80138       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
80139   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80140
80141   /* Loop through the tables in the main database. For each, do
80142   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
80143   ** the contents to the temporary database.
80144   */
80145   rc = execExecSql(db, 
80146       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
80147       "|| ' SELECT * FROM ' || quote(name) || ';'"
80148       "FROM sqlite_master "
80149       "WHERE type = 'table' AND name!='sqlite_sequence' "
80150       "  AND rootpage>0"
80151
80152   );
80153   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80154
80155   /* Copy over the sequence table
80156   */
80157   rc = execExecSql(db, 
80158       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
80159       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
80160   );
80161   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80162   rc = execExecSql(db, 
80163       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
80164       "|| ' SELECT * FROM ' || quote(name) || ';' "
80165       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
80166   );
80167   if( rc!=SQLITE_OK ) goto end_of_vacuum;
80168
80169
80170   /* Copy the triggers, views, and virtual tables from the main database
80171   ** over to the temporary database.  None of these objects has any
80172   ** associated storage, so all we have to do is copy their entries
80173   ** from the SQLITE_MASTER table.
80174   */
80175   rc = execSql(db,
80176       "INSERT INTO vacuum_db.sqlite_master "
80177       "  SELECT type, name, tbl_name, rootpage, sql"
80178       "    FROM sqlite_master"
80179       "   WHERE type='view' OR type='trigger'"
80180       "      OR (type='table' AND rootpage=0)"
80181   );
80182   if( rc ) goto end_of_vacuum;
80183
80184   /* At this point, unless the main db was completely empty, there is now a
80185   ** transaction open on the vacuum database, but not on the main database.
80186   ** Open a btree level transaction on the main database. This allows a
80187   ** call to sqlite3BtreeCopyFile(). The main database btree level
80188   ** transaction is then committed, so the SQL level never knows it was
80189   ** opened for writing. This way, the SQL transaction used to create the
80190   ** temporary database never needs to be committed.
80191   */
80192   if( rc==SQLITE_OK ){
80193     u32 meta;
80194     int i;
80195
80196     /* This array determines which meta meta values are preserved in the
80197     ** vacuum.  Even entries are the meta value number and odd entries
80198     ** are an increment to apply to the meta value after the vacuum.
80199     ** The increment is used to increase the schema cookie so that other
80200     ** connections to the same database will know to reread the schema.
80201     */
80202     static const unsigned char aCopy[] = {
80203        1, 1,    /* Add one to the old schema cookie */
80204        3, 0,    /* Preserve the default page cache size */
80205        5, 0,    /* Preserve the default text encoding */
80206        6, 0,    /* Preserve the user version */
80207     };
80208
80209     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
80210     assert( 1==sqlite3BtreeIsInTrans(pMain) );
80211
80212     /* Copy Btree meta values */
80213     for(i=0; i<ArraySize(aCopy); i+=2){
80214       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
80215       if( rc!=SQLITE_OK ) goto end_of_vacuum;
80216       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
80217       if( rc!=SQLITE_OK ) goto end_of_vacuum;
80218     }
80219
80220     rc = sqlite3BtreeCopyFile(pMain, pTemp);
80221     if( rc!=SQLITE_OK ) goto end_of_vacuum;
80222     rc = sqlite3BtreeCommit(pTemp);
80223     if( rc!=SQLITE_OK ) goto end_of_vacuum;
80224 #ifndef SQLITE_OMIT_AUTOVACUUM
80225     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
80226 #endif
80227   }
80228
80229   if( rc==SQLITE_OK ){
80230     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
80231   }
80232
80233 end_of_vacuum:
80234   /* Restore the original value of db->flags */
80235   db->flags = saved_flags;
80236   db->nChange = saved_nChange;
80237   db->nTotalChange = saved_nTotalChange;
80238
80239   /* Currently there is an SQL level transaction open on the vacuum
80240   ** database. No locks are held on any other files (since the main file
80241   ** was committed at the btree level). So it safe to end the transaction
80242   ** by manually setting the autoCommit flag to true and detaching the
80243   ** vacuum database. The vacuum_db journal file is deleted when the pager
80244   ** is closed by the DETACH.
80245   */
80246   db->autoCommit = 1;
80247
80248   if( pDb ){
80249     sqlite3BtreeClose(pDb->pBt);
80250     pDb->pBt = 0;
80251     pDb->pSchema = 0;
80252   }
80253
80254   sqlite3ResetInternalSchema(db, 0);
80255
80256   return rc;
80257 }
80258 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
80259
80260 /************** End of vacuum.c **********************************************/
80261 /************** Begin file vtab.c ********************************************/
80262 /*
80263 ** 2006 June 10
80264 **
80265 ** The author disclaims copyright to this source code.  In place of
80266 ** a legal notice, here is a blessing:
80267 **
80268 **    May you do good and not evil.
80269 **    May you find forgiveness for yourself and forgive others.
80270 **    May you share freely, never taking more than you give.
80271 **
80272 *************************************************************************
80273 ** This file contains code used to help implement virtual tables.
80274 **
80275 ** $Id: vtab.c,v 1.81 2008/12/10 19:26:24 drh Exp $
80276 */
80277 #ifndef SQLITE_OMIT_VIRTUALTABLE
80278
80279 static int createModule(
80280   sqlite3 *db,                    /* Database in which module is registered */
80281   const char *zName,              /* Name assigned to this module */
80282   const sqlite3_module *pModule,  /* The definition of the module */
80283   void *pAux,                     /* Context pointer for xCreate/xConnect */
80284   void (*xDestroy)(void *)        /* Module destructor function */
80285 ) {
80286   int rc, nName;
80287   Module *pMod;
80288
80289   sqlite3_mutex_enter(db->mutex);
80290   nName = sqlite3Strlen30(zName);
80291   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
80292   if( pMod ){
80293     Module *pDel;
80294     char *zCopy = (char *)(&pMod[1]);
80295     memcpy(zCopy, zName, nName+1);
80296     pMod->zName = zCopy;
80297     pMod->pModule = pModule;
80298     pMod->pAux = pAux;
80299     pMod->xDestroy = xDestroy;
80300     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
80301     if( pDel && pDel->xDestroy ){
80302       pDel->xDestroy(pDel->pAux);
80303     }
80304     sqlite3DbFree(db, pDel);
80305     if( pDel==pMod ){
80306       db->mallocFailed = 1;
80307     }
80308     sqlite3ResetInternalSchema(db, 0);
80309   }else if( xDestroy ){
80310     xDestroy(pAux);
80311   }
80312   rc = sqlite3ApiExit(db, SQLITE_OK);
80313   sqlite3_mutex_leave(db->mutex);
80314   return rc;
80315 }
80316
80317
80318 /*
80319 ** External API function used to create a new virtual-table module.
80320 */
80321 SQLITE_API int sqlite3_create_module(
80322   sqlite3 *db,                    /* Database in which module is registered */
80323   const char *zName,              /* Name assigned to this module */
80324   const sqlite3_module *pModule,  /* The definition of the module */
80325   void *pAux                      /* Context pointer for xCreate/xConnect */
80326 ){
80327   return createModule(db, zName, pModule, pAux, 0);
80328 }
80329
80330 /*
80331 ** External API function used to create a new virtual-table module.
80332 */
80333 SQLITE_API int sqlite3_create_module_v2(
80334   sqlite3 *db,                    /* Database in which module is registered */
80335   const char *zName,              /* Name assigned to this module */
80336   const sqlite3_module *pModule,  /* The definition of the module */
80337   void *pAux,                     /* Context pointer for xCreate/xConnect */
80338   void (*xDestroy)(void *)        /* Module destructor function */
80339 ){
80340   return createModule(db, zName, pModule, pAux, xDestroy);
80341 }
80342
80343 /*
80344 ** Lock the virtual table so that it cannot be disconnected.
80345 ** Locks nest.  Every lock should have a corresponding unlock.
80346 ** If an unlock is omitted, resources leaks will occur.  
80347 **
80348 ** If a disconnect is attempted while a virtual table is locked,
80349 ** the disconnect is deferred until all locks have been removed.
80350 */
80351 SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
80352   pVtab->nRef++;
80353 }
80354
80355 /*
80356 ** Unlock a virtual table.  When the last lock is removed,
80357 ** disconnect the virtual table.
80358 */
80359 SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
80360   pVtab->nRef--;
80361   assert(db);
80362   assert( sqlite3SafetyCheckOk(db) );
80363   if( pVtab->nRef==0 ){
80364     if( db->magic==SQLITE_MAGIC_BUSY ){
80365       (void)sqlite3SafetyOff(db);
80366       pVtab->pModule->xDisconnect(pVtab);
80367       (void)sqlite3SafetyOn(db);
80368     } else {
80369       pVtab->pModule->xDisconnect(pVtab);
80370     }
80371   }
80372 }
80373
80374 /*
80375 ** Clear any and all virtual-table information from the Table record.
80376 ** This routine is called, for example, just before deleting the Table
80377 ** record.
80378 */
80379 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
80380   sqlite3_vtab *pVtab = p->pVtab;
80381   sqlite3 *db = p->db;
80382   if( pVtab ){
80383     assert( p->pMod && p->pMod->pModule );
80384     sqlite3VtabUnlock(db, pVtab);
80385     p->pVtab = 0;
80386   }
80387   if( p->azModuleArg ){
80388     int i;
80389     for(i=0; i<p->nModuleArg; i++){
80390       sqlite3DbFree(db, p->azModuleArg[i]);
80391     }
80392     sqlite3DbFree(db, p->azModuleArg);
80393   }
80394 }
80395
80396 /*
80397 ** Add a new module argument to pTable->azModuleArg[].
80398 ** The string is not copied - the pointer is stored.  The
80399 ** string will be freed automatically when the table is
80400 ** deleted.
80401 */
80402 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
80403   int i = pTable->nModuleArg++;
80404   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
80405   char **azModuleArg;
80406   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
80407   if( azModuleArg==0 ){
80408     int j;
80409     for(j=0; j<i; j++){
80410       sqlite3DbFree(db, pTable->azModuleArg[j]);
80411     }
80412     sqlite3DbFree(db, zArg);
80413     sqlite3DbFree(db, pTable->azModuleArg);
80414     pTable->nModuleArg = 0;
80415   }else{
80416     azModuleArg[i] = zArg;
80417     azModuleArg[i+1] = 0;
80418   }
80419   pTable->azModuleArg = azModuleArg;
80420 }
80421
80422 /*
80423 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
80424 ** statement.  The module name has been parsed, but the optional list
80425 ** of parameters that follow the module name are still pending.
80426 */
80427 SQLITE_PRIVATE void sqlite3VtabBeginParse(
80428   Parse *pParse,        /* Parsing context */
80429   Token *pName1,        /* Name of new table, or database name */
80430   Token *pName2,        /* Name of new table or NULL */
80431   Token *pModuleName    /* Name of the module for the virtual table */
80432 ){
80433   int iDb;              /* The database the table is being created in */
80434   Table *pTable;        /* The new virtual table */
80435   sqlite3 *db;          /* Database connection */
80436
80437   if( pParse->db->flags & SQLITE_SharedCache ){
80438     sqlite3ErrorMsg(pParse, "Cannot use virtual tables in shared-cache mode");
80439     return;
80440   }
80441
80442   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
80443   pTable = pParse->pNewTable;
80444   if( pTable==0 || pParse->nErr ) return;
80445   assert( 0==pTable->pIndex );
80446
80447   db = pParse->db;
80448   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
80449   assert( iDb>=0 );
80450
80451   pTable->tabFlags |= TF_Virtual;
80452   pTable->nModuleArg = 0;
80453   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
80454   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
80455   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
80456   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
80457
80458 #ifndef SQLITE_OMIT_AUTHORIZATION
80459   /* Creating a virtual table invokes the authorization callback twice.
80460   ** The first invocation, to obtain permission to INSERT a row into the
80461   ** sqlite_master table, has already been made by sqlite3StartTable().
80462   ** The second call, to obtain permission to create the table, is made now.
80463   */
80464   if( pTable->azModuleArg ){
80465     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
80466             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
80467   }
80468 #endif
80469 }
80470
80471 /*
80472 ** This routine takes the module argument that has been accumulating
80473 ** in pParse->zArg[] and appends it to the list of arguments on the
80474 ** virtual table currently under construction in pParse->pTable.
80475 */
80476 static void addArgumentToVtab(Parse *pParse){
80477   if( pParse->sArg.z && pParse->pNewTable ){
80478     const char *z = (const char*)pParse->sArg.z;
80479     int n = pParse->sArg.n;
80480     sqlite3 *db = pParse->db;
80481     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
80482   }
80483 }
80484
80485 /*
80486 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
80487 ** has been completely parsed.
80488 */
80489 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
80490   Table *pTab;        /* The table being constructed */
80491   sqlite3 *db;        /* The database connection */
80492   char *zModule;      /* The module name of the table: USING modulename */
80493   Module *pMod = 0;
80494
80495   addArgumentToVtab(pParse);
80496   pParse->sArg.z = 0;
80497
80498   /* Lookup the module name. */
80499   pTab = pParse->pNewTable;
80500   if( pTab==0 ) return;
80501   db = pParse->db;
80502   if( pTab->nModuleArg<1 ) return;
80503   zModule = pTab->azModuleArg[0];
80504   pMod = (Module*)sqlite3HashFind(&db->aModule, zModule,
80505                                   sqlite3Strlen30(zModule));
80506   pTab->pMod = pMod;
80507   
80508   /* If the CREATE VIRTUAL TABLE statement is being entered for the
80509   ** first time (in other words if the virtual table is actually being
80510   ** created now instead of just being read out of sqlite_master) then
80511   ** do additional initialization work and store the statement text
80512   ** in the sqlite_master table.
80513   */
80514   if( !db->init.busy ){
80515     char *zStmt;
80516     char *zWhere;
80517     int iDb;
80518     Vdbe *v;
80519
80520     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
80521     if( pEnd ){
80522       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
80523     }
80524     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
80525
80526     /* A slot for the record has already been allocated in the 
80527     ** SQLITE_MASTER table.  We just need to update that slot with all
80528     ** the information we've collected.  
80529     **
80530     ** The VM register number pParse->regRowid holds the rowid of an
80531     ** entry in the sqlite_master table tht was created for this vtab
80532     ** by sqlite3StartTable().
80533     */
80534     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80535     sqlite3NestedParse(pParse,
80536       "UPDATE %Q.%s "
80537          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
80538        "WHERE rowid=#%d",
80539       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
80540       pTab->zName,
80541       pTab->zName,
80542       zStmt,
80543       pParse->regRowid
80544     );
80545     sqlite3DbFree(db, zStmt);
80546     v = sqlite3GetVdbe(pParse);
80547     sqlite3ChangeCookie(pParse, iDb);
80548
80549     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
80550     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
80551     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
80552     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
80553                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
80554   }
80555
80556   /* If we are rereading the sqlite_master table create the in-memory
80557   ** record of the table. If the module has already been registered,
80558   ** also call the xConnect method here.
80559   */
80560   else {
80561     Table *pOld;
80562     Schema *pSchema = pTab->pSchema;
80563     const char *zName = pTab->zName;
80564     int nName = sqlite3Strlen30(zName) + 1;
80565     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
80566     if( pOld ){
80567       db->mallocFailed = 1;
80568       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
80569       return;
80570     }
80571     pSchema->db = pParse->db;
80572     pParse->pNewTable = 0;
80573   }
80574 }
80575
80576 /*
80577 ** The parser calls this routine when it sees the first token
80578 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
80579 */
80580 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
80581   addArgumentToVtab(pParse);
80582   pParse->sArg.z = 0;
80583   pParse->sArg.n = 0;
80584 }
80585
80586 /*
80587 ** The parser calls this routine for each token after the first token
80588 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
80589 */
80590 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
80591   Token *pArg = &pParse->sArg;
80592   if( pArg->z==0 ){
80593     pArg->z = p->z;
80594     pArg->n = p->n;
80595   }else{
80596     assert(pArg->z < p->z);
80597     pArg->n = (int)(&p->z[p->n] - pArg->z);
80598   }
80599 }
80600
80601 /*
80602 ** Invoke a virtual table constructor (either xCreate or xConnect). The
80603 ** pointer to the function to invoke is passed as the fourth parameter
80604 ** to this procedure.
80605 */
80606 static int vtabCallConstructor(
80607   sqlite3 *db, 
80608   Table *pTab,
80609   Module *pMod,
80610   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
80611   char **pzErr
80612 ){
80613   int rc;
80614   int rc2;
80615   sqlite3_vtab *pVtab = 0;
80616   const char *const*azArg = (const char *const*)pTab->azModuleArg;
80617   int nArg = pTab->nModuleArg;
80618   char *zErr = 0;
80619   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
80620
80621   if( !zModuleName ){
80622     return SQLITE_NOMEM;
80623   }
80624
80625   assert( !db->pVTab );
80626   assert( xConstruct );
80627
80628   db->pVTab = pTab;
80629   rc = sqlite3SafetyOff(db);
80630   assert( rc==SQLITE_OK );
80631   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVtab, &zErr);
80632   rc2 = sqlite3SafetyOn(db);
80633   if( rc==SQLITE_OK && pVtab ){
80634     pVtab->pModule = pMod->pModule;
80635     pVtab->nRef = 1;
80636     pTab->pVtab = pVtab;
80637   }
80638
80639   if( SQLITE_OK!=rc ){
80640     if( zErr==0 ){
80641       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
80642     }else {
80643       *pzErr = sqlite3MPrintf(db, "%s", zErr);
80644       sqlite3DbFree(db, zErr);
80645     }
80646   }else if( db->pVTab ){
80647     const char *zFormat = "vtable constructor did not declare schema: %s";
80648     *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
80649     rc = SQLITE_ERROR;
80650   } 
80651   if( rc==SQLITE_OK ){
80652     rc = rc2;
80653   }
80654   db->pVTab = 0;
80655   sqlite3DbFree(db, zModuleName);
80656
80657   /* If everything went according to plan, loop through the columns
80658   ** of the table to see if any of them contain the token "hidden".
80659   ** If so, set the Column.isHidden flag and remove the token from
80660   ** the type string.
80661   */
80662   if( rc==SQLITE_OK ){
80663     int iCol;
80664     for(iCol=0; iCol<pTab->nCol; iCol++){
80665       char *zType = pTab->aCol[iCol].zType;
80666       int nType;
80667       int i = 0;
80668       if( !zType ) continue;
80669       nType = sqlite3Strlen30(zType);
80670       if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
80671         for(i=0; i<nType; i++){
80672           if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
80673            && (zType[i+7]=='\0' || zType[i+7]==' ')
80674           ){
80675             i++;
80676             break;
80677           }
80678         }
80679       }
80680       if( i<nType ){
80681         int j;
80682         int nDel = 6 + (zType[i+6] ? 1 : 0);
80683         for(j=i; (j+nDel)<=nType; j++){
80684           zType[j] = zType[j+nDel];
80685         }
80686         if( zType[i]=='\0' && i>0 ){
80687           assert(zType[i-1]==' ');
80688           zType[i-1] = '\0';
80689         }
80690         pTab->aCol[iCol].isHidden = 1;
80691       }
80692     }
80693   }
80694   return rc;
80695 }
80696
80697 /*
80698 ** This function is invoked by the parser to call the xConnect() method
80699 ** of the virtual table pTab. If an error occurs, an error code is returned 
80700 ** and an error left in pParse.
80701 **
80702 ** This call is a no-op if table pTab is not a virtual table.
80703 */
80704 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
80705   Module *pMod;
80706   int rc = SQLITE_OK;
80707
80708   if( !pTab || (pTab->tabFlags & TF_Virtual)==0 || pTab->pVtab ){
80709     return SQLITE_OK;
80710   }
80711
80712   pMod = pTab->pMod;
80713   if( !pMod ){
80714     const char *zModule = pTab->azModuleArg[0];
80715     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
80716     rc = SQLITE_ERROR;
80717   } else {
80718     char *zErr = 0;
80719     sqlite3 *db = pParse->db;
80720     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
80721     if( rc!=SQLITE_OK ){
80722       sqlite3ErrorMsg(pParse, "%s", zErr);
80723     }
80724     sqlite3DbFree(db, zErr);
80725   }
80726
80727   return rc;
80728 }
80729
80730 /*
80731 ** Add the virtual table pVtab to the array sqlite3.aVTrans[].
80732 */
80733 static int addToVTrans(sqlite3 *db, sqlite3_vtab *pVtab){
80734   const int ARRAY_INCR = 5;
80735
80736   /* Grow the sqlite3.aVTrans array if required */
80737   if( (db->nVTrans%ARRAY_INCR)==0 ){
80738     sqlite3_vtab **aVTrans;
80739     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
80740     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
80741     if( !aVTrans ){
80742       return SQLITE_NOMEM;
80743     }
80744     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
80745     db->aVTrans = aVTrans;
80746   }
80747
80748   /* Add pVtab to the end of sqlite3.aVTrans */
80749   db->aVTrans[db->nVTrans++] = pVtab;
80750   sqlite3VtabLock(pVtab);
80751   return SQLITE_OK;
80752 }
80753
80754 /*
80755 ** This function is invoked by the vdbe to call the xCreate method
80756 ** of the virtual table named zTab in database iDb. 
80757 **
80758 ** If an error occurs, *pzErr is set to point an an English language
80759 ** description of the error and an SQLITE_XXX error code is returned.
80760 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
80761 */
80762 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
80763   int rc = SQLITE_OK;
80764   Table *pTab;
80765   Module *pMod;
80766   const char *zModule;
80767
80768   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
80769   assert(pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVtab);
80770   pMod = pTab->pMod;
80771   zModule = pTab->azModuleArg[0];
80772
80773   /* If the module has been registered and includes a Create method, 
80774   ** invoke it now. If the module has not been registered, return an 
80775   ** error. Otherwise, do nothing.
80776   */
80777   if( !pMod ){
80778     *pzErr = sqlite3MPrintf(db, "no such module: %s", zModule);
80779     rc = SQLITE_ERROR;
80780   }else{
80781     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
80782   }
80783
80784   if( rc==SQLITE_OK && pTab->pVtab ){
80785       rc = addToVTrans(db, pTab->pVtab);
80786   }
80787
80788   return rc;
80789 }
80790
80791 /*
80792 ** This function is used to set the schema of a virtual table.  It is only
80793 ** valid to call this function from within the xCreate() or xConnect() of a
80794 ** virtual table module.
80795 */
80796 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
80797   Parse sParse;
80798
80799   int rc = SQLITE_OK;
80800   Table *pTab;
80801   char *zErr = 0;
80802
80803   sqlite3_mutex_enter(db->mutex);
80804   pTab = db->pVTab;
80805   if( !pTab ){
80806     sqlite3Error(db, SQLITE_MISUSE, 0);
80807     sqlite3_mutex_leave(db->mutex);
80808     return SQLITE_MISUSE;
80809   }
80810   assert((pTab->tabFlags & TF_Virtual)!=0 && pTab->nCol==0 && pTab->aCol==0);
80811
80812   memset(&sParse, 0, sizeof(Parse));
80813   sParse.declareVtab = 1;
80814   sParse.db = db;
80815
80816   if( 
80817       SQLITE_OK == sqlite3RunParser(&sParse, zCreateTable, &zErr) && 
80818       sParse.pNewTable && 
80819       !sParse.pNewTable->pSelect && 
80820       (sParse.pNewTable->tabFlags & TF_Virtual)==0
80821   ){
80822     pTab->aCol = sParse.pNewTable->aCol;
80823     pTab->nCol = sParse.pNewTable->nCol;
80824     sParse.pNewTable->nCol = 0;
80825     sParse.pNewTable->aCol = 0;
80826     db->pVTab = 0;
80827   } else {
80828     sqlite3Error(db, SQLITE_ERROR, zErr);
80829     sqlite3DbFree(db, zErr);
80830     rc = SQLITE_ERROR;
80831   }
80832   sParse.declareVtab = 0;
80833
80834   sqlite3_finalize((sqlite3_stmt*)sParse.pVdbe);
80835   sqlite3DeleteTable(sParse.pNewTable);
80836   sParse.pNewTable = 0;
80837
80838   assert( (rc&0xff)==rc );
80839   rc = sqlite3ApiExit(db, rc);
80840   sqlite3_mutex_leave(db->mutex);
80841   return rc;
80842 }
80843
80844 /*
80845 ** This function is invoked by the vdbe to call the xDestroy method
80846 ** of the virtual table named zTab in database iDb. This occurs
80847 ** when a DROP TABLE is mentioned.
80848 **
80849 ** This call is a no-op if zTab is not a virtual table.
80850 */
80851 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
80852 {
80853   int rc = SQLITE_OK;
80854   Table *pTab;
80855
80856   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
80857   assert(pTab);
80858   if( pTab->pVtab ){
80859     int (*xDestroy)(sqlite3_vtab *pVTab) = pTab->pMod->pModule->xDestroy;
80860     rc = sqlite3SafetyOff(db);
80861     assert( rc==SQLITE_OK );
80862     if( xDestroy ){
80863       rc = xDestroy(pTab->pVtab);
80864     }
80865     (void)sqlite3SafetyOn(db);
80866     if( rc==SQLITE_OK ){
80867       int i;
80868       for(i=0; i<db->nVTrans; i++){
80869         if( db->aVTrans[i]==pTab->pVtab ){
80870           db->aVTrans[i] = db->aVTrans[--db->nVTrans];
80871           break;
80872         }
80873       }
80874       pTab->pVtab = 0;
80875     }
80876   }
80877
80878   return rc;
80879 }
80880
80881 /*
80882 ** This function invokes either the xRollback or xCommit method
80883 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
80884 ** called is identified by the second argument, "offset", which is
80885 ** the offset of the method to call in the sqlite3_module structure.
80886 **
80887 ** The array is cleared after invoking the callbacks. 
80888 */
80889 static void callFinaliser(sqlite3 *db, int offset){
80890   int i;
80891   if( db->aVTrans ){
80892     for(i=0; i<db->nVTrans && db->aVTrans[i]; i++){
80893       sqlite3_vtab *pVtab = db->aVTrans[i];
80894       int (*x)(sqlite3_vtab *);
80895       x = *(int (**)(sqlite3_vtab *))((char *)pVtab->pModule + offset);
80896       if( x ) x(pVtab);
80897       sqlite3VtabUnlock(db, pVtab);
80898     }
80899     sqlite3DbFree(db, db->aVTrans);
80900     db->nVTrans = 0;
80901     db->aVTrans = 0;
80902   }
80903 }
80904
80905 /*
80906 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
80907 ** array. Return the error code for the first error that occurs, or
80908 ** SQLITE_OK if all xSync operations are successful.
80909 **
80910 ** Set *pzErrmsg to point to a buffer that should be released using 
80911 ** sqlite3DbFree() containing an error message, if one is available.
80912 */
80913 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
80914   int i;
80915   int rc = SQLITE_OK;
80916   int rcsafety;
80917   sqlite3_vtab **aVTrans = db->aVTrans;
80918
80919   rc = sqlite3SafetyOff(db);
80920   db->aVTrans = 0;
80921   for(i=0; rc==SQLITE_OK && i<db->nVTrans && aVTrans[i]; i++){
80922     sqlite3_vtab *pVtab = aVTrans[i];
80923     int (*x)(sqlite3_vtab *);
80924     x = pVtab->pModule->xSync;
80925     if( x ){
80926       rc = x(pVtab);
80927       sqlite3DbFree(db, *pzErrmsg);
80928       *pzErrmsg = pVtab->zErrMsg;
80929       pVtab->zErrMsg = 0;
80930     }
80931   }
80932   db->aVTrans = aVTrans;
80933   rcsafety = sqlite3SafetyOn(db);
80934
80935   if( rc==SQLITE_OK ){
80936     rc = rcsafety;
80937   }
80938   return rc;
80939 }
80940
80941 /*
80942 ** Invoke the xRollback method of all virtual tables in the 
80943 ** sqlite3.aVTrans array. Then clear the array itself.
80944 */
80945 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
80946   callFinaliser(db, offsetof(sqlite3_module,xRollback));
80947   return SQLITE_OK;
80948 }
80949
80950 /*
80951 ** Invoke the xCommit method of all virtual tables in the 
80952 ** sqlite3.aVTrans array. Then clear the array itself.
80953 */
80954 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
80955   callFinaliser(db, offsetof(sqlite3_module,xCommit));
80956   return SQLITE_OK;
80957 }
80958
80959 /*
80960 ** If the virtual table pVtab supports the transaction interface
80961 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
80962 ** not currently open, invoke the xBegin method now.
80963 **
80964 ** If the xBegin call is successful, place the sqlite3_vtab pointer
80965 ** in the sqlite3.aVTrans array.
80966 */
80967 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
80968   int rc = SQLITE_OK;
80969   const sqlite3_module *pModule;
80970
80971   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
80972   ** than zero, then this function is being called from within a
80973   ** virtual module xSync() callback. It is illegal to write to 
80974   ** virtual module tables in this case, so return SQLITE_LOCKED.
80975   */
80976   if( sqlite3VtabInSync(db) ){
80977     return SQLITE_LOCKED;
80978   }
80979   if( !pVtab ){
80980     return SQLITE_OK;
80981   } 
80982   pModule = pVtab->pModule;
80983
80984   if( pModule->xBegin ){
80985     int i;
80986
80987
80988     /* If pVtab is already in the aVTrans array, return early */
80989     for(i=0; (i<db->nVTrans) && 0!=db->aVTrans[i]; i++){
80990       if( db->aVTrans[i]==pVtab ){
80991         return SQLITE_OK;
80992       }
80993     }
80994
80995     /* Invoke the xBegin method */
80996     rc = pModule->xBegin(pVtab);
80997     if( rc==SQLITE_OK ){
80998       rc = addToVTrans(db, pVtab);
80999     }
81000   }
81001   return rc;
81002 }
81003
81004 /*
81005 ** The first parameter (pDef) is a function implementation.  The
81006 ** second parameter (pExpr) is the first argument to this function.
81007 ** If pExpr is a column in a virtual table, then let the virtual
81008 ** table implementation have an opportunity to overload the function.
81009 **
81010 ** This routine is used to allow virtual table implementations to
81011 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
81012 **
81013 ** Return either the pDef argument (indicating no change) or a 
81014 ** new FuncDef structure that is marked as ephemeral using the
81015 ** SQLITE_FUNC_EPHEM flag.
81016 */
81017 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
81018   sqlite3 *db,    /* Database connection for reporting malloc problems */
81019   FuncDef *pDef,  /* Function to possibly overload */
81020   int nArg,       /* Number of arguments to the function */
81021   Expr *pExpr     /* First argument to the function */
81022 ){
81023   Table *pTab;
81024   sqlite3_vtab *pVtab;
81025   sqlite3_module *pMod;
81026   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
81027   void *pArg = 0;
81028   FuncDef *pNew;
81029   int rc = 0;
81030   char *zLowerName;
81031   unsigned char *z;
81032
81033
81034   /* Check to see the left operand is a column in a virtual table */
81035   if( pExpr==0 ) return pDef;
81036   if( pExpr->op!=TK_COLUMN ) return pDef;
81037   pTab = pExpr->pTab;
81038   if( pTab==0 ) return pDef;
81039   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
81040   pVtab = pTab->pVtab;
81041   assert( pVtab!=0 );
81042   assert( pVtab->pModule!=0 );
81043   pMod = (sqlite3_module *)pVtab->pModule;
81044   if( pMod->xFindFunction==0 ) return pDef;
81045  
81046   /* Call the xFindFunction method on the virtual table implementation
81047   ** to see if the implementation wants to overload this function 
81048   */
81049   zLowerName = sqlite3DbStrDup(db, pDef->zName);
81050   if( zLowerName ){
81051     for(z=(unsigned char*)zLowerName; *z; z++){
81052       *z = sqlite3UpperToLower[*z];
81053     }
81054     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
81055     sqlite3DbFree(db, zLowerName);
81056     if( pVtab->zErrMsg ){
81057       sqlite3Error(db, rc, "%s", pVtab->zErrMsg);
81058       sqlite3DbFree(db, pVtab->zErrMsg);
81059       pVtab->zErrMsg = 0;
81060     }
81061   }
81062   if( rc==0 ){
81063     return pDef;
81064   }
81065
81066   /* Create a new ephemeral function definition for the overloaded
81067   ** function */
81068   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
81069                              + sqlite3Strlen30(pDef->zName) );
81070   if( pNew==0 ){
81071     return pDef;
81072   }
81073   *pNew = *pDef;
81074   pNew->zName = (char *)&pNew[1];
81075   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
81076   pNew->xFunc = xFunc;
81077   pNew->pUserData = pArg;
81078   pNew->flags |= SQLITE_FUNC_EPHEM;
81079   return pNew;
81080 }
81081
81082 /*
81083 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
81084 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
81085 ** array if it is missing.  If pTab is already in the array, this routine
81086 ** is a no-op.
81087 */
81088 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
81089   int i, n;
81090   assert( IsVirtual(pTab) );
81091   for(i=0; i<pParse->nVtabLock; i++){
81092     if( pTab==pParse->apVtabLock[i] ) return;
81093   }
81094   n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]);
81095   pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n);
81096   if( pParse->apVtabLock ){
81097     pParse->apVtabLock[pParse->nVtabLock++] = pTab;
81098   }else{
81099     pParse->db->mallocFailed = 1;
81100   }
81101 }
81102
81103 #endif /* SQLITE_OMIT_VIRTUALTABLE */
81104
81105 /************** End of vtab.c ************************************************/
81106 /************** Begin file where.c *******************************************/
81107 /*
81108 ** 2001 September 15
81109 **
81110 ** The author disclaims copyright to this source code.  In place of
81111 ** a legal notice, here is a blessing:
81112 **
81113 **    May you do good and not evil.
81114 **    May you find forgiveness for yourself and forgive others.
81115 **    May you share freely, never taking more than you give.
81116 **
81117 *************************************************************************
81118 ** This module contains C code that generates VDBE code used to process
81119 ** the WHERE clause of SQL statements.  This module is responsible for
81120 ** generating the code that loops through a table looking for applicable
81121 ** rows.  Indices are selected and used to speed the search when doing
81122 ** so is applicable.  Because this module is responsible for selecting
81123 ** indices, you might also think of this module as the "query optimizer".
81124 **
81125 ** $Id: where.c,v 1.368 2009/02/04 03:59:25 shane Exp $
81126 */
81127
81128 /*
81129 ** Trace output macros
81130 */
81131 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
81132 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
81133 #endif
81134 #if 0
81135 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
81136 #else
81137 # define WHERETRACE(X)
81138 #endif
81139
81140 /* Forward reference
81141 */
81142 typedef struct WhereClause WhereClause;
81143 typedef struct WhereMaskSet WhereMaskSet;
81144 typedef struct WhereOrInfo WhereOrInfo;
81145 typedef struct WhereAndInfo WhereAndInfo;
81146 typedef struct WhereCost WhereCost;
81147
81148 /*
81149 ** The query generator uses an array of instances of this structure to
81150 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
81151 ** clause subexpression is separated from the others by AND operators.
81152 ** (Note: the same data structure is also reused to hold a group of terms
81153 ** separated by OR operators.  But at the top-level, everything is AND
81154 ** separated.)
81155 **
81156 ** All WhereTerms are collected into a single WhereClause structure.  
81157 ** The following identity holds:
81158 **
81159 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
81160 **
81161 ** When a term is of the form:
81162 **
81163 **              X <op> <expr>
81164 **
81165 ** where X is a column name and <op> is one of certain operators,
81166 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
81167 ** cursor number and column number for X.  WhereTerm.eOperator records
81168 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
81169 ** use of a bitmask encoding for the operator allows us to search
81170 ** quickly for terms that match any of several different operators.
81171 **
81172 ** A WhereTerm might also be two or more subterms connected by OR:
81173 **
81174 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
81175 **
81176 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
81177 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
81178 ** is collected about the
81179 **
81180 ** If a term in the WHERE clause does not match either of the two previous
81181 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
81182 ** to the original subexpression content and wtFlags is set up appropriately
81183 ** but no other fields in the WhereTerm object are meaningful.
81184 **
81185 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
81186 ** but they do so indirectly.  A single WhereMaskSet structure translates
81187 ** cursor number into bits and the translated bit is stored in the prereq
81188 ** fields.  The translation is used in order to maximize the number of
81189 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
81190 ** spread out over the non-negative integers.  For example, the cursor
81191 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
81192 ** translates these sparse cursor numbers into consecutive integers
81193 ** beginning with 0 in order to make the best possible use of the available
81194 ** bits in the Bitmask.  So, in the example above, the cursor numbers
81195 ** would be mapped into integers 0 through 7.
81196 **
81197 ** The number of terms in a join is limited by the number of bits
81198 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
81199 ** is only able to process joins with 64 or fewer tables.
81200 */
81201 typedef struct WhereTerm WhereTerm;
81202 struct WhereTerm {
81203   Expr *pExpr;            /* Pointer to the subexpression that is this term */
81204   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
81205   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
81206   union {
81207     int leftColumn;         /* Column number of X in "X <op> <expr>" */
81208     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
81209     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
81210   } u;
81211   u16 eOperator;          /* A WO_xx value describing <op> */
81212   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
81213   u8 nChild;              /* Number of children that must disable us */
81214   WhereClause *pWC;       /* The clause this term is part of */
81215   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
81216   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
81217 };
81218
81219 /*
81220 ** Allowed values of WhereTerm.wtFlags
81221 */
81222 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
81223 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
81224 #define TERM_CODED      0x04   /* This term is already coded */
81225 #define TERM_COPIED     0x08   /* Has a child */
81226 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
81227 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
81228 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
81229
81230 /*
81231 ** An instance of the following structure holds all information about a
81232 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
81233 */
81234 struct WhereClause {
81235   Parse *pParse;           /* The parser context */
81236   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
81237   u8 op;                   /* Split operator.  TK_AND or TK_OR */
81238   int nTerm;               /* Number of terms */
81239   int nSlot;               /* Number of entries in a[] */
81240   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
81241   WhereTerm aStatic[4];    /* Initial static space for a[] */
81242 };
81243
81244 /*
81245 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
81246 ** a dynamically allocated instance of the following structure.
81247 */
81248 struct WhereOrInfo {
81249   WhereClause wc;          /* Decomposition into subterms */
81250   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
81251 };
81252
81253 /*
81254 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
81255 ** a dynamically allocated instance of the following structure.
81256 */
81257 struct WhereAndInfo {
81258   WhereClause wc;          /* The subexpression broken out */
81259 };
81260
81261 /*
81262 ** An instance of the following structure keeps track of a mapping
81263 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
81264 **
81265 ** The VDBE cursor numbers are small integers contained in 
81266 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
81267 ** clause, the cursor numbers might not begin with 0 and they might
81268 ** contain gaps in the numbering sequence.  But we want to make maximum
81269 ** use of the bits in our bitmasks.  This structure provides a mapping
81270 ** from the sparse cursor numbers into consecutive integers beginning
81271 ** with 0.
81272 **
81273 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
81274 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
81275 **
81276 ** For example, if the WHERE clause expression used these VDBE
81277 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
81278 ** would map those cursor numbers into bits 0 through 5.
81279 **
81280 ** Note that the mapping is not necessarily ordered.  In the example
81281 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
81282 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
81283 ** does not really matter.  What is important is that sparse cursor
81284 ** numbers all get mapped into bit numbers that begin with 0 and contain
81285 ** no gaps.
81286 */
81287 struct WhereMaskSet {
81288   int n;                        /* Number of assigned cursor values */
81289   int ix[BMS];                  /* Cursor assigned to each bit */
81290 };
81291
81292 /*
81293 ** A WhereCost object records a lookup strategy and the estimated
81294 ** cost of pursuing that strategy.
81295 */
81296 struct WhereCost {
81297   WherePlan plan;    /* The lookup strategy */
81298   double rCost;      /* Overall cost of pursuing this search strategy */
81299   double nRow;       /* Estimated number of output rows */
81300 };
81301
81302 /*
81303 ** Bitmasks for the operators that indices are able to exploit.  An
81304 ** OR-ed combination of these values can be used when searching for
81305 ** terms in the where clause.
81306 */
81307 #define WO_IN     0x001
81308 #define WO_EQ     0x002
81309 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
81310 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
81311 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
81312 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
81313 #define WO_MATCH  0x040
81314 #define WO_ISNULL 0x080
81315 #define WO_OR     0x100       /* Two or more OR-connected terms */
81316 #define WO_AND    0x200       /* Two or more AND-connected terms */
81317
81318 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
81319 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
81320
81321 /*
81322 ** Value for wsFlags returned by bestIndex() and stored in
81323 ** WhereLevel.wsFlags.  These flags determine which search
81324 ** strategies are appropriate.
81325 **
81326 ** The least significant 12 bits is reserved as a mask for WO_ values above.
81327 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
81328 ** But if the table is the right table of a left join, WhereLevel.wsFlags
81329 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
81330 ** the "op" parameter to findTerm when we are resolving equality constraints.
81331 ** ISNULL constraints will then not be used on the right table of a left
81332 ** join.  Tickets #2177 and #2189.
81333 */
81334 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
81335 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
81336 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) */
81337 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
81338 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
81339 #define WHERE_INDEXED      0x00070000  /* Anything that uses an index */
81340 #define WHERE_IN_ABLE      0x00071000  /* Able to support an IN operator */
81341 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
81342 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
81343 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
81344 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
81345 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
81346 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
81347 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
81348 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
81349
81350 /*
81351 ** Initialize a preallocated WhereClause structure.
81352 */
81353 static void whereClauseInit(
81354   WhereClause *pWC,        /* The WhereClause to be initialized */
81355   Parse *pParse,           /* The parsing context */
81356   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
81357 ){
81358   pWC->pParse = pParse;
81359   pWC->pMaskSet = pMaskSet;
81360   pWC->nTerm = 0;
81361   pWC->nSlot = ArraySize(pWC->aStatic);
81362   pWC->a = pWC->aStatic;
81363 }
81364
81365 /* Forward reference */
81366 static void whereClauseClear(WhereClause*);
81367
81368 /*
81369 ** Deallocate all memory associated with a WhereOrInfo object.
81370 */
81371 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
81372   whereClauseClear(&p->wc);
81373   sqlite3DbFree(db, p);
81374 }
81375
81376 /*
81377 ** Deallocate all memory associated with a WhereAndInfo object.
81378 */
81379 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
81380   whereClauseClear(&p->wc);
81381   sqlite3DbFree(db, p);
81382 }
81383
81384 /*
81385 ** Deallocate a WhereClause structure.  The WhereClause structure
81386 ** itself is not freed.  This routine is the inverse of whereClauseInit().
81387 */
81388 static void whereClauseClear(WhereClause *pWC){
81389   int i;
81390   WhereTerm *a;
81391   sqlite3 *db = pWC->pParse->db;
81392   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
81393     if( a->wtFlags & TERM_DYNAMIC ){
81394       sqlite3ExprDelete(db, a->pExpr);
81395     }
81396     if( a->wtFlags & TERM_ORINFO ){
81397       whereOrInfoDelete(db, a->u.pOrInfo);
81398     }else if( a->wtFlags & TERM_ANDINFO ){
81399       whereAndInfoDelete(db, a->u.pAndInfo);
81400     }
81401   }
81402   if( pWC->a!=pWC->aStatic ){
81403     sqlite3DbFree(db, pWC->a);
81404   }
81405 }
81406
81407 /*
81408 ** Add a single new WhereTerm entry to the WhereClause object pWC.
81409 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
81410 ** The index in pWC->a[] of the new WhereTerm is returned on success.
81411 ** 0 is returned if the new WhereTerm could not be added due to a memory
81412 ** allocation error.  The memory allocation failure will be recorded in
81413 ** the db->mallocFailed flag so that higher-level functions can detect it.
81414 **
81415 ** This routine will increase the size of the pWC->a[] array as necessary.
81416 **
81417 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
81418 ** for freeing the expression p is assumed by the WhereClause object pWC.
81419 ** This is true even if this routine fails to allocate a new WhereTerm.
81420 **
81421 ** WARNING:  This routine might reallocate the space used to store
81422 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
81423 ** calling this routine.  Such pointers may be reinitialized by referencing
81424 ** the pWC->a[] array.
81425 */
81426 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
81427   WhereTerm *pTerm;
81428   int idx;
81429   if( pWC->nTerm>=pWC->nSlot ){
81430     WhereTerm *pOld = pWC->a;
81431     sqlite3 *db = pWC->pParse->db;
81432     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
81433     if( pWC->a==0 ){
81434       if( wtFlags & TERM_DYNAMIC ){
81435         sqlite3ExprDelete(db, p);
81436       }
81437       pWC->a = pOld;
81438       return 0;
81439     }
81440     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
81441     if( pOld!=pWC->aStatic ){
81442       sqlite3DbFree(db, pOld);
81443     }
81444     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
81445   }
81446   pTerm = &pWC->a[idx = pWC->nTerm++];
81447   pTerm->pExpr = p;
81448   pTerm->wtFlags = wtFlags;
81449   pTerm->pWC = pWC;
81450   pTerm->iParent = -1;
81451   return idx;
81452 }
81453
81454 /*
81455 ** This routine identifies subexpressions in the WHERE clause where
81456 ** each subexpression is separated by the AND operator or some other
81457 ** operator specified in the op parameter.  The WhereClause structure
81458 ** is filled with pointers to subexpressions.  For example:
81459 **
81460 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
81461 **           \________/     \_______________/     \________________/
81462 **            slot[0]            slot[1]               slot[2]
81463 **
81464 ** The original WHERE clause in pExpr is unaltered.  All this routine
81465 ** does is make slot[] entries point to substructure within pExpr.
81466 **
81467 ** In the previous sentence and in the diagram, "slot[]" refers to
81468 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
81469 ** all terms of the WHERE clause.
81470 */
81471 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
81472   pWC->op = (u8)op;
81473   if( pExpr==0 ) return;
81474   if( pExpr->op!=op ){
81475     whereClauseInsert(pWC, pExpr, 0);
81476   }else{
81477     whereSplit(pWC, pExpr->pLeft, op);
81478     whereSplit(pWC, pExpr->pRight, op);
81479   }
81480 }
81481
81482 /*
81483 ** Initialize an expression mask set
81484 */
81485 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
81486
81487 /*
81488 ** Return the bitmask for the given cursor number.  Return 0 if
81489 ** iCursor is not in the set.
81490 */
81491 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
81492   int i;
81493   for(i=0; i<pMaskSet->n; i++){
81494     if( pMaskSet->ix[i]==iCursor ){
81495       return ((Bitmask)1)<<i;
81496     }
81497   }
81498   return 0;
81499 }
81500
81501 /*
81502 ** Create a new mask for cursor iCursor.
81503 **
81504 ** There is one cursor per table in the FROM clause.  The number of
81505 ** tables in the FROM clause is limited by a test early in the
81506 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
81507 ** array will never overflow.
81508 */
81509 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
81510   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
81511   pMaskSet->ix[pMaskSet->n++] = iCursor;
81512 }
81513
81514 /*
81515 ** This routine walks (recursively) an expression tree and generates
81516 ** a bitmask indicating which tables are used in that expression
81517 ** tree.
81518 **
81519 ** In order for this routine to work, the calling function must have
81520 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
81521 ** the header comment on that routine for additional information.
81522 ** The sqlite3ResolveExprNames() routines looks for column names and
81523 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
81524 ** the VDBE cursor number of the table.  This routine just has to
81525 ** translate the cursor numbers into bitmask values and OR all
81526 ** the bitmasks together.
81527 */
81528 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
81529 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
81530 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
81531   Bitmask mask = 0;
81532   if( p==0 ) return 0;
81533   if( p->op==TK_COLUMN ){
81534     mask = getMask(pMaskSet, p->iTable);
81535     return mask;
81536   }
81537   mask = exprTableUsage(pMaskSet, p->pRight);
81538   mask |= exprTableUsage(pMaskSet, p->pLeft);
81539   mask |= exprListTableUsage(pMaskSet, p->pList);
81540   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
81541   return mask;
81542 }
81543 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
81544   int i;
81545   Bitmask mask = 0;
81546   if( pList ){
81547     for(i=0; i<pList->nExpr; i++){
81548       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
81549     }
81550   }
81551   return mask;
81552 }
81553 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
81554   Bitmask mask = 0;
81555   while( pS ){
81556     mask |= exprListTableUsage(pMaskSet, pS->pEList);
81557     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
81558     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
81559     mask |= exprTableUsage(pMaskSet, pS->pWhere);
81560     mask |= exprTableUsage(pMaskSet, pS->pHaving);
81561     pS = pS->pPrior;
81562   }
81563   return mask;
81564 }
81565
81566 /*
81567 ** Return TRUE if the given operator is one of the operators that is
81568 ** allowed for an indexable WHERE clause term.  The allowed operators are
81569 ** "=", "<", ">", "<=", ">=", and "IN".
81570 */
81571 static int allowedOp(int op){
81572   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
81573   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
81574   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
81575   assert( TK_GE==TK_EQ+4 );
81576   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
81577 }
81578
81579 /*
81580 ** Swap two objects of type TYPE.
81581 */
81582 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
81583
81584 /*
81585 ** Commute a comparison operator.  Expressions of the form "X op Y"
81586 ** are converted into "Y op X".
81587 **
81588 ** If a collation sequence is associated with either the left or right
81589 ** side of the comparison, it remains associated with the same side after
81590 ** the commutation. So "Y collate NOCASE op X" becomes 
81591 ** "X collate NOCASE op Y". This is because any collation sequence on
81592 ** the left hand side of a comparison overrides any collation sequence 
81593 ** attached to the right. For the same reason the EP_ExpCollate flag
81594 ** is not commuted.
81595 */
81596 static void exprCommute(Parse *pParse, Expr *pExpr){
81597   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
81598   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
81599   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
81600   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
81601   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
81602   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
81603   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
81604   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
81605   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
81606   if( pExpr->op>=TK_GT ){
81607     assert( TK_LT==TK_GT+2 );
81608     assert( TK_GE==TK_LE+2 );
81609     assert( TK_GT>TK_EQ );
81610     assert( TK_GT<TK_LE );
81611     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
81612     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
81613   }
81614 }
81615
81616 /*
81617 ** Translate from TK_xx operator to WO_xx bitmask.
81618 */
81619 static u16 operatorMask(int op){
81620   u16 c;
81621   assert( allowedOp(op) );
81622   if( op==TK_IN ){
81623     c = WO_IN;
81624   }else if( op==TK_ISNULL ){
81625     c = WO_ISNULL;
81626   }else{
81627     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
81628     c = (u16)(WO_EQ<<(op-TK_EQ));
81629   }
81630   assert( op!=TK_ISNULL || c==WO_ISNULL );
81631   assert( op!=TK_IN || c==WO_IN );
81632   assert( op!=TK_EQ || c==WO_EQ );
81633   assert( op!=TK_LT || c==WO_LT );
81634   assert( op!=TK_LE || c==WO_LE );
81635   assert( op!=TK_GT || c==WO_GT );
81636   assert( op!=TK_GE || c==WO_GE );
81637   return c;
81638 }
81639
81640 /*
81641 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
81642 ** where X is a reference to the iColumn of table iCur and <op> is one of
81643 ** the WO_xx operator codes specified by the op parameter.
81644 ** Return a pointer to the term.  Return 0 if not found.
81645 */
81646 static WhereTerm *findTerm(
81647   WhereClause *pWC,     /* The WHERE clause to be searched */
81648   int iCur,             /* Cursor number of LHS */
81649   int iColumn,          /* Column number of LHS */
81650   Bitmask notReady,     /* RHS must not overlap with this mask */
81651   u32 op,               /* Mask of WO_xx values describing operator */
81652   Index *pIdx           /* Must be compatible with this index, if not NULL */
81653 ){
81654   WhereTerm *pTerm;
81655   int k;
81656   assert( iCur>=0 );
81657   op &= WO_ALL;
81658   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
81659     if( pTerm->leftCursor==iCur
81660        && (pTerm->prereqRight & notReady)==0
81661        && pTerm->u.leftColumn==iColumn
81662        && (pTerm->eOperator & op)!=0
81663     ){
81664       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
81665         Expr *pX = pTerm->pExpr;
81666         CollSeq *pColl;
81667         char idxaff;
81668         int j;
81669         Parse *pParse = pWC->pParse;
81670
81671         idxaff = pIdx->pTable->aCol[iColumn].affinity;
81672         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
81673
81674         /* Figure out the collation sequence required from an index for
81675         ** it to be useful for optimising expression pX. Store this
81676         ** value in variable pColl.
81677         */
81678         assert(pX->pLeft);
81679         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
81680         assert(pColl || pParse->nErr);
81681
81682         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
81683           if( NEVER(j>=pIdx->nColumn) ) return 0;
81684         }
81685         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
81686       }
81687       return pTerm;
81688     }
81689   }
81690   return 0;
81691 }
81692
81693 /* Forward reference */
81694 static void exprAnalyze(SrcList*, WhereClause*, int);
81695
81696 /*
81697 ** Call exprAnalyze on all terms in a WHERE clause.  
81698 **
81699 **
81700 */
81701 static void exprAnalyzeAll(
81702   SrcList *pTabList,       /* the FROM clause */
81703   WhereClause *pWC         /* the WHERE clause to be analyzed */
81704 ){
81705   int i;
81706   for(i=pWC->nTerm-1; i>=0; i--){
81707     exprAnalyze(pTabList, pWC, i);
81708   }
81709 }
81710
81711 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
81712 /*
81713 ** Check to see if the given expression is a LIKE or GLOB operator that
81714 ** can be optimized using inequality constraints.  Return TRUE if it is
81715 ** so and false if not.
81716 **
81717 ** In order for the operator to be optimizible, the RHS must be a string
81718 ** literal that does not begin with a wildcard.  
81719 */
81720 static int isLikeOrGlob(
81721   Parse *pParse,    /* Parsing and code generating context */
81722   Expr *pExpr,      /* Test this expression */
81723   int *pnPattern,   /* Number of non-wildcard prefix characters */
81724   int *pisComplete, /* True if the only wildcard is % in the last character */
81725   int *pnoCase      /* True if uppercase is equivalent to lowercase */
81726 ){
81727   const char *z;             /* String on RHS of LIKE operator */
81728   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
81729   ExprList *pList;           /* List of operands to the LIKE operator */
81730   int c;                     /* One character in z[] */
81731   int cnt;                   /* Number of non-wildcard prefix characters */
81732   char wc[3];                /* Wildcard characters */
81733   CollSeq *pColl;            /* Collating sequence for LHS */
81734   sqlite3 *db = pParse->db;  /* Database connection */
81735
81736   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
81737     return 0;
81738   }
81739 #ifdef SQLITE_EBCDIC
81740   if( *pnoCase ) return 0;
81741 #endif
81742   pList = pExpr->pList;
81743   pRight = pList->a[0].pExpr;
81744   if( pRight->op!=TK_STRING ){
81745     return 0;
81746   }
81747   pLeft = pList->a[1].pExpr;
81748   if( pLeft->op!=TK_COLUMN ){
81749     return 0;
81750   }
81751   pColl = sqlite3ExprCollSeq(pParse, pLeft);
81752   assert( pColl!=0 || pLeft->iColumn==-1 );
81753   if( pColl==0 ){
81754     /* No collation is defined for the ROWID.  Use the default. */
81755     pColl = db->pDfltColl;
81756   }
81757   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
81758       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
81759     return 0;
81760   }
81761   sqlite3DequoteExpr(db, pRight);
81762   z = (char *)pRight->token.z;
81763   cnt = 0;
81764   if( z ){
81765     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
81766   }
81767   if( cnt==0 || 255==(u8)z[cnt-1] ){
81768     return 0;
81769   }
81770   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
81771   *pnPattern = cnt;
81772   return 1;
81773 }
81774 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
81775
81776
81777 #ifndef SQLITE_OMIT_VIRTUALTABLE
81778 /*
81779 ** Check to see if the given expression is of the form
81780 **
81781 **         column MATCH expr
81782 **
81783 ** If it is then return TRUE.  If not, return FALSE.
81784 */
81785 static int isMatchOfColumn(
81786   Expr *pExpr      /* Test this expression */
81787 ){
81788   ExprList *pList;
81789
81790   if( pExpr->op!=TK_FUNCTION ){
81791     return 0;
81792   }
81793   if( pExpr->token.n!=5 ||
81794        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
81795     return 0;
81796   }
81797   pList = pExpr->pList;
81798   if( pList->nExpr!=2 ){
81799     return 0;
81800   }
81801   if( pList->a[1].pExpr->op != TK_COLUMN ){
81802     return 0;
81803   }
81804   return 1;
81805 }
81806 #endif /* SQLITE_OMIT_VIRTUALTABLE */
81807
81808 /*
81809 ** If the pBase expression originated in the ON or USING clause of
81810 ** a join, then transfer the appropriate markings over to derived.
81811 */
81812 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
81813   pDerived->flags |= pBase->flags & EP_FromJoin;
81814   pDerived->iRightJoinTable = pBase->iRightJoinTable;
81815 }
81816
81817 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
81818 /*
81819 ** Analyze a term that consists of two or more OR-connected
81820 ** subterms.  So in:
81821 **
81822 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
81823 **                          ^^^^^^^^^^^^^^^^^^^^
81824 **
81825 ** This routine analyzes terms such as the middle term in the above example.
81826 ** A WhereOrTerm object is computed and attached to the term under
81827 ** analysis, regardless of the outcome of the analysis.  Hence:
81828 **
81829 **     WhereTerm.wtFlags   |=  TERM_ORINFO
81830 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
81831 **
81832 ** The term being analyzed must have two or more of OR-connected subterms.
81833 ** A single subterm might be a set of AND-connected sub-subterms.
81834 ** Examples of terms under analysis:
81835 **
81836 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
81837 **     (B)     x=expr1 OR expr2=x OR x=expr3
81838 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
81839 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
81840 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
81841 **
81842 ** CASE 1:
81843 **
81844 ** If all subterms are of the form T.C=expr for some single column of C
81845 ** a single table T (as shown in example B above) then create a new virtual
81846 ** term that is an equivalent IN expression.  In other words, if the term
81847 ** being analyzed is:
81848 **
81849 **      x = expr1  OR  expr2 = x  OR  x = expr3
81850 **
81851 ** then create a new virtual term like this:
81852 **
81853 **      x IN (expr1,expr2,expr3)
81854 **
81855 ** CASE 2:
81856 **
81857 ** If all subterms are indexable by a single table T, then set
81858 **
81859 **     WhereTerm.eOperator              =  WO_OR
81860 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
81861 **
81862 ** A subterm is "indexable" if it is of the form
81863 ** "T.C <op> <expr>" where C is any column of table T and 
81864 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
81865 ** A subterm is also indexable if it is an AND of two or more
81866 ** subsubterms at least one of which is indexable.  Indexable AND 
81867 ** subterms have their eOperator set to WO_AND and they have
81868 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
81869 **
81870 ** From another point of view, "indexable" means that the subterm could
81871 ** potentially be used with an index if an appropriate index exists.
81872 ** This analysis does not consider whether or not the index exists; that
81873 ** is something the bestIndex() routine will determine.  This analysis
81874 ** only looks at whether subterms appropriate for indexing exist.
81875 **
81876 ** All examples A through E above all satisfy case 2.  But if a term
81877 ** also statisfies case 1 (such as B) we know that the optimizer will
81878 ** always prefer case 1, so in that case we pretend that case 2 is not
81879 ** satisfied.
81880 **
81881 ** It might be the case that multiple tables are indexable.  For example,
81882 ** (E) above is indexable on tables P, Q, and R.
81883 **
81884 ** Terms that satisfy case 2 are candidates for lookup by using
81885 ** separate indices to find rowids for each subterm and composing
81886 ** the union of all rowids using a RowSet object.  This is similar
81887 ** to "bitmap indices" in other database engines.
81888 **
81889 ** OTHERWISE:
81890 **
81891 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
81892 ** zero.  This term is not useful for search.
81893 */
81894 static void exprAnalyzeOrTerm(
81895   SrcList *pSrc,            /* the FROM clause */
81896   WhereClause *pWC,         /* the complete WHERE clause */
81897   int idxTerm               /* Index of the OR-term to be analyzed */
81898 ){
81899   Parse *pParse = pWC->pParse;            /* Parser context */
81900   sqlite3 *db = pParse->db;               /* Database connection */
81901   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
81902   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
81903   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
81904   int i;                                  /* Loop counters */
81905   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
81906   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
81907   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
81908   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
81909   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
81910
81911   /*
81912   ** Break the OR clause into its separate subterms.  The subterms are
81913   ** stored in a WhereClause structure containing within the WhereOrInfo
81914   ** object that is attached to the original OR clause term.
81915   */
81916   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
81917   assert( pExpr->op==TK_OR );
81918   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
81919   if( pOrInfo==0 ) return;
81920   pTerm->wtFlags |= TERM_ORINFO;
81921   pOrWc = &pOrInfo->wc;
81922   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
81923   whereSplit(pOrWc, pExpr, TK_OR);
81924   exprAnalyzeAll(pSrc, pOrWc);
81925   if( db->mallocFailed ) return;
81926   assert( pOrWc->nTerm>=2 );
81927
81928   /*
81929   ** Compute the set of tables that might satisfy cases 1 or 2.
81930   */
81931   indexable = chngToIN = ~(Bitmask)0;
81932   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
81933     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
81934       WhereAndInfo *pAndInfo;
81935       assert( pOrTerm->eOperator==0 );
81936       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
81937       chngToIN = 0;
81938       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
81939       if( pAndInfo ){
81940         WhereClause *pAndWC;
81941         WhereTerm *pAndTerm;
81942         int j;
81943         Bitmask b = 0;
81944         pOrTerm->u.pAndInfo = pAndInfo;
81945         pOrTerm->wtFlags |= TERM_ANDINFO;
81946         pOrTerm->eOperator = WO_AND;
81947         pAndWC = &pAndInfo->wc;
81948         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
81949         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
81950         exprAnalyzeAll(pSrc, pAndWC);
81951         testcase( db->mallocFailed );
81952         if( !db->mallocFailed ){
81953           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
81954             assert( pAndTerm->pExpr );
81955             if( allowedOp(pAndTerm->pExpr->op) ){
81956               b |= getMask(pMaskSet, pAndTerm->leftCursor);
81957             }
81958           }
81959         }
81960         indexable &= b;
81961       }
81962     }else if( pOrTerm->wtFlags & TERM_COPIED ){
81963       /* Skip this term for now.  We revisit it when we process the
81964       ** corresponding TERM_VIRTUAL term */
81965     }else{
81966       Bitmask b;
81967       b = getMask(pMaskSet, pOrTerm->leftCursor);
81968       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
81969         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
81970         b |= getMask(pMaskSet, pOther->leftCursor);
81971       }
81972       indexable &= b;
81973       if( pOrTerm->eOperator!=WO_EQ ){
81974         chngToIN = 0;
81975       }else{
81976         chngToIN &= b;
81977       }
81978     }
81979   }
81980
81981   /*
81982   ** Record the set of tables that satisfy case 2.  The set might be
81983   ** empty.
81984   */
81985   pOrInfo->indexable = indexable;
81986   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
81987
81988   /*
81989   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
81990   ** we have to do some additional checking to see if case 1 really
81991   ** is satisfied.
81992   */
81993   if( chngToIN ){
81994     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
81995     int iColumn = -1;         /* Column index on lhs of IN operator */
81996     int iCursor = -1;         /* Table cursor common to all terms */
81997     int j = 0;                /* Loop counter */
81998
81999     /* Search for a table and column that appears on one side or the
82000     ** other of the == operator in every subterm.  That table and column
82001     ** will be recorded in iCursor and iColumn.  There might not be any
82002     ** such table and column.  Set okToChngToIN if an appropriate table
82003     ** and column is found but leave okToChngToIN false if not found.
82004     */
82005     for(j=0; j<2 && !okToChngToIN; j++){
82006       pOrTerm = pOrWc->a;
82007       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
82008         assert( pOrTerm->eOperator==WO_EQ );
82009         pOrTerm->wtFlags &= ~TERM_OR_OK;
82010         if( pOrTerm->leftCursor==iColumn ) continue;
82011         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ) continue;
82012         iColumn = pOrTerm->u.leftColumn;
82013         iCursor = pOrTerm->leftCursor;
82014         break;
82015       }
82016       if( i<0 ){
82017         assert( j==1 );
82018         assert( (chngToIN&(chngToIN-1))==0 );
82019         assert( chngToIN==getMask(pMaskSet, iColumn) );
82020         break;
82021       }
82022       okToChngToIN = 1;
82023       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
82024         assert( pOrTerm->eOperator==WO_EQ );
82025         if( pOrTerm->leftCursor!=iCursor ){
82026           pOrTerm->wtFlags &= ~TERM_OR_OK;
82027         }else if( pOrTerm->u.leftColumn!=iColumn ){
82028           okToChngToIN = 0;
82029         }else{
82030           int affLeft, affRight;
82031           /* If the right-hand side is also a column, then the affinities
82032           ** of both right and left sides must be such that no type
82033           ** conversions are required on the right.  (Ticket #2249)
82034           */
82035           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
82036           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
82037           if( affRight!=0 && affRight!=affLeft ){
82038             okToChngToIN = 0;
82039           }else{
82040             pOrTerm->wtFlags |= TERM_OR_OK;
82041           }
82042         }
82043       }
82044     }
82045
82046     /* At this point, okToChngToIN is true if original pTerm satisfies
82047     ** case 1.  In that case, construct a new virtual term that is 
82048     ** pTerm converted into an IN operator.
82049     */
82050     if( okToChngToIN ){
82051       Expr *pDup;            /* A transient duplicate expression */
82052       ExprList *pList = 0;   /* The RHS of the IN operator */
82053       Expr *pLeft = 0;       /* The LHS of the IN operator */
82054       Expr *pNew;            /* The complete IN operator */
82055
82056       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
82057         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
82058         assert( pOrTerm->eOperator==WO_EQ );
82059         assert( pOrTerm->leftCursor==iCursor );
82060         assert( pOrTerm->u.leftColumn==iColumn );
82061         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight);
82062         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0);
82063         pLeft = pOrTerm->pExpr->pLeft;
82064       }
82065       assert( pLeft!=0 );
82066       pDup = sqlite3ExprDup(db, pLeft);
82067       pNew = sqlite3Expr(db, TK_IN, pDup, 0, 0);
82068       if( pNew ){
82069         int idxNew;
82070         transferJoinMarkings(pNew, pExpr);
82071         pNew->pList = pList;
82072         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
82073         testcase( idxNew==0 );
82074         exprAnalyze(pSrc, pWC, idxNew);
82075         pTerm = &pWC->a[idxTerm];
82076         pWC->a[idxNew].iParent = idxTerm;
82077         pTerm->nChild = 1;
82078       }else{
82079         sqlite3ExprListDelete(db, pList);
82080       }
82081       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
82082     }
82083   }
82084 }
82085 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
82086
82087
82088 /*
82089 ** The input to this routine is an WhereTerm structure with only the
82090 ** "pExpr" field filled in.  The job of this routine is to analyze the
82091 ** subexpression and populate all the other fields of the WhereTerm
82092 ** structure.
82093 **
82094 ** If the expression is of the form "<expr> <op> X" it gets commuted
82095 ** to the standard form of "X <op> <expr>".
82096 **
82097 ** If the expression is of the form "X <op> Y" where both X and Y are
82098 ** columns, then the original expression is unchanged and a new virtual
82099 ** term of the form "Y <op> X" is added to the WHERE clause and
82100 ** analyzed separately.  The original term is marked with TERM_COPIED
82101 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
82102 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
82103 ** is a commuted copy of a prior term.)  The original term has nChild=1
82104 ** and the copy has idxParent set to the index of the original term.
82105 */
82106 static void exprAnalyze(
82107   SrcList *pSrc,            /* the FROM clause */
82108   WhereClause *pWC,         /* the WHERE clause */
82109   int idxTerm               /* Index of the term to be analyzed */
82110 ){
82111   WhereTerm *pTerm;                /* The term to be analyzed */
82112   WhereMaskSet *pMaskSet;          /* Set of table index masks */
82113   Expr *pExpr;                     /* The expression to be analyzed */
82114   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
82115   Bitmask prereqAll;               /* Prerequesites of pExpr */
82116   Bitmask extraRight = 0;
82117   int nPattern;
82118   int isComplete;
82119   int noCase;
82120   int op;                          /* Top-level operator.  pExpr->op */
82121   Parse *pParse = pWC->pParse;     /* Parsing context */
82122   sqlite3 *db = pParse->db;        /* Database connection */
82123
82124   if( db->mallocFailed ){
82125     return;
82126   }
82127   pTerm = &pWC->a[idxTerm];
82128   pMaskSet = pWC->pMaskSet;
82129   pExpr = pTerm->pExpr;
82130   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
82131   op = pExpr->op;
82132   if( op==TK_IN ){
82133     assert( pExpr->pRight==0 );
82134     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
82135                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
82136   }else if( op==TK_ISNULL ){
82137     pTerm->prereqRight = 0;
82138   }else{
82139     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
82140   }
82141   prereqAll = exprTableUsage(pMaskSet, pExpr);
82142   if( ExprHasProperty(pExpr, EP_FromJoin) ){
82143     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
82144     prereqAll |= x;
82145     extraRight = x-1;  /* ON clause terms may not be used with an index
82146                        ** on left table of a LEFT JOIN.  Ticket #3015 */
82147   }
82148   pTerm->prereqAll = prereqAll;
82149   pTerm->leftCursor = -1;
82150   pTerm->iParent = -1;
82151   pTerm->eOperator = 0;
82152   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
82153     Expr *pLeft = pExpr->pLeft;
82154     Expr *pRight = pExpr->pRight;
82155     if( pLeft->op==TK_COLUMN ){
82156       pTerm->leftCursor = pLeft->iTable;
82157       pTerm->u.leftColumn = pLeft->iColumn;
82158       pTerm->eOperator = operatorMask(op);
82159     }
82160     if( pRight && pRight->op==TK_COLUMN ){
82161       WhereTerm *pNew;
82162       Expr *pDup;
82163       if( pTerm->leftCursor>=0 ){
82164         int idxNew;
82165         pDup = sqlite3ExprDup(db, pExpr);
82166         if( db->mallocFailed ){
82167           sqlite3ExprDelete(db, pDup);
82168           return;
82169         }
82170         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
82171         if( idxNew==0 ) return;
82172         pNew = &pWC->a[idxNew];
82173         pNew->iParent = idxTerm;
82174         pTerm = &pWC->a[idxTerm];
82175         pTerm->nChild = 1;
82176         pTerm->wtFlags |= TERM_COPIED;
82177       }else{
82178         pDup = pExpr;
82179         pNew = pTerm;
82180       }
82181       exprCommute(pParse, pDup);
82182       pLeft = pDup->pLeft;
82183       pNew->leftCursor = pLeft->iTable;
82184       pNew->u.leftColumn = pLeft->iColumn;
82185       pNew->prereqRight = prereqLeft;
82186       pNew->prereqAll = prereqAll;
82187       pNew->eOperator = operatorMask(pDup->op);
82188     }
82189   }
82190
82191 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
82192   /* If a term is the BETWEEN operator, create two new virtual terms
82193   ** that define the range that the BETWEEN implements.  For example:
82194   **
82195   **      a BETWEEN b AND c
82196   **
82197   ** is converted into:
82198   **
82199   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
82200   **
82201   ** The two new terms are added onto the end of the WhereClause object.
82202   ** The new terms are "dynamic" and are children of the original BETWEEN
82203   ** term.  That means that if the BETWEEN term is coded, the children are
82204   ** skipped.  Or, if the children are satisfied by an index, the original
82205   ** BETWEEN term is skipped.
82206   */
82207   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
82208     ExprList *pList = pExpr->pList;
82209     int i;
82210     static const u8 ops[] = {TK_GE, TK_LE};
82211     assert( pList!=0 );
82212     assert( pList->nExpr==2 );
82213     for(i=0; i<2; i++){
82214       Expr *pNewExpr;
82215       int idxNew;
82216       pNewExpr = sqlite3Expr(db, ops[i], sqlite3ExprDup(db, pExpr->pLeft),
82217                              sqlite3ExprDup(db, pList->a[i].pExpr), 0);
82218       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
82219       testcase( idxNew==0 );
82220       exprAnalyze(pSrc, pWC, idxNew);
82221       pTerm = &pWC->a[idxTerm];
82222       pWC->a[idxNew].iParent = idxTerm;
82223     }
82224     pTerm->nChild = 2;
82225   }
82226 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
82227
82228 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
82229   /* Analyze a term that is composed of two or more subterms connected by
82230   ** an OR operator.
82231   */
82232   else if( pExpr->op==TK_OR ){
82233     assert( pWC->op==TK_AND );
82234     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
82235   }
82236 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
82237
82238 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
82239   /* Add constraints to reduce the search space on a LIKE or GLOB
82240   ** operator.
82241   **
82242   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
82243   **
82244   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
82245   **
82246   ** The last character of the prefix "abc" is incremented to form the
82247   ** termination condition "abd".
82248   */
82249   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase)
82250          && pWC->op==TK_AND ){
82251     Expr *pLeft, *pRight;
82252     Expr *pStr1, *pStr2;
82253     Expr *pNewExpr1, *pNewExpr2;
82254     int idxNew1, idxNew2;
82255
82256     pLeft = pExpr->pList->a[1].pExpr;
82257     pRight = pExpr->pList->a[0].pExpr;
82258     pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
82259     if( pStr1 ){
82260       sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
82261       pStr1->token.n = nPattern;
82262       pStr1->flags = EP_Dequoted;
82263     }
82264     pStr2 = sqlite3ExprDup(db, pStr1);
82265     if( !db->mallocFailed ){
82266       u8 c, *pC;
82267       assert( pStr2->token.dyn );
82268       pC = (u8*)&pStr2->token.z[nPattern-1];
82269       c = *pC;
82270       if( noCase ){
82271         if( c=='@' ) isComplete = 0;
82272         c = sqlite3UpperToLower[c];
82273       }
82274       *pC = c + 1;
82275     }
82276     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0);
82277     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
82278     testcase( idxNew1==0 );
82279     exprAnalyze(pSrc, pWC, idxNew1);
82280     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft), pStr2, 0);
82281     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
82282     testcase( idxNew2==0 );
82283     exprAnalyze(pSrc, pWC, idxNew2);
82284     pTerm = &pWC->a[idxTerm];
82285     if( isComplete ){
82286       pWC->a[idxNew1].iParent = idxTerm;
82287       pWC->a[idxNew2].iParent = idxTerm;
82288       pTerm->nChild = 2;
82289     }
82290   }
82291 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
82292
82293 #ifndef SQLITE_OMIT_VIRTUALTABLE
82294   /* Add a WO_MATCH auxiliary term to the constraint set if the
82295   ** current expression is of the form:  column MATCH expr.
82296   ** This information is used by the xBestIndex methods of
82297   ** virtual tables.  The native query optimizer does not attempt
82298   ** to do anything with MATCH functions.
82299   */
82300   if( isMatchOfColumn(pExpr) ){
82301     int idxNew;
82302     Expr *pRight, *pLeft;
82303     WhereTerm *pNewTerm;
82304     Bitmask prereqColumn, prereqExpr;
82305
82306     pRight = pExpr->pList->a[0].pExpr;
82307     pLeft = pExpr->pList->a[1].pExpr;
82308     prereqExpr = exprTableUsage(pMaskSet, pRight);
82309     prereqColumn = exprTableUsage(pMaskSet, pLeft);
82310     if( (prereqExpr & prereqColumn)==0 ){
82311       Expr *pNewExpr;
82312       pNewExpr = sqlite3Expr(db, TK_MATCH, 0, sqlite3ExprDup(db, pRight), 0);
82313       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
82314       testcase( idxNew==0 );
82315       pNewTerm = &pWC->a[idxNew];
82316       pNewTerm->prereqRight = prereqExpr;
82317       pNewTerm->leftCursor = pLeft->iTable;
82318       pNewTerm->u.leftColumn = pLeft->iColumn;
82319       pNewTerm->eOperator = WO_MATCH;
82320       pNewTerm->iParent = idxTerm;
82321       pTerm = &pWC->a[idxTerm];
82322       pTerm->nChild = 1;
82323       pTerm->wtFlags |= TERM_COPIED;
82324       pNewTerm->prereqAll = pTerm->prereqAll;
82325     }
82326   }
82327 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82328
82329   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
82330   ** an index for tables to the left of the join.
82331   */
82332   pTerm->prereqRight |= extraRight;
82333 }
82334
82335 /*
82336 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
82337 ** a reference to any table other than the iBase table.
82338 */
82339 static int referencesOtherTables(
82340   ExprList *pList,          /* Search expressions in ths list */
82341   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
82342   int iFirst,               /* Be searching with the iFirst-th expression */
82343   int iBase                 /* Ignore references to this table */
82344 ){
82345   Bitmask allowed = ~getMask(pMaskSet, iBase);
82346   while( iFirst<pList->nExpr ){
82347     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
82348       return 1;
82349     }
82350   }
82351   return 0;
82352 }
82353
82354
82355 /*
82356 ** This routine decides if pIdx can be used to satisfy the ORDER BY
82357 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
82358 ** ORDER BY clause, this routine returns 0.
82359 **
82360 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
82361 ** left-most table in the FROM clause of that same SELECT statement and
82362 ** the table has a cursor number of "base".  pIdx is an index on pTab.
82363 **
82364 ** nEqCol is the number of columns of pIdx that are used as equality
82365 ** constraints.  Any of these columns may be missing from the ORDER BY
82366 ** clause and the match can still be a success.
82367 **
82368 ** All terms of the ORDER BY that match against the index must be either
82369 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
82370 ** index do not need to satisfy this constraint.)  The *pbRev value is
82371 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
82372 ** the ORDER BY clause is all ASC.
82373 */
82374 static int isSortingIndex(
82375   Parse *pParse,          /* Parsing context */
82376   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
82377   Index *pIdx,            /* The index we are testing */
82378   int base,               /* Cursor number for the table to be sorted */
82379   ExprList *pOrderBy,     /* The ORDER BY clause */
82380   int nEqCol,             /* Number of index columns with == constraints */
82381   int *pbRev              /* Set to 1 if ORDER BY is DESC */
82382 ){
82383   int i, j;                       /* Loop counters */
82384   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
82385   int nTerm;                      /* Number of ORDER BY terms */
82386   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
82387   sqlite3 *db = pParse->db;
82388
82389   assert( pOrderBy!=0 );
82390   nTerm = pOrderBy->nExpr;
82391   assert( nTerm>0 );
82392
82393   /* Match terms of the ORDER BY clause against columns of
82394   ** the index.
82395   **
82396   ** Note that indices have pIdx->nColumn regular columns plus
82397   ** one additional column containing the rowid.  The rowid column
82398   ** of the index is also allowed to match against the ORDER BY
82399   ** clause.
82400   */
82401   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
82402     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
82403     CollSeq *pColl;    /* The collating sequence of pExpr */
82404     int termSortOrder; /* Sort order for this term */
82405     int iColumn;       /* The i-th column of the index.  -1 for rowid */
82406     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
82407     const char *zColl; /* Name of the collating sequence for i-th index term */
82408
82409     pExpr = pTerm->pExpr;
82410     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
82411       /* Can not use an index sort on anything that is not a column in the
82412       ** left-most table of the FROM clause */
82413       break;
82414     }
82415     pColl = sqlite3ExprCollSeq(pParse, pExpr);
82416     if( !pColl ){
82417       pColl = db->pDfltColl;
82418     }
82419     if( i<pIdx->nColumn ){
82420       iColumn = pIdx->aiColumn[i];
82421       if( iColumn==pIdx->pTable->iPKey ){
82422         iColumn = -1;
82423       }
82424       iSortOrder = pIdx->aSortOrder[i];
82425       zColl = pIdx->azColl[i];
82426     }else{
82427       iColumn = -1;
82428       iSortOrder = 0;
82429       zColl = pColl->zName;
82430     }
82431     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
82432       /* Term j of the ORDER BY clause does not match column i of the index */
82433       if( i<nEqCol ){
82434         /* If an index column that is constrained by == fails to match an
82435         ** ORDER BY term, that is OK.  Just ignore that column of the index
82436         */
82437         continue;
82438       }else if( i==pIdx->nColumn ){
82439         /* Index column i is the rowid.  All other terms match. */
82440         break;
82441       }else{
82442         /* If an index column fails to match and is not constrained by ==
82443         ** then the index cannot satisfy the ORDER BY constraint.
82444         */
82445         return 0;
82446       }
82447     }
82448     assert( pIdx->aSortOrder!=0 );
82449     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
82450     assert( iSortOrder==0 || iSortOrder==1 );
82451     termSortOrder = iSortOrder ^ pTerm->sortOrder;
82452     if( i>nEqCol ){
82453       if( termSortOrder!=sortOrder ){
82454         /* Indices can only be used if all ORDER BY terms past the
82455         ** equality constraints are all either DESC or ASC. */
82456         return 0;
82457       }
82458     }else{
82459       sortOrder = termSortOrder;
82460     }
82461     j++;
82462     pTerm++;
82463     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
82464       /* If the indexed column is the primary key and everything matches
82465       ** so far and none of the ORDER BY terms to the right reference other
82466       ** tables in the join, then we are assured that the index can be used 
82467       ** to sort because the primary key is unique and so none of the other
82468       ** columns will make any difference
82469       */
82470       j = nTerm;
82471     }
82472   }
82473
82474   *pbRev = sortOrder!=0;
82475   if( j>=nTerm ){
82476     /* All terms of the ORDER BY clause are covered by this index so
82477     ** this index can be used for sorting. */
82478     return 1;
82479   }
82480   if( pIdx->onError!=OE_None && i==pIdx->nColumn
82481       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
82482     /* All terms of this index match some prefix of the ORDER BY clause
82483     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
82484     ** clause reference other tables in a join.  If this is all true then
82485     ** the order by clause is superfluous. */
82486     return 1;
82487   }
82488   return 0;
82489 }
82490
82491 /*
82492 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
82493 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
82494 ** true for reverse ROWID and false for forward ROWID order.
82495 */
82496 static int sortableByRowid(
82497   int base,               /* Cursor number for table to be sorted */
82498   ExprList *pOrderBy,     /* The ORDER BY clause */
82499   WhereMaskSet *pMaskSet, /* Mapping from table cursors to bitmaps */
82500   int *pbRev              /* Set to 1 if ORDER BY is DESC */
82501 ){
82502   Expr *p;
82503
82504   assert( pOrderBy!=0 );
82505   assert( pOrderBy->nExpr>0 );
82506   p = pOrderBy->a[0].pExpr;
82507   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
82508     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
82509     *pbRev = pOrderBy->a[0].sortOrder;
82510     return 1;
82511   }
82512   return 0;
82513 }
82514
82515 /*
82516 ** Prepare a crude estimate of the logarithm of the input value.
82517 ** The results need not be exact.  This is only used for estimating
82518 ** the total cost of performing operations with O(logN) or O(NlogN)
82519 ** complexity.  Because N is just a guess, it is no great tragedy if
82520 ** logN is a little off.
82521 */
82522 static double estLog(double N){
82523   double logN = 1;
82524   double x = 10;
82525   while( N>x ){
82526     logN += 1;
82527     x *= 10;
82528   }
82529   return logN;
82530 }
82531
82532 /*
82533 ** Two routines for printing the content of an sqlite3_index_info
82534 ** structure.  Used for testing and debugging only.  If neither
82535 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
82536 ** are no-ops.
82537 */
82538 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
82539 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
82540   int i;
82541   if( !sqlite3WhereTrace ) return;
82542   for(i=0; i<p->nConstraint; i++){
82543     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
82544        i,
82545        p->aConstraint[i].iColumn,
82546        p->aConstraint[i].iTermOffset,
82547        p->aConstraint[i].op,
82548        p->aConstraint[i].usable);
82549   }
82550   for(i=0; i<p->nOrderBy; i++){
82551     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
82552        i,
82553        p->aOrderBy[i].iColumn,
82554        p->aOrderBy[i].desc);
82555   }
82556 }
82557 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
82558   int i;
82559   if( !sqlite3WhereTrace ) return;
82560   for(i=0; i<p->nConstraint; i++){
82561     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
82562        i,
82563        p->aConstraintUsage[i].argvIndex,
82564        p->aConstraintUsage[i].omit);
82565   }
82566   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
82567   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
82568   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
82569   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
82570 }
82571 #else
82572 #define TRACE_IDX_INPUTS(A)
82573 #define TRACE_IDX_OUTPUTS(A)
82574 #endif
82575
82576 #ifndef SQLITE_OMIT_VIRTUALTABLE
82577 /*
82578 ** Compute the best index for a virtual table.
82579 **
82580 ** The best index is computed by the xBestIndex method of the virtual
82581 ** table module.  This routine is really just a wrapper that sets up
82582 ** the sqlite3_index_info structure that is used to communicate with
82583 ** xBestIndex.
82584 **
82585 ** In a join, this routine might be called multiple times for the
82586 ** same virtual table.  The sqlite3_index_info structure is created
82587 ** and initialized on the first invocation and reused on all subsequent
82588 ** invocations.  The sqlite3_index_info structure is also used when
82589 ** code is generated to access the virtual table.  The whereInfoDelete() 
82590 ** routine takes care of freeing the sqlite3_index_info structure after
82591 ** everybody has finished with it.
82592 */
82593 static double bestVirtualIndex(
82594   Parse *pParse,                 /* The parsing context */
82595   WhereClause *pWC,              /* The WHERE clause */
82596   struct SrcList_item *pSrc,     /* The FROM clause term to search */
82597   Bitmask notReady,              /* Mask of cursors that are not available */
82598   ExprList *pOrderBy,            /* The order by clause */
82599   int orderByUsable,             /* True if we can potential sort */
82600   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
82601 ){
82602   Table *pTab = pSrc->pTab;
82603   sqlite3_vtab *pVtab = pTab->pVtab;
82604   sqlite3_index_info *pIdxInfo;
82605   struct sqlite3_index_constraint *pIdxCons;
82606   struct sqlite3_index_orderby *pIdxOrderBy;
82607   struct sqlite3_index_constraint_usage *pUsage;
82608   WhereTerm *pTerm;
82609   int i, j;
82610   int nOrderBy;
82611   int rc;
82612
82613   /* If the sqlite3_index_info structure has not been previously
82614   ** allocated and initialized for this virtual table, then allocate
82615   ** and initialize it now
82616   */
82617   pIdxInfo = *ppIdxInfo;
82618   if( pIdxInfo==0 ){
82619     int nTerm;
82620     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
82621
82622     /* Count the number of possible WHERE clause constraints referring
82623     ** to this virtual table */
82624     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82625       if( pTerm->leftCursor != pSrc->iCursor ) continue;
82626       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82627       testcase( pTerm->eOperator==WO_IN );
82628       testcase( pTerm->eOperator==WO_ISNULL );
82629       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82630       nTerm++;
82631     }
82632
82633     /* If the ORDER BY clause contains only columns in the current 
82634     ** virtual table then allocate space for the aOrderBy part of
82635     ** the sqlite3_index_info structure.
82636     */
82637     nOrderBy = 0;
82638     if( pOrderBy ){
82639       for(i=0; i<pOrderBy->nExpr; i++){
82640         Expr *pExpr = pOrderBy->a[i].pExpr;
82641         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
82642       }
82643       if( i==pOrderBy->nExpr ){
82644         nOrderBy = pOrderBy->nExpr;
82645       }
82646     }
82647
82648     /* Allocate the sqlite3_index_info structure
82649     */
82650     pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
82651                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
82652                              + sizeof(*pIdxOrderBy)*nOrderBy );
82653     if( pIdxInfo==0 ){
82654       sqlite3ErrorMsg(pParse, "out of memory");
82655       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82656       return (double)0;
82657     }
82658     *ppIdxInfo = pIdxInfo;
82659
82660     /* Initialize the structure.  The sqlite3_index_info structure contains
82661     ** many fields that are declared "const" to prevent xBestIndex from
82662     ** changing them.  We have to do some funky casting in order to
82663     ** initialize those fields.
82664     */
82665     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
82666     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
82667     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
82668     *(int*)&pIdxInfo->nConstraint = nTerm;
82669     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82670     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
82671     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
82672     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
82673                                                                      pUsage;
82674
82675     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82676       if( pTerm->leftCursor != pSrc->iCursor ) continue;
82677       assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82678       testcase( pTerm->eOperator==WO_IN );
82679       testcase( pTerm->eOperator==WO_ISNULL );
82680       if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82681       pIdxCons[j].iColumn = pTerm->u.leftColumn;
82682       pIdxCons[j].iTermOffset = i;
82683       pIdxCons[j].op = (u8)pTerm->eOperator;
82684       /* The direct assignment in the previous line is possible only because
82685       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
82686       ** following asserts verify this fact. */
82687       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
82688       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
82689       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
82690       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
82691       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
82692       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
82693       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
82694       j++;
82695     }
82696     for(i=0; i<nOrderBy; i++){
82697       Expr *pExpr = pOrderBy->a[i].pExpr;
82698       pIdxOrderBy[i].iColumn = pExpr->iColumn;
82699       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
82700     }
82701   }
82702
82703   /* At this point, the sqlite3_index_info structure that pIdxInfo points
82704   ** to will have been initialized, either during the current invocation or
82705   ** during some prior invocation.  Now we just have to customize the
82706   ** details of pIdxInfo for the current invocation and pass it to
82707   ** xBestIndex.
82708   */
82709
82710   /* The module name must be defined. Also, by this point there must
82711   ** be a pointer to an sqlite3_vtab structure. Otherwise
82712   ** sqlite3ViewGetColumnNames() would have picked up the error. 
82713   */
82714   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
82715   assert( pVtab );
82716 #if 0
82717   if( pTab->pVtab==0 ){
82718     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
82719         pTab->azModuleArg[0], pTab->zName);
82720     return 0.0;
82721   }
82722 #endif
82723
82724   /* Set the aConstraint[].usable fields and initialize all 
82725   ** output variables to zero.
82726   **
82727   ** aConstraint[].usable is true for constraints where the right-hand
82728   ** side contains only references to tables to the left of the current
82729   ** table.  In other words, if the constraint is of the form:
82730   **
82731   **           column = expr
82732   **
82733   ** and we are evaluating a join, then the constraint on column is 
82734   ** only valid if all tables referenced in expr occur to the left
82735   ** of the table containing column.
82736   **
82737   ** The aConstraints[] array contains entries for all constraints
82738   ** on the current table.  That way we only have to compute it once
82739   ** even though we might try to pick the best index multiple times.
82740   ** For each attempt at picking an index, the order of tables in the
82741   ** join might be different so we have to recompute the usable flag
82742   ** each time.
82743   */
82744   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
82745   pUsage = pIdxInfo->aConstraintUsage;
82746   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
82747     j = pIdxCons->iTermOffset;
82748     pTerm = &pWC->a[j];
82749     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0 ?1:0;
82750   }
82751   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
82752   if( pIdxInfo->needToFreeIdxStr ){
82753     sqlite3_free(pIdxInfo->idxStr);
82754   }
82755   pIdxInfo->idxStr = 0;
82756   pIdxInfo->idxNum = 0;
82757   pIdxInfo->needToFreeIdxStr = 0;
82758   pIdxInfo->orderByConsumed = 0;
82759   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
82760   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
82761   nOrderBy = pIdxInfo->nOrderBy;
82762   if( pIdxInfo->nOrderBy && !orderByUsable ){
82763     *(int*)&pIdxInfo->nOrderBy = 0;
82764   }
82765
82766   (void)sqlite3SafetyOff(pParse->db);
82767   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
82768   TRACE_IDX_INPUTS(pIdxInfo);
82769   rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
82770   TRACE_IDX_OUTPUTS(pIdxInfo);
82771   (void)sqlite3SafetyOn(pParse->db);
82772
82773   if( rc!=SQLITE_OK ){
82774     if( rc==SQLITE_NOMEM ){
82775       pParse->db->mallocFailed = 1;
82776     }else if( !pVtab->zErrMsg ){
82777       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
82778     }else{
82779       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
82780     }
82781   }
82782   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
82783   pVtab->zErrMsg = 0;
82784
82785   for(i=0; i<pIdxInfo->nConstraint; i++){
82786     if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
82787       sqlite3ErrorMsg(pParse, 
82788           "table %s: xBestIndex returned an invalid plan", pTab->zName);
82789       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82790       return (double)0;
82791     }
82792   }
82793
82794   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82795   return pIdxInfo->estimatedCost;
82796 }
82797 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82798
82799 /*
82800 ** Find the query plan for accessing a particular table.  Write the
82801 ** best query plan and its cost into the WhereCost object supplied as the
82802 ** last parameter.
82803 **
82804 ** The lowest cost plan wins.  The cost is an estimate of the amount of
82805 ** CPU and disk I/O need to process the request using the selected plan.
82806 ** Factors that influence cost include:
82807 **
82808 **    *  The estimated number of rows that will be retrieved.  (The
82809 **       fewer the better.)
82810 **
82811 **    *  Whether or not sorting must occur.
82812 **
82813 **    *  Whether or not there must be separate lookups in the
82814 **       index and in the main table.
82815 **
82816 ** If there was an INDEXED BY clause attached to the table in the SELECT
82817 ** statement, then this function only considers plans using the 
82818 ** named index. If one cannot be found, then the returned cost is
82819 ** SQLITE_BIG_DBL. If a plan can be found that uses the named index, 
82820 ** then the cost is calculated in the usual way.
82821 **
82822 ** If a NOT INDEXED clause was attached to the table in the SELECT 
82823 ** statement, then no indexes are considered. However, the selected 
82824 ** plan may still take advantage of the tables built-in rowid
82825 ** index.
82826 */
82827 static void bestIndex(
82828   Parse *pParse,              /* The parsing context */
82829   WhereClause *pWC,           /* The WHERE clause */
82830   struct SrcList_item *pSrc,  /* The FROM clause term to search */
82831   Bitmask notReady,           /* Mask of cursors that are not available */
82832   ExprList *pOrderBy,         /* The ORDER BY clause */
82833   WhereCost *pCost            /* Lowest cost query plan */
82834 ){
82835   WhereTerm *pTerm;           /* A single term of the WHERE clause */
82836   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
82837   Index *pProbe;              /* An index we are evaluating */
82838   int rev;                    /* True to scan in reverse order */
82839   int wsFlags;                /* Flags associated with pProbe */
82840   int nEq;                    /* Number of == or IN constraints */
82841   int eqTermMask;             /* Mask of valid equality operators */
82842   double cost;                /* Cost of using pProbe */
82843   double nRow;                /* Estimated number of rows in result set */
82844   int i;                      /* Loop counter */
82845   Bitmask maskSrc;            /* Bitmask for the pSrc table */
82846
82847   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
82848   pProbe = pSrc->pTab->pIndex;
82849   if( pSrc->notIndexed ){
82850     pProbe = 0;
82851   }
82852
82853   /* If the table has no indices and there are no terms in the where
82854   ** clause that refer to the ROWID, then we will never be able to do
82855   ** anything other than a full table scan on this table.  We might as
82856   ** well put it first in the join order.  That way, perhaps it can be
82857   ** referenced by other tables in the join.
82858   */
82859   memset(pCost, 0, sizeof(*pCost));
82860   if( pProbe==0 &&
82861      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
82862      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
82863     return;
82864   }
82865   pCost->rCost = SQLITE_BIG_DBL;
82866
82867   /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
82868   ** an INDEXED BY clause attached to this table, skip this step.
82869   */
82870   if( !pSrc->pIndex ){
82871     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
82872     if( pTerm ){
82873       Expr *pExpr;
82874       pCost->plan.wsFlags = WHERE_ROWID_EQ;
82875       if( pTerm->eOperator & WO_EQ ){
82876         /* Rowid== is always the best pick.  Look no further.  Because only
82877         ** a single row is generated, output is always in sorted order */
82878         pCost->plan.wsFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
82879         pCost->plan.nEq = 1;
82880         WHERETRACE(("... best is rowid\n"));
82881         pCost->rCost = 0;
82882         pCost->nRow = 1;
82883         return;
82884       }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
82885         /* Rowid IN (LIST): cost is NlogN where N is the number of list
82886         ** elements.  */
82887         pCost->rCost = pCost->nRow = pExpr->pList->nExpr;
82888         pCost->rCost *= estLog(pCost->rCost);
82889       }else{
82890         /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
82891         ** in the result of the inner select.  We have no way to estimate
82892         ** that value so make a wild guess. */
82893         pCost->nRow = 100;
82894         pCost->rCost = 200;
82895       }
82896       WHERETRACE(("... rowid IN cost: %.9g\n", pCost->rCost));
82897     }
82898   
82899     /* Estimate the cost of a table scan.  If we do not know how many
82900     ** entries are in the table, use 1 million as a guess.
82901     */
82902     cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
82903     WHERETRACE(("... table scan base cost: %.9g\n", cost));
82904     wsFlags = WHERE_ROWID_RANGE;
82905   
82906     /* Check for constraints on a range of rowids in a table scan.
82907     */
82908     pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
82909     if( pTerm ){
82910       if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
82911         wsFlags |= WHERE_TOP_LIMIT;
82912         cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds of rows */
82913       }
82914       if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
82915         wsFlags |= WHERE_BTM_LIMIT;
82916         cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
82917       }
82918       WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
82919     }else{
82920       wsFlags = 0;
82921     }
82922     nRow = cost;
82923   
82924     /* If the table scan does not satisfy the ORDER BY clause, increase
82925     ** the cost by NlogN to cover the expense of sorting. */
82926     if( pOrderBy ){
82927       if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
82928         wsFlags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
82929         if( rev ){
82930           wsFlags |= WHERE_REVERSE;
82931         }
82932       }else{
82933         cost += cost*estLog(cost);
82934         WHERETRACE(("... sorting increases cost to %.9g\n", cost));
82935       }
82936     }
82937     if( cost<pCost->rCost ){
82938       pCost->rCost = cost;
82939       pCost->nRow = nRow;
82940       pCost->plan.wsFlags = wsFlags;
82941     }
82942   }
82943
82944 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
82945   /* Search for an OR-clause that can be used to look up the table.
82946   */
82947   maskSrc = getMask(pWC->pMaskSet, iCur);
82948   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82949     WhereClause tempWC;
82950     tempWC = *pWC;
82951     if( pTerm->eOperator==WO_OR 
82952         && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
82953         && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 ){
82954       WhereClause *pOrWC = &pTerm->u.pOrInfo->wc;
82955       WhereTerm *pOrTerm;
82956       int j;
82957       int sortable = 0;
82958       double rTotal = 0;
82959       nRow = 0;
82960       for(j=0, pOrTerm=pOrWC->a; j<pOrWC->nTerm; j++, pOrTerm++){
82961         WhereCost sTermCost;
82962         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", j,i));
82963         if( pOrTerm->eOperator==WO_AND ){
82964           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
82965           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
82966         }else if( pOrTerm->leftCursor==iCur ){
82967           tempWC.a = pOrTerm;
82968           tempWC.nTerm = 1;
82969           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
82970         }else{
82971           continue;
82972         }
82973         rTotal += sTermCost.rCost;
82974         nRow += sTermCost.nRow;
82975         if( rTotal>=pCost->rCost ) break;
82976       }
82977       if( pOrderBy!=0 ){
82978         if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) && !rev ){
82979           sortable = 1;
82980         }else{
82981           rTotal += nRow*estLog(nRow);
82982           WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
82983         }
82984       }
82985       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n",
82986                   rTotal, nRow));
82987       if( rTotal<pCost->rCost ){
82988         pCost->rCost = rTotal;
82989         pCost->nRow = nRow;
82990         pCost->plan.wsFlags = WHERE_MULTI_OR;
82991         pCost->plan.u.pTerm = pTerm;
82992         if( sortable ){
82993           pCost->plan.wsFlags = WHERE_ORDERBY|WHERE_MULTI_OR;
82994         }
82995       }
82996     }
82997   }
82998 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
82999
83000   /* If the pSrc table is the right table of a LEFT JOIN then we may not
83001   ** use an index to satisfy IS NULL constraints on that table.  This is
83002   ** because columns might end up being NULL if the table does not match -
83003   ** a circumstance which the index cannot help us discover.  Ticket #2177.
83004   */
83005   if( (pSrc->jointype & JT_LEFT)!=0 ){
83006     eqTermMask = WO_EQ|WO_IN;
83007   }else{
83008     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
83009   }
83010
83011   /* Look at each index.
83012   */
83013   if( pSrc->pIndex ){
83014     pProbe = pSrc->pIndex;
83015   }
83016   for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
83017     double inMultiplier = 1;
83018
83019     WHERETRACE(("... index %s:\n", pProbe->zName));
83020
83021     /* Count the number of columns in the index that are satisfied
83022     ** by x=EXPR constraints or x IN (...) constraints.
83023     */
83024     wsFlags = 0;
83025     for(i=0; i<pProbe->nColumn; i++){
83026       int j = pProbe->aiColumn[i];
83027       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
83028       if( pTerm==0 ) break;
83029       wsFlags |= WHERE_COLUMN_EQ;
83030       if( pTerm->eOperator & WO_IN ){
83031         Expr *pExpr = pTerm->pExpr;
83032         wsFlags |= WHERE_COLUMN_IN;
83033         if( pExpr->pSelect!=0 ){
83034           inMultiplier *= 25;
83035         }else if( pExpr->pList ){
83036           inMultiplier *= pExpr->pList->nExpr + 1;
83037         }
83038       }
83039     }
83040     nRow = pProbe->aiRowEst[i] * inMultiplier;
83041     cost = nRow * estLog(inMultiplier);
83042     nEq = i;
83043     if( pProbe->onError!=OE_None && (wsFlags & WHERE_COLUMN_IN)==0
83044          && nEq==pProbe->nColumn ){
83045       wsFlags |= WHERE_UNIQUE;
83046     }
83047     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n",nEq,inMultiplier,cost));
83048
83049     /* Look for range constraints
83050     */
83051     if( nEq<pProbe->nColumn ){
83052       int j = pProbe->aiColumn[nEq];
83053       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
83054       if( pTerm ){
83055         wsFlags |= WHERE_COLUMN_RANGE;
83056         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
83057           wsFlags |= WHERE_TOP_LIMIT;
83058           cost /= 3;
83059           nRow /= 3;
83060         }
83061         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
83062           wsFlags |= WHERE_BTM_LIMIT;
83063           cost /= 3;
83064           nRow /= 3;
83065         }
83066         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
83067       }
83068     }
83069
83070     /* Add the additional cost of sorting if that is a factor.
83071     */
83072     if( pOrderBy ){
83073       if( (wsFlags & WHERE_COLUMN_IN)==0 &&
83074            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
83075         if( wsFlags==0 ){
83076           wsFlags = WHERE_COLUMN_RANGE;
83077         }
83078         wsFlags |= WHERE_ORDERBY;
83079         if( rev ){
83080           wsFlags |= WHERE_REVERSE;
83081         }
83082       }else{
83083         cost += cost*estLog(cost);
83084         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
83085       }
83086     }
83087
83088     /* Check to see if we can get away with using just the index without
83089     ** ever reading the table.  If that is the case, then halve the
83090     ** cost of this index.
83091     */
83092     if( wsFlags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
83093       Bitmask m = pSrc->colUsed;
83094       int j;
83095       for(j=0; j<pProbe->nColumn; j++){
83096         int x = pProbe->aiColumn[j];
83097         if( x<BMS-1 ){
83098           m &= ~(((Bitmask)1)<<x);
83099         }
83100       }
83101       if( m==0 ){
83102         wsFlags |= WHERE_IDX_ONLY;
83103         cost /= 2;
83104         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
83105       }
83106     }
83107
83108     /* If this index has achieved the lowest cost so far, then use it.
83109     */
83110     if( wsFlags!=0 && cost < pCost->rCost ){
83111       pCost->rCost = cost;
83112       pCost->nRow = nRow;
83113       pCost->plan.wsFlags = wsFlags;
83114       pCost->plan.nEq = nEq;
83115       assert( pCost->plan.wsFlags & WHERE_INDEXED );
83116       pCost->plan.u.pIdx = pProbe;
83117     }
83118   }
83119
83120   /* Report the best result
83121   */
83122   pCost->plan.wsFlags |= eqTermMask;
83123   WHERETRACE(("best index is %s, cost=%.9g, nrow=%.9g, wsFlags=%x, nEq=%d\n",
83124         (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
83125              pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
83126         pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
83127 }
83128
83129
83130 /*
83131 ** Disable a term in the WHERE clause.  Except, do not disable the term
83132 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
83133 ** or USING clause of that join.
83134 **
83135 ** Consider the term t2.z='ok' in the following queries:
83136 **
83137 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
83138 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
83139 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
83140 **
83141 ** The t2.z='ok' is disabled in the in (2) because it originates
83142 ** in the ON clause.  The term is disabled in (3) because it is not part
83143 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
83144 **
83145 ** Disabling a term causes that term to not be tested in the inner loop
83146 ** of the join.  Disabling is an optimization.  When terms are satisfied
83147 ** by indices, we disable them to prevent redundant tests in the inner
83148 ** loop.  We would get the correct results if nothing were ever disabled,
83149 ** but joins might run a little slower.  The trick is to disable as much
83150 ** as we can without disabling too much.  If we disabled in (1), we'd get
83151 ** the wrong answer.  See ticket #813.
83152 */
83153 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
83154   if( pTerm
83155       && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
83156       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
83157   ){
83158     pTerm->wtFlags |= TERM_CODED;
83159     if( pTerm->iParent>=0 ){
83160       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
83161       if( (--pOther->nChild)==0 ){
83162         disableTerm(pLevel, pOther);
83163       }
83164     }
83165   }
83166 }
83167
83168 /*
83169 ** Apply the affinities associated with the first n columns of index
83170 ** pIdx to the values in the n registers starting at base.
83171 */
83172 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
83173   if( n>0 ){
83174     Vdbe *v = pParse->pVdbe;
83175     assert( v!=0 );
83176     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
83177     sqlite3IndexAffinityStr(v, pIdx);
83178     sqlite3ExprCacheAffinityChange(pParse, base, n);
83179   }
83180 }
83181
83182
83183 /*
83184 ** Generate code for a single equality term of the WHERE clause.  An equality
83185 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
83186 ** coded.
83187 **
83188 ** The current value for the constraint is left in register iReg.
83189 **
83190 ** For a constraint of the form X=expr, the expression is evaluated and its
83191 ** result is left on the stack.  For constraints of the form X IN (...)
83192 ** this routine sets up a loop that will iterate over all values of X.
83193 */
83194 static int codeEqualityTerm(
83195   Parse *pParse,      /* The parsing context */
83196   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
83197   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
83198   int iTarget         /* Attempt to leave results in this register */
83199 ){
83200   Expr *pX = pTerm->pExpr;
83201   Vdbe *v = pParse->pVdbe;
83202   int iReg;                  /* Register holding results */
83203
83204   assert( iTarget>0 );
83205   if( pX->op==TK_EQ ){
83206     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
83207   }else if( pX->op==TK_ISNULL ){
83208     iReg = iTarget;
83209     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
83210 #ifndef SQLITE_OMIT_SUBQUERY
83211   }else{
83212     int eType;
83213     int iTab;
83214     struct InLoop *pIn;
83215
83216     assert( pX->op==TK_IN );
83217     iReg = iTarget;
83218     eType = sqlite3FindInIndex(pParse, pX, 0);
83219     iTab = pX->iTable;
83220     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83221     VdbeComment((v, "%.*s", pX->span.n, pX->span.z));
83222     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
83223     if( pLevel->u.in.nIn==0 ){
83224       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
83225     }
83226     pLevel->u.in.nIn++;
83227     pLevel->u.in.aInLoop =
83228        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
83229                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
83230     pIn = pLevel->u.in.aInLoop;
83231     if( pIn ){
83232       pIn += pLevel->u.in.nIn - 1;
83233       pIn->iCur = iTab;
83234       if( eType==IN_INDEX_ROWID ){
83235         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
83236       }else{
83237         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
83238       }
83239       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
83240     }else{
83241       pLevel->u.in.nIn = 0;
83242     }
83243 #endif
83244   }
83245   disableTerm(pLevel, pTerm);
83246   return iReg;
83247 }
83248
83249 /*
83250 ** Generate code that will evaluate all == and IN constraints for an
83251 ** index.  The values for all constraints are left on the stack.
83252 **
83253 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
83254 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
83255 ** The index has as many as three equality constraints, but in this
83256 ** example, the third "c" value is an inequality.  So only two 
83257 ** constraints are coded.  This routine will generate code to evaluate
83258 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
83259 ** in consecutive registers and the index of the first register is returned.
83260 **
83261 ** In the example above nEq==2.  But this subroutine works for any value
83262 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
83263 ** The only thing it does is allocate the pLevel->iMem memory cell.
83264 **
83265 ** This routine always allocates at least one memory cell and returns
83266 ** the index of that memory cell. The code that
83267 ** calls this routine will use that memory cell to store the termination
83268 ** key value of the loop.  If one or more IN operators appear, then
83269 ** this routine allocates an additional nEq memory cells for internal
83270 ** use.
83271 */
83272 static int codeAllEqualityTerms(
83273   Parse *pParse,        /* Parsing context */
83274   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
83275   WhereClause *pWC,     /* The WHERE clause */
83276   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
83277   int nExtraReg         /* Number of extra registers to allocate */
83278 ){
83279   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
83280   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
83281   Index *pIdx;                  /* The index being used for this loop */
83282   int iCur = pLevel->iTabCur;   /* The cursor of the table */
83283   WhereTerm *pTerm;             /* A single constraint term */
83284   int j;                        /* Loop counter */
83285   int regBase;                  /* Base register */
83286   int nReg;                     /* Number of registers to allocate */
83287
83288   /* This module is only called on query plans that use an index. */
83289   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
83290   pIdx = pLevel->plan.u.pIdx;
83291
83292   /* Figure out how many memory cells we will need then allocate them.
83293   */
83294   regBase = pParse->nMem + 1;
83295   nReg = pLevel->plan.nEq + nExtraReg;
83296   pParse->nMem += nReg;
83297
83298   /* Evaluate the equality constraints
83299   */
83300   assert( pIdx->nColumn>=nEq );
83301   for(j=0; j<nEq; j++){
83302     int r1;
83303     int k = pIdx->aiColumn[j];
83304     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
83305     if( NEVER(pTerm==0) ) break;
83306     assert( (pTerm->wtFlags & TERM_CODED)==0 );
83307     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
83308     if( r1!=regBase+j ){
83309       if( nReg==1 ){
83310         sqlite3ReleaseTempReg(pParse, regBase);
83311         regBase = r1;
83312       }else{
83313         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
83314       }
83315     }
83316     testcase( pTerm->eOperator & WO_ISNULL );
83317     testcase( pTerm->eOperator & WO_IN );
83318     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
83319       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
83320     }
83321   }
83322   return regBase;
83323 }
83324
83325 /*
83326 ** Return TRUE if the WhereClause pWC contains no terms that
83327 ** are not virtual and which have not been coded.
83328 **
83329 ** To put it another way, return TRUE if no additional WHERE clauses
83330 ** tests are required in order to establish that the current row
83331 ** should go to output and return FALSE if there are some terms of
83332 ** the WHERE clause that need to be validated before outputing the row.
83333 */
83334 static int whereRowReadyForOutput(WhereClause *pWC){
83335   WhereTerm *pTerm;
83336   int j;
83337  
83338   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
83339     if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED))==0 ) return 0;
83340   }
83341   return 1;
83342 }
83343
83344 /*
83345 ** Generate code for the start of the iLevel-th loop in the WHERE clause
83346 ** implementation described by pWInfo.
83347 */
83348 static Bitmask codeOneLoopStart(
83349   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
83350   int iLevel,          /* Which level of pWInfo->a[] should be coded */
83351   u8 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
83352   Bitmask notReady     /* Which tables are currently available */
83353 ){
83354   int j, k;            /* Loop counters */
83355   int iCur;            /* The VDBE cursor for the table */
83356   int addrNxt;         /* Where to jump to continue with the next IN case */
83357   int omitTable;       /* True if we use the index only */
83358   int bRev;            /* True if we need to scan in reverse order */
83359   WhereLevel *pLevel;  /* The where level to be coded */
83360   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
83361   WhereTerm *pTerm;               /* A WHERE clause term */
83362   Parse *pParse;                  /* Parsing context */
83363   Vdbe *v;                        /* The prepared stmt under constructions */
83364   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
83365   int addrBrk;                    /* Jump here to break out of the loop */
83366   int addrCont;                   /* Jump here to continue with next cycle */
83367   int regRowSet;       /* Write rowids to this RowSet if non-negative */
83368   int codeRowSetEarly; /* True if index fully constrains the search */
83369   
83370
83371   pParse = pWInfo->pParse;
83372   v = pParse->pVdbe;
83373   pWC = pWInfo->pWC;
83374   pLevel = &pWInfo->a[iLevel];
83375   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
83376   iCur = pTabItem->iCursor;
83377   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
83378   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0;
83379   regRowSet = pWInfo->regRowSet;
83380   codeRowSetEarly = 0;
83381
83382   /* Create labels for the "break" and "continue" instructions
83383   ** for the current loop.  Jump to addrBrk to break out of a loop.
83384   ** Jump to cont to go immediately to the next iteration of the
83385   ** loop.
83386   **
83387   ** When there is an IN operator, we also have a "addrNxt" label that
83388   ** means to continue with the next IN value combination.  When
83389   ** there are no IN operators in the constraints, the "addrNxt" label
83390   ** is the same as "addrBrk".
83391   */
83392   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
83393   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
83394
83395   /* If this is the right table of a LEFT OUTER JOIN, allocate and
83396   ** initialize a memory cell that records if this table matches any
83397   ** row of the left table of the join.
83398   */
83399   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
83400     pLevel->iLeftJoin = ++pParse->nMem;
83401     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
83402     VdbeComment((v, "init LEFT JOIN no-match flag"));
83403   }
83404
83405 #ifndef SQLITE_OMIT_VIRTUALTABLE
83406   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
83407     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
83408     **          to access the data.
83409     */
83410     int iReg;   /* P3 Value for OP_VFilter */
83411     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
83412     int nConstraint = pVtabIdx->nConstraint;
83413     struct sqlite3_index_constraint_usage *aUsage =
83414                                                 pVtabIdx->aConstraintUsage;
83415     const struct sqlite3_index_constraint *aConstraint =
83416                                                 pVtabIdx->aConstraint;
83417
83418     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
83419     pParse->disableColCache++;
83420     for(j=1; j<=nConstraint; j++){
83421       for(k=0; k<nConstraint; k++){
83422         if( aUsage[k].argvIndex==j ){
83423           int iTerm = aConstraint[k].iTermOffset;
83424           assert( pParse->disableColCache );
83425           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
83426           break;
83427         }
83428       }
83429       if( k==nConstraint ) break;
83430     }
83431     assert( pParse->disableColCache );
83432     pParse->disableColCache--;
83433     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
83434     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
83435     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
83436                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
83437     pVtabIdx->needToFreeIdxStr = 0;
83438     for(j=0; j<nConstraint; j++){
83439       if( aUsage[j].omit ){
83440         int iTerm = aConstraint[j].iTermOffset;
83441         disableTerm(pLevel, &pWC->a[iTerm]);
83442       }
83443     }
83444     pLevel->op = OP_VNext;
83445     pLevel->p1 = iCur;
83446     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
83447     codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83448     if( codeRowSetEarly ){
83449       sqlite3VdbeAddOp2(v, OP_VRowid, iCur, iReg);
83450       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, iReg);
83451     }
83452     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
83453   }else
83454 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83455
83456   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
83457     /* Case 1:  We can directly reference a single row using an
83458     **          equality comparison against the ROWID field.  Or
83459     **          we reference multiple rows using a "rowid IN (...)"
83460     **          construct.
83461     */
83462     int r1;
83463     int rtmp = sqlite3GetTempReg(pParse);
83464     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
83465     assert( pTerm!=0 );
83466     assert( pTerm->pExpr!=0 );
83467     assert( pTerm->leftCursor==iCur );
83468     assert( omitTable==0 );
83469     r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
83470     addrNxt = pLevel->addrNxt;
83471     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, addrNxt);
83472     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, r1);
83473     codeRowSetEarly = (pWC->nTerm==1 && regRowSet>=0) ?1:0;
83474     if( codeRowSetEarly ){
83475       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83476     }
83477     sqlite3ReleaseTempReg(pParse, rtmp);
83478     VdbeComment((v, "pk"));
83479     pLevel->op = OP_Noop;
83480   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
83481     /* Case 2:  We have an inequality comparison against the ROWID field.
83482     */
83483     int testOp = OP_Noop;
83484     int start;
83485     int memEndValue = 0;
83486     WhereTerm *pStart, *pEnd;
83487
83488     assert( omitTable==0 );
83489     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
83490     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
83491     if( bRev ){
83492       pTerm = pStart;
83493       pStart = pEnd;
83494       pEnd = pTerm;
83495     }
83496     if( pStart ){
83497       Expr *pX;             /* The expression that defines the start bound */
83498       int r1, rTemp;        /* Registers for holding the start boundary */
83499
83500       /* The following constant maps TK_xx codes into corresponding 
83501       ** seek opcodes.  It depends on a particular ordering of TK_xx
83502       */
83503       const u8 aMoveOp[] = {
83504            /* TK_GT */  OP_SeekGt,
83505            /* TK_LE */  OP_SeekLe,
83506            /* TK_LT */  OP_SeekLt,
83507            /* TK_GE */  OP_SeekGe
83508       };
83509       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
83510       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
83511       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
83512
83513       pX = pStart->pExpr;
83514       assert( pX!=0 );
83515       assert( pStart->leftCursor==iCur );
83516       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
83517       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
83518       VdbeComment((v, "pk"));
83519       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
83520       sqlite3ReleaseTempReg(pParse, rTemp);
83521       disableTerm(pLevel, pStart);
83522     }else{
83523       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
83524     }
83525     if( pEnd ){
83526       Expr *pX;
83527       pX = pEnd->pExpr;
83528       assert( pX!=0 );
83529       assert( pEnd->leftCursor==iCur );
83530       memEndValue = ++pParse->nMem;
83531       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
83532       if( pX->op==TK_LT || pX->op==TK_GT ){
83533         testOp = bRev ? OP_Le : OP_Ge;
83534       }else{
83535         testOp = bRev ? OP_Lt : OP_Gt;
83536       }
83537       disableTerm(pLevel, pEnd);
83538     }
83539     start = sqlite3VdbeCurrentAddr(v);
83540     pLevel->op = bRev ? OP_Prev : OP_Next;
83541     pLevel->p1 = iCur;
83542     pLevel->p2 = start;
83543     pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
83544     codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83545     if( codeRowSetEarly || testOp!=OP_Noop ){
83546       int r1 = sqlite3GetTempReg(pParse);
83547       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83548       if( testOp!=OP_Noop ){
83549         sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, r1);
83550         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
83551       }
83552       if( codeRowSetEarly ){
83553         sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83554       }
83555       sqlite3ReleaseTempReg(pParse, r1);
83556     }
83557   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
83558     /* Case 3: A scan using an index.
83559     **
83560     **         The WHERE clause may contain zero or more equality 
83561     **         terms ("==" or "IN" operators) that refer to the N
83562     **         left-most columns of the index. It may also contain
83563     **         inequality constraints (>, <, >= or <=) on the indexed
83564     **         column that immediately follows the N equalities. Only 
83565     **         the right-most column can be an inequality - the rest must
83566     **         use the "==" and "IN" operators. For example, if the 
83567     **         index is on (x,y,z), then the following clauses are all 
83568     **         optimized:
83569     **
83570     **            x=5
83571     **            x=5 AND y=10
83572     **            x=5 AND y<10
83573     **            x=5 AND y>5 AND y<10
83574     **            x=5 AND y=5 AND z<=10
83575     **
83576     **         The z<10 term of the following cannot be used, only
83577     **         the x=5 term:
83578     **
83579     **            x=5 AND z<10
83580     **
83581     **         N may be zero if there are inequality constraints.
83582     **         If there are no inequality constraints, then N is at
83583     **         least one.
83584     **
83585     **         This case is also used when there are no WHERE clause
83586     **         constraints but an index is selected anyway, in order
83587     **         to force the output order to conform to an ORDER BY.
83588     */  
83589     int aStartOp[] = {
83590       0,
83591       0,
83592       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
83593       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
83594       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
83595       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
83596       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
83597       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
83598     };
83599     int aEndOp[] = {
83600       OP_Noop,             /* 0: (!end_constraints) */
83601       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
83602       OP_IdxLT             /* 2: (end_constraints && bRev) */
83603     };
83604     int nEq = pLevel->plan.nEq;
83605     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
83606     int regBase;                 /* Base register holding constraint values */
83607     int r1;                      /* Temp register */
83608     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
83609     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
83610     int startEq;                 /* True if range start uses ==, >= or <= */
83611     int endEq;                   /* True if range end uses ==, >= or <= */
83612     int start_constraints;       /* Start of range is constrained */
83613     int nConstraint;             /* Number of constraint terms */
83614     Index *pIdx;         /* The index we will be using */
83615     int iIdxCur;         /* The VDBE cursor for the index */
83616     int nExtraReg = 0;   /* Number of extra registers needed */
83617     int op;              /* Instruction opcode */
83618
83619     pIdx = pLevel->plan.u.pIdx;
83620     iIdxCur = pLevel->iIdxCur;
83621     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
83622
83623     /* If this loop satisfies a sort order (pOrderBy) request that 
83624     ** was passed to this function to implement a "SELECT min(x) ..." 
83625     ** query, then the caller will only allow the loop to run for
83626     ** a single iteration. This means that the first row returned
83627     ** should not have a NULL value stored in 'x'. If column 'x' is
83628     ** the first one after the nEq equality constraints in the index,
83629     ** this requires some special handling.
83630     */
83631     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
83632      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
83633      && (pIdx->nColumn>nEq)
83634     ){
83635       /* assert( pOrderBy->nExpr==1 ); */
83636       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
83637       isMinQuery = 1;
83638       nExtraReg = 1;
83639     }
83640
83641     /* Find any inequality constraint terms for the start and end 
83642     ** of the range. 
83643     */
83644     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
83645       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
83646       nExtraReg = 1;
83647     }
83648     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
83649       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
83650       nExtraReg = 1;
83651     }
83652
83653     /* Generate code to evaluate all constraint terms using == or IN
83654     ** and store the values of those terms in an array of registers
83655     ** starting at regBase.
83656     */
83657     regBase = codeAllEqualityTerms(pParse, pLevel, pWC, notReady, nExtraReg);
83658     addrNxt = pLevel->addrNxt;
83659
83660
83661     /* If we are doing a reverse order scan on an ascending index, or
83662     ** a forward order scan on a descending index, interchange the 
83663     ** start and end terms (pRangeStart and pRangeEnd).
83664     */
83665     if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
83666       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
83667     }
83668
83669     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
83670     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
83671     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
83672     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
83673     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
83674     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
83675     start_constraints = pRangeStart || nEq>0;
83676
83677     /* Seek the index cursor to the start of the range. */
83678     nConstraint = nEq;
83679     if( pRangeStart ){
83680       int dcc = pParse->disableColCache;
83681       if( pRangeEnd ){
83682         pParse->disableColCache++;
83683       }
83684       sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
83685       pParse->disableColCache = dcc;
83686       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
83687       nConstraint++;
83688     }else if( isMinQuery ){
83689       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
83690       nConstraint++;
83691       startEq = 0;
83692       start_constraints = 1;
83693     }
83694     codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
83695     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
83696     assert( op!=0 );
83697     testcase( op==OP_Rewind );
83698     testcase( op==OP_Last );
83699     testcase( op==OP_SeekGt );
83700     testcase( op==OP_SeekGe );
83701     testcase( op==OP_SeekLe );
83702     testcase( op==OP_SeekLt );
83703     sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase, 
83704                       SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
83705
83706     /* Load the value for the inequality constraint at the end of the
83707     ** range (if any).
83708     */
83709     nConstraint = nEq;
83710     if( pRangeEnd ){
83711       sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
83712       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
83713       codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
83714       nConstraint++;
83715     }
83716
83717     /* Top of the loop body */
83718     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
83719
83720     /* Check if the index cursor is past the end of the range. */
83721     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
83722     testcase( op==OP_Noop );
83723     testcase( op==OP_IdxGE );
83724     testcase( op==OP_IdxLT );
83725     if( op!=OP_Noop ){
83726       sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
83727                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
83728       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
83729     }
83730
83731     /* If there are inequality constraints, check that the value
83732     ** of the table column that the inequality contrains is not NULL.
83733     ** If it is, jump to the next iteration of the loop.
83734     */
83735     r1 = sqlite3GetTempReg(pParse);
83736     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
83737     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
83738     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
83739       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
83740       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
83741     }
83742
83743     /* Seek the table cursor, if required */
83744     disableTerm(pLevel, pRangeStart);
83745     disableTerm(pLevel, pRangeEnd);
83746     codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83747     if( !omitTable || codeRowSetEarly ){
83748       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
83749       if( codeRowSetEarly ){
83750         sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83751       }else{
83752         sqlite3VdbeAddOp2(v, OP_Seek, iCur, r1);  /* Deferred seek */
83753       }
83754     }
83755     sqlite3ReleaseTempReg(pParse, r1);
83756
83757     /* Record the instruction used to terminate the loop. Disable 
83758     ** WHERE clause terms made redundant by the index range scan.
83759     */
83760     pLevel->op = bRev ? OP_Prev : OP_Next;
83761     pLevel->p1 = iIdxCur;
83762   }else
83763
83764 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
83765   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
83766     /* Case 4:  Two or more separately indexed terms connected by OR
83767     **
83768     ** Example:
83769     **
83770     **   CREATE TABLE t1(a,b,c,d);
83771     **   CREATE INDEX i1 ON t1(a);
83772     **   CREATE INDEX i2 ON t1(b);
83773     **   CREATE INDEX i3 ON t1(c);
83774     **
83775     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
83776     **
83777     ** In the example, there are three indexed terms connected by OR.
83778     ** The top of the loop is constructed by creating a RowSet object
83779     ** and populating it.  Then looping over elements of the rowset.
83780     **
83781     **        Null 1
83782     **        # fill RowSet 1 with entries where a=5 using i1
83783     **        # fill Rowset 1 with entries where b=7 using i2
83784     **        # fill Rowset 1 with entries where c=11 and d=13 i3 and t1
83785     **     A: RowSetRead 1, B, 2
83786     **        Seek       i, 2
83787     **
83788     ** The bottom of the loop looks like this:
83789     **
83790     **        Goto       0, A
83791     **     B:
83792     */
83793     int regOrRowset;       /* Register holding the RowSet object */
83794     int regNextRowid;      /* Register holding next rowid */
83795     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
83796     WhereTerm *pOrTerm;    /* A single subterm within the OR-clause */
83797     SrcList oneTab;        /* Shortened table list */
83798    
83799     pTerm = pLevel->plan.u.pTerm;
83800     assert( pTerm!=0 );
83801     assert( pTerm->eOperator==WO_OR );
83802     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
83803     pOrWc = &pTerm->u.pOrInfo->wc;
83804     codeRowSetEarly = (regRowSet>=0 && pWC->nTerm==1) ?1:0;
83805
83806     if( codeRowSetEarly ){
83807       regOrRowset = regRowSet;
83808     }else{
83809       regOrRowset = sqlite3GetTempReg(pParse);
83810       sqlite3VdbeAddOp2(v, OP_Null, 0, regOrRowset);
83811     }
83812     oneTab.nSrc = 1;
83813     oneTab.nAlloc = 1;
83814     oneTab.a[0] = *pTabItem;
83815     for(j=0, pOrTerm=pOrWc->a; j<pOrWc->nTerm; j++, pOrTerm++){
83816       WhereInfo *pSubWInfo;
83817       if( pOrTerm->leftCursor!=iCur && pOrTerm->eOperator!=WO_AND ) continue;
83818       pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
83819                         WHERE_FILL_ROWSET | WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE,
83820                         regOrRowset);
83821       if( pSubWInfo ){
83822         sqlite3WhereEnd(pSubWInfo);
83823       }
83824     }
83825     sqlite3VdbeResolveLabel(v, addrCont);
83826     if( !codeRowSetEarly ){
83827       regNextRowid = sqlite3GetTempReg(pParse);
83828       addrCont = 
83829          sqlite3VdbeAddOp3(v, OP_RowSetRead, regOrRowset,addrBrk,regNextRowid);
83830       sqlite3VdbeAddOp2(v, OP_Seek, iCur, regNextRowid);
83831       sqlite3ReleaseTempReg(pParse, regNextRowid);
83832       /* sqlite3ReleaseTempReg(pParse, regOrRowset); // Preserve the RowSet */
83833       pLevel->op = OP_Goto;
83834       pLevel->p2 = addrCont;
83835     }else{
83836       pLevel->op = OP_Noop;
83837     }
83838     disableTerm(pLevel, pTerm);
83839   }else
83840 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
83841
83842   {
83843     /* Case 5:  There is no usable index.  We must do a complete
83844     **          scan of the entire table.
83845     */
83846     assert( omitTable==0 );
83847     assert( bRev==0 );
83848     pLevel->op = OP_Next;
83849     pLevel->p1 = iCur;
83850     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addrBrk);
83851     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
83852     codeRowSetEarly = 0;
83853   }
83854   notReady &= ~getMask(pWC->pMaskSet, iCur);
83855
83856   /* Insert code to test every subexpression that can be completely
83857   ** computed using the current set of tables.
83858   */
83859   k = 0;
83860   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
83861     Expr *pE;
83862     testcase( pTerm->wtFlags & TERM_VIRTUAL );
83863     testcase( pTerm->wtFlags & TERM_CODED );
83864     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
83865     if( (pTerm->prereqAll & notReady)!=0 ) continue;
83866     pE = pTerm->pExpr;
83867     assert( pE!=0 );
83868     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
83869       continue;
83870     }
83871     pParse->disableColCache += k;
83872     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
83873     pParse->disableColCache -= k;
83874     k = 1;
83875     pTerm->wtFlags |= TERM_CODED;
83876   }
83877
83878   /* For a LEFT OUTER JOIN, generate code that will record the fact that
83879   ** at least one row of the right table has matched the left table.  
83880   */
83881   if( pLevel->iLeftJoin ){
83882     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
83883     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
83884     VdbeComment((v, "record LEFT JOIN hit"));
83885     sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
83886     sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
83887     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
83888       testcase( pTerm->wtFlags & TERM_VIRTUAL );
83889       testcase( pTerm->wtFlags & TERM_CODED );
83890       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
83891       if( (pTerm->prereqAll & notReady)!=0 ) continue;
83892       assert( pTerm->pExpr );
83893       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
83894       pTerm->wtFlags |= TERM_CODED;
83895     }
83896   }
83897
83898   /*
83899   ** If it was requested to store the results in a rowset and that has
83900   ** not already been do, then do so now.
83901   */
83902   if( regRowSet>=0 && !codeRowSetEarly ){
83903     int r1 = sqlite3GetTempReg(pParse);
83904 #ifndef SQLITE_OMIT_VIRTUALTABLE
83905     if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
83906       sqlite3VdbeAddOp2(v, OP_VRowid, iCur, r1);
83907     }else
83908 #endif
83909     {
83910       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83911     }
83912     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83913     sqlite3ReleaseTempReg(pParse, r1);
83914   }
83915
83916   return notReady;
83917 }
83918
83919 #if defined(SQLITE_TEST)
83920 /*
83921 ** The following variable holds a text description of query plan generated
83922 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
83923 ** overwrites the previous.  This information is used for testing and
83924 ** analysis only.
83925 */
83926 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
83927 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
83928
83929 #endif /* SQLITE_TEST */
83930
83931
83932 /*
83933 ** Free a WhereInfo structure
83934 */
83935 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
83936   if( pWInfo ){
83937     int i;
83938     for(i=0; i<pWInfo->nLevel; i++){
83939       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
83940       if( pInfo ){
83941         assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed );
83942         if( pInfo->needToFreeIdxStr ){
83943           sqlite3_free(pInfo->idxStr);
83944         }
83945         sqlite3DbFree(db, pInfo);
83946       }
83947     }
83948     whereClauseClear(pWInfo->pWC);
83949     sqlite3DbFree(db, pWInfo);
83950   }
83951 }
83952
83953
83954 /*
83955 ** Generate the beginning of the loop used for WHERE clause processing.
83956 ** The return value is a pointer to an opaque structure that contains
83957 ** information needed to terminate the loop.  Later, the calling routine
83958 ** should invoke sqlite3WhereEnd() with the return value of this function
83959 ** in order to complete the WHERE clause processing.
83960 **
83961 ** If an error occurs, this routine returns NULL.
83962 **
83963 ** The basic idea is to do a nested loop, one loop for each table in
83964 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
83965 ** same as a SELECT with only a single table in the FROM clause.)  For
83966 ** example, if the SQL is this:
83967 **
83968 **       SELECT * FROM t1, t2, t3 WHERE ...;
83969 **
83970 ** Then the code generated is conceptually like the following:
83971 **
83972 **      foreach row1 in t1 do       \    Code generated
83973 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
83974 **          foreach row3 in t3 do   /
83975 **            ...
83976 **          end                     \    Code generated
83977 **        end                        |-- by sqlite3WhereEnd()
83978 **      end                         /
83979 **
83980 ** Note that the loops might not be nested in the order in which they
83981 ** appear in the FROM clause if a different order is better able to make
83982 ** use of indices.  Note also that when the IN operator appears in
83983 ** the WHERE clause, it might result in additional nested loops for
83984 ** scanning through all values on the right-hand side of the IN.
83985 **
83986 ** There are Btree cursors associated with each table.  t1 uses cursor
83987 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
83988 ** And so forth.  This routine generates code to open those VDBE cursors
83989 ** and sqlite3WhereEnd() generates the code to close them.
83990 **
83991 ** The code that sqlite3WhereBegin() generates leaves the cursors named
83992 ** in pTabList pointing at their appropriate entries.  The [...] code
83993 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
83994 ** data from the various tables of the loop.
83995 **
83996 ** If the WHERE clause is empty, the foreach loops must each scan their
83997 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
83998 ** the tables have indices and there are terms in the WHERE clause that
83999 ** refer to those indices, a complete table scan can be avoided and the
84000 ** code will run much faster.  Most of the work of this routine is checking
84001 ** to see if there are indices that can be used to speed up the loop.
84002 **
84003 ** Terms of the WHERE clause are also used to limit which rows actually
84004 ** make it to the "..." in the middle of the loop.  After each "foreach",
84005 ** terms of the WHERE clause that use only terms in that loop and outer
84006 ** loops are evaluated and if false a jump is made around all subsequent
84007 ** inner loops (or around the "..." if the test occurs within the inner-
84008 ** most loop)
84009 **
84010 ** OUTER JOINS
84011 **
84012 ** An outer join of tables t1 and t2 is conceptally coded as follows:
84013 **
84014 **    foreach row1 in t1 do
84015 **      flag = 0
84016 **      foreach row2 in t2 do
84017 **        start:
84018 **          ...
84019 **          flag = 1
84020 **      end
84021 **      if flag==0 then
84022 **        move the row2 cursor to a null row
84023 **        goto start
84024 **      fi
84025 **    end
84026 **
84027 ** ORDER BY CLAUSE PROCESSING
84028 **
84029 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
84030 ** if there is one.  If there is no ORDER BY clause or if this routine
84031 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
84032 **
84033 ** If an index can be used so that the natural output order of the table
84034 ** scan is correct for the ORDER BY clause, then that index is used and
84035 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
84036 ** unnecessary sort of the result set if an index appropriate for the
84037 ** ORDER BY clause already exists.
84038 **
84039 ** If the where clause loops cannot be arranged to provide the correct
84040 ** output order, then the *ppOrderBy is unchanged.
84041 */
84042 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
84043   Parse *pParse,        /* The parser context */
84044   SrcList *pTabList,    /* A list of all tables to be scanned */
84045   Expr *pWhere,         /* The WHERE clause */
84046   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
84047   u8 wctrlFlags,        /* One of the WHERE_* flags defined in sqliteInt.h */
84048   int regRowSet         /* Register hold RowSet if WHERE_FILL_ROWSET is set */
84049 ){
84050   int i;                     /* Loop counter */
84051   WhereInfo *pWInfo;         /* Will become the return value of this function */
84052   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
84053   Bitmask notReady;          /* Cursors that are not yet positioned */
84054   WhereMaskSet *pMaskSet;    /* The expression mask set */
84055   WhereClause *pWC;               /* Decomposition of the WHERE clause */
84056   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
84057   WhereLevel *pLevel;             /* A single level in the pWInfo list */
84058   int iFrom;                      /* First unused FROM clause element */
84059   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
84060   sqlite3 *db;               /* Database connection */
84061   ExprList *pOrderBy = 0;
84062
84063   /* The number of tables in the FROM clause is limited by the number of
84064   ** bits in a Bitmask 
84065   */
84066   if( pTabList->nSrc>BMS ){
84067     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
84068     return 0;
84069   }
84070
84071   if( ppOrderBy ){
84072     pOrderBy = *ppOrderBy;
84073   }
84074
84075   /* Allocate and initialize the WhereInfo structure that will become the
84076   ** return value.
84077   */
84078   db = pParse->db;
84079   pWInfo = sqlite3DbMallocZero(db,  
84080                       sizeof(WhereInfo)
84081                       + (pTabList->nSrc-1)*sizeof(WhereLevel)
84082                       + sizeof(WhereClause)
84083                       + sizeof(WhereMaskSet)
84084            );
84085   if( db->mallocFailed ){
84086     goto whereBeginError;
84087   }
84088   pWInfo->nLevel = pTabList->nSrc;
84089   pWInfo->pParse = pParse;
84090   pWInfo->pTabList = pTabList;
84091   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
84092   pWInfo->regRowSet = (wctrlFlags & WHERE_FILL_ROWSET) ? regRowSet : -1;
84093   pWInfo->pWC = pWC = (WhereClause*)&pWInfo->a[pWInfo->nLevel];
84094   pWInfo->wctrlFlags = wctrlFlags;
84095   pMaskSet = (WhereMaskSet*)&pWC[1];
84096
84097   /* Split the WHERE clause into separate subexpressions where each
84098   ** subexpression is separated by an AND operator.
84099   */
84100   initMaskSet(pMaskSet);
84101   whereClauseInit(pWC, pParse, pMaskSet);
84102   sqlite3ExprCodeConstants(pParse, pWhere);
84103   whereSplit(pWC, pWhere, TK_AND);
84104     
84105   /* Special case: a WHERE clause that is constant.  Evaluate the
84106   ** expression and either jump over all of the code or fall thru.
84107   */
84108   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
84109     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
84110     pWhere = 0;
84111   }
84112
84113   /* Assign a bit from the bitmask to every term in the FROM clause.
84114   **
84115   ** When assigning bitmask values to FROM clause cursors, it must be
84116   ** the case that if X is the bitmask for the N-th FROM clause term then
84117   ** the bitmask for all FROM clause terms to the left of the N-th term
84118   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
84119   ** its Expr.iRightJoinTable value to find the bitmask of the right table
84120   ** of the join.  Subtracting one from the right table bitmask gives a
84121   ** bitmask for all tables to the left of the join.  Knowing the bitmask
84122   ** for all tables to the left of a left join is important.  Ticket #3015.
84123   */
84124   for(i=0; i<pTabList->nSrc; i++){
84125     createMask(pMaskSet, pTabList->a[i].iCursor);
84126   }
84127 #ifndef NDEBUG
84128   {
84129     Bitmask toTheLeft = 0;
84130     for(i=0; i<pTabList->nSrc; i++){
84131       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
84132       assert( (m-1)==toTheLeft );
84133       toTheLeft |= m;
84134     }
84135   }
84136 #endif
84137
84138   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
84139   ** add new virtual terms onto the end of the WHERE clause.  We do not
84140   ** want to analyze these virtual terms, so start analyzing at the end
84141   ** and work forward so that the added virtual terms are never processed.
84142   */
84143   exprAnalyzeAll(pTabList, pWC);
84144   if( db->mallocFailed ){
84145     goto whereBeginError;
84146   }
84147
84148   /* Chose the best index to use for each table in the FROM clause.
84149   **
84150   ** This loop fills in the following fields:
84151   **
84152   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
84153   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
84154   **   pWInfo->a[].nEq       The number of == and IN constraints
84155   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
84156   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
84157   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
84158   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
84159   **
84160   ** This loop also figures out the nesting order of tables in the FROM
84161   ** clause.
84162   */
84163   notReady = ~(Bitmask)0;
84164   pTabItem = pTabList->a;
84165   pLevel = pWInfo->a;
84166   andFlags = ~0;
84167   WHERETRACE(("*** Optimizer Start ***\n"));
84168   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
84169     WhereCost bestPlan;         /* Most efficient plan seen so far */
84170     Index *pIdx;                /* Index for FROM table at pTabItem */
84171     int j;                      /* For looping over FROM tables */
84172     int bestJ = 0;              /* The value of j */
84173     Bitmask m;                  /* Bitmask value for j or bestJ */
84174     int once = 0;               /* True when first table is seen */
84175
84176     memset(&bestPlan, 0, sizeof(bestPlan));
84177     bestPlan.rCost = SQLITE_BIG_DBL;
84178     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
84179       int doNotReorder;  /* True if this table should not be reordered */
84180       WhereCost sCost;   /* Cost information from bestIndex() */
84181
84182       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
84183       if( once && doNotReorder ) break;
84184       m = getMask(pMaskSet, pTabItem->iCursor);
84185       if( (m & notReady)==0 ){
84186         if( j==iFrom ) iFrom++;
84187         continue;
84188       }
84189       assert( pTabItem->pTab );
84190 #ifndef SQLITE_OMIT_VIRTUALTABLE
84191       if( IsVirtual(pTabItem->pTab) ){
84192         sqlite3_index_info *pVtabIdx; /* Current virtual index */
84193         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
84194         sCost.rCost = bestVirtualIndex(pParse, pWC, pTabItem, notReady,
84195                                        ppOrderBy ? *ppOrderBy : 0, i==0,
84196                                        ppIdxInfo);
84197         sCost.plan.wsFlags = WHERE_VIRTUALTABLE;
84198         sCost.plan.u.pVtabIdx = pVtabIdx = *ppIdxInfo;
84199         if( pVtabIdx && pVtabIdx->orderByConsumed ){
84200           sCost.plan.wsFlags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
84201         }
84202         sCost.plan.nEq = 0;
84203         /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84204         if( (SQLITE_BIG_DBL/((double)2))<sCost.rCost ){
84205           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
84206           ** inital value of lowestCost in this loop. If it is, then
84207           ** the (cost<lowestCost) test below will never be true.
84208           */ 
84209           /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84210           sCost.rCost = (SQLITE_BIG_DBL/((double)2));
84211         }
84212       }else 
84213 #endif
84214       {
84215         bestIndex(pParse, pWC, pTabItem, notReady,
84216                   (i==0 && ppOrderBy) ? *ppOrderBy : 0, &sCost);
84217       }
84218       if( once==0 || sCost.rCost<bestPlan.rCost ){
84219         once = 1;
84220         bestPlan = sCost;
84221         bestJ = j;
84222       }
84223       if( doNotReorder ) break;
84224     }
84225     assert( once );
84226     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
84227     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
84228            pLevel-pWInfo->a));
84229     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
84230       *ppOrderBy = 0;
84231     }
84232     andFlags &= bestPlan.plan.wsFlags;
84233     pLevel->plan = bestPlan.plan;
84234     if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
84235       pLevel->iIdxCur = pParse->nTab++;
84236     }else{
84237       pLevel->iIdxCur = -1;
84238     }
84239     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
84240     pLevel->iFrom = (u8)bestJ;
84241
84242     /* Check that if the table scanned by this loop iteration had an
84243     ** INDEXED BY clause attached to it, that the named index is being
84244     ** used for the scan. If not, then query compilation has failed.
84245     ** Return an error.
84246     */
84247     pIdx = pTabList->a[bestJ].pIndex;
84248     if( pIdx ){
84249       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
84250         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
84251         goto whereBeginError;
84252       }else{
84253         /* If an INDEXED BY clause is used, the bestIndex() function is
84254         ** guaranteed to find the index specified in the INDEXED BY clause
84255         ** if it find an index at all. */
84256         assert( bestPlan.plan.u.pIdx==pIdx );
84257       }
84258     }
84259   }
84260   WHERETRACE(("*** Optimizer Finished ***\n"));
84261   if( db->mallocFailed ){
84262     goto whereBeginError;
84263   }
84264
84265   /* If the total query only selects a single row, then the ORDER BY
84266   ** clause is irrelevant.
84267   */
84268   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
84269     *ppOrderBy = 0;
84270   }
84271
84272   /* If the caller is an UPDATE or DELETE statement that is requesting
84273   ** to use a one-pass algorithm, determine if this is appropriate.
84274   ** The one-pass algorithm only works if the WHERE clause constraints
84275   ** the statement to update a single row.
84276   */
84277   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
84278   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
84279     pWInfo->okOnePass = 1;
84280     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
84281   }
84282
84283   /* Open all tables in the pTabList and any indices selected for
84284   ** searching those tables.
84285   */
84286   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
84287   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
84288     Table *pTab;     /* Table to open */
84289     int iDb;         /* Index of database containing table/index */
84290
84291 #ifndef SQLITE_OMIT_EXPLAIN
84292     if( pParse->explain==2 ){
84293       char *zMsg;
84294       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
84295       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
84296       if( pItem->zAlias ){
84297         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
84298       }
84299       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
84300         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
84301            zMsg, pLevel->plan.u.pIdx->zName);
84302       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
84303         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
84304       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
84305         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
84306       }
84307 #ifndef SQLITE_OMIT_VIRTUALTABLE
84308       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
84309         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
84310         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
84311                     pVtabIdx->idxNum, pVtabIdx->idxStr);
84312       }
84313 #endif
84314       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
84315         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
84316       }
84317       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
84318     }
84319 #endif /* SQLITE_OMIT_EXPLAIN */
84320     pTabItem = &pTabList->a[pLevel->iFrom];
84321     pTab = pTabItem->pTab;
84322     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84323     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
84324 #ifndef SQLITE_OMIT_VIRTUALTABLE
84325     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
84326       int iCur = pTabItem->iCursor;
84327       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
84328                         (const char*)pTab->pVtab, P4_VTAB);
84329     }else
84330 #endif
84331     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
84332          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
84333       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
84334       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
84335       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
84336         Bitmask b = pTabItem->colUsed;
84337         int n = 0;
84338         for(; b; b=b>>1, n++){}
84339         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n);
84340         assert( n<=pTab->nCol );
84341       }
84342     }else{
84343       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
84344     }
84345     pLevel->iTabCur = pTabItem->iCursor;
84346     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
84347       Index *pIx = pLevel->plan.u.pIdx;
84348       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
84349       int iIdxCur = pLevel->iIdxCur;
84350       assert( pIx->pSchema==pTab->pSchema );
84351       assert( iIdxCur>=0 );
84352       sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1);
84353       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
84354                         (char*)pKey, P4_KEYINFO_HANDOFF);
84355       VdbeComment((v, "%s", pIx->zName));
84356     }
84357     sqlite3CodeVerifySchema(pParse, iDb);
84358   }
84359   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
84360
84361   /* Generate the code to do the search.  Each iteration of the for
84362   ** loop below generates code for a single nested loop of the VM
84363   ** program.
84364   */
84365   notReady = ~(Bitmask)0;
84366   for(i=0; i<pTabList->nSrc; i++){
84367     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
84368     pWInfo->iContinue = pWInfo->a[i].addrCont;
84369   }
84370
84371 #ifdef SQLITE_TEST  /* For testing and debugging use only */
84372   /* Record in the query plan information about the current table
84373   ** and the index used to access it (if any).  If the table itself
84374   ** is not used, its name is just '{}'.  If no index is used
84375   ** the index is listed as "{}".  If the primary key is used the
84376   ** index name is '*'.
84377   */
84378   for(i=0; i<pTabList->nSrc; i++){
84379     char *z;
84380     int n;
84381     pLevel = &pWInfo->a[i];
84382     pTabItem = &pTabList->a[pLevel->iFrom];
84383     z = pTabItem->zAlias;
84384     if( z==0 ) z = pTabItem->pTab->zName;
84385     n = sqlite3Strlen30(z);
84386     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
84387       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
84388         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
84389         nQPlan += 2;
84390       }else{
84391         memcpy(&sqlite3_query_plan[nQPlan], z, n);
84392         nQPlan += n;
84393       }
84394       sqlite3_query_plan[nQPlan++] = ' ';
84395     }
84396     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
84397     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
84398     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
84399       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
84400       nQPlan += 2;
84401     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
84402       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
84403       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
84404         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
84405         nQPlan += n;
84406         sqlite3_query_plan[nQPlan++] = ' ';
84407       }
84408     }else{
84409       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
84410       nQPlan += 3;
84411     }
84412   }
84413   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
84414     sqlite3_query_plan[--nQPlan] = 0;
84415   }
84416   sqlite3_query_plan[nQPlan] = 0;
84417   nQPlan = 0;
84418 #endif /* SQLITE_TEST // Testing and debugging use only */
84419
84420   /* Record the continuation address in the WhereInfo structure.  Then
84421   ** clean up and return.
84422   */
84423   return pWInfo;
84424
84425   /* Jump here if malloc fails */
84426 whereBeginError:
84427   whereInfoFree(db, pWInfo);
84428   return 0;
84429 }
84430
84431 /*
84432 ** Generate the end of the WHERE loop.  See comments on 
84433 ** sqlite3WhereBegin() for additional information.
84434 */
84435 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
84436   Parse *pParse = pWInfo->pParse;
84437   Vdbe *v = pParse->pVdbe;
84438   int i;
84439   WhereLevel *pLevel;
84440   SrcList *pTabList = pWInfo->pTabList;
84441   sqlite3 *db = pParse->db;
84442
84443   /* Generate loop termination code.
84444   */
84445   sqlite3ExprClearColumnCache(pParse, -1);
84446   for(i=pTabList->nSrc-1; i>=0; i--){
84447     pLevel = &pWInfo->a[i];
84448     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
84449     if( pLevel->op!=OP_Noop ){
84450       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
84451       sqlite3VdbeChangeP5(v, pLevel->p5);
84452     }
84453     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
84454       struct InLoop *pIn;
84455       int j;
84456       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
84457       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
84458         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
84459         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
84460         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
84461       }
84462       sqlite3DbFree(db, pLevel->u.in.aInLoop);
84463     }
84464     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
84465     if( pLevel->iLeftJoin ){
84466       int addr;
84467       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
84468       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
84469       if( pLevel->iIdxCur>=0 ){
84470         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
84471       }
84472       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
84473       sqlite3VdbeJumpHere(v, addr);
84474     }
84475   }
84476
84477   /* The "break" point is here, just past the end of the outer loop.
84478   ** Set it.
84479   */
84480   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
84481
84482   /* Close all of the cursors that were opened by sqlite3WhereBegin.
84483   */
84484   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
84485     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
84486     Table *pTab = pTabItem->pTab;
84487     assert( pTab!=0 );
84488     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
84489     if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
84490       if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
84491         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
84492       }
84493       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
84494         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
84495       }
84496     }
84497
84498     /* If this scan uses an index, make code substitutions to read data
84499     ** from the index in preference to the table. Sometimes, this means
84500     ** the table need never be read from. This is a performance boost,
84501     ** as the vdbe level waits until the table is read before actually
84502     ** seeking the table cursor to the record corresponding to the current
84503     ** position in the index.
84504     ** 
84505     ** Calls to the code generator in between sqlite3WhereBegin and
84506     ** sqlite3WhereEnd will have created code that references the table
84507     ** directly.  This loop scans all that code looking for opcodes
84508     ** that reference the table and converts them into opcodes that
84509     ** reference the index.
84510     */
84511     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
84512       int k, j, last;
84513       VdbeOp *pOp;
84514       Index *pIdx = pLevel->plan.u.pIdx;
84515       int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;
84516
84517       assert( pIdx!=0 );
84518       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
84519       last = sqlite3VdbeCurrentAddr(v);
84520       for(k=pWInfo->iTop; k<last; k++, pOp++){
84521         if( pOp->p1!=pLevel->iTabCur ) continue;
84522         if( pOp->opcode==OP_Column ){
84523           for(j=0; j<pIdx->nColumn; j++){
84524             if( pOp->p2==pIdx->aiColumn[j] ){
84525               pOp->p2 = j;
84526               pOp->p1 = pLevel->iIdxCur;
84527               break;
84528             }
84529           }
84530           assert(!useIndexOnly || j<pIdx->nColumn);
84531         }else if( pOp->opcode==OP_Rowid ){
84532           pOp->p1 = pLevel->iIdxCur;
84533           pOp->opcode = OP_IdxRowid;
84534         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
84535           pOp->opcode = OP_Noop;
84536         }
84537       }
84538     }
84539   }
84540
84541   /* Final cleanup
84542   */
84543   whereInfoFree(db, pWInfo);
84544   return;
84545 }
84546
84547 /************** End of where.c ***********************************************/
84548 /************** Begin file parse.c *******************************************/
84549 /* Driver template for the LEMON parser generator.
84550 ** The author disclaims copyright to this source code.
84551 */
84552 /* First off, code is included that follows the "include" declaration
84553 ** in the input grammar file. */
84554
84555
84556 /*
84557 ** An instance of this structure holds information about the
84558 ** LIMIT clause of a SELECT statement.
84559 */
84560 struct LimitVal {
84561   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
84562   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
84563 };
84564
84565 /*
84566 ** An instance of this structure is used to store the LIKE,
84567 ** GLOB, NOT LIKE, and NOT GLOB operators.
84568 */
84569 struct LikeOp {
84570   Token eOperator;  /* "like" or "glob" or "regexp" */
84571   int not;         /* True if the NOT keyword is present */
84572 };
84573
84574 /*
84575 ** An instance of the following structure describes the event of a
84576 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
84577 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
84578 **
84579 **      UPDATE ON (a,b,c)
84580 **
84581 ** Then the "b" IdList records the list "a,b,c".
84582 */
84583 struct TrigEvent { int a; IdList * b; };
84584
84585 /*
84586 ** An instance of this structure holds the ATTACH key and the key type.
84587 */
84588 struct AttachKey { int type;  Token key; };
84589
84590 /* Next is all token values, in a form suitable for use by makeheaders.
84591 ** This section will be null unless lemon is run with the -m switch.
84592 */
84593 /* 
84594 ** These constants (all generated automatically by the parser generator)
84595 ** specify the various kinds of tokens (terminals) that the parser
84596 ** understands. 
84597 **
84598 ** Each symbol here is a terminal symbol in the grammar.
84599 */
84600 /* Make sure the INTERFACE macro is defined.
84601 */
84602 #ifndef INTERFACE
84603 # define INTERFACE 1
84604 #endif
84605 /* The next thing included is series of defines which control
84606 ** various aspects of the generated parser.
84607 **    YYCODETYPE         is the data type used for storing terminal
84608 **                       and nonterminal numbers.  "unsigned char" is
84609 **                       used if there are fewer than 250 terminals
84610 **                       and nonterminals.  "int" is used otherwise.
84611 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
84612 **                       to no legal terminal or nonterminal number.  This
84613 **                       number is used to fill in empty slots of the hash 
84614 **                       table.
84615 **    YYFALLBACK         If defined, this indicates that one or more tokens
84616 **                       have fall-back values which should be used if the
84617 **                       original value of the token will not parse.
84618 **    YYACTIONTYPE       is the data type used for storing terminal
84619 **                       and nonterminal numbers.  "unsigned char" is
84620 **                       used if there are fewer than 250 rules and
84621 **                       states combined.  "int" is used otherwise.
84622 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
84623 **                       directly to the parser from the tokenizer.
84624 **    YYMINORTYPE        is the data type used for all minor tokens.
84625 **                       This is typically a union of many types, one of
84626 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
84627 **                       for base tokens is called "yy0".
84628 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
84629 **                       zero the stack is dynamically sized using realloc()
84630 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
84631 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
84632 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
84633 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
84634 **    YYNSTATE           the combined number of states.
84635 **    YYNRULE            the number of rules in the grammar
84636 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
84637 **                       defined, then do no error processing.
84638 */
84639 #define YYCODETYPE unsigned char
84640 #define YYNOCODE 251
84641 #define YYACTIONTYPE unsigned short int
84642 #define YYWILDCARD 64
84643 #define sqlite3ParserTOKENTYPE Token
84644 typedef union {
84645   int yyinit;
84646   sqlite3ParserTOKENTYPE yy0;
84647   struct LimitVal yy64;
84648   Expr* yy122;
84649   Select* yy159;
84650   IdList* yy180;
84651   struct {int value; int mask;} yy207;
84652   struct LikeOp yy318;
84653   TriggerStep* yy327;
84654   SrcList* yy347;
84655   int yy392;
84656   struct TrigEvent yy410;
84657   ExprList* yy442;
84658 } YYMINORTYPE;
84659 #ifndef YYSTACKDEPTH
84660 #define YYSTACKDEPTH 100
84661 #endif
84662 #define sqlite3ParserARG_SDECL Parse *pParse;
84663 #define sqlite3ParserARG_PDECL ,Parse *pParse
84664 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
84665 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
84666 #define YYNSTATE 610
84667 #define YYNRULE 319
84668 #define YYFALLBACK 1
84669 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
84670 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
84671 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
84672
84673 /* The yyzerominor constant is used to initialize instances of
84674 ** YYMINORTYPE objects to zero. */
84675 static const YYMINORTYPE yyzerominor = { 0 };
84676
84677
84678 /* Next are the tables used to determine what action to take based on the
84679 ** current state and lookahead token.  These tables are used to implement
84680 ** functions that take a state number and lookahead value and return an
84681 ** action integer.  
84682 **
84683 ** Suppose the action integer is N.  Then the action is determined as
84684 ** follows
84685 **
84686 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
84687 **                                      token onto the stack and goto state N.
84688 **
84689 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
84690 **
84691 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
84692 **
84693 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
84694 **
84695 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
84696 **                                      slots in the yy_action[] table.
84697 **
84698 ** The action table is constructed as a single large table named yy_action[].
84699 ** Given state S and lookahead X, the action is computed as
84700 **
84701 **      yy_action[ yy_shift_ofst[S] + X ]
84702 **
84703 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
84704 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
84705 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
84706 ** and that yy_default[S] should be used instead.  
84707 **
84708 ** The formula above is for computing the action when the lookahead is
84709 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
84710 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
84711 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
84712 ** YY_SHIFT_USE_DFLT.
84713 **
84714 ** The following are the tables generated in this section:
84715 **
84716 **  yy_action[]        A single table containing all actions.
84717 **  yy_lookahead[]     A table containing the lookahead for each entry in
84718 **                     yy_action.  Used to detect hash collisions.
84719 **  yy_shift_ofst[]    For each state, the offset into yy_action for
84720 **                     shifting terminals.
84721 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
84722 **                     shifting non-terminals after a reduce.
84723 **  yy_default[]       Default action for each state.
84724 */
84725 static const YYACTIONTYPE yy_action[] = {
84726  /*     0 */   304,  930,  120,  609,    1,  178,  264,  436,   62,   62,
84727  /*    10 */    62,   62,  214,   64,   64,   64,   64,   65,   65,   66,
84728  /*    20 */    66,   66,   67,  216,  593,  467,  336,  174,  443,  449,
84729  /*    30 */    69,   64,   64,   64,   64,   65,   65,   66,   66,   66,
84730  /*    40 */    67,  216,  315,  592,  591,  355,   61,   60,  309,  453,
84731  /*    50 */   454,  450,  450,   63,   63,   62,   62,   62,   62,  216,
84732  /*    60 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
84733  /*    70 */   216,  304,  431,  312,  436,  509,  430,   83,   64,   64,
84734  /*    80 */    64,   64,   65,   65,   66,   66,   66,   67,  216,  406,
84735  /*    90 */   403,  411,   65,   65,   66,   66,   66,   67,  216,  443,
84736  /*   100 */   449,  551,  526,   59,  588,  217,  171,   57,  550,  411,
84737  /*   110 */    68,  428,   70,  155,  610,  406,  403,   61,   60,  309,
84738  /*   120 */   453,  454,  450,  450,   63,   63,   62,   62,   62,   62,
84739  /*   130 */   595,   64,   64,   64,   64,   65,   65,   66,   66,   66,
84740  /*   140 */    67,  216,  304,  228,  414,  415,  416,  312,  469,  170,
84741  /*   150 */   114,  256,  357,  261,  358,  181,  330,  562,  412,  413,
84742  /*   160 */   187,  561,  265,  359,  362,  363,  465,  218,  150,  151,
84743  /*   170 */   443,  449,   95,  153,  364,  376,  412,  413,  510,  432,
84744  /*   180 */    36,  492,  438,  411,  465,  218,  589,  590,   61,   60,
84745  /*   190 */   309,  453,  454,  450,  450,   63,   63,   62,   62,   62,
84746  /*   200 */    62,  649,   64,   64,   64,   64,   65,   65,   66,   66,
84747  /*   210 */    66,   67,  216,  304,  440,  440,  440,  228,  109,  264,
84748  /*   220 */   501,  330,  469,  511,  114,  256,  357,  261,  358,  181,
84749  /*   230 */   330,  247,   68,  480,   70,  155,  265,   68,  552,   70,
84750  /*   240 */   155,  443,  449,  187,  432,   35,  359,  362,  363,  569,
84751  /*   250 */   412,  413,  510,  432,   42,  229,  438,  364,  207,   61,
84752  /*   260 */    60,  309,  453,  454,  450,  450,   63,   63,   62,   62,
84753  /*   270 */    62,   62,  264,   64,   64,   64,   64,   65,   65,   66,
84754  /*   280 */    66,   66,   67,  216,  304,  570,  344,  427,  440,  440,
84755  /*   290 */   440,  354,  433,  346,  221,  539,  325,  408,  411,  387,
84756  /*   300 */   282,  281,  213,   66,   66,   66,   67,  216,  316,  206,
84757  /*   310 */   214,  187,  443,  449,  359,  362,  363,  299,  545,    2,
84758  /*   320 */   467,  543,  174,  411,   68,  364,   70,  155,  569,  384,
84759  /*   330 */    61,   60,  309,  453,  454,  450,  450,   63,   63,   62,
84760  /*   340 */    62,   62,   62,  433,   64,   64,   64,   64,   65,   65,
84761  /*   350 */    66,   66,   66,   67,  216,  465,  304,   68,  544,   70,
84762  /*   360 */   155,  426,  542,  593,  330,  412,  413,  394,  425,   20,
84763  /*   370 */   539,  436,  178,  330,  436,  330,  514,  515,  387,  282,
84764  /*   380 */   281,  198,  592,  241,  443,  449,  248,  432,   50,  214,
84765  /*   390 */   412,  413,  152,  553,  402,  230,  432,   42,  432,   35,
84766  /*   400 */   162,   78,   61,   60,  309,  453,  454,  450,  450,   63,
84767  /*   410 */    63,   62,   62,   62,   62,  433,   64,   64,   64,   64,
84768  /*   420 */    65,   65,   66,   66,   66,   67,  216,  330,  304,  198,
84769  /*   430 */   474,  330,  505,  320,  433,  367,  154,  220,  436,  385,
84770  /*   440 */   348,  436,  544,  397,  217,  475,  163,  161,  411,  240,
84771  /*   450 */   432,   28,  554,   20,  432,   50,  443,  449,  307,  341,
84772  /*   460 */   476,  381,  516,  433,  182,  485,  310,  460,  461,   19,
84773  /*   470 */   433,  145,  517,   81,   61,   60,  309,  453,  454,  450,
84774  /*   480 */   450,   63,   63,   62,   62,   62,   62,  385,   64,   64,
84775  /*   490 */    64,   64,   65,   65,   66,   66,   66,   67,  216,  304,
84776  /*   500 */   321,  504,  353,  508,   17,  457,   77,  330,   79,  388,
84777  /*   510 */   335,  460,  461,  470,  512,  412,  413,  411,  123,  306,
84778  /*   520 */   160,  444,  445,  429,  265,  432,    3,  443,  449,  217,
84779  /*   530 */   432,   29,  377,  564,  349,  607,  921,  380,  921,   67,
84780  /*   540 */   216,  488,  447,  448,  492,   61,   60,  309,  453,  454,
84781  /*   550 */   450,  450,   63,   63,   62,   62,   62,   62,  148,   64,
84782  /*   560 */    64,   64,   64,   65,   65,   66,   66,   66,   67,  216,
84783  /*   570 */   304,  446,  389,  217,  525,   23,  492,  604,  124,  411,
84784  /*   580 */   487,  396,  474,  222,  412,  413,  531,  607,  920,  333,
84785  /*   590 */   920,  456,  456,  333,  411,  456,  456,  475,  443,  449,
84786  /*   600 */   214,  333,  286,  456,  456,  249,  333,  532,  456,  456,
84787  /*   610 */   489,  566,  476,  395,  340,  252,   61,   60,  309,  453,
84788  /*   620 */   454,  450,  450,   63,   63,   62,   62,   62,   62,  604,
84789  /*   630 */    64,   64,   64,   64,   65,   65,   66,   66,   66,   67,
84790  /*   640 */   216,  304,  289,  330,  287,  268,  412,  413,  330,  159,
84791  /*   650 */   853,   21,  330,  503,  330,  436,  330,  257,  330,  314,
84792  /*   660 */   330,  412,  413,  182,  567,  515,  432,   24,  258,  443,
84793  /*   670 */   449,  432,   33,  214,  487,  432,   54,  432,   53,  432,
84794  /*   680 */    99,  432,   97,  432,  102,  270,  386,   61,   60,  309,
84795  /*   690 */   453,  454,  450,  450,   63,   63,   62,   62,   62,   62,
84796  /*   700 */   331,   64,   64,   64,   64,   65,   65,   66,   66,   66,
84797  /*   710 */    67,  216,  304,  330,  560,  374,  560,   94,  306,  330,
84798  /*   720 */   234,  330,  436,  288,  330,  274,  330,  272,  330,  333,
84799  /*   730 */   330,  456,  456,  330,  603,  303,  432,  103,  405,    1,
84800  /*   740 */   443,  449,  432,  108,  432,  110,  492,  432,   16,  432,
84801  /*   750 */   100,  432,   34,  432,   98,  496,  432,   25,   61,   60,
84802  /*   760 */   309,  453,  454,  450,  450,   63,   63,   62,   62,   62,
84803  /*   770 */    62,  330,   64,   64,   64,   64,   65,   65,   66,   66,
84804  /*   780 */    66,   67,  216,  304,  330,  254,  330,  183,  184,  185,
84805  /*   790 */   330,  544,  330,  486,  432,   55,  330,  496,  330,  215,
84806  /*   800 */   330,  600,   20,  330,  410,  384,   56,  432,  111,  432,
84807  /*   810 */   112,  443,  449,  432,  113,  432,   26,  311,    5,  432,
84808  /*   820 */    37,  432,   38,  432,   27,  276,  432,   39,  264,   61,
84809  /*   830 */    60,  309,  453,  454,  450,  450,   63,   63,   62,   62,
84810  /*   840 */    62,   62,  330,   64,   64,   64,   64,   65,   65,   66,
84811  /*   850 */    66,   66,   67,  216,  304,  330,  202,  330,  431,  375,
84812  /*   860 */   420,  330,  430,  330,  317,  432,   40,  277,  330,  487,
84813  /*   870 */   330,  233,  330,  421,  330,  177,  161,  496,  432,   41,
84814  /*   880 */   432,   43,  443,  449,  432,   44,  432,   45,  276,  276,
84815  /*   890 */   433,  432,   30,  432,   31,  432,   46,  432,   47,  264,
84816  /*   900 */    61,   71,  309,  453,  454,  450,  450,   63,   63,   62,
84817  /*   910 */    62,   62,   62,  330,   64,   64,   64,   64,   65,   65,
84818  /*   920 */    66,   66,   66,   67,  216,  304,  330,  276,  330,  276,
84819  /*   930 */   578,  580,  330,  157,  330,  318,  432,   48,  159,  319,
84820  /*   940 */   352,  330,  276,  323,  119,  463,  463,  422,  332,  432,
84821  /*   950 */    49,  432,   32,  443,  449,  432,   10,  432,   51,  276,
84822  /*   960 */   276,  276,  186,  487,  432,   52,  466,  433,  200,  399,
84823  /*   970 */   115,  581,   60,  309,  453,  454,  450,  450,   63,   63,
84824  /*   980 */    62,   62,   62,   62,  582,   64,   64,   64,   64,   65,
84825  /*   990 */    65,   66,   66,   66,   67,  216,  304,  189,  192,  605,
84826  /*  1000 */   482,  231,  232,  292,  458,  494,   22,  179,  439,  483,
84827  /*  1010 */   520,  521,  530,  529,  535,  267,  186,  186,  366,  401,
84828  /*  1020 */   186,  565,  342,  186,  443,  449,  451,  573,  574,  179,
84829  /*  1030 */    92,  433,  433,  585,   18,   92,  602,  478,  302,  523,
84830  /*  1040 */   606,  351,  491,  495,  309,  453,  454,  450,  450,   63,
84831  /*  1050 */    63,   62,   62,   62,   62,  497,   64,   64,   64,   64,
84832  /*  1060 */    65,   65,   66,   66,   66,   67,  216,  165,  262,   85,
84833  /*  1070 */   527,  528,  235,  236,  237,  168,  239,  533,  105,  534,
84834  /*  1080 */   263,  546,  269,   73,  337,    8,    4,  195,  271,  273,
84835  /*  1090 */   308,  211,  275,  294,  280,  371,  379,  382,  383,  334,
84836  /*  1100 */   283,  284,  295,  285,  577,  587,  293,  296,  297,  599,
84837  /*  1110 */   147,  242,  462,  423,  209,  464,  569,  339,  338,  250,
84838  /*  1120 */   208,  481,  526,  210,  572,  484,  437,  469,  259,  537,
84839  /*  1130 */   540,  290,  393,  584,  166,  409,  417,  418,  536,  538,
84840  /*  1140 */   330,    7,  326,  361,  419,  167,   85,   76,   75,  156,
84841  /*  1150 */   169,  347,  345,   84,  327,  176,   74,  328,  329,   58,
84842  /*  1160 */   434,  438,   80,  432,   35,  479,  392,  291,  281,  243,
84843  /*  1170 */   246,  244,  305,  245,  121,   86,  435,  214,  350,  214,
84844  /*  1180 */   356,  513,  518,  433,  251,  313,  260,  523,  125,  493,
84845  /*  1190 */   499,  519,  253,  440,  440,  440,  441,  442,   11,   73,
84846  /*  1200 */   337,  398,    4,  522,  219,  344,  308,  500,  524,  255,
84847  /*  1210 */   343,  226,  368,  300,  225,  334,   73,  337,  227,    4,
84848  /*  1220 */   541,  547,  548,  308,  549,  190,  301,  555,  191,  372,
84849  /*  1230 */   370,  193,  334,  339,  194,  557,   89,  196,  278,  378,
84850  /*  1240 */   558,  117,  568,  469,  199,  133,  390,  391,  575,  143,
84851  /*  1250 */   339,  134,  135,  583,  136,  139,  137,  142,  322,  596,
84852  /*  1260 */   469,   93,   96,   76,   75,  502,  597,  598,  601,  101,
84853  /*  1270 */   224,  104,   74,  328,  329,  107,  407,  438,  238,  424,
84854  /*  1280 */    76,   75,  118,  455,  650,  651,  172,  173,  452,   74,
84855  /*  1290 */   328,  329,  324,   72,  438,  459,  468,  471,  144,  158,
84856  /*  1300 */     6,  472,   13,  473,  175,  477,   82,  490,   12,  440,
84857  /*  1310 */   440,  440,  441,  442,   11,  122,  498,  180,  164,  506,
84858  /*  1320 */   507,   87,  116,  223,  126,  127,  440,  440,  440,  441,
84859  /*  1330 */   442,   11,  266,   88,  128,  188,  360,  365,  258,  369,
84860  /*  1340 */   146,  556,  129,  179,  130,  373,  559,  279,  563,  197,
84861  /*  1350 */   131,    9,  571,  201,  132,   14,  203,  576,  204,  579,
84862  /*  1360 */   138,  205,   90,  141,   91,  140,   15,  106,  594,  586,
84863  /*  1370 */   400,  298,  212,  404,  149,  608,
84864 };
84865 static const YYCODETYPE yy_lookahead[] = {
84866  /*     0 */    19,  142,  143,  144,  145,   24,  150,   26,   74,   75,
84867  /*    10 */    76,   77,  115,   79,   80,   81,   82,   83,   84,   85,
84868  /*    20 */    86,   87,   88,   89,  150,  165,  166,  167,   47,   48,
84869  /*    30 */    78,   79,   80,   81,   82,   83,   84,   85,   86,   87,
84870  /*    40 */    88,   89,  186,  169,  170,   85,   65,   66,   67,   68,
84871  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   89,
84872  /*    60 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
84873  /*    70 */    89,   19,  112,   19,   93,  173,  116,   25,   79,   80,
84874  /*    80 */    81,   82,   83,   84,   85,   86,   87,   88,   89,    1,
84875  /*    90 */     2,   26,   83,   84,   85,   86,   87,   88,   89,   47,
84876  /*   100 */    48,  180,  181,   51,  230,  231,   22,   22,  187,   26,
84877  /*   110 */   221,   26,  223,  224,    0,    1,    2,   65,   66,   67,
84878  /*   120 */    68,   69,   70,   71,   72,   73,   74,   75,   76,   77,
84879  /*   130 */   241,   79,   80,   81,   82,   83,   84,   85,   86,   87,
84880  /*   140 */    88,   89,   19,   89,    7,    8,    9,   19,   63,   95,
84881  /*   150 */    96,   97,   98,   99,  100,  101,  150,   28,   93,   94,
84882  /*   160 */    95,   32,  108,   98,   99,  100,   83,   84,   83,   84,
84883  /*   170 */    47,   48,   49,   25,  109,   46,   93,   94,   93,  173,
84884  /*   180 */   174,  165,   97,   26,   83,   84,  103,  104,   65,   66,
84885  /*   190 */    67,   68,   69,   70,   71,   72,   73,   74,   75,   76,
84886  /*   200 */    77,  117,   79,   80,   81,   82,   83,   84,   85,   86,
84887  /*   210 */    87,   88,   89,   19,  129,  130,  131,   89,   24,  150,
84888  /*   220 */   204,  150,   63,  173,   96,   97,   98,   99,  100,  101,
84889  /*   230 */   150,  225,  221,  222,  223,  224,  108,  221,  185,  223,
84890  /*   240 */   224,   47,   48,   95,  173,  174,   98,   99,  100,   54,
84891  /*   250 */    93,   94,   93,  173,  174,  186,   97,  109,  159,   65,
84892  /*   260 */    66,   67,   68,   69,   70,   71,   72,   73,   74,   75,
84893  /*   270 */    76,   77,  150,   79,   80,   81,   82,   83,   84,   85,
84894  /*   280 */    86,   87,   88,   89,   19,   11,  215,  172,  129,  130,
84895  /*   290 */   131,  220,  193,  213,  214,  180,  146,  147,   26,  104,
84896  /*   300 */   105,  106,  152,   85,   86,   87,   88,   89,  186,  159,
84897  /*   310 */   115,   95,   47,   48,   98,   99,  100,  162,  185,   22,
84898  /*   320 */   165,  166,  167,   26,  221,  109,  223,  224,   54,  150,
84899  /*   330 */    65,   66,   67,   68,   69,   70,   71,   72,   73,   74,
84900  /*   340 */    75,   76,   77,  193,   79,   80,   81,   82,   83,   84,
84901  /*   350 */    85,   86,   87,   88,   89,   83,   19,  221,  150,  223,
84902  /*   360 */   224,  171,  172,  150,  150,   93,   94,  217,  160,  161,
84903  /*   370 */   180,   26,   24,  150,   26,  150,  189,  190,  104,  105,
84904  /*   380 */   106,  159,  169,  194,   47,   48,  150,  173,  174,  115,
84905  /*   390 */    93,   94,  184,  185,  244,  216,  173,  174,  173,  174,
84906  /*   400 */   159,  136,   65,   66,   67,   68,   69,   70,   71,   72,
84907  /*   410 */    73,   74,   75,   76,   77,  193,   79,   80,   81,   82,
84908  /*   420 */    83,   84,   85,   86,   87,   88,   89,  150,   19,  159,
84909  /*   430 */    12,  150,   23,  219,  193,   19,  159,  214,   93,  217,
84910  /*   440 */   215,   93,  150,  230,  231,   27,  205,  206,   26,  157,
84911  /*   450 */   173,  174,  160,  161,  173,  174,   47,   48,  154,  190,
84912  /*   460 */    42,  239,   44,  193,   48,   25,  168,  169,  170,   22,
84913  /*   470 */   193,   24,   54,  136,   65,   66,   67,   68,   69,   70,
84914  /*   480 */    71,   72,   73,   74,   75,   76,   77,  217,   79,   80,
84915  /*   490 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   19,
84916  /*   500 */   219,   23,  150,   23,  234,   23,  135,  150,  137,  239,
84917  /*   510 */   168,  169,  170,   23,  164,   93,   94,   26,   23,  103,
84918  /*   520 */   150,   47,   48,  173,  108,  173,  174,   47,   48,  231,
84919  /*   530 */   173,  174,  228,   21,  150,   22,   23,  233,   25,   88,
84920  /*   540 */    89,  119,   68,   69,  165,   65,   66,   67,   68,   69,
84921  /*   550 */    70,   71,   72,   73,   74,   75,   76,   77,  118,   79,
84922  /*   560 */    80,   81,   82,   83,   84,   85,   86,   87,   88,   89,
84923  /*   570 */    19,   97,   60,  231,   23,   22,  165,   64,   23,   26,
84924  /*   580 */    25,   96,   12,  204,   93,   94,   34,   22,   23,  111,
84925  /*   590 */    25,  113,  114,  111,   26,  113,  114,   27,   47,   48,
84926  /*   600 */   115,  111,   17,  113,  114,  150,  111,   55,  113,  114,
84927  /*   610 */   119,   99,   42,  128,   44,  204,   65,   66,   67,   68,
84928  /*   620 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   64,
84929  /*   630 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
84930  /*   640 */    89,   19,   57,  150,   59,   23,   93,   94,  150,   94,
84931  /*   650 */   138,   22,  150,   85,  150,   26,  150,   97,  150,  107,
84932  /*   660 */   150,   93,   94,   48,  189,  190,  173,  174,  108,   47,
84933  /*   670 */    48,  173,  174,  115,  119,  173,  174,  173,  174,  173,
84934  /*   680 */   174,  173,  174,  173,  174,   17,  128,   65,   66,   67,
84935  /*   690 */    68,   69,   70,   71,   72,   73,   74,   75,   76,   77,
84936  /*   700 */   150,   79,   80,   81,   82,   83,   84,   85,   86,   87,
84937  /*   710 */    88,   89,   19,  150,  104,  105,  106,   24,  103,  150,
84938  /*   720 */   148,  150,   93,  138,  150,   57,  150,   59,  150,  111,
84939  /*   730 */   150,  113,  114,  150,  247,  248,  173,  174,  144,  145,
84940  /*   740 */    47,   48,  173,  174,  173,  174,  165,  173,  174,  173,
84941  /*   750 */   174,  173,  174,  173,  174,  150,  173,  174,   65,   66,
84942  /*   760 */    67,   68,   69,   70,   71,   72,   73,   74,   75,   76,
84943  /*   770 */    77,  150,   79,   80,   81,   82,   83,   84,   85,   86,
84944  /*   780 */    87,   88,   89,   19,  150,  204,  150,  104,  105,  106,
84945  /*   790 */   150,  150,  150,  207,  173,  174,  150,  150,  150,  196,
84946  /*   800 */   150,  160,  161,  150,  150,  150,  203,  173,  174,  173,
84947  /*   810 */   174,   47,   48,  173,  174,  173,  174,  212,  195,  173,
84948  /*   820 */   174,  173,  174,  173,  174,  150,  173,  174,  150,   65,
84949  /*   830 */    66,   67,   68,   69,   70,   71,   72,   73,   74,   75,
84950  /*   840 */    76,   77,  150,   79,   80,   81,   82,   83,   84,   85,
84951  /*   850 */    86,   87,   88,   89,   19,  150,  159,  150,  112,  212,
84952  /*   860 */   150,  150,  116,  150,  186,  173,  174,  192,  150,   25,
84953  /*   870 */   150,  216,  150,  150,  150,  205,  206,  150,  173,  174,
84954  /*   880 */   173,  174,   47,   48,  173,  174,  173,  174,  150,  150,
84955  /*   890 */   193,  173,  174,  173,  174,  173,  174,  173,  174,  150,
84956  /*   900 */    65,   66,   67,   68,   69,   70,   71,   72,   73,   74,
84957  /*   910 */    75,   76,   77,  150,   79,   80,   81,   82,   83,   84,
84958  /*   920 */    85,   86,   87,   88,   89,   19,  150,  150,  150,  150,
84959  /*   930 */   192,  192,  150,  159,  150,  186,  173,  174,   94,  212,
84960  /*   940 */    19,  150,  150,  245,  246,  129,  130,  150,   19,  173,
84961  /*   950 */   174,  173,  174,   47,   48,  173,  174,  173,  174,  150,
84962  /*   960 */   150,  150,   25,  119,  173,  174,  165,  193,   25,  192,
84963  /*   970 */   150,  192,   66,   67,   68,   69,   70,   71,   72,   73,
84964  /*   980 */    74,   75,   76,   77,  192,   79,   80,   81,   82,   83,
84965  /*   990 */    84,   85,   86,   87,   88,   89,   19,  159,  159,   23,
84966  /*  1000 */    30,  192,  192,  192,   23,   23,   25,   25,  150,   39,
84967  /*  1010 */     7,    8,   96,   97,   23,   23,   25,   25,   23,  242,
84968  /*  1020 */    25,   23,  150,   25,   47,   48,   97,   23,   23,   25,
84969  /*  1030 */    25,  193,  193,   23,   22,   25,   23,  150,   25,  102,
84970  /*  1040 */    64,  120,  150,  150,   67,   68,   69,   70,   71,   72,
84971  /*  1050 */    73,   74,   75,   76,   77,  150,   79,   80,   81,   82,
84972  /*  1060 */    83,   84,   85,   86,   87,   88,   89,    5,  150,  126,
84973  /*  1070 */   150,  182,   10,   11,   12,   13,   14,  182,   16,  182,
84974  /*  1080 */   150,  150,  150,   19,   20,   73,   22,  235,  150,  150,
84975  /*  1090 */    26,   29,  150,   31,  150,  236,  150,  150,  150,   35,
84976  /*  1100 */   150,  150,   40,  150,  150,  150,  150,  150,  150,  150,
84977  /*  1110 */   195,  197,  232,  153,   52,  232,   54,   53,  227,  208,
84978  /*  1120 */    58,  176,  181,   61,  198,  176,  165,   63,  176,  165,
84979  /*  1130 */   165,  208,  208,  198,    6,  149,  149,  149,  176,  176,
84980  /*  1140 */   150,   25,  149,  177,   13,  151,  126,   83,   84,  159,
84981  /*  1150 */   151,  123,  122,  124,  158,  117,   92,   93,   94,  125,
84982  /*  1160 */   193,   97,  135,  173,  174,  156,  104,  105,  106,  198,
84983  /*  1170 */   201,  199,  110,  200,  156,  103,  202,  115,  121,  115,
84984  /*  1180 */   103,  175,  175,  193,  209,   45,  175,  102,   22,  210,
84985  /*  1190 */   210,  183,  209,  129,  130,  131,  132,  133,  134,   19,
84986  /*  1200 */    20,  139,   22,  177,  226,  215,   26,  210,  175,  209,
84987  /*  1210 */   220,   89,   18,  178,  229,   35,   19,   20,  229,   22,
84988  /*  1220 */   183,  175,  175,   26,  175,  155,  178,  156,  155,   43,
84989  /*  1230 */   156,  155,   35,   53,  156,  156,  135,  155,  237,  156,
84990  /*  1240 */   238,   65,  188,   63,  188,   22,  156,   18,  198,  218,
84991  /*  1250 */    53,  191,  191,  198,  191,  188,  191,  218,  156,   38,
84992  /*  1260 */    63,  240,  240,   83,   84,   85,  156,  156,   36,  163,
84993  /*  1270 */   179,  179,   92,   93,   94,  243,    1,   97,   15,   23,
84994  /*  1280 */    83,   84,  246,  112,  117,  117,  117,  117,   97,   92,
84995  /*  1290 */    93,   94,  249,   22,   97,   23,   23,   11,   22,   22,
84996  /*  1300 */    33,   23,   33,   23,   25,   23,   25,  119,   25,  129,
84997  /*  1310 */   130,  131,  132,  133,  134,   22,  120,   33,  117,   23,
84998  /*  1320 */    23,   22,   37,   49,   22,   22,  129,  130,  131,  132,
84999  /*  1330 */   133,  134,   23,   22,   22,  101,   49,   49,  108,   19,
85000  /*  1340 */    24,   20,  103,   25,   50,   41,   56,  138,   50,  103,
85001  /*  1350 */    22,    5,    1,  127,  107,   22,  118,    1,   17,   20,
85002  /*  1360 */   118,  121,   73,  127,   73,  107,   22,   17,   23,  128,
85003  /*  1370 */    62,  140,   15,    3,   22,    4,
85004 };
85005 #define YY_SHIFT_USE_DFLT (-104)
85006 #define YY_SHIFT_MAX 404
85007 static const short yy_shift_ofst[] = {
85008  /*     0 */    88, 1062, 1064,  -19, 1064, 1197, 1197,   65,   83,  195,
85009  /*    10 */   123, 1197, 1197, 1197, 1197, 1197,  -48,  274,  272,  157,
85010  /*    20 */   345,  101,  101, -103,   52,  194,  265,  337,  409,  480,
85011  /*    30 */   551,  622,  693,  764,  835,  764,  764,  764,  764,  764,
85012  /*    40 */   764,  764,  764,  764,  764,  764,  764,  764,  764,  764,
85013  /*    50 */   764,  764,  764,  906,  977,  977, 1180, 1197, 1197, 1197,
85014  /*    60 */  1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197,
85015  /*    70 */  1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197,
85016  /*    80 */  1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197, 1197,
85017  /*    90 */  1197, 1197, 1197, 1197, 1197, 1197, 1197,  -66,  -66,   -1,
85018  /*   100 */    -1,   54,    9,  218,  416,  512,  157,  157,  451,  345,
85019  /*   110 */   -30, -104, -104, -104,   85,  128,  418,  418,  513,  565,
85020  /*   120 */   114,  348,  157,  348,  348,  157,  157,  157,  157,  157,
85021  /*   130 */   157,  157,  157,  157,  157,  157,  157,  157,  157,  157,
85022  /*   140 */   157,  157,  485,  558, -103, -103, -103, -104, -104, -104,
85023  /*   150 */   159,  159,  148,  216,  478,  297,  482,  490,  570,  422,
85024  /*   160 */   491,  553,  495,  555,  568,  137,  157,  157,  157,  157,
85025  /*   170 */   157,  -40,  157,  157,  629,  157,  157,  844,  157,  157,
85026  /*   180 */   157,  157,  157,  552,  552,  552,  157,  157,  157,  618,
85027  /*   190 */   157,  157,  618,  157,  129,  610,  157,  157,  618,  157,
85028  /*   200 */   157,  157,  618,  157,  157,  157,  618,  618,  157,  157,
85029  /*   210 */   157,  157,  157,  447,  746,  440,  345,  816,  816,  371,
85030  /*   220 */   970,  970,  921,  970,  615,  970,  345,  970,  345,  937,
85031  /*   230 */   943,  921,  921,  943, 1128, 1128, 1128, 1128, 1131, 1131,
85032  /*   240 */  1116, -103, 1020, 1028, 1029, 1030, 1034, 1027, 1038, 1038,
85033  /*   250 */  1072, 1057, 1072, 1057, 1072, 1057, 1077, 1077, 1140, 1077,
85034  /*   260 */  1085, 1077, 1166, 1122, 1122, 1140, 1077, 1077, 1077, 1166,
85035  /*   270 */  1194, 1038, 1194, 1038, 1194, 1038, 1038, 1186, 1101, 1194,
85036  /*   280 */  1038, 1176, 1176, 1223, 1020, 1038, 1229, 1229, 1229, 1229,
85037  /*   290 */  1020, 1176, 1223, 1038, 1221, 1221, 1038, 1038, 1232, -104,
85038  /*   300 */  -104, -104, -104, -104,  474,  585,  683,  668,   84,  929,
85039  /*   310 */   981,  982,  560, 1003,  916,  991,  992,  995,  998, 1004,
85040  /*   320 */  1005, 1010, 1012, 1013,  976, 1275, 1263, 1256, 1167, 1168,
85041  /*   330 */  1169, 1170, 1191, 1171, 1271, 1272, 1273, 1276, 1286, 1277,
85042  /*   340 */  1278, 1279, 1280, 1282, 1281, 1267, 1283, 1269, 1281, 1188,
85043  /*   350 */  1293, 1284, 1196, 1201, 1296, 1297, 1285, 1274, 1299, 1287,
85044  /*   360 */  1302, 1309, 1303, 1311, 1288, 1312, 1234, 1230, 1320, 1321,
85045  /*   370 */  1316, 1239, 1304, 1290, 1294, 1318, 1298, 1209, 1246, 1328,
85046  /*   380 */  1346, 1351, 1247, 1289, 1291, 1226, 1333, 1238, 1356, 1341,
85047  /*   390 */  1240, 1339, 1242, 1258, 1236, 1344, 1241, 1345, 1350, 1308,
85048  /*   400 */  1357, 1231, 1352, 1370, 1371,
85049 };
85050 #define YY_REDUCE_USE_DFLT (-145)
85051 #define YY_REDUCE_MAX 303
85052 static const short yy_reduce_ofst[] = {
85053  /*     0 */  -141,  150,  990,   16,  277,   71,   80,  208, -126,  270,
85054  /*    10 */  -111,    6,  223,  225,  214,  281,   11,  222,  213,  292,
85055  /*    20 */   155,  298,  342,  241,  136,  136,  136,  136,  136,  136,
85056  /*    30 */   136,  136,  136,  136,  136,  136,  136,  136,  136,  136,
85057  /*    40 */   136,  136,  136,  136,  136,  136,  136,  136,  136,  136,
85058  /*    50 */   136,  136,  136,  136,  136,  136,  352,  357,  493,  498,
85059  /*    60 */   502,  504,  506,  508,  510,  563,  569,  571,  574,  576,
85060  /*    70 */   578,  580,  583,  621,  634,  636,  640,  642,  646,  648,
85061  /*    80 */   650,  653,  692,  705,  707,  711,  713,  718,  720,  722,
85062  /*    90 */   724,  763,  776,  778,  782,  784,  791,  136,  136,  136,
85063  /*   100 */   136,  190,  136,  136,  -79,  304,  777,  641,  103, -140,
85064  /*   110 */   103,  103,  103,  103,  350,  115,  187,  475,  487,  487,
85065  /*   120 */   594,  379,  605,  411,  581, -144,   69,  122,  678,  675,
85066  /*   130 */   647,  749,  179,  727,  738,  739,  779,  792,  809,  810,
85067  /*   140 */   655,  811,   99,  697,  774,  838,  839,  603,  670,  698,
85068  /*   150 */   -98,   50,   53,  133,  189,  236,  189,  189,  269,  370,
85069  /*   160 */   384,  455,  189,  586,  550,  572,  654,  710,  723,  797,
85070  /*   170 */   820,  623,  550,  858,  801,  872,  887,  586,  892,  893,
85071  /*   180 */   905,  918,  920,  889,  895,  897,  930,  931,  932,  189,
85072  /*   190 */   938,  939,  189,  942,  852,  859,  944,  946,  189,  947,
85073  /*   200 */   948,  950,  189,  951,  953,  954,  189,  189,  955,  956,
85074  /*   210 */   957,  958,  959,  960,  915,  914,  961,  880,  883,  891,
85075  /*   220 */   945,  949,  911,  952,  941,  962,  964,  963,  965,  966,
85076  /*   230 */   926,  923,  924,  935,  986,  987,  988,  993,  994,  999,
85077  /*   240 */   996,  967,  971,  972,  973,  969,  974,  978, 1009, 1018,
85078  /*   250 */   975,  979,  983,  980, 1000,  997, 1006, 1007, 1008, 1011,
85079  /*   260 */  1026, 1033, 1035,  985,  989, 1037, 1046, 1047, 1049, 1048,
85080  /*   270 */  1070, 1071, 1073, 1074, 1076, 1078, 1079, 1001, 1002, 1082,
85081  /*   280 */  1083, 1054, 1056, 1031, 1050, 1090, 1060, 1061, 1063, 1065,
85082  /*   290 */  1055, 1067, 1039, 1102, 1021, 1022, 1110, 1111, 1032, 1106,
85083  /*   300 */  1091, 1092, 1036, 1043,
85084 };
85085 static const YYACTIONTYPE yy_default[] = {
85086  /*     0 */   615,  929,  848,  736,  929,  848,  929,  929,  875,  929,
85087  /*    10 */   904,  846,  929,  929,  929,  929,  820,  929,  875,  929,
85088  /*    20 */   652,  875,  875,  740,  771,  929,  929,  929,  929,  929,
85089  /*    30 */   929,  929,  929,  772,  929,  850,  845,  841,  843,  842,
85090  /*    40 */   849,  773,  762,  769,  776,  751,  888,  778,  779,  785,
85091  /*    50 */   786,  905,  903,  808,  807,  826,  929,  929,  929,  929,
85092  /*    60 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85093  /*    70 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85094  /*    80 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85095  /*    90 */   929,  929,  929,  929,  929,  929,  929,  810,  832,  809,
85096  /*   100 */   819,  645,  811,  812,  705,  640,  929,  929,  813,  929,
85097  /*   110 */   814,  827,  828,  829,  929,  929,  929,  929,  929,  929,
85098  /*   120 */   615,  736,  929,  736,  736,  929,  929,  929,  929,  929,
85099  /*   130 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85100  /*   140 */   929,  929,  929,  929,  929,  929,  929,  730,  740,  922,
85101  /*   150 */   929,  929,  696,  929,  929,  929,  929,  929,  929,  929,
85102  /*   160 */   929,  929,  929,  929,  929,  623,  621,  929,  929,  929,
85103  /*   170 */   929,  728,  929,  929,  654,  929,  929,  738,  929,  929,
85104  /*   180 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  642,
85105  /*   190 */   929,  929,  717,  929,  881,  929,  929,  929,  895,  929,
85106  /*   200 */   929,  929,  893,  929,  929,  929,  719,  781,  861,  929,
85107  /*   210 */   908,  910,  929,  929,  728,  737,  929,  929,  929,  844,
85108  /*   220 */   765,  765,  753,  765,  675,  765,  929,  765,  929,  678,
85109  /*   230 */   775,  753,  753,  775,  620,  620,  620,  620,  631,  631,
85110  /*   240 */   695,  929,  775,  766,  768,  758,  770,  929,  744,  744,
85111  /*   250 */   752,  757,  752,  757,  752,  757,  707,  707,  692,  707,
85112  /*   260 */   678,  707,  854,  858,  858,  692,  707,  707,  707,  854,
85113  /*   270 */   637,  744,  637,  744,  637,  744,  744,  885,  887,  637,
85114  /*   280 */   744,  709,  709,  787,  775,  744,  716,  716,  716,  716,
85115  /*   290 */   775,  709,  787,  744,  907,  907,  744,  744,  915,  662,
85116  /*   300 */   680,  680,  922,  927,  929,  929,  929,  929,  794,  929,
85117  /*   310 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85118  /*   320 */   929,  929,  868,  929,  929,  929,  629,  929,  799,  795,
85119  /*   330 */   929,  796,  929,  722,  929,  929,  929,  929,  929,  929,
85120  /*   340 */   929,  929,  929,  929,  847,  929,  759,  929,  767,  929,
85121  /*   350 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85122  /*   360 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85123  /*   370 */   929,  929,  929,  929,  883,  884,  929,  929,  929,  929,
85124  /*   380 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  929,
85125  /*   390 */   929,  929,  929,  929,  929,  929,  929,  929,  929,  914,
85126  /*   400 */   929,  929,  917,  616,  929,  611,  613,  614,  618,  619,
85127  /*   410 */   622,  649,  650,  651,  624,  625,  626,  627,  628,  630,
85128  /*   420 */   634,  632,  633,  635,  641,  643,  661,  663,  647,  665,
85129  /*   430 */   726,  727,  791,  720,  721,  725,  648,  802,  793,  797,
85130  /*   440 */   798,  800,  801,  815,  816,  818,  824,  831,  834,  817,
85131  /*   450 */   822,  823,  825,  830,  833,  723,  724,  837,  655,  656,
85132  /*   460 */   659,  660,  871,  873,  872,  874,  658,  657,  803,  806,
85133  /*   470 */   839,  840,  896,  897,  898,  899,  900,  835,  745,  838,
85134  /*   480 */   821,  760,  763,  764,  761,  729,  739,  747,  748,  749,
85135  /*   490 */   750,  734,  735,  741,  756,  789,  790,  754,  755,  742,
85136  /*   500 */   743,  731,  732,  733,  836,  792,  804,  805,  666,  667,
85137  /*   510 */   799,  668,  669,  670,  708,  711,  712,  713,  671,  690,
85138  /*   520 */   693,  694,  672,  679,  673,  674,  681,  682,  683,  686,
85139  /*   530 */   687,  688,  689,  684,  685,  855,  856,  859,  857,  676,
85140  /*   540 */   677,  691,  664,  653,  646,  697,  700,  701,  702,  703,
85141  /*   550 */   704,  706,  698,  699,  644,  636,  638,  746,  877,  886,
85142  /*   560 */   882,  878,  879,  880,  639,  851,  852,  710,  783,  784,
85143  /*   570 */   876,  889,  891,  788,  892,  894,  890,  919,  714,  715,
85144  /*   580 */   718,  860,  901,  774,  777,  780,  782,  862,  863,  864,
85145  /*   590 */   865,  866,  869,  870,  867,  902,  906,  909,  911,  912,
85146  /*   600 */   913,  916,  918,  923,  924,  925,  928,  926,  617,  612,
85147 };
85148 #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0]))
85149
85150 /* The next table maps tokens into fallback tokens.  If a construct
85151 ** like the following:
85152 ** 
85153 **      %fallback ID X Y Z.
85154 **
85155 ** appears in the grammar, then ID becomes a fallback token for X, Y,
85156 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
85157 ** but it does not parse, the type of the token is changed to ID and
85158 ** the parse is retried before an error is thrown.
85159 */
85160 #ifdef YYFALLBACK
85161 static const YYCODETYPE yyFallback[] = {
85162     0,  /*          $ => nothing */
85163     0,  /*       SEMI => nothing */
85164    26,  /*    EXPLAIN => ID */
85165    26,  /*      QUERY => ID */
85166    26,  /*       PLAN => ID */
85167    26,  /*      BEGIN => ID */
85168     0,  /* TRANSACTION => nothing */
85169    26,  /*   DEFERRED => ID */
85170    26,  /*  IMMEDIATE => ID */
85171    26,  /*  EXCLUSIVE => ID */
85172     0,  /*     COMMIT => nothing */
85173    26,  /*        END => ID */
85174    26,  /*   ROLLBACK => ID */
85175    26,  /*  SAVEPOINT => ID */
85176    26,  /*    RELEASE => ID */
85177     0,  /*         TO => nothing */
85178     0,  /*     CREATE => nothing */
85179     0,  /*      TABLE => nothing */
85180    26,  /*         IF => ID */
85181     0,  /*        NOT => nothing */
85182     0,  /*     EXISTS => nothing */
85183    26,  /*       TEMP => ID */
85184     0,  /*         LP => nothing */
85185     0,  /*         RP => nothing */
85186     0,  /*         AS => nothing */
85187     0,  /*      COMMA => nothing */
85188     0,  /*         ID => nothing */
85189    26,  /*      ABORT => ID */
85190    26,  /*      AFTER => ID */
85191    26,  /*    ANALYZE => ID */
85192    26,  /*        ASC => ID */
85193    26,  /*     ATTACH => ID */
85194    26,  /*     BEFORE => ID */
85195    26,  /*         BY => ID */
85196    26,  /*    CASCADE => ID */
85197    26,  /*       CAST => ID */
85198    26,  /*   COLUMNKW => ID */
85199    26,  /*   CONFLICT => ID */
85200    26,  /*   DATABASE => ID */
85201    26,  /*       DESC => ID */
85202    26,  /*     DETACH => ID */
85203    26,  /*       EACH => ID */
85204    26,  /*       FAIL => ID */
85205    26,  /*        FOR => ID */
85206    26,  /*     IGNORE => ID */
85207    26,  /*  INITIALLY => ID */
85208    26,  /*    INSTEAD => ID */
85209    26,  /*    LIKE_KW => ID */
85210    26,  /*      MATCH => ID */
85211    26,  /*        KEY => ID */
85212    26,  /*         OF => ID */
85213    26,  /*     OFFSET => ID */
85214    26,  /*     PRAGMA => ID */
85215    26,  /*      RAISE => ID */
85216    26,  /*    REPLACE => ID */
85217    26,  /*   RESTRICT => ID */
85218    26,  /*        ROW => ID */
85219    26,  /*    TRIGGER => ID */
85220    26,  /*     VACUUM => ID */
85221    26,  /*       VIEW => ID */
85222    26,  /*    VIRTUAL => ID */
85223    26,  /*    REINDEX => ID */
85224    26,  /*     RENAME => ID */
85225    26,  /*   CTIME_KW => ID */
85226     0,  /*        ANY => nothing */
85227     0,  /*         OR => nothing */
85228     0,  /*        AND => nothing */
85229     0,  /*         IS => nothing */
85230     0,  /*    BETWEEN => nothing */
85231     0,  /*         IN => nothing */
85232     0,  /*     ISNULL => nothing */
85233     0,  /*    NOTNULL => nothing */
85234     0,  /*         NE => nothing */
85235     0,  /*         EQ => nothing */
85236     0,  /*         GT => nothing */
85237     0,  /*         LE => nothing */
85238     0,  /*         LT => nothing */
85239     0,  /*         GE => nothing */
85240     0,  /*     ESCAPE => nothing */
85241     0,  /*     BITAND => nothing */
85242     0,  /*      BITOR => nothing */
85243     0,  /*     LSHIFT => nothing */
85244     0,  /*     RSHIFT => nothing */
85245     0,  /*       PLUS => nothing */
85246     0,  /*      MINUS => nothing */
85247     0,  /*       STAR => nothing */
85248     0,  /*      SLASH => nothing */
85249     0,  /*        REM => nothing */
85250     0,  /*     CONCAT => nothing */
85251     0,  /*    COLLATE => nothing */
85252     0,  /*     UMINUS => nothing */
85253     0,  /*      UPLUS => nothing */
85254     0,  /*     BITNOT => nothing */
85255     0,  /*     STRING => nothing */
85256     0,  /*    JOIN_KW => nothing */
85257     0,  /* CONSTRAINT => nothing */
85258     0,  /*    DEFAULT => nothing */
85259     0,  /*       NULL => nothing */
85260     0,  /*    PRIMARY => nothing */
85261     0,  /*     UNIQUE => nothing */
85262     0,  /*      CHECK => nothing */
85263     0,  /* REFERENCES => nothing */
85264     0,  /*   AUTOINCR => nothing */
85265     0,  /*         ON => nothing */
85266     0,  /*     DELETE => nothing */
85267     0,  /*     UPDATE => nothing */
85268     0,  /*     INSERT => nothing */
85269     0,  /*        SET => nothing */
85270     0,  /* DEFERRABLE => nothing */
85271     0,  /*    FOREIGN => nothing */
85272     0,  /*       DROP => nothing */
85273     0,  /*      UNION => nothing */
85274     0,  /*        ALL => nothing */
85275     0,  /*     EXCEPT => nothing */
85276     0,  /*  INTERSECT => nothing */
85277     0,  /*     SELECT => nothing */
85278     0,  /*   DISTINCT => nothing */
85279     0,  /*        DOT => nothing */
85280     0,  /*       FROM => nothing */
85281     0,  /*       JOIN => nothing */
85282     0,  /*    INDEXED => nothing */
85283     0,  /*      USING => nothing */
85284     0,  /*      ORDER => nothing */
85285     0,  /*      GROUP => nothing */
85286     0,  /*     HAVING => nothing */
85287     0,  /*      LIMIT => nothing */
85288     0,  /*      WHERE => nothing */
85289     0,  /*       INTO => nothing */
85290     0,  /*     VALUES => nothing */
85291     0,  /*    INTEGER => nothing */
85292     0,  /*      FLOAT => nothing */
85293     0,  /*       BLOB => nothing */
85294     0,  /*   REGISTER => nothing */
85295     0,  /*   VARIABLE => nothing */
85296     0,  /*       CASE => nothing */
85297     0,  /*       WHEN => nothing */
85298     0,  /*       THEN => nothing */
85299     0,  /*       ELSE => nothing */
85300     0,  /*      INDEX => nothing */
85301     0,  /*      ALTER => nothing */
85302     0,  /*        ADD => nothing */
85303 };
85304 #endif /* YYFALLBACK */
85305
85306 /* The following structure represents a single element of the
85307 ** parser's stack.  Information stored includes:
85308 **
85309 **   +  The state number for the parser at this level of the stack.
85310 **
85311 **   +  The value of the token stored at this level of the stack.
85312 **      (In other words, the "major" token.)
85313 **
85314 **   +  The semantic value stored at this level of the stack.  This is
85315 **      the information used by the action routines in the grammar.
85316 **      It is sometimes called the "minor" token.
85317 */
85318 struct yyStackEntry {
85319   YYACTIONTYPE stateno;  /* The state-number */
85320   YYCODETYPE major;      /* The major token value.  This is the code
85321                          ** number for the token at this stack level */
85322   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
85323                          ** is the value of the token  */
85324 };
85325 typedef struct yyStackEntry yyStackEntry;
85326
85327 /* The state of the parser is completely contained in an instance of
85328 ** the following structure */
85329 struct yyParser {
85330   int yyidx;                    /* Index of top element in stack */
85331 #ifdef YYTRACKMAXSTACKDEPTH
85332   int yyidxMax;                 /* Maximum value of yyidx */
85333 #endif
85334   int yyerrcnt;                 /* Shifts left before out of the error */
85335   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
85336 #if YYSTACKDEPTH<=0
85337   int yystksz;                  /* Current side of the stack */
85338   yyStackEntry *yystack;        /* The parser's stack */
85339 #else
85340   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
85341 #endif
85342 };
85343 typedef struct yyParser yyParser;
85344
85345 #ifndef NDEBUG
85346 static FILE *yyTraceFILE = 0;
85347 static char *yyTracePrompt = 0;
85348 #endif /* NDEBUG */
85349
85350 #ifndef NDEBUG
85351 /* 
85352 ** Turn parser tracing on by giving a stream to which to write the trace
85353 ** and a prompt to preface each trace message.  Tracing is turned off
85354 ** by making either argument NULL 
85355 **
85356 ** Inputs:
85357 ** <ul>
85358 ** <li> A FILE* to which trace output should be written.
85359 **      If NULL, then tracing is turned off.
85360 ** <li> A prefix string written at the beginning of every
85361 **      line of trace output.  If NULL, then tracing is
85362 **      turned off.
85363 ** </ul>
85364 **
85365 ** Outputs:
85366 ** None.
85367 */
85368 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
85369   yyTraceFILE = TraceFILE;
85370   yyTracePrompt = zTracePrompt;
85371   if( yyTraceFILE==0 ) yyTracePrompt = 0;
85372   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
85373 }
85374 #endif /* NDEBUG */
85375
85376 #ifndef NDEBUG
85377 /* For tracing shifts, the names of all terminals and nonterminals
85378 ** are required.  The following table supplies these names */
85379 static const char *const yyTokenName[] = { 
85380   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
85381   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
85382   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
85383   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
85384   "CREATE",        "TABLE",         "IF",            "NOT",         
85385   "EXISTS",        "TEMP",          "LP",            "RP",          
85386   "AS",            "COMMA",         "ID",            "ABORT",       
85387   "AFTER",         "ANALYZE",       "ASC",           "ATTACH",      
85388   "BEFORE",        "BY",            "CASCADE",       "CAST",        
85389   "COLUMNKW",      "CONFLICT",      "DATABASE",      "DESC",        
85390   "DETACH",        "EACH",          "FAIL",          "FOR",         
85391   "IGNORE",        "INITIALLY",     "INSTEAD",       "LIKE_KW",     
85392   "MATCH",         "KEY",           "OF",            "OFFSET",      
85393   "PRAGMA",        "RAISE",         "REPLACE",       "RESTRICT",    
85394   "ROW",           "TRIGGER",       "VACUUM",        "VIEW",        
85395   "VIRTUAL",       "REINDEX",       "RENAME",        "CTIME_KW",    
85396   "ANY",           "OR",            "AND",           "IS",          
85397   "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",     
85398   "NE",            "EQ",            "GT",            "LE",          
85399   "LT",            "GE",            "ESCAPE",        "BITAND",      
85400   "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",        
85401   "MINUS",         "STAR",          "SLASH",         "REM",         
85402   "CONCAT",        "COLLATE",       "UMINUS",        "UPLUS",       
85403   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",  
85404   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
85405   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
85406   "DELETE",        "UPDATE",        "INSERT",        "SET",         
85407   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       
85408   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
85409   "DISTINCT",      "DOT",           "FROM",          "JOIN",        
85410   "INDEXED",       "USING",         "ORDER",         "GROUP",       
85411   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
85412   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
85413   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
85414   "THEN",          "ELSE",          "INDEX",         "ALTER",       
85415   "ADD",           "error",         "input",         "cmdlist",     
85416   "ecmd",          "explain",       "cmdx",          "cmd",         
85417   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
85418   "create_table",  "create_table_args",  "temp",          "ifnotexists", 
85419   "dbnm",          "columnlist",    "conslist_opt",  "select",      
85420   "column",        "columnid",      "type",          "carglist",    
85421   "id",            "ids",           "typetoken",     "typename",    
85422   "signed",        "plus_num",      "minus_num",     "carg",        
85423   "ccons",         "term",          "expr",          "onconf",      
85424   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
85425   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
85426   "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
85427   "orconf",        "resolvetype",   "raisetype",     "ifexists",    
85428   "fullname",      "oneselect",     "multiselect_op",  "distinct",    
85429   "selcollist",    "from",          "where_opt",     "groupby_opt", 
85430   "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
85431   "as",            "seltablist",    "stl_prefix",    "joinop",      
85432   "indexed_opt",   "on_opt",        "using_opt",     "joinop2",     
85433   "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
85434   "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
85435   "exprlist",      "likeop",        "escape",        "between_op",  
85436   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
85437   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
85438   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
85439   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
85440   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
85441   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
85442   "lp",            "anylist",     
85443 };
85444 #endif /* NDEBUG */
85445
85446 #ifndef NDEBUG
85447 /* For tracing reduce actions, the names of all rules are required.
85448 */
85449 static const char *const yyRuleName[] = {
85450  /*   0 */ "input ::= cmdlist",
85451  /*   1 */ "cmdlist ::= cmdlist ecmd",
85452  /*   2 */ "cmdlist ::= ecmd",
85453  /*   3 */ "ecmd ::= SEMI",
85454  /*   4 */ "ecmd ::= explain cmdx SEMI",
85455  /*   5 */ "explain ::=",
85456  /*   6 */ "explain ::= EXPLAIN",
85457  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
85458  /*   8 */ "cmdx ::= cmd",
85459  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
85460  /*  10 */ "trans_opt ::=",
85461  /*  11 */ "trans_opt ::= TRANSACTION",
85462  /*  12 */ "trans_opt ::= TRANSACTION nm",
85463  /*  13 */ "transtype ::=",
85464  /*  14 */ "transtype ::= DEFERRED",
85465  /*  15 */ "transtype ::= IMMEDIATE",
85466  /*  16 */ "transtype ::= EXCLUSIVE",
85467  /*  17 */ "cmd ::= COMMIT trans_opt",
85468  /*  18 */ "cmd ::= END trans_opt",
85469  /*  19 */ "cmd ::= ROLLBACK trans_opt",
85470  /*  20 */ "savepoint_opt ::= SAVEPOINT",
85471  /*  21 */ "savepoint_opt ::=",
85472  /*  22 */ "cmd ::= SAVEPOINT nm",
85473  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
85474  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
85475  /*  25 */ "cmd ::= create_table create_table_args",
85476  /*  26 */ "create_table ::= CREATE temp TABLE ifnotexists nm dbnm",
85477  /*  27 */ "ifnotexists ::=",
85478  /*  28 */ "ifnotexists ::= IF NOT EXISTS",
85479  /*  29 */ "temp ::= TEMP",
85480  /*  30 */ "temp ::=",
85481  /*  31 */ "create_table_args ::= LP columnlist conslist_opt RP",
85482  /*  32 */ "create_table_args ::= AS select",
85483  /*  33 */ "columnlist ::= columnlist COMMA column",
85484  /*  34 */ "columnlist ::= column",
85485  /*  35 */ "column ::= columnid type carglist",
85486  /*  36 */ "columnid ::= nm",
85487  /*  37 */ "id ::= ID",
85488  /*  38 */ "ids ::= ID|STRING",
85489  /*  39 */ "nm ::= ID",
85490  /*  40 */ "nm ::= STRING",
85491  /*  41 */ "nm ::= JOIN_KW",
85492  /*  42 */ "type ::=",
85493  /*  43 */ "type ::= typetoken",
85494  /*  44 */ "typetoken ::= typename",
85495  /*  45 */ "typetoken ::= typename LP signed RP",
85496  /*  46 */ "typetoken ::= typename LP signed COMMA signed RP",
85497  /*  47 */ "typename ::= ids",
85498  /*  48 */ "typename ::= typename ids",
85499  /*  49 */ "signed ::= plus_num",
85500  /*  50 */ "signed ::= minus_num",
85501  /*  51 */ "carglist ::= carglist carg",
85502  /*  52 */ "carglist ::=",
85503  /*  53 */ "carg ::= CONSTRAINT nm ccons",
85504  /*  54 */ "carg ::= ccons",
85505  /*  55 */ "ccons ::= DEFAULT term",
85506  /*  56 */ "ccons ::= DEFAULT LP expr RP",
85507  /*  57 */ "ccons ::= DEFAULT PLUS term",
85508  /*  58 */ "ccons ::= DEFAULT MINUS term",
85509  /*  59 */ "ccons ::= DEFAULT id",
85510  /*  60 */ "ccons ::= NULL onconf",
85511  /*  61 */ "ccons ::= NOT NULL onconf",
85512  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
85513  /*  63 */ "ccons ::= UNIQUE onconf",
85514  /*  64 */ "ccons ::= CHECK LP expr RP",
85515  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
85516  /*  66 */ "ccons ::= defer_subclause",
85517  /*  67 */ "ccons ::= COLLATE ids",
85518  /*  68 */ "autoinc ::=",
85519  /*  69 */ "autoinc ::= AUTOINCR",
85520  /*  70 */ "refargs ::=",
85521  /*  71 */ "refargs ::= refargs refarg",
85522  /*  72 */ "refarg ::= MATCH nm",
85523  /*  73 */ "refarg ::= ON DELETE refact",
85524  /*  74 */ "refarg ::= ON UPDATE refact",
85525  /*  75 */ "refarg ::= ON INSERT refact",
85526  /*  76 */ "refact ::= SET NULL",
85527  /*  77 */ "refact ::= SET DEFAULT",
85528  /*  78 */ "refact ::= CASCADE",
85529  /*  79 */ "refact ::= RESTRICT",
85530  /*  80 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
85531  /*  81 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
85532  /*  82 */ "init_deferred_pred_opt ::=",
85533  /*  83 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
85534  /*  84 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
85535  /*  85 */ "conslist_opt ::=",
85536  /*  86 */ "conslist_opt ::= COMMA conslist",
85537  /*  87 */ "conslist ::= conslist COMMA tcons",
85538  /*  88 */ "conslist ::= conslist tcons",
85539  /*  89 */ "conslist ::= tcons",
85540  /*  90 */ "tcons ::= CONSTRAINT nm",
85541  /*  91 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
85542  /*  92 */ "tcons ::= UNIQUE LP idxlist RP onconf",
85543  /*  93 */ "tcons ::= CHECK LP expr RP onconf",
85544  /*  94 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
85545  /*  95 */ "defer_subclause_opt ::=",
85546  /*  96 */ "defer_subclause_opt ::= defer_subclause",
85547  /*  97 */ "onconf ::=",
85548  /*  98 */ "onconf ::= ON CONFLICT resolvetype",
85549  /*  99 */ "orconf ::=",
85550  /* 100 */ "orconf ::= OR resolvetype",
85551  /* 101 */ "resolvetype ::= raisetype",
85552  /* 102 */ "resolvetype ::= IGNORE",
85553  /* 103 */ "resolvetype ::= REPLACE",
85554  /* 104 */ "cmd ::= DROP TABLE ifexists fullname",
85555  /* 105 */ "ifexists ::= IF EXISTS",
85556  /* 106 */ "ifexists ::=",
85557  /* 107 */ "cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select",
85558  /* 108 */ "cmd ::= DROP VIEW ifexists fullname",
85559  /* 109 */ "cmd ::= select",
85560  /* 110 */ "select ::= oneselect",
85561  /* 111 */ "select ::= select multiselect_op oneselect",
85562  /* 112 */ "multiselect_op ::= UNION",
85563  /* 113 */ "multiselect_op ::= UNION ALL",
85564  /* 114 */ "multiselect_op ::= EXCEPT|INTERSECT",
85565  /* 115 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
85566  /* 116 */ "distinct ::= DISTINCT",
85567  /* 117 */ "distinct ::= ALL",
85568  /* 118 */ "distinct ::=",
85569  /* 119 */ "sclp ::= selcollist COMMA",
85570  /* 120 */ "sclp ::=",
85571  /* 121 */ "selcollist ::= sclp expr as",
85572  /* 122 */ "selcollist ::= sclp STAR",
85573  /* 123 */ "selcollist ::= sclp nm DOT STAR",
85574  /* 124 */ "as ::= AS nm",
85575  /* 125 */ "as ::= ids",
85576  /* 126 */ "as ::=",
85577  /* 127 */ "from ::=",
85578  /* 128 */ "from ::= FROM seltablist",
85579  /* 129 */ "stl_prefix ::= seltablist joinop",
85580  /* 130 */ "stl_prefix ::=",
85581  /* 131 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
85582  /* 132 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
85583  /* 133 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
85584  /* 134 */ "dbnm ::=",
85585  /* 135 */ "dbnm ::= DOT nm",
85586  /* 136 */ "fullname ::= nm dbnm",
85587  /* 137 */ "joinop ::= COMMA|JOIN",
85588  /* 138 */ "joinop ::= JOIN_KW JOIN",
85589  /* 139 */ "joinop ::= JOIN_KW nm JOIN",
85590  /* 140 */ "joinop ::= JOIN_KW nm nm JOIN",
85591  /* 141 */ "on_opt ::= ON expr",
85592  /* 142 */ "on_opt ::=",
85593  /* 143 */ "indexed_opt ::=",
85594  /* 144 */ "indexed_opt ::= INDEXED BY nm",
85595  /* 145 */ "indexed_opt ::= NOT INDEXED",
85596  /* 146 */ "using_opt ::= USING LP inscollist RP",
85597  /* 147 */ "using_opt ::=",
85598  /* 148 */ "orderby_opt ::=",
85599  /* 149 */ "orderby_opt ::= ORDER BY sortlist",
85600  /* 150 */ "sortlist ::= sortlist COMMA sortitem sortorder",
85601  /* 151 */ "sortlist ::= sortitem sortorder",
85602  /* 152 */ "sortitem ::= expr",
85603  /* 153 */ "sortorder ::= ASC",
85604  /* 154 */ "sortorder ::= DESC",
85605  /* 155 */ "sortorder ::=",
85606  /* 156 */ "groupby_opt ::=",
85607  /* 157 */ "groupby_opt ::= GROUP BY nexprlist",
85608  /* 158 */ "having_opt ::=",
85609  /* 159 */ "having_opt ::= HAVING expr",
85610  /* 160 */ "limit_opt ::=",
85611  /* 161 */ "limit_opt ::= LIMIT expr",
85612  /* 162 */ "limit_opt ::= LIMIT expr OFFSET expr",
85613  /* 163 */ "limit_opt ::= LIMIT expr COMMA expr",
85614  /* 164 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
85615  /* 165 */ "where_opt ::=",
85616  /* 166 */ "where_opt ::= WHERE expr",
85617  /* 167 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
85618  /* 168 */ "setlist ::= setlist COMMA nm EQ expr",
85619  /* 169 */ "setlist ::= nm EQ expr",
85620  /* 170 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
85621  /* 171 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
85622  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
85623  /* 173 */ "insert_cmd ::= INSERT orconf",
85624  /* 174 */ "insert_cmd ::= REPLACE",
85625  /* 175 */ "itemlist ::= itemlist COMMA expr",
85626  /* 176 */ "itemlist ::= expr",
85627  /* 177 */ "inscollist_opt ::=",
85628  /* 178 */ "inscollist_opt ::= LP inscollist RP",
85629  /* 179 */ "inscollist ::= inscollist COMMA nm",
85630  /* 180 */ "inscollist ::= nm",
85631  /* 181 */ "expr ::= term",
85632  /* 182 */ "expr ::= LP expr RP",
85633  /* 183 */ "term ::= NULL",
85634  /* 184 */ "expr ::= ID",
85635  /* 185 */ "expr ::= JOIN_KW",
85636  /* 186 */ "expr ::= nm DOT nm",
85637  /* 187 */ "expr ::= nm DOT nm DOT nm",
85638  /* 188 */ "term ::= INTEGER|FLOAT|BLOB",
85639  /* 189 */ "term ::= STRING",
85640  /* 190 */ "expr ::= REGISTER",
85641  /* 191 */ "expr ::= VARIABLE",
85642  /* 192 */ "expr ::= expr COLLATE ids",
85643  /* 193 */ "expr ::= CAST LP expr AS typetoken RP",
85644  /* 194 */ "expr ::= ID LP distinct exprlist RP",
85645  /* 195 */ "expr ::= ID LP STAR RP",
85646  /* 196 */ "term ::= CTIME_KW",
85647  /* 197 */ "expr ::= expr AND expr",
85648  /* 198 */ "expr ::= expr OR expr",
85649  /* 199 */ "expr ::= expr LT|GT|GE|LE expr",
85650  /* 200 */ "expr ::= expr EQ|NE expr",
85651  /* 201 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
85652  /* 202 */ "expr ::= expr PLUS|MINUS expr",
85653  /* 203 */ "expr ::= expr STAR|SLASH|REM expr",
85654  /* 204 */ "expr ::= expr CONCAT expr",
85655  /* 205 */ "likeop ::= LIKE_KW",
85656  /* 206 */ "likeop ::= NOT LIKE_KW",
85657  /* 207 */ "likeop ::= MATCH",
85658  /* 208 */ "likeop ::= NOT MATCH",
85659  /* 209 */ "escape ::= ESCAPE expr",
85660  /* 210 */ "escape ::=",
85661  /* 211 */ "expr ::= expr likeop expr escape",
85662  /* 212 */ "expr ::= expr ISNULL|NOTNULL",
85663  /* 213 */ "expr ::= expr IS NULL",
85664  /* 214 */ "expr ::= expr NOT NULL",
85665  /* 215 */ "expr ::= expr IS NOT NULL",
85666  /* 216 */ "expr ::= NOT expr",
85667  /* 217 */ "expr ::= BITNOT expr",
85668  /* 218 */ "expr ::= MINUS expr",
85669  /* 219 */ "expr ::= PLUS expr",
85670  /* 220 */ "between_op ::= BETWEEN",
85671  /* 221 */ "between_op ::= NOT BETWEEN",
85672  /* 222 */ "expr ::= expr between_op expr AND expr",
85673  /* 223 */ "in_op ::= IN",
85674  /* 224 */ "in_op ::= NOT IN",
85675  /* 225 */ "expr ::= expr in_op LP exprlist RP",
85676  /* 226 */ "expr ::= LP select RP",
85677  /* 227 */ "expr ::= expr in_op LP select RP",
85678  /* 228 */ "expr ::= expr in_op nm dbnm",
85679  /* 229 */ "expr ::= EXISTS LP select RP",
85680  /* 230 */ "expr ::= CASE case_operand case_exprlist case_else END",
85681  /* 231 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
85682  /* 232 */ "case_exprlist ::= WHEN expr THEN expr",
85683  /* 233 */ "case_else ::= ELSE expr",
85684  /* 234 */ "case_else ::=",
85685  /* 235 */ "case_operand ::= expr",
85686  /* 236 */ "case_operand ::=",
85687  /* 237 */ "exprlist ::= nexprlist",
85688  /* 238 */ "exprlist ::=",
85689  /* 239 */ "nexprlist ::= nexprlist COMMA expr",
85690  /* 240 */ "nexprlist ::= expr",
85691  /* 241 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
85692  /* 242 */ "uniqueflag ::= UNIQUE",
85693  /* 243 */ "uniqueflag ::=",
85694  /* 244 */ "idxlist_opt ::=",
85695  /* 245 */ "idxlist_opt ::= LP idxlist RP",
85696  /* 246 */ "idxlist ::= idxlist COMMA nm collate sortorder",
85697  /* 247 */ "idxlist ::= nm collate sortorder",
85698  /* 248 */ "collate ::=",
85699  /* 249 */ "collate ::= COLLATE ids",
85700  /* 250 */ "cmd ::= DROP INDEX ifexists fullname",
85701  /* 251 */ "cmd ::= VACUUM",
85702  /* 252 */ "cmd ::= VACUUM nm",
85703  /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
85704  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ ON",
85705  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ DELETE",
85706  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
85707  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
85708  /* 258 */ "cmd ::= PRAGMA nm dbnm",
85709  /* 259 */ "nmnum ::= plus_num",
85710  /* 260 */ "nmnum ::= nm",
85711  /* 261 */ "plus_num ::= plus_opt number",
85712  /* 262 */ "minus_num ::= MINUS number",
85713  /* 263 */ "number ::= INTEGER|FLOAT",
85714  /* 264 */ "plus_opt ::= PLUS",
85715  /* 265 */ "plus_opt ::=",
85716  /* 266 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
85717  /* 267 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
85718  /* 268 */ "trigger_time ::= BEFORE",
85719  /* 269 */ "trigger_time ::= AFTER",
85720  /* 270 */ "trigger_time ::= INSTEAD OF",
85721  /* 271 */ "trigger_time ::=",
85722  /* 272 */ "trigger_event ::= DELETE|INSERT",
85723  /* 273 */ "trigger_event ::= UPDATE",
85724  /* 274 */ "trigger_event ::= UPDATE OF inscollist",
85725  /* 275 */ "foreach_clause ::=",
85726  /* 276 */ "foreach_clause ::= FOR EACH ROW",
85727  /* 277 */ "when_clause ::=",
85728  /* 278 */ "when_clause ::= WHEN expr",
85729  /* 279 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
85730  /* 280 */ "trigger_cmd_list ::= trigger_cmd SEMI",
85731  /* 281 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
85732  /* 282 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
85733  /* 283 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
85734  /* 284 */ "trigger_cmd ::= DELETE FROM nm where_opt",
85735  /* 285 */ "trigger_cmd ::= select",
85736  /* 286 */ "expr ::= RAISE LP IGNORE RP",
85737  /* 287 */ "expr ::= RAISE LP raisetype COMMA nm RP",
85738  /* 288 */ "raisetype ::= ROLLBACK",
85739  /* 289 */ "raisetype ::= ABORT",
85740  /* 290 */ "raisetype ::= FAIL",
85741  /* 291 */ "cmd ::= DROP TRIGGER ifexists fullname",
85742  /* 292 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
85743  /* 293 */ "cmd ::= DETACH database_kw_opt expr",
85744  /* 294 */ "key_opt ::=",
85745  /* 295 */ "key_opt ::= KEY expr",
85746  /* 296 */ "database_kw_opt ::= DATABASE",
85747  /* 297 */ "database_kw_opt ::=",
85748  /* 298 */ "cmd ::= REINDEX",
85749  /* 299 */ "cmd ::= REINDEX nm dbnm",
85750  /* 300 */ "cmd ::= ANALYZE",
85751  /* 301 */ "cmd ::= ANALYZE nm dbnm",
85752  /* 302 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
85753  /* 303 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
85754  /* 304 */ "add_column_fullname ::= fullname",
85755  /* 305 */ "kwcolumn_opt ::=",
85756  /* 306 */ "kwcolumn_opt ::= COLUMNKW",
85757  /* 307 */ "cmd ::= create_vtab",
85758  /* 308 */ "cmd ::= create_vtab LP vtabarglist RP",
85759  /* 309 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm",
85760  /* 310 */ "vtabarglist ::= vtabarg",
85761  /* 311 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
85762  /* 312 */ "vtabarg ::=",
85763  /* 313 */ "vtabarg ::= vtabarg vtabargtoken",
85764  /* 314 */ "vtabargtoken ::= ANY",
85765  /* 315 */ "vtabargtoken ::= lp anylist RP",
85766  /* 316 */ "lp ::= LP",
85767  /* 317 */ "anylist ::=",
85768  /* 318 */ "anylist ::= anylist ANY",
85769 };
85770 #endif /* NDEBUG */
85771
85772
85773 #if YYSTACKDEPTH<=0
85774 /*
85775 ** Try to increase the size of the parser stack.
85776 */
85777 static void yyGrowStack(yyParser *p){
85778   int newSize;
85779   yyStackEntry *pNew;
85780
85781   newSize = p->yystksz*2 + 100;
85782   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
85783   if( pNew ){
85784     p->yystack = pNew;
85785     p->yystksz = newSize;
85786 #ifndef NDEBUG
85787     if( yyTraceFILE ){
85788       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
85789               yyTracePrompt, p->yystksz);
85790     }
85791 #endif
85792   }
85793 }
85794 #endif
85795
85796 /* 
85797 ** This function allocates a new parser.
85798 ** The only argument is a pointer to a function which works like
85799 ** malloc.
85800 **
85801 ** Inputs:
85802 ** A pointer to the function used to allocate memory.
85803 **
85804 ** Outputs:
85805 ** A pointer to a parser.  This pointer is used in subsequent calls
85806 ** to sqlite3Parser and sqlite3ParserFree.
85807 */
85808 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
85809   yyParser *pParser;
85810   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
85811   if( pParser ){
85812     pParser->yyidx = -1;
85813 #ifdef YYTRACKMAXSTACKDEPTH
85814     pParser->yyidxMax = 0;
85815 #endif
85816 #if YYSTACKDEPTH<=0
85817     pParser->yystack = NULL;
85818     pParser->yystksz = 0;
85819     yyGrowStack(pParser);
85820 #endif
85821   }
85822   return pParser;
85823 }
85824
85825 /* The following function deletes the value associated with a
85826 ** symbol.  The symbol can be either a terminal or nonterminal.
85827 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
85828 ** the value.
85829 */
85830 static void yy_destructor(
85831   yyParser *yypParser,    /* The parser */
85832   YYCODETYPE yymajor,     /* Type code for object to destroy */
85833   YYMINORTYPE *yypminor   /* The object to be destroyed */
85834 ){
85835   sqlite3ParserARG_FETCH;
85836   switch( yymajor ){
85837     /* Here is inserted the actions which take place when a
85838     ** terminal or non-terminal is destroyed.  This can happen
85839     ** when the symbol is popped from the stack during a
85840     ** reduce or during error processing or when a parser is 
85841     ** being destroyed before it is finished parsing.
85842     **
85843     ** Note: during a reduce, the only symbols destroyed are those
85844     ** which appear on the RHS of the rule, but which are not used
85845     ** inside the C code.
85846     */
85847     case 159: /* select */
85848     case 193: /* oneselect */
85849 {
85850 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
85851 }
85852       break;
85853     case 173: /* term */
85854     case 174: /* expr */
85855     case 198: /* where_opt */
85856     case 200: /* having_opt */
85857     case 209: /* on_opt */
85858     case 214: /* sortitem */
85859     case 222: /* escape */
85860     case 225: /* case_operand */
85861     case 227: /* case_else */
85862     case 238: /* when_clause */
85863     case 241: /* key_opt */
85864 {
85865 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
85866 }
85867       break;
85868     case 178: /* idxlist_opt */
85869     case 186: /* idxlist */
85870     case 196: /* selcollist */
85871     case 199: /* groupby_opt */
85872     case 201: /* orderby_opt */
85873     case 203: /* sclp */
85874     case 213: /* sortlist */
85875     case 215: /* nexprlist */
85876     case 216: /* setlist */
85877     case 219: /* itemlist */
85878     case 220: /* exprlist */
85879     case 226: /* case_exprlist */
85880 {
85881 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
85882 }
85883       break;
85884     case 192: /* fullname */
85885     case 197: /* from */
85886     case 205: /* seltablist */
85887     case 206: /* stl_prefix */
85888 {
85889 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
85890 }
85891       break;
85892     case 210: /* using_opt */
85893     case 212: /* inscollist */
85894     case 218: /* inscollist_opt */
85895 {
85896 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
85897 }
85898       break;
85899     case 234: /* trigger_cmd_list */
85900     case 239: /* trigger_cmd */
85901 {
85902 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
85903 }
85904       break;
85905     case 236: /* trigger_event */
85906 {
85907 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
85908 }
85909       break;
85910     default:  break;   /* If no destructor action specified: do nothing */
85911   }
85912 }
85913
85914 /*
85915 ** Pop the parser's stack once.
85916 **
85917 ** If there is a destructor routine associated with the token which
85918 ** is popped from the stack, then call it.
85919 **
85920 ** Return the major token number for the symbol popped.
85921 */
85922 static int yy_pop_parser_stack(yyParser *pParser){
85923   YYCODETYPE yymajor;
85924   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
85925
85926   if( pParser->yyidx<0 ) return 0;
85927 #ifndef NDEBUG
85928   if( yyTraceFILE && pParser->yyidx>=0 ){
85929     fprintf(yyTraceFILE,"%sPopping %s\n",
85930       yyTracePrompt,
85931       yyTokenName[yytos->major]);
85932   }
85933 #endif
85934   yymajor = yytos->major;
85935   yy_destructor(pParser, yymajor, &yytos->minor);
85936   pParser->yyidx--;
85937   return yymajor;
85938 }
85939
85940 /* 
85941 ** Deallocate and destroy a parser.  Destructors are all called for
85942 ** all stack elements before shutting the parser down.
85943 **
85944 ** Inputs:
85945 ** <ul>
85946 ** <li>  A pointer to the parser.  This should be a pointer
85947 **       obtained from sqlite3ParserAlloc.
85948 ** <li>  A pointer to a function used to reclaim memory obtained
85949 **       from malloc.
85950 ** </ul>
85951 */
85952 SQLITE_PRIVATE void sqlite3ParserFree(
85953   void *p,                    /* The parser to be deleted */
85954   void (*freeProc)(void*)     /* Function used to reclaim memory */
85955 ){
85956   yyParser *pParser = (yyParser*)p;
85957   if( pParser==0 ) return;
85958   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
85959 #if YYSTACKDEPTH<=0
85960   free(pParser->yystack);
85961 #endif
85962   (*freeProc)((void*)pParser);
85963 }
85964
85965 /*
85966 ** Return the peak depth of the stack for a parser.
85967 */
85968 #ifdef YYTRACKMAXSTACKDEPTH
85969 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
85970   yyParser *pParser = (yyParser*)p;
85971   return pParser->yyidxMax;
85972 }
85973 #endif
85974
85975 /*
85976 ** Find the appropriate action for a parser given the terminal
85977 ** look-ahead token iLookAhead.
85978 **
85979 ** If the look-ahead token is YYNOCODE, then check to see if the action is
85980 ** independent of the look-ahead.  If it is, return the action, otherwise
85981 ** return YY_NO_ACTION.
85982 */
85983 static int yy_find_shift_action(
85984   yyParser *pParser,        /* The parser */
85985   YYCODETYPE iLookAhead     /* The look-ahead token */
85986 ){
85987   int i;
85988   int stateno = pParser->yystack[pParser->yyidx].stateno;
85989  
85990   if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
85991     return yy_default[stateno];
85992   }
85993   assert( iLookAhead!=YYNOCODE );
85994   i += iLookAhead;
85995   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
85996     if( iLookAhead>0 ){
85997 #ifdef YYFALLBACK
85998       YYCODETYPE iFallback;            /* Fallback token */
85999       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
86000              && (iFallback = yyFallback[iLookAhead])!=0 ){
86001 #ifndef NDEBUG
86002         if( yyTraceFILE ){
86003           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
86004              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
86005         }
86006 #endif
86007         return yy_find_shift_action(pParser, iFallback);
86008       }
86009 #endif
86010 #ifdef YYWILDCARD
86011       {
86012         int j = i - iLookAhead + YYWILDCARD;
86013         if( j>=0 && j<YY_SZ_ACTTAB && yy_lookahead[j]==YYWILDCARD ){
86014 #ifndef NDEBUG
86015           if( yyTraceFILE ){
86016             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
86017                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
86018           }
86019 #endif /* NDEBUG */
86020           return yy_action[j];
86021         }
86022       }
86023 #endif /* YYWILDCARD */
86024     }
86025     return yy_default[stateno];
86026   }else{
86027     return yy_action[i];
86028   }
86029 }
86030
86031 /*
86032 ** Find the appropriate action for a parser given the non-terminal
86033 ** look-ahead token iLookAhead.
86034 **
86035 ** If the look-ahead token is YYNOCODE, then check to see if the action is
86036 ** independent of the look-ahead.  If it is, return the action, otherwise
86037 ** return YY_NO_ACTION.
86038 */
86039 static int yy_find_reduce_action(
86040   int stateno,              /* Current state number */
86041   YYCODETYPE iLookAhead     /* The look-ahead token */
86042 ){
86043   int i;
86044 #ifdef YYERRORSYMBOL
86045   if( stateno>YY_REDUCE_MAX ){
86046     return yy_default[stateno];
86047   }
86048 #else
86049   assert( stateno<=YY_REDUCE_MAX );
86050 #endif
86051   i = yy_reduce_ofst[stateno];
86052   assert( i!=YY_REDUCE_USE_DFLT );
86053   assert( iLookAhead!=YYNOCODE );
86054   i += iLookAhead;
86055 #ifdef YYERRORSYMBOL
86056   if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){
86057     return yy_default[stateno];
86058   }
86059 #else
86060   assert( i>=0 && i<YY_SZ_ACTTAB );
86061   assert( yy_lookahead[i]==iLookAhead );
86062 #endif
86063   return yy_action[i];
86064 }
86065
86066 /*
86067 ** The following routine is called if the stack overflows.
86068 */
86069 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
86070    sqlite3ParserARG_FETCH;
86071    yypParser->yyidx--;
86072 #ifndef NDEBUG
86073    if( yyTraceFILE ){
86074      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
86075    }
86076 #endif
86077    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
86078    /* Here code is inserted which will execute if the parser
86079    ** stack every overflows */
86080
86081   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
86082   sqlite3ErrorMsg(pParse, "parser stack overflow");
86083   pParse->parseError = 1;
86084    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
86085 }
86086
86087 /*
86088 ** Perform a shift action.
86089 */
86090 static void yy_shift(
86091   yyParser *yypParser,          /* The parser to be shifted */
86092   int yyNewState,               /* The new state to shift in */
86093   int yyMajor,                  /* The major token to shift in */
86094   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
86095 ){
86096   yyStackEntry *yytos;
86097   yypParser->yyidx++;
86098 #ifdef YYTRACKMAXSTACKDEPTH
86099   if( yypParser->yyidx>yypParser->yyidxMax ){
86100     yypParser->yyidxMax = yypParser->yyidx;
86101   }
86102 #endif
86103 #if YYSTACKDEPTH>0 
86104   if( yypParser->yyidx>=YYSTACKDEPTH ){
86105     yyStackOverflow(yypParser, yypMinor);
86106     return;
86107   }
86108 #else
86109   if( yypParser->yyidx>=yypParser->yystksz ){
86110     yyGrowStack(yypParser);
86111     if( yypParser->yyidx>=yypParser->yystksz ){
86112       yyStackOverflow(yypParser, yypMinor);
86113       return;
86114     }
86115   }
86116 #endif
86117   yytos = &yypParser->yystack[yypParser->yyidx];
86118   yytos->stateno = (YYACTIONTYPE)yyNewState;
86119   yytos->major = (YYCODETYPE)yyMajor;
86120   yytos->minor = *yypMinor;
86121 #ifndef NDEBUG
86122   if( yyTraceFILE && yypParser->yyidx>0 ){
86123     int i;
86124     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
86125     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
86126     for(i=1; i<=yypParser->yyidx; i++)
86127       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
86128     fprintf(yyTraceFILE,"\n");
86129   }
86130 #endif
86131 }
86132
86133 /* The following table contains information about every rule that
86134 ** is used during the reduce.
86135 */
86136 static const struct {
86137   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
86138   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
86139 } yyRuleInfo[] = {
86140   { 142, 1 },
86141   { 143, 2 },
86142   { 143, 1 },
86143   { 144, 1 },
86144   { 144, 3 },
86145   { 145, 0 },
86146   { 145, 1 },
86147   { 145, 3 },
86148   { 146, 1 },
86149   { 147, 3 },
86150   { 149, 0 },
86151   { 149, 1 },
86152   { 149, 2 },
86153   { 148, 0 },
86154   { 148, 1 },
86155   { 148, 1 },
86156   { 148, 1 },
86157   { 147, 2 },
86158   { 147, 2 },
86159   { 147, 2 },
86160   { 151, 1 },
86161   { 151, 0 },
86162   { 147, 2 },
86163   { 147, 3 },
86164   { 147, 5 },
86165   { 147, 2 },
86166   { 152, 6 },
86167   { 155, 0 },
86168   { 155, 3 },
86169   { 154, 1 },
86170   { 154, 0 },
86171   { 153, 4 },
86172   { 153, 2 },
86173   { 157, 3 },
86174   { 157, 1 },
86175   { 160, 3 },
86176   { 161, 1 },
86177   { 164, 1 },
86178   { 165, 1 },
86179   { 150, 1 },
86180   { 150, 1 },
86181   { 150, 1 },
86182   { 162, 0 },
86183   { 162, 1 },
86184   { 166, 1 },
86185   { 166, 4 },
86186   { 166, 6 },
86187   { 167, 1 },
86188   { 167, 2 },
86189   { 168, 1 },
86190   { 168, 1 },
86191   { 163, 2 },
86192   { 163, 0 },
86193   { 171, 3 },
86194   { 171, 1 },
86195   { 172, 2 },
86196   { 172, 4 },
86197   { 172, 3 },
86198   { 172, 3 },
86199   { 172, 2 },
86200   { 172, 2 },
86201   { 172, 3 },
86202   { 172, 5 },
86203   { 172, 2 },
86204   { 172, 4 },
86205   { 172, 4 },
86206   { 172, 1 },
86207   { 172, 2 },
86208   { 177, 0 },
86209   { 177, 1 },
86210   { 179, 0 },
86211   { 179, 2 },
86212   { 181, 2 },
86213   { 181, 3 },
86214   { 181, 3 },
86215   { 181, 3 },
86216   { 182, 2 },
86217   { 182, 2 },
86218   { 182, 1 },
86219   { 182, 1 },
86220   { 180, 3 },
86221   { 180, 2 },
86222   { 183, 0 },
86223   { 183, 2 },
86224   { 183, 2 },
86225   { 158, 0 },
86226   { 158, 2 },
86227   { 184, 3 },
86228   { 184, 2 },
86229   { 184, 1 },
86230   { 185, 2 },
86231   { 185, 7 },
86232   { 185, 5 },
86233   { 185, 5 },
86234   { 185, 10 },
86235   { 187, 0 },
86236   { 187, 1 },
86237   { 175, 0 },
86238   { 175, 3 },
86239   { 188, 0 },
86240   { 188, 2 },
86241   { 189, 1 },
86242   { 189, 1 },
86243   { 189, 1 },
86244   { 147, 4 },
86245   { 191, 2 },
86246   { 191, 0 },
86247   { 147, 8 },
86248   { 147, 4 },
86249   { 147, 1 },
86250   { 159, 1 },
86251   { 159, 3 },
86252   { 194, 1 },
86253   { 194, 2 },
86254   { 194, 1 },
86255   { 193, 9 },
86256   { 195, 1 },
86257   { 195, 1 },
86258   { 195, 0 },
86259   { 203, 2 },
86260   { 203, 0 },
86261   { 196, 3 },
86262   { 196, 2 },
86263   { 196, 4 },
86264   { 204, 2 },
86265   { 204, 1 },
86266   { 204, 0 },
86267   { 197, 0 },
86268   { 197, 2 },
86269   { 206, 2 },
86270   { 206, 0 },
86271   { 205, 7 },
86272   { 205, 7 },
86273   { 205, 7 },
86274   { 156, 0 },
86275   { 156, 2 },
86276   { 192, 2 },
86277   { 207, 1 },
86278   { 207, 2 },
86279   { 207, 3 },
86280   { 207, 4 },
86281   { 209, 2 },
86282   { 209, 0 },
86283   { 208, 0 },
86284   { 208, 3 },
86285   { 208, 2 },
86286   { 210, 4 },
86287   { 210, 0 },
86288   { 201, 0 },
86289   { 201, 3 },
86290   { 213, 4 },
86291   { 213, 2 },
86292   { 214, 1 },
86293   { 176, 1 },
86294   { 176, 1 },
86295   { 176, 0 },
86296   { 199, 0 },
86297   { 199, 3 },
86298   { 200, 0 },
86299   { 200, 2 },
86300   { 202, 0 },
86301   { 202, 2 },
86302   { 202, 4 },
86303   { 202, 4 },
86304   { 147, 5 },
86305   { 198, 0 },
86306   { 198, 2 },
86307   { 147, 7 },
86308   { 216, 5 },
86309   { 216, 3 },
86310   { 147, 8 },
86311   { 147, 5 },
86312   { 147, 6 },
86313   { 217, 2 },
86314   { 217, 1 },
86315   { 219, 3 },
86316   { 219, 1 },
86317   { 218, 0 },
86318   { 218, 3 },
86319   { 212, 3 },
86320   { 212, 1 },
86321   { 174, 1 },
86322   { 174, 3 },
86323   { 173, 1 },
86324   { 174, 1 },
86325   { 174, 1 },
86326   { 174, 3 },
86327   { 174, 5 },
86328   { 173, 1 },
86329   { 173, 1 },
86330   { 174, 1 },
86331   { 174, 1 },
86332   { 174, 3 },
86333   { 174, 6 },
86334   { 174, 5 },
86335   { 174, 4 },
86336   { 173, 1 },
86337   { 174, 3 },
86338   { 174, 3 },
86339   { 174, 3 },
86340   { 174, 3 },
86341   { 174, 3 },
86342   { 174, 3 },
86343   { 174, 3 },
86344   { 174, 3 },
86345   { 221, 1 },
86346   { 221, 2 },
86347   { 221, 1 },
86348   { 221, 2 },
86349   { 222, 2 },
86350   { 222, 0 },
86351   { 174, 4 },
86352   { 174, 2 },
86353   { 174, 3 },
86354   { 174, 3 },
86355   { 174, 4 },
86356   { 174, 2 },
86357   { 174, 2 },
86358   { 174, 2 },
86359   { 174, 2 },
86360   { 223, 1 },
86361   { 223, 2 },
86362   { 174, 5 },
86363   { 224, 1 },
86364   { 224, 2 },
86365   { 174, 5 },
86366   { 174, 3 },
86367   { 174, 5 },
86368   { 174, 4 },
86369   { 174, 4 },
86370   { 174, 5 },
86371   { 226, 5 },
86372   { 226, 4 },
86373   { 227, 2 },
86374   { 227, 0 },
86375   { 225, 1 },
86376   { 225, 0 },
86377   { 220, 1 },
86378   { 220, 0 },
86379   { 215, 3 },
86380   { 215, 1 },
86381   { 147, 11 },
86382   { 228, 1 },
86383   { 228, 0 },
86384   { 178, 0 },
86385   { 178, 3 },
86386   { 186, 5 },
86387   { 186, 3 },
86388   { 229, 0 },
86389   { 229, 2 },
86390   { 147, 4 },
86391   { 147, 1 },
86392   { 147, 2 },
86393   { 147, 5 },
86394   { 147, 5 },
86395   { 147, 5 },
86396   { 147, 5 },
86397   { 147, 6 },
86398   { 147, 3 },
86399   { 230, 1 },
86400   { 230, 1 },
86401   { 169, 2 },
86402   { 170, 2 },
86403   { 232, 1 },
86404   { 231, 1 },
86405   { 231, 0 },
86406   { 147, 5 },
86407   { 233, 11 },
86408   { 235, 1 },
86409   { 235, 1 },
86410   { 235, 2 },
86411   { 235, 0 },
86412   { 236, 1 },
86413   { 236, 1 },
86414   { 236, 3 },
86415   { 237, 0 },
86416   { 237, 3 },
86417   { 238, 0 },
86418   { 238, 2 },
86419   { 234, 3 },
86420   { 234, 2 },
86421   { 239, 6 },
86422   { 239, 8 },
86423   { 239, 5 },
86424   { 239, 4 },
86425   { 239, 1 },
86426   { 174, 4 },
86427   { 174, 6 },
86428   { 190, 1 },
86429   { 190, 1 },
86430   { 190, 1 },
86431   { 147, 4 },
86432   { 147, 6 },
86433   { 147, 3 },
86434   { 241, 0 },
86435   { 241, 2 },
86436   { 240, 1 },
86437   { 240, 0 },
86438   { 147, 1 },
86439   { 147, 3 },
86440   { 147, 1 },
86441   { 147, 3 },
86442   { 147, 6 },
86443   { 147, 6 },
86444   { 242, 1 },
86445   { 243, 0 },
86446   { 243, 1 },
86447   { 147, 1 },
86448   { 147, 4 },
86449   { 244, 7 },
86450   { 245, 1 },
86451   { 245, 3 },
86452   { 246, 0 },
86453   { 246, 2 },
86454   { 247, 1 },
86455   { 247, 3 },
86456   { 248, 1 },
86457   { 249, 0 },
86458   { 249, 2 },
86459 };
86460
86461 static void yy_accept(yyParser*);  /* Forward Declaration */
86462
86463 /*
86464 ** Perform a reduce action and the shift that must immediately
86465 ** follow the reduce.
86466 */
86467 static void yy_reduce(
86468   yyParser *yypParser,         /* The parser */
86469   int yyruleno                 /* Number of the rule by which to reduce */
86470 ){
86471   int yygoto;                     /* The next state */
86472   int yyact;                      /* The next action */
86473   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
86474   yyStackEntry *yymsp;            /* The top of the parser's stack */
86475   int yysize;                     /* Amount to pop the stack */
86476   sqlite3ParserARG_FETCH;
86477   yymsp = &yypParser->yystack[yypParser->yyidx];
86478 #ifndef NDEBUG
86479   if( yyTraceFILE && yyruleno>=0 
86480         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
86481     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
86482       yyRuleName[yyruleno]);
86483   }
86484 #endif /* NDEBUG */
86485
86486   /* Silence complaints from purify about yygotominor being uninitialized
86487   ** in some cases when it is copied into the stack after the following
86488   ** switch.  yygotominor is uninitialized when a rule reduces that does
86489   ** not set the value of its left-hand side nonterminal.  Leaving the
86490   ** value of the nonterminal uninitialized is utterly harmless as long
86491   ** as the value is never used.  So really the only thing this code
86492   ** accomplishes is to quieten purify.  
86493   **
86494   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
86495   ** without this code, their parser segfaults.  I'm not sure what there
86496   ** parser is doing to make this happen.  This is the second bug report
86497   ** from wireshark this week.  Clearly they are stressing Lemon in ways
86498   ** that it has not been previously stressed...  (SQLite ticket #2172)
86499   */
86500   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
86501   yygotominor = yyzerominor;
86502
86503
86504   switch( yyruleno ){
86505   /* Beginning here are the reduction cases.  A typical example
86506   ** follows:
86507   **   case 0:
86508   **  #line <lineno> <grammarfile>
86509   **     { ... }           // User supplied code
86510   **  #line <lineno> <thisfile>
86511   **     break;
86512   */
86513       case 0: /* input ::= cmdlist */
86514       case 1: /* cmdlist ::= cmdlist ecmd */
86515       case 2: /* cmdlist ::= ecmd */
86516       case 3: /* ecmd ::= SEMI */
86517       case 4: /* ecmd ::= explain cmdx SEMI */
86518       case 10: /* trans_opt ::= */
86519       case 11: /* trans_opt ::= TRANSACTION */
86520       case 12: /* trans_opt ::= TRANSACTION nm */
86521       case 20: /* savepoint_opt ::= SAVEPOINT */
86522       case 21: /* savepoint_opt ::= */
86523       case 25: /* cmd ::= create_table create_table_args */
86524       case 33: /* columnlist ::= columnlist COMMA column */
86525       case 34: /* columnlist ::= column */
86526       case 42: /* type ::= */
86527       case 49: /* signed ::= plus_num */
86528       case 50: /* signed ::= minus_num */
86529       case 51: /* carglist ::= carglist carg */
86530       case 52: /* carglist ::= */
86531       case 53: /* carg ::= CONSTRAINT nm ccons */
86532       case 54: /* carg ::= ccons */
86533       case 60: /* ccons ::= NULL onconf */
86534       case 87: /* conslist ::= conslist COMMA tcons */
86535       case 88: /* conslist ::= conslist tcons */
86536       case 89: /* conslist ::= tcons */
86537       case 90: /* tcons ::= CONSTRAINT nm */
86538       case 264: /* plus_opt ::= PLUS */
86539       case 265: /* plus_opt ::= */
86540       case 275: /* foreach_clause ::= */
86541       case 276: /* foreach_clause ::= FOR EACH ROW */
86542       case 296: /* database_kw_opt ::= DATABASE */
86543       case 297: /* database_kw_opt ::= */
86544       case 305: /* kwcolumn_opt ::= */
86545       case 306: /* kwcolumn_opt ::= COLUMNKW */
86546       case 310: /* vtabarglist ::= vtabarg */
86547       case 311: /* vtabarglist ::= vtabarglist COMMA vtabarg */
86548       case 313: /* vtabarg ::= vtabarg vtabargtoken */
86549       case 317: /* anylist ::= */
86550 {
86551 }
86552         break;
86553       case 5: /* explain ::= */
86554 { sqlite3BeginParse(pParse, 0); }
86555         break;
86556       case 6: /* explain ::= EXPLAIN */
86557 { sqlite3BeginParse(pParse, 1); }
86558         break;
86559       case 7: /* explain ::= EXPLAIN QUERY PLAN */
86560 { sqlite3BeginParse(pParse, 2); }
86561         break;
86562       case 8: /* cmdx ::= cmd */
86563 { sqlite3FinishCoding(pParse); }
86564         break;
86565       case 9: /* cmd ::= BEGIN transtype trans_opt */
86566 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
86567         break;
86568       case 13: /* transtype ::= */
86569 {yygotominor.yy392 = TK_DEFERRED;}
86570         break;
86571       case 14: /* transtype ::= DEFERRED */
86572       case 15: /* transtype ::= IMMEDIATE */
86573       case 16: /* transtype ::= EXCLUSIVE */
86574       case 112: /* multiselect_op ::= UNION */
86575       case 114: /* multiselect_op ::= EXCEPT|INTERSECT */
86576 {yygotominor.yy392 = yymsp[0].major;}
86577         break;
86578       case 17: /* cmd ::= COMMIT trans_opt */
86579       case 18: /* cmd ::= END trans_opt */
86580 {sqlite3CommitTransaction(pParse);}
86581         break;
86582       case 19: /* cmd ::= ROLLBACK trans_opt */
86583 {sqlite3RollbackTransaction(pParse);}
86584         break;
86585       case 22: /* cmd ::= SAVEPOINT nm */
86586 {
86587   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
86588 }
86589         break;
86590       case 23: /* cmd ::= RELEASE savepoint_opt nm */
86591 {
86592   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
86593 }
86594         break;
86595       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
86596 {
86597   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
86598 }
86599         break;
86600       case 26: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
86601 {
86602    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
86603 }
86604         break;
86605       case 27: /* ifnotexists ::= */
86606       case 30: /* temp ::= */
86607       case 68: /* autoinc ::= */
86608       case 82: /* init_deferred_pred_opt ::= */
86609       case 84: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
86610       case 95: /* defer_subclause_opt ::= */
86611       case 106: /* ifexists ::= */
86612       case 117: /* distinct ::= ALL */
86613       case 118: /* distinct ::= */
86614       case 220: /* between_op ::= BETWEEN */
86615       case 223: /* in_op ::= IN */
86616 {yygotominor.yy392 = 0;}
86617         break;
86618       case 28: /* ifnotexists ::= IF NOT EXISTS */
86619       case 29: /* temp ::= TEMP */
86620       case 69: /* autoinc ::= AUTOINCR */
86621       case 83: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
86622       case 105: /* ifexists ::= IF EXISTS */
86623       case 116: /* distinct ::= DISTINCT */
86624       case 221: /* between_op ::= NOT BETWEEN */
86625       case 224: /* in_op ::= NOT IN */
86626 {yygotominor.yy392 = 1;}
86627         break;
86628       case 31: /* create_table_args ::= LP columnlist conslist_opt RP */
86629 {
86630   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
86631 }
86632         break;
86633       case 32: /* create_table_args ::= AS select */
86634 {
86635   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
86636   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
86637 }
86638         break;
86639       case 35: /* column ::= columnid type carglist */
86640 {
86641   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
86642   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
86643 }
86644         break;
86645       case 36: /* columnid ::= nm */
86646 {
86647   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
86648   yygotominor.yy0 = yymsp[0].minor.yy0;
86649 }
86650         break;
86651       case 37: /* id ::= ID */
86652       case 38: /* ids ::= ID|STRING */
86653       case 39: /* nm ::= ID */
86654       case 40: /* nm ::= STRING */
86655       case 41: /* nm ::= JOIN_KW */
86656       case 44: /* typetoken ::= typename */
86657       case 47: /* typename ::= ids */
86658       case 124: /* as ::= AS nm */
86659       case 125: /* as ::= ids */
86660       case 135: /* dbnm ::= DOT nm */
86661       case 144: /* indexed_opt ::= INDEXED BY nm */
86662       case 249: /* collate ::= COLLATE ids */
86663       case 259: /* nmnum ::= plus_num */
86664       case 260: /* nmnum ::= nm */
86665       case 261: /* plus_num ::= plus_opt number */
86666       case 262: /* minus_num ::= MINUS number */
86667       case 263: /* number ::= INTEGER|FLOAT */
86668 {yygotominor.yy0 = yymsp[0].minor.yy0;}
86669         break;
86670       case 43: /* type ::= typetoken */
86671 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
86672         break;
86673       case 45: /* typetoken ::= typename LP signed RP */
86674 {
86675   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
86676   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
86677 }
86678         break;
86679       case 46: /* typetoken ::= typename LP signed COMMA signed RP */
86680 {
86681   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
86682   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
86683 }
86684         break;
86685       case 48: /* typename ::= typename ids */
86686 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
86687         break;
86688       case 55: /* ccons ::= DEFAULT term */
86689       case 57: /* ccons ::= DEFAULT PLUS term */
86690 {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy122);}
86691         break;
86692       case 56: /* ccons ::= DEFAULT LP expr RP */
86693 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy122);}
86694         break;
86695       case 58: /* ccons ::= DEFAULT MINUS term */
86696 {
86697   Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy122, 0, 0);
86698   sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
86699   sqlite3AddDefaultValue(pParse,p);
86700 }
86701         break;
86702       case 59: /* ccons ::= DEFAULT id */
86703 {
86704   Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
86705   sqlite3AddDefaultValue(pParse,p);
86706 }
86707         break;
86708       case 61: /* ccons ::= NOT NULL onconf */
86709 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
86710         break;
86711       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
86712 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
86713         break;
86714       case 63: /* ccons ::= UNIQUE onconf */
86715 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
86716         break;
86717       case 64: /* ccons ::= CHECK LP expr RP */
86718 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy122);}
86719         break;
86720       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
86721 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
86722         break;
86723       case 66: /* ccons ::= defer_subclause */
86724 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
86725         break;
86726       case 67: /* ccons ::= COLLATE ids */
86727 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
86728         break;
86729       case 70: /* refargs ::= */
86730 { yygotominor.yy392 = OE_Restrict * 0x010101; }
86731         break;
86732       case 71: /* refargs ::= refargs refarg */
86733 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
86734         break;
86735       case 72: /* refarg ::= MATCH nm */
86736 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
86737         break;
86738       case 73: /* refarg ::= ON DELETE refact */
86739 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
86740         break;
86741       case 74: /* refarg ::= ON UPDATE refact */
86742 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
86743         break;
86744       case 75: /* refarg ::= ON INSERT refact */
86745 { yygotominor.yy207.value = yymsp[0].minor.yy392<<16; yygotominor.yy207.mask = 0xff0000; }
86746         break;
86747       case 76: /* refact ::= SET NULL */
86748 { yygotominor.yy392 = OE_SetNull; }
86749         break;
86750       case 77: /* refact ::= SET DEFAULT */
86751 { yygotominor.yy392 = OE_SetDflt; }
86752         break;
86753       case 78: /* refact ::= CASCADE */
86754 { yygotominor.yy392 = OE_Cascade; }
86755         break;
86756       case 79: /* refact ::= RESTRICT */
86757 { yygotominor.yy392 = OE_Restrict; }
86758         break;
86759       case 80: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
86760       case 81: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
86761       case 96: /* defer_subclause_opt ::= defer_subclause */
86762       case 98: /* onconf ::= ON CONFLICT resolvetype */
86763       case 100: /* orconf ::= OR resolvetype */
86764       case 101: /* resolvetype ::= raisetype */
86765       case 173: /* insert_cmd ::= INSERT orconf */
86766 {yygotominor.yy392 = yymsp[0].minor.yy392;}
86767         break;
86768       case 85: /* conslist_opt ::= */
86769 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
86770         break;
86771       case 86: /* conslist_opt ::= COMMA conslist */
86772 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
86773         break;
86774       case 91: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
86775 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
86776         break;
86777       case 92: /* tcons ::= UNIQUE LP idxlist RP onconf */
86778 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
86779         break;
86780       case 93: /* tcons ::= CHECK LP expr RP onconf */
86781 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy122);}
86782         break;
86783       case 94: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
86784 {
86785     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
86786     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
86787 }
86788         break;
86789       case 97: /* onconf ::= */
86790       case 99: /* orconf ::= */
86791 {yygotominor.yy392 = OE_Default;}
86792         break;
86793       case 102: /* resolvetype ::= IGNORE */
86794 {yygotominor.yy392 = OE_Ignore;}
86795         break;
86796       case 103: /* resolvetype ::= REPLACE */
86797       case 174: /* insert_cmd ::= REPLACE */
86798 {yygotominor.yy392 = OE_Replace;}
86799         break;
86800       case 104: /* cmd ::= DROP TABLE ifexists fullname */
86801 {
86802   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
86803 }
86804         break;
86805       case 107: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
86806 {
86807   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
86808 }
86809         break;
86810       case 108: /* cmd ::= DROP VIEW ifexists fullname */
86811 {
86812   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
86813 }
86814         break;
86815       case 109: /* cmd ::= select */
86816 {
86817   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
86818   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
86819   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
86820 }
86821         break;
86822       case 110: /* select ::= oneselect */
86823 {yygotominor.yy159 = yymsp[0].minor.yy159;}
86824         break;
86825       case 111: /* select ::= select multiselect_op oneselect */
86826 {
86827   if( yymsp[0].minor.yy159 ){
86828     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
86829     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
86830   }else{
86831     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
86832   }
86833   yygotominor.yy159 = yymsp[0].minor.yy159;
86834 }
86835         break;
86836       case 113: /* multiselect_op ::= UNION ALL */
86837 {yygotominor.yy392 = TK_ALL;}
86838         break;
86839       case 115: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
86840 {
86841   yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
86842 }
86843         break;
86844       case 119: /* sclp ::= selcollist COMMA */
86845       case 245: /* idxlist_opt ::= LP idxlist RP */
86846 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
86847         break;
86848       case 120: /* sclp ::= */
86849       case 148: /* orderby_opt ::= */
86850       case 156: /* groupby_opt ::= */
86851       case 238: /* exprlist ::= */
86852       case 244: /* idxlist_opt ::= */
86853 {yygotominor.yy442 = 0;}
86854         break;
86855       case 121: /* selcollist ::= sclp expr as */
86856 {
86857    yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
86858 }
86859         break;
86860       case 122: /* selcollist ::= sclp STAR */
86861 {
86862   Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
86863   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p, 0);
86864 }
86865         break;
86866       case 123: /* selcollist ::= sclp nm DOT STAR */
86867 {
86868   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
86869   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
86870   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
86871   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot, 0);
86872 }
86873         break;
86874       case 126: /* as ::= */
86875 {yygotominor.yy0.n = 0;}
86876         break;
86877       case 127: /* from ::= */
86878 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
86879         break;
86880       case 128: /* from ::= FROM seltablist */
86881 {
86882   yygotominor.yy347 = yymsp[0].minor.yy347;
86883   sqlite3SrcListShiftJoinType(yygotominor.yy347);
86884 }
86885         break;
86886       case 129: /* stl_prefix ::= seltablist joinop */
86887 {
86888    yygotominor.yy347 = yymsp[-1].minor.yy347;
86889    if( yygotominor.yy347 && yygotominor.yy347->nSrc>0 ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
86890 }
86891         break;
86892       case 130: /* stl_prefix ::= */
86893 {yygotominor.yy347 = 0;}
86894         break;
86895       case 131: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
86896 {
86897   yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
86898   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
86899 }
86900         break;
86901       case 132: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
86902 {
86903     yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
86904   }
86905         break;
86906       case 133: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
86907 {
86908     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
86909       yygotominor.yy347 = yymsp[-4].minor.yy347;
86910     }else{
86911       Select *pSubquery;
86912       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
86913       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
86914       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
86915     }
86916   }
86917         break;
86918       case 134: /* dbnm ::= */
86919       case 143: /* indexed_opt ::= */
86920 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
86921         break;
86922       case 136: /* fullname ::= nm dbnm */
86923 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
86924         break;
86925       case 137: /* joinop ::= COMMA|JOIN */
86926 { yygotominor.yy392 = JT_INNER; }
86927         break;
86928       case 138: /* joinop ::= JOIN_KW JOIN */
86929 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
86930         break;
86931       case 139: /* joinop ::= JOIN_KW nm JOIN */
86932 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
86933         break;
86934       case 140: /* joinop ::= JOIN_KW nm nm JOIN */
86935 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
86936         break;
86937       case 141: /* on_opt ::= ON expr */
86938       case 152: /* sortitem ::= expr */
86939       case 159: /* having_opt ::= HAVING expr */
86940       case 166: /* where_opt ::= WHERE expr */
86941       case 181: /* expr ::= term */
86942       case 209: /* escape ::= ESCAPE expr */
86943       case 233: /* case_else ::= ELSE expr */
86944       case 235: /* case_operand ::= expr */
86945 {yygotominor.yy122 = yymsp[0].minor.yy122;}
86946         break;
86947       case 142: /* on_opt ::= */
86948       case 158: /* having_opt ::= */
86949       case 165: /* where_opt ::= */
86950       case 210: /* escape ::= */
86951       case 234: /* case_else ::= */
86952       case 236: /* case_operand ::= */
86953 {yygotominor.yy122 = 0;}
86954         break;
86955       case 145: /* indexed_opt ::= NOT INDEXED */
86956 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
86957         break;
86958       case 146: /* using_opt ::= USING LP inscollist RP */
86959       case 178: /* inscollist_opt ::= LP inscollist RP */
86960 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
86961         break;
86962       case 147: /* using_opt ::= */
86963       case 177: /* inscollist_opt ::= */
86964 {yygotominor.yy180 = 0;}
86965         break;
86966       case 149: /* orderby_opt ::= ORDER BY sortlist */
86967       case 157: /* groupby_opt ::= GROUP BY nexprlist */
86968       case 237: /* exprlist ::= nexprlist */
86969 {yygotominor.yy442 = yymsp[0].minor.yy442;}
86970         break;
86971       case 150: /* sortlist ::= sortlist COMMA sortitem sortorder */
86972 {
86973   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy122,0);
86974   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
86975 }
86976         break;
86977       case 151: /* sortlist ::= sortitem sortorder */
86978 {
86979   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy122,0);
86980   if( yygotominor.yy442 && yygotominor.yy442->a ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
86981 }
86982         break;
86983       case 153: /* sortorder ::= ASC */
86984       case 155: /* sortorder ::= */
86985 {yygotominor.yy392 = SQLITE_SO_ASC;}
86986         break;
86987       case 154: /* sortorder ::= DESC */
86988 {yygotominor.yy392 = SQLITE_SO_DESC;}
86989         break;
86990       case 160: /* limit_opt ::= */
86991 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
86992         break;
86993       case 161: /* limit_opt ::= LIMIT expr */
86994 {yygotominor.yy64.pLimit = yymsp[0].minor.yy122; yygotominor.yy64.pOffset = 0;}
86995         break;
86996       case 162: /* limit_opt ::= LIMIT expr OFFSET expr */
86997 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy122; yygotominor.yy64.pOffset = yymsp[0].minor.yy122;}
86998         break;
86999       case 163: /* limit_opt ::= LIMIT expr COMMA expr */
87000 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy122; yygotominor.yy64.pLimit = yymsp[0].minor.yy122;}
87001         break;
87002       case 164: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
87003 {
87004   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
87005   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
87006 }
87007         break;
87008       case 167: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
87009 {
87010   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
87011   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
87012   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy392);
87013 }
87014         break;
87015       case 168: /* setlist ::= setlist COMMA nm EQ expr */
87016 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442,yymsp[0].minor.yy122,&yymsp[-2].minor.yy0);}
87017         break;
87018       case 169: /* setlist ::= nm EQ expr */
87019 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy122,&yymsp[-2].minor.yy0);}
87020         break;
87021       case 170: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
87022 {sqlite3Insert(pParse, yymsp[-5].minor.yy347, yymsp[-1].minor.yy442, 0, yymsp[-4].minor.yy180, yymsp[-7].minor.yy392);}
87023         break;
87024       case 171: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
87025 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy392);}
87026         break;
87027       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
87028 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy392);}
87029         break;
87030       case 175: /* itemlist ::= itemlist COMMA expr */
87031       case 239: /* nexprlist ::= nexprlist COMMA expr */
87032 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy122,0);}
87033         break;
87034       case 176: /* itemlist ::= expr */
87035       case 240: /* nexprlist ::= expr */
87036 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy122,0);}
87037         break;
87038       case 179: /* inscollist ::= inscollist COMMA nm */
87039 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
87040         break;
87041       case 180: /* inscollist ::= nm */
87042 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
87043         break;
87044       case 182: /* expr ::= LP expr RP */
87045 {yygotominor.yy122 = yymsp[-1].minor.yy122; sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
87046         break;
87047       case 183: /* term ::= NULL */
87048       case 188: /* term ::= INTEGER|FLOAT|BLOB */
87049       case 189: /* term ::= STRING */
87050 {yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
87051         break;
87052       case 184: /* expr ::= ID */
87053       case 185: /* expr ::= JOIN_KW */
87054 {yygotominor.yy122 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
87055         break;
87056       case 186: /* expr ::= nm DOT nm */
87057 {
87058   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
87059   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
87060   yygotominor.yy122 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
87061 }
87062         break;
87063       case 187: /* expr ::= nm DOT nm DOT nm */
87064 {
87065   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
87066   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
87067   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
87068   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
87069   yygotominor.yy122 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
87070 }
87071         break;
87072       case 190: /* expr ::= REGISTER */
87073 {yygotominor.yy122 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
87074         break;
87075       case 191: /* expr ::= VARIABLE */
87076 {
87077   Token *pToken = &yymsp[0].minor.yy0;
87078   Expr *pExpr = yygotominor.yy122 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
87079   sqlite3ExprAssignVarNumber(pParse, pExpr);
87080 }
87081         break;
87082       case 192: /* expr ::= expr COLLATE ids */
87083 {
87084   yygotominor.yy122 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy122, &yymsp[0].minor.yy0);
87085 }
87086         break;
87087       case 193: /* expr ::= CAST LP expr AS typetoken RP */
87088 {
87089   yygotominor.yy122 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy122, 0, &yymsp[-1].minor.yy0);
87090   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
87091 }
87092         break;
87093       case 194: /* expr ::= ID LP distinct exprlist RP */
87094 {
87095   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>SQLITE_MAX_FUNCTION_ARG ){
87096     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
87097   }
87098   yygotominor.yy122 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
87099   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
87100   if( yymsp[-2].minor.yy392 && yygotominor.yy122 ){
87101     yygotominor.yy122->flags |= EP_Distinct;
87102   }
87103 }
87104         break;
87105       case 195: /* expr ::= ID LP STAR RP */
87106 {
87107   yygotominor.yy122 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
87108   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
87109 }
87110         break;
87111       case 196: /* term ::= CTIME_KW */
87112 {
87113   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
87114   ** treated as functions that return constants */
87115   yygotominor.yy122 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
87116   if( yygotominor.yy122 ){
87117     yygotominor.yy122->op = TK_CONST_FUNC;  
87118     yygotominor.yy122->span = yymsp[0].minor.yy0;
87119   }
87120 }
87121         break;
87122       case 197: /* expr ::= expr AND expr */
87123       case 198: /* expr ::= expr OR expr */
87124       case 199: /* expr ::= expr LT|GT|GE|LE expr */
87125       case 200: /* expr ::= expr EQ|NE expr */
87126       case 201: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
87127       case 202: /* expr ::= expr PLUS|MINUS expr */
87128       case 203: /* expr ::= expr STAR|SLASH|REM expr */
87129       case 204: /* expr ::= expr CONCAT expr */
87130 {yygotominor.yy122 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy122,yymsp[0].minor.yy122,0);}
87131         break;
87132       case 205: /* likeop ::= LIKE_KW */
87133       case 207: /* likeop ::= MATCH */
87134 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
87135         break;
87136       case 206: /* likeop ::= NOT LIKE_KW */
87137       case 208: /* likeop ::= NOT MATCH */
87138 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
87139         break;
87140       case 211: /* expr ::= expr likeop expr escape */
87141 {
87142   ExprList *pList;
87143   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy122, 0);
87144   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy122, 0);
87145   if( yymsp[0].minor.yy122 ){
87146     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy122, 0);
87147   }
87148   yygotominor.yy122 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy318.eOperator);
87149   if( yymsp[-2].minor.yy318.not ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
87150   sqlite3ExprSpan(yygotominor.yy122, &yymsp[-3].minor.yy122->span, &yymsp[-1].minor.yy122->span);
87151   if( yygotominor.yy122 ) yygotominor.yy122->flags |= EP_InfixFunc;
87152 }
87153         break;
87154       case 212: /* expr ::= expr ISNULL|NOTNULL */
87155 {
87156   yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy122, 0, 0);
87157   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy122->span,&yymsp[0].minor.yy0);
87158 }
87159         break;
87160       case 213: /* expr ::= expr IS NULL */
87161 {
87162   yygotominor.yy122 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy122, 0, 0);
87163   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy122->span,&yymsp[0].minor.yy0);
87164 }
87165         break;
87166       case 214: /* expr ::= expr NOT NULL */
87167 {
87168   yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy122, 0, 0);
87169   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy122->span,&yymsp[0].minor.yy0);
87170 }
87171         break;
87172       case 215: /* expr ::= expr IS NOT NULL */
87173 {
87174   yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy122, 0, 0);
87175   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy122->span,&yymsp[0].minor.yy0);
87176 }
87177         break;
87178       case 216: /* expr ::= NOT expr */
87179       case 217: /* expr ::= BITNOT expr */
87180 {
87181   yygotominor.yy122 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy122, 0, 0);
87182   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
87183 }
87184         break;
87185       case 218: /* expr ::= MINUS expr */
87186 {
87187   yygotominor.yy122 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy122, 0, 0);
87188   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
87189 }
87190         break;
87191       case 219: /* expr ::= PLUS expr */
87192 {
87193   yygotominor.yy122 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy122, 0, 0);
87194   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy122->span);
87195 }
87196         break;
87197       case 222: /* expr ::= expr between_op expr AND expr */
87198 {
87199   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy122, 0);
87200   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy122, 0);
87201   yygotominor.yy122 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy122, 0, 0);
87202   if( yygotominor.yy122 ){
87203     yygotominor.yy122->pList = pList;
87204   }else{
87205     sqlite3ExprListDelete(pParse->db, pList);
87206   } 
87207   if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
87208   sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy122->span);
87209 }
87210         break;
87211       case 225: /* expr ::= expr in_op LP exprlist RP */
87212 {
87213     yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy122, 0, 0);
87214     if( yygotominor.yy122 ){
87215       yygotominor.yy122->pList = yymsp[-1].minor.yy442;
87216       sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87217     }else{
87218       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
87219     }
87220     if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
87221     sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy0);
87222   }
87223         break;
87224       case 226: /* expr ::= LP select RP */
87225 {
87226     yygotominor.yy122 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
87227     if( yygotominor.yy122 ){
87228       yygotominor.yy122->pSelect = yymsp[-1].minor.yy159;
87229       sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87230     }else{
87231       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
87232     }
87233     sqlite3ExprSpan(yygotominor.yy122,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
87234   }
87235         break;
87236       case 227: /* expr ::= expr in_op LP select RP */
87237 {
87238     yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy122, 0, 0);
87239     if( yygotominor.yy122 ){
87240       yygotominor.yy122->pSelect = yymsp[-1].minor.yy159;
87241       sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87242     }else{
87243       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
87244     }
87245     if( yymsp[-3].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
87246     sqlite3ExprSpan(yygotominor.yy122,&yymsp[-4].minor.yy122->span,&yymsp[0].minor.yy0);
87247   }
87248         break;
87249       case 228: /* expr ::= expr in_op nm dbnm */
87250 {
87251     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
87252     yygotominor.yy122 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy122, 0, 0);
87253     if( yygotominor.yy122 ){
87254       yygotominor.yy122->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
87255       sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87256     }else{
87257       sqlite3SrcListDelete(pParse->db, pSrc);
87258     }
87259     if( yymsp[-2].minor.yy392 ) yygotominor.yy122 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy122, 0, 0);
87260     sqlite3ExprSpan(yygotominor.yy122,&yymsp[-3].minor.yy122->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
87261   }
87262         break;
87263       case 229: /* expr ::= EXISTS LP select RP */
87264 {
87265     Expr *p = yygotominor.yy122 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
87266     if( p ){
87267       p->pSelect = yymsp[-1].minor.yy159;
87268       sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
87269       sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87270     }else{
87271       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
87272     }
87273   }
87274         break;
87275       case 230: /* expr ::= CASE case_operand case_exprlist case_else END */
87276 {
87277   yygotominor.yy122 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
87278   if( yygotominor.yy122 ){
87279     yygotominor.yy122->pList = yymsp[-2].minor.yy442;
87280     sqlite3ExprSetHeight(pParse, yygotominor.yy122);
87281   }else{
87282     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
87283   }
87284   sqlite3ExprSpan(yygotominor.yy122, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
87285 }
87286         break;
87287       case 231: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
87288 {
87289   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy122, 0);
87290   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy122, 0);
87291 }
87292         break;
87293       case 232: /* case_exprlist ::= WHEN expr THEN expr */
87294 {
87295   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy122, 0);
87296   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy122, 0);
87297 }
87298         break;
87299       case 241: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
87300 {
87301   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
87302                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
87303                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
87304 }
87305         break;
87306       case 242: /* uniqueflag ::= UNIQUE */
87307       case 289: /* raisetype ::= ABORT */
87308 {yygotominor.yy392 = OE_Abort;}
87309         break;
87310       case 243: /* uniqueflag ::= */
87311 {yygotominor.yy392 = OE_None;}
87312         break;
87313       case 246: /* idxlist ::= idxlist COMMA nm collate sortorder */
87314 {
87315   Expr *p = 0;
87316   if( yymsp[-1].minor.yy0.n>0 ){
87317     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
87318     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
87319   }
87320   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p, &yymsp[-2].minor.yy0);
87321   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
87322   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
87323 }
87324         break;
87325       case 247: /* idxlist ::= nm collate sortorder */
87326 {
87327   Expr *p = 0;
87328   if( yymsp[-1].minor.yy0.n>0 ){
87329     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
87330     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
87331   }
87332   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
87333   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
87334   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
87335 }
87336         break;
87337       case 248: /* collate ::= */
87338 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
87339         break;
87340       case 250: /* cmd ::= DROP INDEX ifexists fullname */
87341 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
87342         break;
87343       case 251: /* cmd ::= VACUUM */
87344       case 252: /* cmd ::= VACUUM nm */
87345 {sqlite3Vacuum(pParse);}
87346         break;
87347       case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
87348       case 254: /* cmd ::= PRAGMA nm dbnm EQ ON */
87349       case 255: /* cmd ::= PRAGMA nm dbnm EQ DELETE */
87350 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
87351         break;
87352       case 256: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
87353 {
87354   sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);
87355 }
87356         break;
87357       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
87358 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
87359         break;
87360       case 258: /* cmd ::= PRAGMA nm dbnm */
87361 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
87362         break;
87363       case 266: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
87364 {
87365   Token all;
87366   all.z = yymsp[-3].minor.yy0.z;
87367   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
87368   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
87369 }
87370         break;
87371       case 267: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
87372 {
87373   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
87374   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
87375 }
87376         break;
87377       case 268: /* trigger_time ::= BEFORE */
87378       case 271: /* trigger_time ::= */
87379 { yygotominor.yy392 = TK_BEFORE; }
87380         break;
87381       case 269: /* trigger_time ::= AFTER */
87382 { yygotominor.yy392 = TK_AFTER;  }
87383         break;
87384       case 270: /* trigger_time ::= INSTEAD OF */
87385 { yygotominor.yy392 = TK_INSTEAD;}
87386         break;
87387       case 272: /* trigger_event ::= DELETE|INSERT */
87388       case 273: /* trigger_event ::= UPDATE */
87389 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
87390         break;
87391       case 274: /* trigger_event ::= UPDATE OF inscollist */
87392 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
87393         break;
87394       case 277: /* when_clause ::= */
87395       case 294: /* key_opt ::= */
87396 { yygotominor.yy122 = 0; }
87397         break;
87398       case 278: /* when_clause ::= WHEN expr */
87399       case 295: /* key_opt ::= KEY expr */
87400 { yygotominor.yy122 = yymsp[0].minor.yy122; }
87401         break;
87402       case 279: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
87403 {
87404 /*
87405   if( yymsp[-2].minor.yy327 ){
87406     yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
87407   }else{
87408     yymsp[-2].minor.yy327 = yymsp[-1].minor.yy327;
87409   }
87410 */
87411   assert( yymsp[-2].minor.yy327!=0 );
87412   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
87413   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
87414   yygotominor.yy327 = yymsp[-2].minor.yy327;
87415 }
87416         break;
87417       case 280: /* trigger_cmd_list ::= trigger_cmd SEMI */
87418
87419   /* if( yymsp[-1].minor.yy327 ) */
87420   assert( yymsp[-1].minor.yy327!=0 );
87421   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
87422   yygotominor.yy327 = yymsp[-1].minor.yy327;
87423 }
87424         break;
87425       case 281: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
87426 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-4].minor.yy392); }
87427         break;
87428       case 282: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
87429 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy180, yymsp[-1].minor.yy442, 0, yymsp[-7].minor.yy392);}
87430         break;
87431       case 283: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
87432 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy392);}
87433         break;
87434       case 284: /* trigger_cmd ::= DELETE FROM nm where_opt */
87435 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy122);}
87436         break;
87437       case 285: /* trigger_cmd ::= select */
87438 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
87439         break;
87440       case 286: /* expr ::= RAISE LP IGNORE RP */
87441 {
87442   yygotominor.yy122 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
87443   if( yygotominor.yy122 ){
87444     yygotominor.yy122->iColumn = OE_Ignore;
87445     sqlite3ExprSpan(yygotominor.yy122, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
87446   }
87447 }
87448         break;
87449       case 287: /* expr ::= RAISE LP raisetype COMMA nm RP */
87450 {
87451   yygotominor.yy122 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
87452   if( yygotominor.yy122 ) {
87453     yygotominor.yy122->iColumn = yymsp[-3].minor.yy392;
87454     sqlite3ExprSpan(yygotominor.yy122, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
87455   }
87456 }
87457         break;
87458       case 288: /* raisetype ::= ROLLBACK */
87459 {yygotominor.yy392 = OE_Rollback;}
87460         break;
87461       case 290: /* raisetype ::= FAIL */
87462 {yygotominor.yy392 = OE_Fail;}
87463         break;
87464       case 291: /* cmd ::= DROP TRIGGER ifexists fullname */
87465 {
87466   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
87467 }
87468         break;
87469       case 292: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
87470 {
87471   sqlite3Attach(pParse, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, yymsp[0].minor.yy122);
87472 }
87473         break;
87474       case 293: /* cmd ::= DETACH database_kw_opt expr */
87475 {
87476   sqlite3Detach(pParse, yymsp[0].minor.yy122);
87477 }
87478         break;
87479       case 298: /* cmd ::= REINDEX */
87480 {sqlite3Reindex(pParse, 0, 0);}
87481         break;
87482       case 299: /* cmd ::= REINDEX nm dbnm */
87483 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
87484         break;
87485       case 300: /* cmd ::= ANALYZE */
87486 {sqlite3Analyze(pParse, 0, 0);}
87487         break;
87488       case 301: /* cmd ::= ANALYZE nm dbnm */
87489 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
87490         break;
87491       case 302: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
87492 {
87493   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
87494 }
87495         break;
87496       case 303: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
87497 {
87498   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
87499 }
87500         break;
87501       case 304: /* add_column_fullname ::= fullname */
87502 {
87503   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
87504 }
87505         break;
87506       case 307: /* cmd ::= create_vtab */
87507 {sqlite3VtabFinishParse(pParse,0);}
87508         break;
87509       case 308: /* cmd ::= create_vtab LP vtabarglist RP */
87510 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
87511         break;
87512       case 309: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */
87513 {
87514     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
87515 }
87516         break;
87517       case 312: /* vtabarg ::= */
87518 {sqlite3VtabArgInit(pParse);}
87519         break;
87520       case 314: /* vtabargtoken ::= ANY */
87521       case 315: /* vtabargtoken ::= lp anylist RP */
87522       case 316: /* lp ::= LP */
87523       case 318: /* anylist ::= anylist ANY */
87524 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
87525         break;
87526   };
87527   yygoto = yyRuleInfo[yyruleno].lhs;
87528   yysize = yyRuleInfo[yyruleno].nrhs;
87529   yypParser->yyidx -= yysize;
87530   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
87531   if( yyact < YYNSTATE ){
87532 #ifdef NDEBUG
87533     /* If we are not debugging and the reduce action popped at least
87534     ** one element off the stack, then we can push the new element back
87535     ** onto the stack here, and skip the stack overflow test in yy_shift().
87536     ** That gives a significant speed improvement. */
87537     if( yysize ){
87538       yypParser->yyidx++;
87539       yymsp -= yysize-1;
87540       yymsp->stateno = (YYACTIONTYPE)yyact;
87541       yymsp->major = (YYCODETYPE)yygoto;
87542       yymsp->minor = yygotominor;
87543     }else
87544 #endif
87545     {
87546       yy_shift(yypParser,yyact,yygoto,&yygotominor);
87547     }
87548   }else{
87549     assert( yyact == YYNSTATE + YYNRULE + 1 );
87550     yy_accept(yypParser);
87551   }
87552 }
87553
87554 /*
87555 ** The following code executes when the parse fails
87556 */
87557 static void yy_parse_failed(
87558   yyParser *yypParser           /* The parser */
87559 ){
87560   sqlite3ParserARG_FETCH;
87561 #ifndef NDEBUG
87562   if( yyTraceFILE ){
87563     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
87564   }
87565 #endif
87566   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
87567   /* Here code is inserted which will be executed whenever the
87568   ** parser fails */
87569   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
87570 }
87571
87572 /*
87573 ** The following code executes when a syntax error first occurs.
87574 */
87575 static void yy_syntax_error(
87576   yyParser *yypParser,           /* The parser */
87577   int yymajor,                   /* The major type of the error token */
87578   YYMINORTYPE yyminor            /* The minor type of the error token */
87579 ){
87580   sqlite3ParserARG_FETCH;
87581 #define TOKEN (yyminor.yy0)
87582
87583   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
87584   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
87585   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
87586   pParse->parseError = 1;
87587   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
87588 }
87589
87590 /*
87591 ** The following is executed when the parser accepts
87592 */
87593 static void yy_accept(
87594   yyParser *yypParser           /* The parser */
87595 ){
87596   sqlite3ParserARG_FETCH;
87597 #ifndef NDEBUG
87598   if( yyTraceFILE ){
87599     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
87600   }
87601 #endif
87602   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
87603   /* Here code is inserted which will be executed whenever the
87604   ** parser accepts */
87605   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
87606 }
87607
87608 /* The main parser program.
87609 ** The first argument is a pointer to a structure obtained from
87610 ** "sqlite3ParserAlloc" which describes the current state of the parser.
87611 ** The second argument is the major token number.  The third is
87612 ** the minor token.  The fourth optional argument is whatever the
87613 ** user wants (and specified in the grammar) and is available for
87614 ** use by the action routines.
87615 **
87616 ** Inputs:
87617 ** <ul>
87618 ** <li> A pointer to the parser (an opaque structure.)
87619 ** <li> The major token number.
87620 ** <li> The minor token number.
87621 ** <li> An option argument of a grammar-specified type.
87622 ** </ul>
87623 **
87624 ** Outputs:
87625 ** None.
87626 */
87627 SQLITE_PRIVATE void sqlite3Parser(
87628   void *yyp,                   /* The parser */
87629   int yymajor,                 /* The major token code number */
87630   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
87631   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
87632 ){
87633   YYMINORTYPE yyminorunion;
87634   int yyact;            /* The parser action. */
87635   int yyendofinput;     /* True if we are at the end of input */
87636 #ifdef YYERRORSYMBOL
87637   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
87638 #endif
87639   yyParser *yypParser;  /* The parser */
87640
87641   /* (re)initialize the parser, if necessary */
87642   yypParser = (yyParser*)yyp;
87643   if( yypParser->yyidx<0 ){
87644 #if YYSTACKDEPTH<=0
87645     if( yypParser->yystksz <=0 ){
87646       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
87647       yyminorunion = yyzerominor;
87648       yyStackOverflow(yypParser, &yyminorunion);
87649       return;
87650     }
87651 #endif
87652     yypParser->yyidx = 0;
87653     yypParser->yyerrcnt = -1;
87654     yypParser->yystack[0].stateno = 0;
87655     yypParser->yystack[0].major = 0;
87656   }
87657   yyminorunion.yy0 = yyminor;
87658   yyendofinput = (yymajor==0);
87659   sqlite3ParserARG_STORE;
87660
87661 #ifndef NDEBUG
87662   if( yyTraceFILE ){
87663     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
87664   }
87665 #endif
87666
87667   do{
87668     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
87669     if( yyact<YYNSTATE ){
87670       assert( !yyendofinput );  /* Impossible to shift the $ token */
87671       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
87672       yypParser->yyerrcnt--;
87673       yymajor = YYNOCODE;
87674     }else if( yyact < YYNSTATE + YYNRULE ){
87675       yy_reduce(yypParser,yyact-YYNSTATE);
87676     }else{
87677       assert( yyact == YY_ERROR_ACTION );
87678 #ifdef YYERRORSYMBOL
87679       int yymx;
87680 #endif
87681 #ifndef NDEBUG
87682       if( yyTraceFILE ){
87683         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
87684       }
87685 #endif
87686 #ifdef YYERRORSYMBOL
87687       /* A syntax error has occurred.
87688       ** The response to an error depends upon whether or not the
87689       ** grammar defines an error token "ERROR".  
87690       **
87691       ** This is what we do if the grammar does define ERROR:
87692       **
87693       **  * Call the %syntax_error function.
87694       **
87695       **  * Begin popping the stack until we enter a state where
87696       **    it is legal to shift the error symbol, then shift
87697       **    the error symbol.
87698       **
87699       **  * Set the error count to three.
87700       **
87701       **  * Begin accepting and shifting new tokens.  No new error
87702       **    processing will occur until three tokens have been
87703       **    shifted successfully.
87704       **
87705       */
87706       if( yypParser->yyerrcnt<0 ){
87707         yy_syntax_error(yypParser,yymajor,yyminorunion);
87708       }
87709       yymx = yypParser->yystack[yypParser->yyidx].major;
87710       if( yymx==YYERRORSYMBOL || yyerrorhit ){
87711 #ifndef NDEBUG
87712         if( yyTraceFILE ){
87713           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
87714              yyTracePrompt,yyTokenName[yymajor]);
87715         }
87716 #endif
87717         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
87718         yymajor = YYNOCODE;
87719       }else{
87720          while(
87721           yypParser->yyidx >= 0 &&
87722           yymx != YYERRORSYMBOL &&
87723           (yyact = yy_find_reduce_action(
87724                         yypParser->yystack[yypParser->yyidx].stateno,
87725                         YYERRORSYMBOL)) >= YYNSTATE
87726         ){
87727           yy_pop_parser_stack(yypParser);
87728         }
87729         if( yypParser->yyidx < 0 || yymajor==0 ){
87730           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
87731           yy_parse_failed(yypParser);
87732           yymajor = YYNOCODE;
87733         }else if( yymx!=YYERRORSYMBOL ){
87734           YYMINORTYPE u2;
87735           u2.YYERRSYMDT = 0;
87736           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
87737         }
87738       }
87739       yypParser->yyerrcnt = 3;
87740       yyerrorhit = 1;
87741 #else  /* YYERRORSYMBOL is not defined */
87742       /* This is what we do if the grammar does not define ERROR:
87743       **
87744       **  * Report an error message, and throw away the input token.
87745       **
87746       **  * If the input token is $, then fail the parse.
87747       **
87748       ** As before, subsequent error messages are suppressed until
87749       ** three input tokens have been successfully shifted.
87750       */
87751       if( yypParser->yyerrcnt<=0 ){
87752         yy_syntax_error(yypParser,yymajor,yyminorunion);
87753       }
87754       yypParser->yyerrcnt = 3;
87755       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
87756       if( yyendofinput ){
87757         yy_parse_failed(yypParser);
87758       }
87759       yymajor = YYNOCODE;
87760 #endif
87761     }
87762   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
87763   return;
87764 }
87765
87766 /************** End of parse.c ***********************************************/
87767 /************** Begin file tokenize.c ****************************************/
87768 /*
87769 ** 2001 September 15
87770 **
87771 ** The author disclaims copyright to this source code.  In place of
87772 ** a legal notice, here is a blessing:
87773 **
87774 **    May you do good and not evil.
87775 **    May you find forgiveness for yourself and forgive others.
87776 **    May you share freely, never taking more than you give.
87777 **
87778 *************************************************************************
87779 ** An tokenizer for SQL
87780 **
87781 ** This file contains C code that splits an SQL input string up into
87782 ** individual tokens and sends those tokens one-by-one over to the
87783 ** parser for analysis.
87784 **
87785 ** $Id: tokenize.c,v 1.153 2009/01/20 16:53:41 danielk1977 Exp $
87786 */
87787
87788 /*
87789 ** The charMap() macro maps alphabetic characters into their
87790 ** lower-case ASCII equivalent.  On ASCII machines, this is just
87791 ** an upper-to-lower case map.  On EBCDIC machines we also need
87792 ** to adjust the encoding.  Only alphabetic characters and underscores
87793 ** need to be translated.
87794 */
87795 #ifdef SQLITE_ASCII
87796 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
87797 #endif
87798 #ifdef SQLITE_EBCDIC
87799 # define charMap(X) ebcdicToAscii[(unsigned char)X]
87800 const unsigned char ebcdicToAscii[] = {
87801 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
87802    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
87803    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
87804    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
87805    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
87806    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
87807    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
87808    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
87809    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
87810    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
87811    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
87812    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
87813    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
87814    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
87815    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
87816    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
87817    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
87818 };
87819 #endif
87820
87821 /*
87822 ** The sqlite3KeywordCode function looks up an identifier to determine if
87823 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
87824 ** returned.  If the input is not a keyword, TK_ID is returned.
87825 **
87826 ** The implementation of this routine was generated by a program,
87827 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
87828 ** The output of the mkkeywordhash.c program is written into a file
87829 ** named keywordhash.h and then included into this source file by
87830 ** the #include below.
87831 */
87832 /************** Include keywordhash.h in the middle of tokenize.c ************/
87833 /************** Begin file keywordhash.h *************************************/
87834 /***** This file contains automatically generated code ******
87835 **
87836 ** The code in this file has been automatically generated by
87837 **
87838 **     $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.37 2009/02/01 00:00:46 drh Exp $
87839 **
87840 ** The code in this file implements a function that determines whether
87841 ** or not a given identifier is really an SQL keyword.  The same thing
87842 ** might be implemented more directly using a hand-written hash table.
87843 ** But by using this automatically generated code, the size of the code
87844 ** is substantially reduced.  This is important for embedded applications
87845 ** on platforms with limited memory.
87846 */
87847 /* Hash score: 171 */
87848 static int keywordCode(const char *z, int n){
87849   /* zText[] encodes 801 bytes of keywords in 541 bytes */
87850   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
87851   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
87852   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
87853   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
87854   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
87855   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
87856   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
87857   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
87858   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
87859   /*   INITIALLY                                                          */
87860   static const char zText[540] = {
87861     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
87862     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
87863     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
87864     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
87865     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
87866     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
87867     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
87868     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
87869     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
87870     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
87871     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
87872     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
87873     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
87874     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
87875     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
87876     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
87877     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
87878     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
87879     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
87880     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
87881     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
87882     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
87883     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
87884     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
87885     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
87886     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
87887     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
87888     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
87889     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
87890     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
87891   };
87892   static const unsigned char aHash[127] = {
87893       70,  99, 112,  68,   0,  43,   0,   0,  76,   0,  71,   0,   0,
87894       41,  12,  72,  15,   0, 111,  79,  49, 106,   0,  19,   0,   0,
87895      116,   0, 114, 109,   0,  22,  87,   0,   9,   0,   0,  64,  65,
87896        0,  63,   6,   0,  47,  84,  96,   0, 113,  95,   0,   0,  44,
87897        0,  97,  24,   0,  17,   0, 117,  48,  23,   0,   5, 104,  25,
87898       90,   0,   0, 119, 100,  55, 118,  52,   7,  50,   0,  85,   0,
87899       94,  26,   0,  93,   0,   0,   0,  89,  86,  91,  82, 103,  14,
87900       38, 102,   0,  75,   0,  18,  83, 105,  31,   0, 115,  74, 107,
87901       57,  45,  78,   0,   0,  88,  39,   0, 110,   0,  35,   0,   0,
87902       28,   0,  80,  53,  58,   0,  20,  56,   0,  51,
87903   };
87904   static const unsigned char aNext[119] = {
87905        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
87906        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
87907        0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
87908        0,   0,   0,   0,  32,  21,   0,   0,   0,  42,   3,  46,   0,
87909        0,   0,   0,  29,   0,   0,  37,   0,   0,   0,   1,  60,   0,
87910        0,  61,   0,  40,   0,   0,   0,   0,   0,   0,   0,  59,   0,
87911        0,   0,   0,  30,  54,  16,  33,  10,   0,   0,   0,   0,   0,
87912        0,   0,  11,  66,  73,   0,   8,   0,  98,  92,   0, 101,   0,
87913       81,   0,  69,   0,   0, 108,  27,  36,  67,  77,   0,  34,  62,
87914        0,   0,
87915   };
87916   static const unsigned char aLen[119] = {
87917        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
87918        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
87919       11,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,   4,
87920        6,   2,   3,   4,   9,   2,   6,   5,   6,   6,   5,   6,   5,
87921        5,   7,   7,   7,   3,   4,   4,   7,   3,   6,   4,   7,   6,
87922       12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,   7,   5,
87923        4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,   6,   6,
87924        8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,   4,   4,
87925        2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,   6,   4,
87926        9,   3,
87927   };
87928   static const unsigned short int aOffset[119] = {
87929        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
87930       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
87931       86,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152, 159,
87932      162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197, 203,
87933      206, 210, 217, 223, 223, 226, 229, 233, 234, 238, 244, 248, 255,
87934      261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320, 326, 332,
87935      337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383, 387, 393,
87936      399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458, 462, 466,
87937      469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516, 521, 527,
87938      531, 536,
87939   };
87940   static const unsigned char aCode[119] = {
87941     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
87942     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
87943     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
87944     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
87945     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
87946     TK_EXCEPT,     TK_TRANSACTION,TK_ON,         TK_JOIN_KW,    TK_ALTER,      
87947     TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  TK_INTERSECT,  
87948     TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       TK_OFFSET,     
87949     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       TK_OR,         
87950     TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     TK_GROUP,      
87951     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    TK_BETWEEN,    
87952     TK_NOTNULL,    TK_NOT,        TK_NULL,       TK_LIKE_KW,    TK_CASCADE,    
87953     TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    TK_CREATE,     
87954     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     
87955     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      
87956     TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       TK_WHERE,      
87957     TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,        TK_DEFAULT,    
87958     TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       TK_COLUMNKW,   
87959     TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   
87960     TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       
87961     TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    TK_BY,         
87962     TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,   TK_JOIN_KW,    
87963     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,      
87964     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,        
87965   };
87966   int h, i;
87967   if( n<2 ) return TK_ID;
87968   h = ((charMap(z[0])*4) ^
87969       (charMap(z[n-1])*3) ^
87970       n) % 127;
87971   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
87972     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
87973       testcase( i==0 ); /* TK_REINDEX */
87974       testcase( i==1 ); /* TK_INDEXED */
87975       testcase( i==2 ); /* TK_INDEX */
87976       testcase( i==3 ); /* TK_DESC */
87977       testcase( i==4 ); /* TK_ESCAPE */
87978       testcase( i==5 ); /* TK_EACH */
87979       testcase( i==6 ); /* TK_CHECK */
87980       testcase( i==7 ); /* TK_KEY */
87981       testcase( i==8 ); /* TK_BEFORE */
87982       testcase( i==9 ); /* TK_FOREIGN */
87983       testcase( i==10 ); /* TK_FOR */
87984       testcase( i==11 ); /* TK_IGNORE */
87985       testcase( i==12 ); /* TK_LIKE_KW */
87986       testcase( i==13 ); /* TK_EXPLAIN */
87987       testcase( i==14 ); /* TK_INSTEAD */
87988       testcase( i==15 ); /* TK_ADD */
87989       testcase( i==16 ); /* TK_DATABASE */
87990       testcase( i==17 ); /* TK_AS */
87991       testcase( i==18 ); /* TK_SELECT */
87992       testcase( i==19 ); /* TK_TABLE */
87993       testcase( i==20 ); /* TK_JOIN_KW */
87994       testcase( i==21 ); /* TK_THEN */
87995       testcase( i==22 ); /* TK_END */
87996       testcase( i==23 ); /* TK_DEFERRABLE */
87997       testcase( i==24 ); /* TK_ELSE */
87998       testcase( i==25 ); /* TK_EXCEPT */
87999       testcase( i==26 ); /* TK_TRANSACTION */
88000       testcase( i==27 ); /* TK_ON */
88001       testcase( i==28 ); /* TK_JOIN_KW */
88002       testcase( i==29 ); /* TK_ALTER */
88003       testcase( i==30 ); /* TK_RAISE */
88004       testcase( i==31 ); /* TK_EXCLUSIVE */
88005       testcase( i==32 ); /* TK_EXISTS */
88006       testcase( i==33 ); /* TK_SAVEPOINT */
88007       testcase( i==34 ); /* TK_INTERSECT */
88008       testcase( i==35 ); /* TK_TRIGGER */
88009       testcase( i==36 ); /* TK_REFERENCES */
88010       testcase( i==37 ); /* TK_CONSTRAINT */
88011       testcase( i==38 ); /* TK_INTO */
88012       testcase( i==39 ); /* TK_OFFSET */
88013       testcase( i==40 ); /* TK_OF */
88014       testcase( i==41 ); /* TK_SET */
88015       testcase( i==42 ); /* TK_TEMP */
88016       testcase( i==43 ); /* TK_TEMP */
88017       testcase( i==44 ); /* TK_OR */
88018       testcase( i==45 ); /* TK_UNIQUE */
88019       testcase( i==46 ); /* TK_QUERY */
88020       testcase( i==47 ); /* TK_ATTACH */
88021       testcase( i==48 ); /* TK_HAVING */
88022       testcase( i==49 ); /* TK_GROUP */
88023       testcase( i==50 ); /* TK_UPDATE */
88024       testcase( i==51 ); /* TK_BEGIN */
88025       testcase( i==52 ); /* TK_JOIN_KW */
88026       testcase( i==53 ); /* TK_RELEASE */
88027       testcase( i==54 ); /* TK_BETWEEN */
88028       testcase( i==55 ); /* TK_NOTNULL */
88029       testcase( i==56 ); /* TK_NOT */
88030       testcase( i==57 ); /* TK_NULL */
88031       testcase( i==58 ); /* TK_LIKE_KW */
88032       testcase( i==59 ); /* TK_CASCADE */
88033       testcase( i==60 ); /* TK_ASC */
88034       testcase( i==61 ); /* TK_DELETE */
88035       testcase( i==62 ); /* TK_CASE */
88036       testcase( i==63 ); /* TK_COLLATE */
88037       testcase( i==64 ); /* TK_CREATE */
88038       testcase( i==65 ); /* TK_CTIME_KW */
88039       testcase( i==66 ); /* TK_DETACH */
88040       testcase( i==67 ); /* TK_IMMEDIATE */
88041       testcase( i==68 ); /* TK_JOIN */
88042       testcase( i==69 ); /* TK_INSERT */
88043       testcase( i==70 ); /* TK_MATCH */
88044       testcase( i==71 ); /* TK_PLAN */
88045       testcase( i==72 ); /* TK_ANALYZE */
88046       testcase( i==73 ); /* TK_PRAGMA */
88047       testcase( i==74 ); /* TK_ABORT */
88048       testcase( i==75 ); /* TK_VALUES */
88049       testcase( i==76 ); /* TK_VIRTUAL */
88050       testcase( i==77 ); /* TK_LIMIT */
88051       testcase( i==78 ); /* TK_WHEN */
88052       testcase( i==79 ); /* TK_WHERE */
88053       testcase( i==80 ); /* TK_RENAME */
88054       testcase( i==81 ); /* TK_AFTER */
88055       testcase( i==82 ); /* TK_REPLACE */
88056       testcase( i==83 ); /* TK_AND */
88057       testcase( i==84 ); /* TK_DEFAULT */
88058       testcase( i==85 ); /* TK_AUTOINCR */
88059       testcase( i==86 ); /* TK_TO */
88060       testcase( i==87 ); /* TK_IN */
88061       testcase( i==88 ); /* TK_CAST */
88062       testcase( i==89 ); /* TK_COLUMNKW */
88063       testcase( i==90 ); /* TK_COMMIT */
88064       testcase( i==91 ); /* TK_CONFLICT */
88065       testcase( i==92 ); /* TK_JOIN_KW */
88066       testcase( i==93 ); /* TK_CTIME_KW */
88067       testcase( i==94 ); /* TK_CTIME_KW */
88068       testcase( i==95 ); /* TK_PRIMARY */
88069       testcase( i==96 ); /* TK_DEFERRED */
88070       testcase( i==97 ); /* TK_DISTINCT */
88071       testcase( i==98 ); /* TK_IS */
88072       testcase( i==99 ); /* TK_DROP */
88073       testcase( i==100 ); /* TK_FAIL */
88074       testcase( i==101 ); /* TK_FROM */
88075       testcase( i==102 ); /* TK_JOIN_KW */
88076       testcase( i==103 ); /* TK_LIKE_KW */
88077       testcase( i==104 ); /* TK_BY */
88078       testcase( i==105 ); /* TK_IF */
88079       testcase( i==106 ); /* TK_ISNULL */
88080       testcase( i==107 ); /* TK_ORDER */
88081       testcase( i==108 ); /* TK_RESTRICT */
88082       testcase( i==109 ); /* TK_JOIN_KW */
88083       testcase( i==110 ); /* TK_JOIN_KW */
88084       testcase( i==111 ); /* TK_ROLLBACK */
88085       testcase( i==112 ); /* TK_ROW */
88086       testcase( i==113 ); /* TK_UNION */
88087       testcase( i==114 ); /* TK_USING */
88088       testcase( i==115 ); /* TK_VACUUM */
88089       testcase( i==116 ); /* TK_VIEW */
88090       testcase( i==117 ); /* TK_INITIALLY */
88091       testcase( i==118 ); /* TK_ALL */
88092       return aCode[i];
88093     }
88094   }
88095   return TK_ID;
88096 }
88097 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
88098   return keywordCode((char*)z, n);
88099 }
88100
88101 /************** End of keywordhash.h *****************************************/
88102 /************** Continuing where we left off in tokenize.c *******************/
88103
88104
88105 /*
88106 ** If X is a character that can be used in an identifier then
88107 ** IdChar(X) will be true.  Otherwise it is false.
88108 **
88109 ** For ASCII, any character with the high-order bit set is
88110 ** allowed in an identifier.  For 7-bit characters, 
88111 ** sqlite3IsIdChar[X] must be 1.
88112 **
88113 ** For EBCDIC, the rules are more complex but have the same
88114 ** end result.
88115 **
88116 ** Ticket #1066.  the SQL standard does not allow '$' in the
88117 ** middle of identfiers.  But many SQL implementations do. 
88118 ** SQLite will allow '$' in identifiers for compatibility.
88119 ** But the feature is undocumented.
88120 */
88121 #ifdef SQLITE_ASCII
88122 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[] = {
88123 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
88124     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
88125     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
88126     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
88127     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
88128     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
88129     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
88130 };
88131 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
88132 #endif
88133 #ifdef SQLITE_EBCDIC
88134 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
88135 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
88136     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
88137     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
88138     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
88139     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
88140     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
88141     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
88142     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
88143     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
88144     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
88145     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
88146     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
88147     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
88148 };
88149 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
88150 #endif
88151
88152
88153 /*
88154 ** Return the length of the token that begins at z[0]. 
88155 ** Store the token type in *tokenType before returning.
88156 */
88157 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
88158   int i, c;
88159   switch( *z ){
88160     case ' ': case '\t': case '\n': case '\f': case '\r': {
88161       for(i=1; sqlite3Isspace(z[i]); i++){}
88162       *tokenType = TK_SPACE;
88163       return i;
88164     }
88165     case '-': {
88166       if( z[1]=='-' ){
88167         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
88168         *tokenType = TK_SPACE;
88169         return i;
88170       }
88171       *tokenType = TK_MINUS;
88172       return 1;
88173     }
88174     case '(': {
88175       *tokenType = TK_LP;
88176       return 1;
88177     }
88178     case ')': {
88179       *tokenType = TK_RP;
88180       return 1;
88181     }
88182     case ';': {
88183       *tokenType = TK_SEMI;
88184       return 1;
88185     }
88186     case '+': {
88187       *tokenType = TK_PLUS;
88188       return 1;
88189     }
88190     case '*': {
88191       *tokenType = TK_STAR;
88192       return 1;
88193     }
88194     case '/': {
88195       if( z[1]!='*' || z[2]==0 ){
88196         *tokenType = TK_SLASH;
88197         return 1;
88198       }
88199       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
88200       if( c ) i++;
88201       *tokenType = TK_SPACE;
88202       return i;
88203     }
88204     case '%': {
88205       *tokenType = TK_REM;
88206       return 1;
88207     }
88208     case '=': {
88209       *tokenType = TK_EQ;
88210       return 1 + (z[1]=='=');
88211     }
88212     case '<': {
88213       if( (c=z[1])=='=' ){
88214         *tokenType = TK_LE;
88215         return 2;
88216       }else if( c=='>' ){
88217         *tokenType = TK_NE;
88218         return 2;
88219       }else if( c=='<' ){
88220         *tokenType = TK_LSHIFT;
88221         return 2;
88222       }else{
88223         *tokenType = TK_LT;
88224         return 1;
88225       }
88226     }
88227     case '>': {
88228       if( (c=z[1])=='=' ){
88229         *tokenType = TK_GE;
88230         return 2;
88231       }else if( c=='>' ){
88232         *tokenType = TK_RSHIFT;
88233         return 2;
88234       }else{
88235         *tokenType = TK_GT;
88236         return 1;
88237       }
88238     }
88239     case '!': {
88240       if( z[1]!='=' ){
88241         *tokenType = TK_ILLEGAL;
88242         return 2;
88243       }else{
88244         *tokenType = TK_NE;
88245         return 2;
88246       }
88247     }
88248     case '|': {
88249       if( z[1]!='|' ){
88250         *tokenType = TK_BITOR;
88251         return 1;
88252       }else{
88253         *tokenType = TK_CONCAT;
88254         return 2;
88255       }
88256     }
88257     case ',': {
88258       *tokenType = TK_COMMA;
88259       return 1;
88260     }
88261     case '&': {
88262       *tokenType = TK_BITAND;
88263       return 1;
88264     }
88265     case '~': {
88266       *tokenType = TK_BITNOT;
88267       return 1;
88268     }
88269     case '`':
88270     case '\'':
88271     case '"': {
88272       int delim = z[0];
88273       for(i=1; (c=z[i])!=0; i++){
88274         if( c==delim ){
88275           if( z[i+1]==delim ){
88276             i++;
88277           }else{
88278             break;
88279           }
88280         }
88281       }
88282       if( c=='\'' ){
88283         *tokenType = TK_STRING;
88284         return i+1;
88285       }else if( c!=0 ){
88286         *tokenType = TK_ID;
88287         return i+1;
88288       }else{
88289         *tokenType = TK_ILLEGAL;
88290         return i;
88291       }
88292     }
88293     case '.': {
88294 #ifndef SQLITE_OMIT_FLOATING_POINT
88295       if( !sqlite3Isdigit(z[1]) )
88296 #endif
88297       {
88298         *tokenType = TK_DOT;
88299         return 1;
88300       }
88301       /* If the next character is a digit, this is a floating point
88302       ** number that begins with ".".  Fall thru into the next case */
88303     }
88304     case '0': case '1': case '2': case '3': case '4':
88305     case '5': case '6': case '7': case '8': case '9': {
88306       *tokenType = TK_INTEGER;
88307       for(i=0; sqlite3Isdigit(z[i]); i++){}
88308 #ifndef SQLITE_OMIT_FLOATING_POINT
88309       if( z[i]=='.' ){
88310         i++;
88311         while( sqlite3Isdigit(z[i]) ){ i++; }
88312         *tokenType = TK_FLOAT;
88313       }
88314       if( (z[i]=='e' || z[i]=='E') &&
88315            ( sqlite3Isdigit(z[i+1]) 
88316             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
88317            )
88318       ){
88319         i += 2;
88320         while( sqlite3Isdigit(z[i]) ){ i++; }
88321         *tokenType = TK_FLOAT;
88322       }
88323 #endif
88324       while( IdChar(z[i]) ){
88325         *tokenType = TK_ILLEGAL;
88326         i++;
88327       }
88328       return i;
88329     }
88330     case '[': {
88331       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
88332       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
88333       return i;
88334     }
88335     case '?': {
88336       *tokenType = TK_VARIABLE;
88337       for(i=1; sqlite3Isdigit(z[i]); i++){}
88338       return i;
88339     }
88340     case '#': {
88341       for(i=1; sqlite3Isdigit(z[i]); i++){}
88342       if( i>1 ){
88343         /* Parameters of the form #NNN (where NNN is a number) are used
88344         ** internally by sqlite3NestedParse.  */
88345         *tokenType = TK_REGISTER;
88346         return i;
88347       }
88348       /* Fall through into the next case if the '#' is not followed by
88349       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
88350     }
88351 #ifndef SQLITE_OMIT_TCL_VARIABLE
88352     case '$':
88353 #endif
88354     case '@':  /* For compatibility with MS SQL Server */
88355     case ':': {
88356       int n = 0;
88357       *tokenType = TK_VARIABLE;
88358       for(i=1; (c=z[i])!=0; i++){
88359         if( IdChar(c) ){
88360           n++;
88361 #ifndef SQLITE_OMIT_TCL_VARIABLE
88362         }else if( c=='(' && n>0 ){
88363           do{
88364             i++;
88365           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
88366           if( c==')' ){
88367             i++;
88368           }else{
88369             *tokenType = TK_ILLEGAL;
88370           }
88371           break;
88372         }else if( c==':' && z[i+1]==':' ){
88373           i++;
88374 #endif
88375         }else{
88376           break;
88377         }
88378       }
88379       if( n==0 ) *tokenType = TK_ILLEGAL;
88380       return i;
88381     }
88382 #ifndef SQLITE_OMIT_BLOB_LITERAL
88383     case 'x': case 'X': {
88384       if( z[1]=='\'' ){
88385         *tokenType = TK_BLOB;
88386         for(i=2; (c=z[i])!=0 && c!='\''; i++){
88387           if( !sqlite3Isxdigit(c) ){
88388             *tokenType = TK_ILLEGAL;
88389           }
88390         }
88391         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
88392         if( c ) i++;
88393         return i;
88394       }
88395       /* Otherwise fall through to the next case */
88396     }
88397 #endif
88398     default: {
88399       if( !IdChar(*z) ){
88400         break;
88401       }
88402       for(i=1; IdChar(z[i]); i++){}
88403       *tokenType = keywordCode((char*)z, i);
88404       return i;
88405     }
88406   }
88407   *tokenType = TK_ILLEGAL;
88408   return 1;
88409 }
88410
88411 /*
88412 ** Run the parser on the given SQL string.  The parser structure is
88413 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
88414 ** then an and attempt is made to write an error message into 
88415 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
88416 ** error message.
88417 */
88418 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
88419   int nErr = 0;
88420   int i;
88421   void *pEngine;
88422   int tokenType;
88423   int lastTokenParsed = -1;
88424   sqlite3 *db = pParse->db;
88425   int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
88426
88427   if( db->activeVdbeCnt==0 ){
88428     db->u1.isInterrupted = 0;
88429   }
88430   pParse->rc = SQLITE_OK;
88431   pParse->zTail = pParse->zSql = zSql;
88432   i = 0;
88433   assert( pzErrMsg!=0 );
88434   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
88435   if( pEngine==0 ){
88436     db->mallocFailed = 1;
88437     return SQLITE_NOMEM;
88438   }
88439   assert( pParse->sLastToken.dyn==0 );
88440   assert( pParse->pNewTable==0 );
88441   assert( pParse->pNewTrigger==0 );
88442   assert( pParse->nVar==0 );
88443   assert( pParse->nVarExpr==0 );
88444   assert( pParse->nVarExprAlloc==0 );
88445   assert( pParse->apVarExpr==0 );
88446   while( !db->mallocFailed && zSql[i]!=0 ){
88447     assert( i>=0 );
88448     pParse->sLastToken.z = (u8*)&zSql[i];
88449     assert( pParse->sLastToken.dyn==0 );
88450     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
88451     i += pParse->sLastToken.n;
88452     if( i>mxSqlLen ){
88453       pParse->rc = SQLITE_TOOBIG;
88454       break;
88455     }
88456     switch( tokenType ){
88457       case TK_SPACE: {
88458         if( db->u1.isInterrupted ){
88459           pParse->rc = SQLITE_INTERRUPT;
88460           sqlite3SetString(pzErrMsg, db, "interrupt");
88461           goto abort_parse;
88462         }
88463         break;
88464       }
88465       case TK_ILLEGAL: {
88466         sqlite3DbFree(db, *pzErrMsg);
88467         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
88468                         &pParse->sLastToken);
88469         nErr++;
88470         goto abort_parse;
88471       }
88472       case TK_SEMI: {
88473         pParse->zTail = &zSql[i];
88474         /* Fall thru into the default case */
88475       }
88476       default: {
88477         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
88478         lastTokenParsed = tokenType;
88479         if( pParse->rc!=SQLITE_OK ){
88480           goto abort_parse;
88481         }
88482         break;
88483       }
88484     }
88485   }
88486 abort_parse:
88487   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
88488     if( lastTokenParsed!=TK_SEMI ){
88489       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
88490       pParse->zTail = &zSql[i];
88491     }
88492     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
88493   }
88494 #ifdef YYTRACKMAXSTACKDEPTH
88495   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
88496       sqlite3ParserStackPeak(pEngine)
88497   );
88498 #endif /* YYDEBUG */
88499   sqlite3ParserFree(pEngine, sqlite3_free);
88500   if( db->mallocFailed ){
88501     pParse->rc = SQLITE_NOMEM;
88502   }
88503   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
88504     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
88505   }
88506   if( pParse->zErrMsg ){
88507     if( *pzErrMsg==0 ){
88508       *pzErrMsg = pParse->zErrMsg;
88509     }else{
88510       sqlite3DbFree(db, pParse->zErrMsg);
88511     }
88512     pParse->zErrMsg = 0;
88513     nErr++;
88514   }
88515   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
88516     sqlite3VdbeDelete(pParse->pVdbe);
88517     pParse->pVdbe = 0;
88518   }
88519 #ifndef SQLITE_OMIT_SHARED_CACHE
88520   if( pParse->nested==0 ){
88521     sqlite3DbFree(db, pParse->aTableLock);
88522     pParse->aTableLock = 0;
88523     pParse->nTableLock = 0;
88524   }
88525 #endif
88526 #ifndef SQLITE_OMIT_VIRTUALTABLE
88527   sqlite3DbFree(db, pParse->apVtabLock);
88528 #endif
88529
88530   if( !IN_DECLARE_VTAB ){
88531     /* If the pParse->declareVtab flag is set, do not delete any table 
88532     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
88533     ** will take responsibility for freeing the Table structure.
88534     */
88535     sqlite3DeleteTable(pParse->pNewTable);
88536   }
88537
88538   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
88539   sqlite3DbFree(db, pParse->apVarExpr);
88540   sqlite3DbFree(db, pParse->aAlias);
88541   while( pParse->pZombieTab ){
88542     Table *p = pParse->pZombieTab;
88543     pParse->pZombieTab = p->pNextZombie;
88544     sqlite3DeleteTable(p);
88545   }
88546   if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
88547     pParse->rc = SQLITE_ERROR;
88548   }
88549   return nErr;
88550 }
88551
88552 /************** End of tokenize.c ********************************************/
88553 /************** Begin file complete.c ****************************************/
88554 /*
88555 ** 2001 September 15
88556 **
88557 ** The author disclaims copyright to this source code.  In place of
88558 ** a legal notice, here is a blessing:
88559 **
88560 **    May you do good and not evil.
88561 **    May you find forgiveness for yourself and forgive others.
88562 **    May you share freely, never taking more than you give.
88563 **
88564 *************************************************************************
88565 ** An tokenizer for SQL
88566 **
88567 ** This file contains C code that implements the sqlite3_complete() API.
88568 ** This code used to be part of the tokenizer.c source file.  But by
88569 ** separating it out, the code will be automatically omitted from
88570 ** static links that do not use it.
88571 **
88572 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
88573 */
88574 #ifndef SQLITE_OMIT_COMPLETE
88575
88576 /*
88577 ** This is defined in tokenize.c.  We just have to import the definition.
88578 */
88579 #ifndef SQLITE_AMALGAMATION
88580 #ifdef SQLITE_ASCII
88581 SQLITE_PRIVATE const char sqlite3IsAsciiIdChar[];
88582 #define IdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && sqlite3IsAsciiIdChar[c-0x20]))
88583 #endif
88584 #ifdef SQLITE_EBCDIC
88585 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
88586 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
88587 #endif
88588 #endif /* SQLITE_AMALGAMATION */
88589
88590
88591 /*
88592 ** Token types used by the sqlite3_complete() routine.  See the header
88593 ** comments on that procedure for additional information.
88594 */
88595 #define tkSEMI    0
88596 #define tkWS      1
88597 #define tkOTHER   2
88598 #define tkEXPLAIN 3
88599 #define tkCREATE  4
88600 #define tkTEMP    5
88601 #define tkTRIGGER 6
88602 #define tkEND     7
88603
88604 /*
88605 ** Return TRUE if the given SQL string ends in a semicolon.
88606 **
88607 ** Special handling is require for CREATE TRIGGER statements.
88608 ** Whenever the CREATE TRIGGER keywords are seen, the statement
88609 ** must end with ";END;".
88610 **
88611 ** This implementation uses a state machine with 7 states:
88612 **
88613 **   (0) START     At the beginning or end of an SQL statement.  This routine
88614 **                 returns 1 if it ends in the START state and 0 if it ends
88615 **                 in any other state.
88616 **
88617 **   (1) NORMAL    We are in the middle of statement which ends with a single
88618 **                 semicolon.
88619 **
88620 **   (2) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
88621 **                 a statement.
88622 **
88623 **   (3) CREATE    The keyword CREATE has been seen at the beginning of a
88624 **                 statement, possibly preceeded by EXPLAIN and/or followed by
88625 **                 TEMP or TEMPORARY
88626 **
88627 **   (4) TRIGGER   We are in the middle of a trigger definition that must be
88628 **                 ended by a semicolon, the keyword END, and another semicolon.
88629 **
88630 **   (5) SEMI      We've seen the first semicolon in the ";END;" that occurs at
88631 **                 the end of a trigger definition.
88632 **
88633 **   (6) END       We've seen the ";END" of the ";END;" that occurs at the end
88634 **                 of a trigger difinition.
88635 **
88636 ** Transitions between states above are determined by tokens extracted
88637 ** from the input.  The following tokens are significant:
88638 **
88639 **   (0) tkSEMI      A semicolon.
88640 **   (1) tkWS        Whitespace
88641 **   (2) tkOTHER     Any other SQL token.
88642 **   (3) tkEXPLAIN   The "explain" keyword.
88643 **   (4) tkCREATE    The "create" keyword.
88644 **   (5) tkTEMP      The "temp" or "temporary" keyword.
88645 **   (6) tkTRIGGER   The "trigger" keyword.
88646 **   (7) tkEND       The "end" keyword.
88647 **
88648 ** Whitespace never causes a state transition and is always ignored.
88649 **
88650 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
88651 ** to recognize the end of a trigger can be omitted.  All we have to do
88652 ** is look for a semicolon that is not part of an string or comment.
88653 */
88654 SQLITE_API int sqlite3_complete(const char *zSql){
88655   u8 state = 0;   /* Current state, using numbers defined in header comment */
88656   u8 token;       /* Value of the next token */
88657
88658 #ifndef SQLITE_OMIT_TRIGGER
88659   /* A complex statement machine used to detect the end of a CREATE TRIGGER
88660   ** statement.  This is the normal case.
88661   */
88662   static const u8 trans[7][8] = {
88663                      /* Token:                                                */
88664      /* State:       **  SEMI  WS  OTHER EXPLAIN  CREATE  TEMP  TRIGGER  END  */
88665      /* 0   START: */ {    0,  0,     1,      2,      3,    1,       1,   1,  },
88666      /* 1  NORMAL: */ {    0,  1,     1,      1,      1,    1,       1,   1,  },
88667      /* 2 EXPLAIN: */ {    0,  2,     1,      1,      3,    1,       1,   1,  },
88668      /* 3  CREATE: */ {    0,  3,     1,      1,      1,    3,       4,   1,  },
88669      /* 4 TRIGGER: */ {    5,  4,     4,      4,      4,    4,       4,   4,  },
88670      /* 5    SEMI: */ {    5,  5,     4,      4,      4,    4,       4,   6,  },
88671      /* 6     END: */ {    0,  6,     4,      4,      4,    4,       4,   4,  },
88672   };
88673 #else
88674   /* If triggers are not suppored by this compile then the statement machine
88675   ** used to detect the end of a statement is much simplier
88676   */
88677   static const u8 trans[2][3] = {
88678                      /* Token:           */
88679      /* State:       **  SEMI  WS  OTHER */
88680      /* 0   START: */ {    0,  0,     1, },
88681      /* 1  NORMAL: */ {    0,  1,     1, },
88682   };
88683 #endif /* SQLITE_OMIT_TRIGGER */
88684
88685   while( *zSql ){
88686     switch( *zSql ){
88687       case ';': {  /* A semicolon */
88688         token = tkSEMI;
88689         break;
88690       }
88691       case ' ':
88692       case '\r':
88693       case '\t':
88694       case '\n':
88695       case '\f': {  /* White space is ignored */
88696         token = tkWS;
88697         break;
88698       }
88699       case '/': {   /* C-style comments */
88700         if( zSql[1]!='*' ){
88701           token = tkOTHER;
88702           break;
88703         }
88704         zSql += 2;
88705         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
88706         if( zSql[0]==0 ) return 0;
88707         zSql++;
88708         token = tkWS;
88709         break;
88710       }
88711       case '-': {   /* SQL-style comments from "--" to end of line */
88712         if( zSql[1]!='-' ){
88713           token = tkOTHER;
88714           break;
88715         }
88716         while( *zSql && *zSql!='\n' ){ zSql++; }
88717         if( *zSql==0 ) return state==0;
88718         token = tkWS;
88719         break;
88720       }
88721       case '[': {   /* Microsoft-style identifiers in [...] */
88722         zSql++;
88723         while( *zSql && *zSql!=']' ){ zSql++; }
88724         if( *zSql==0 ) return 0;
88725         token = tkOTHER;
88726         break;
88727       }
88728       case '`':     /* Grave-accent quoted symbols used by MySQL */
88729       case '"':     /* single- and double-quoted strings */
88730       case '\'': {
88731         int c = *zSql;
88732         zSql++;
88733         while( *zSql && *zSql!=c ){ zSql++; }
88734         if( *zSql==0 ) return 0;
88735         token = tkOTHER;
88736         break;
88737       }
88738       default: {
88739         int c;
88740         if( IdChar((u8)*zSql) ){
88741           /* Keywords and unquoted identifiers */
88742           int nId;
88743           for(nId=1; IdChar(zSql[nId]); nId++){}
88744 #ifdef SQLITE_OMIT_TRIGGER
88745           token = tkOTHER;
88746 #else
88747           switch( *zSql ){
88748             case 'c': case 'C': {
88749               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
88750                 token = tkCREATE;
88751               }else{
88752                 token = tkOTHER;
88753               }
88754               break;
88755             }
88756             case 't': case 'T': {
88757               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
88758                 token = tkTRIGGER;
88759               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
88760                 token = tkTEMP;
88761               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
88762                 token = tkTEMP;
88763               }else{
88764                 token = tkOTHER;
88765               }
88766               break;
88767             }
88768             case 'e':  case 'E': {
88769               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
88770                 token = tkEND;
88771               }else
88772 #ifndef SQLITE_OMIT_EXPLAIN
88773               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
88774                 token = tkEXPLAIN;
88775               }else
88776 #endif
88777               {
88778                 token = tkOTHER;
88779               }
88780               break;
88781             }
88782             default: {
88783               token = tkOTHER;
88784               break;
88785             }
88786           }
88787 #endif /* SQLITE_OMIT_TRIGGER */
88788           zSql += nId-1;
88789         }else{
88790           /* Operators and special symbols */
88791           token = tkOTHER;
88792         }
88793         break;
88794       }
88795     }
88796     state = trans[state][token];
88797     zSql++;
88798   }
88799   return state==0;
88800 }
88801
88802 #ifndef SQLITE_OMIT_UTF16
88803 /*
88804 ** This routine is the same as the sqlite3_complete() routine described
88805 ** above, except that the parameter is required to be UTF-16 encoded, not
88806 ** UTF-8.
88807 */
88808 SQLITE_API int sqlite3_complete16(const void *zSql){
88809   sqlite3_value *pVal;
88810   char const *zSql8;
88811   int rc = SQLITE_NOMEM;
88812
88813 #ifndef SQLITE_OMIT_AUTOINIT
88814   rc = sqlite3_initialize();
88815   if( rc ) return rc;
88816 #endif
88817   pVal = sqlite3ValueNew(0);
88818   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
88819   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
88820   if( zSql8 ){
88821     rc = sqlite3_complete(zSql8);
88822   }else{
88823     rc = SQLITE_NOMEM;
88824   }
88825   sqlite3ValueFree(pVal);
88826   return sqlite3ApiExit(0, rc);
88827 }
88828 #endif /* SQLITE_OMIT_UTF16 */
88829 #endif /* SQLITE_OMIT_COMPLETE */
88830
88831 /************** End of complete.c ********************************************/
88832 /************** Begin file main.c ********************************************/
88833 /*
88834 ** 2001 September 15
88835 **
88836 ** The author disclaims copyright to this source code.  In place of
88837 ** a legal notice, here is a blessing:
88838 **
88839 **    May you do good and not evil.
88840 **    May you find forgiveness for yourself and forgive others.
88841 **    May you share freely, never taking more than you give.
88842 **
88843 *************************************************************************
88844 ** Main file for the SQLite library.  The routines in this file
88845 ** implement the programmer interface to the library.  Routines in
88846 ** other files are for internal use by SQLite and should not be
88847 ** accessed by users of the library.
88848 **
88849 ** $Id: main.c,v 1.528 2009/02/05 16:31:46 drh Exp $
88850 */
88851
88852 #ifdef SQLITE_ENABLE_FTS3
88853 /************** Include fts3.h in the middle of main.c ***********************/
88854 /************** Begin file fts3.h ********************************************/
88855 /*
88856 ** 2006 Oct 10
88857 **
88858 ** The author disclaims copyright to this source code.  In place of
88859 ** a legal notice, here is a blessing:
88860 **
88861 **    May you do good and not evil.
88862 **    May you find forgiveness for yourself and forgive others.
88863 **    May you share freely, never taking more than you give.
88864 **
88865 ******************************************************************************
88866 **
88867 ** This header file is used by programs that want to link against the
88868 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
88869 */
88870
88871 #if 0
88872 extern "C" {
88873 #endif  /* __cplusplus */
88874
88875 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
88876
88877 #if 0
88878 }  /* extern "C" */
88879 #endif  /* __cplusplus */
88880
88881 /************** End of fts3.h ************************************************/
88882 /************** Continuing where we left off in main.c ***********************/
88883 #endif
88884 #ifdef SQLITE_ENABLE_RTREE
88885 /************** Include rtree.h in the middle of main.c **********************/
88886 /************** Begin file rtree.h *******************************************/
88887 /*
88888 ** 2008 May 26
88889 **
88890 ** The author disclaims copyright to this source code.  In place of
88891 ** a legal notice, here is a blessing:
88892 **
88893 **    May you do good and not evil.
88894 **    May you find forgiveness for yourself and forgive others.
88895 **    May you share freely, never taking more than you give.
88896 **
88897 ******************************************************************************
88898 **
88899 ** This header file is used by programs that want to link against the
88900 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
88901 */
88902
88903 #if 0
88904 extern "C" {
88905 #endif  /* __cplusplus */
88906
88907 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
88908
88909 #if 0
88910 }  /* extern "C" */
88911 #endif  /* __cplusplus */
88912
88913 /************** End of rtree.h ***********************************************/
88914 /************** Continuing where we left off in main.c ***********************/
88915 #endif
88916 #ifdef SQLITE_ENABLE_ICU
88917 /************** Include sqliteicu.h in the middle of main.c ******************/
88918 /************** Begin file sqliteicu.h ***************************************/
88919 /*
88920 ** 2008 May 26
88921 **
88922 ** The author disclaims copyright to this source code.  In place of
88923 ** a legal notice, here is a blessing:
88924 **
88925 **    May you do good and not evil.
88926 **    May you find forgiveness for yourself and forgive others.
88927 **    May you share freely, never taking more than you give.
88928 **
88929 ******************************************************************************
88930 **
88931 ** This header file is used by programs that want to link against the
88932 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
88933 */
88934
88935 #if 0
88936 extern "C" {
88937 #endif  /* __cplusplus */
88938
88939 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
88940
88941 #if 0
88942 }  /* extern "C" */
88943 #endif  /* __cplusplus */
88944
88945
88946 /************** End of sqliteicu.h *******************************************/
88947 /************** Continuing where we left off in main.c ***********************/
88948 #endif
88949
88950 /*
88951 ** The version of the library
88952 */
88953 #ifndef SQLITE_AMALGAMATION
88954 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
88955 #endif
88956 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
88957 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
88958 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
88959
88960 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
88961 /*
88962 ** If the following function pointer is not NULL and if
88963 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
88964 ** I/O active are written using this function.  These messages
88965 ** are intended for debugging activity only.
88966 */
88967 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
88968 #endif
88969
88970 /*
88971 ** If the following global variable points to a string which is the
88972 ** name of a directory, then that directory will be used to store
88973 ** temporary files.
88974 **
88975 ** See also the "PRAGMA temp_store_directory" SQL command.
88976 */
88977 SQLITE_API char *sqlite3_temp_directory = 0;
88978
88979 /*
88980 ** Initialize SQLite.  
88981 **
88982 ** This routine must be called to initialize the memory allocation,
88983 ** VFS, and mutex subsystems prior to doing any serious work with
88984 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
88985 ** this routine will be called automatically by key routines such as
88986 ** sqlite3_open().  
88987 **
88988 ** This routine is a no-op except on its very first call for the process,
88989 ** or for the first call after a call to sqlite3_shutdown.
88990 **
88991 ** The first thread to call this routine runs the initialization to
88992 ** completion.  If subsequent threads call this routine before the first
88993 ** thread has finished the initialization process, then the subsequent
88994 ** threads must block until the first thread finishes with the initialization.
88995 **
88996 ** The first thread might call this routine recursively.  Recursive
88997 ** calls to this routine should not block, of course.  Otherwise the
88998 ** initialization process would never complete.
88999 **
89000 ** Let X be the first thread to enter this routine.  Let Y be some other
89001 ** thread.  Then while the initial invocation of this routine by X is
89002 ** incomplete, it is required that:
89003 **
89004 **    *  Calls to this routine from Y must block until the outer-most
89005 **       call by X completes.
89006 **
89007 **    *  Recursive calls to this routine from thread X return immediately
89008 **       without blocking.
89009 */
89010 SQLITE_API int sqlite3_initialize(void){
89011   sqlite3_mutex *pMaster;                      /* The main static mutex */
89012   int rc;                                      /* Result code */
89013
89014 #ifdef SQLITE_OMIT_WSD
89015   rc = sqlite3_wsd_init(4096, 24);
89016   if( rc!=SQLITE_OK ){
89017     return rc;
89018   }
89019 #endif
89020
89021   /* If SQLite is already completely initialized, then this call
89022   ** to sqlite3_initialize() should be a no-op.  But the initialization
89023   ** must be complete.  So isInit must not be set until the very end
89024   ** of this routine.
89025   */
89026   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
89027
89028   /* Make sure the mutex subsystem is initialized.  If unable to 
89029   ** initialize the mutex subsystem, return early with the error.
89030   ** If the system is so sick that we are unable to allocate a mutex,
89031   ** there is not much SQLite is going to be able to do.
89032   **
89033   ** The mutex subsystem must take care of serializing its own
89034   ** initialization.
89035   */
89036   rc = sqlite3MutexInit();
89037   if( rc ) return rc;
89038
89039   /* Initialize the malloc() system and the recursive pInitMutex mutex.
89040   ** This operation is protected by the STATIC_MASTER mutex.  Note that
89041   ** MutexAlloc() is called for a static mutex prior to initializing the
89042   ** malloc subsystem - this implies that the allocation of a static
89043   ** mutex must not require support from the malloc subsystem.
89044   */
89045   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
89046   sqlite3_mutex_enter(pMaster);
89047   if( !sqlite3GlobalConfig.isMallocInit ){
89048     rc = sqlite3MallocInit();
89049   }
89050   if( rc==SQLITE_OK ){
89051     sqlite3GlobalConfig.isMallocInit = 1;
89052     if( !sqlite3GlobalConfig.pInitMutex ){
89053       sqlite3GlobalConfig.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
89054       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
89055         rc = SQLITE_NOMEM;
89056       }
89057     }
89058   }
89059   if( rc==SQLITE_OK ){
89060     sqlite3GlobalConfig.nRefInitMutex++;
89061   }
89062   sqlite3_mutex_leave(pMaster);
89063
89064   /* If unable to initialize the malloc subsystem, then return early.
89065   ** There is little hope of getting SQLite to run if the malloc
89066   ** subsystem cannot be initialized.
89067   */
89068   if( rc!=SQLITE_OK ){
89069     return rc;
89070   }
89071
89072   /* Do the rest of the initialization under the recursive mutex so
89073   ** that we will be able to handle recursive calls into
89074   ** sqlite3_initialize().  The recursive calls normally come through
89075   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
89076   ** recursive calls might also be possible.
89077   */
89078   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
89079   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
89080     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89081     sqlite3GlobalConfig.inProgress = 1;
89082     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
89083     sqlite3RegisterGlobalFunctions();
89084     rc = sqlite3_os_init();
89085     if( rc==SQLITE_OK ){
89086       rc = sqlite3PcacheInitialize();
89087       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
89088           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
89089     }
89090     sqlite3GlobalConfig.inProgress = 0;
89091     sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
89092   }
89093   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
89094
89095   /* Go back under the static mutex and clean up the recursive
89096   ** mutex to prevent a resource leak.
89097   */
89098   sqlite3_mutex_enter(pMaster);
89099   sqlite3GlobalConfig.nRefInitMutex--;
89100   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
89101     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
89102     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
89103     sqlite3GlobalConfig.pInitMutex = 0;
89104   }
89105   sqlite3_mutex_leave(pMaster);
89106
89107   /* The following is just a sanity check to make sure SQLite has
89108   ** been compiled correctly.  It is important to run this code, but
89109   ** we don't want to run it too often and soak up CPU cycles for no
89110   ** reason.  So we run it once during initialization.
89111   */
89112 #ifndef NDEBUG
89113 #ifndef SQLITE_OMIT_FLOATING_POINT
89114   /* This section of code's only "output" is via assert() statements. */
89115   if ( rc==SQLITE_OK ){
89116     u64 x = (((u64)1)<<63)-1;
89117     double y;
89118     assert(sizeof(x)==8);
89119     assert(sizeof(x)==sizeof(y));
89120     memcpy(&y, &x, 8);
89121     assert( sqlite3IsNaN(y) );
89122   }
89123 #endif
89124 #endif
89125
89126   return rc;
89127 }
89128
89129 /*
89130 ** Undo the effects of sqlite3_initialize().  Must not be called while
89131 ** there are outstanding database connections or memory allocations or
89132 ** while any part of SQLite is otherwise in use in any thread.  This
89133 ** routine is not threadsafe.  Not by a long shot.
89134 */
89135 SQLITE_API int sqlite3_shutdown(void){
89136   sqlite3GlobalConfig.isMallocInit = 0;
89137   sqlite3PcacheShutdown();
89138   if( sqlite3GlobalConfig.isInit ){
89139     sqlite3_os_end();
89140   }
89141   sqlite3MallocEnd();
89142   sqlite3MutexEnd();
89143   sqlite3GlobalConfig.isInit = 0;
89144   return SQLITE_OK;
89145 }
89146
89147 /*
89148 ** This API allows applications to modify the global configuration of
89149 ** the SQLite library at run-time.
89150 **
89151 ** This routine should only be called when there are no outstanding
89152 ** database connections or memory allocations.  This routine is not
89153 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
89154 ** behavior.
89155 */
89156 SQLITE_API int sqlite3_config(int op, ...){
89157   va_list ap;
89158   int rc = SQLITE_OK;
89159
89160   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
89161   ** the SQLite library is in use. */
89162   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
89163
89164   va_start(ap, op);
89165   switch( op ){
89166
89167     /* Mutex configuration options are only available in a threadsafe
89168     ** compile. 
89169     */
89170 #if SQLITE_THREADSAFE
89171     case SQLITE_CONFIG_SINGLETHREAD: {
89172       /* Disable all mutexing */
89173       sqlite3GlobalConfig.bCoreMutex = 0;
89174       sqlite3GlobalConfig.bFullMutex = 0;
89175       break;
89176     }
89177     case SQLITE_CONFIG_MULTITHREAD: {
89178       /* Disable mutexing of database connections */
89179       /* Enable mutexing of core data structures */
89180       sqlite3GlobalConfig.bCoreMutex = 1;
89181       sqlite3GlobalConfig.bFullMutex = 0;
89182       break;
89183     }
89184     case SQLITE_CONFIG_SERIALIZED: {
89185       /* Enable all mutexing */
89186       sqlite3GlobalConfig.bCoreMutex = 1;
89187       sqlite3GlobalConfig.bFullMutex = 1;
89188       break;
89189     }
89190     case SQLITE_CONFIG_MUTEX: {
89191       /* Specify an alternative mutex implementation */
89192       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
89193       break;
89194     }
89195     case SQLITE_CONFIG_GETMUTEX: {
89196       /* Retrieve the current mutex implementation */
89197       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
89198       break;
89199     }
89200 #endif
89201
89202
89203     case SQLITE_CONFIG_MALLOC: {
89204       /* Specify an alternative malloc implementation */
89205       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
89206       break;
89207     }
89208     case SQLITE_CONFIG_GETMALLOC: {
89209       /* Retrieve the current malloc() implementation */
89210       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
89211       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
89212       break;
89213     }
89214     case SQLITE_CONFIG_MEMSTATUS: {
89215       /* Enable or disable the malloc status collection */
89216       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
89217       break;
89218     }
89219     case SQLITE_CONFIG_SCRATCH: {
89220       /* Designate a buffer for scratch memory space */
89221       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
89222       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
89223       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
89224       break;
89225     }
89226     case SQLITE_CONFIG_PAGECACHE: {
89227       /* Designate a buffer for scratch memory space */
89228       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
89229       sqlite3GlobalConfig.szPage = va_arg(ap, int);
89230       sqlite3GlobalConfig.nPage = va_arg(ap, int);
89231       break;
89232     }
89233
89234     case SQLITE_CONFIG_PCACHE: {
89235       /* Specify an alternative malloc implementation */
89236       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
89237       break;
89238     }
89239
89240     case SQLITE_CONFIG_GETPCACHE: {
89241       if( sqlite3GlobalConfig.pcache.xInit==0 ){
89242         sqlite3PCacheSetDefault();
89243       }
89244       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
89245       break;
89246     }
89247
89248 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
89249     case SQLITE_CONFIG_HEAP: {
89250       /* Designate a buffer for heap memory space */
89251       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
89252       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
89253       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
89254
89255       if( sqlite3GlobalConfig.pHeap==0 ){
89256         /* If the heap pointer is NULL, then restore the malloc implementation
89257         ** back to NULL pointers too.  This will cause the malloc to go
89258         ** back to its default implementation when sqlite3_initialize() is
89259         ** run.
89260         */
89261         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
89262       }else{
89263         /* The heap pointer is not NULL, then install one of the
89264         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
89265         ** ENABLE_MEMSYS5 is defined, return an error.
89266         ** the default case and return an error.
89267         */
89268 #ifdef SQLITE_ENABLE_MEMSYS3
89269         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
89270 #endif
89271 #ifdef SQLITE_ENABLE_MEMSYS5
89272         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
89273 #endif
89274       }
89275       break;
89276     }
89277 #endif
89278
89279     case SQLITE_CONFIG_LOOKASIDE: {
89280       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
89281       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
89282       break;
89283     }
89284
89285     default: {
89286       rc = SQLITE_ERROR;
89287       break;
89288     }
89289   }
89290   va_end(ap);
89291   return rc;
89292 }
89293
89294 /*
89295 ** Set up the lookaside buffers for a database connection.
89296 ** Return SQLITE_OK on success.  
89297 ** If lookaside is already active, return SQLITE_BUSY.
89298 **
89299 ** The sz parameter is the number of bytes in each lookaside slot.
89300 ** The cnt parameter is the number of slots.  If pStart is NULL the
89301 ** space for the lookaside memory is obtained from sqlite3_malloc().
89302 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
89303 ** the lookaside memory.
89304 */
89305 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
89306   void *pStart;
89307   if( db->lookaside.nOut ){
89308     return SQLITE_BUSY;
89309   }
89310   /* Free any existing lookaside buffer for this handle before
89311   ** allocating a new one so we don't have to have space for 
89312   ** both at the same time.
89313   */
89314   if( db->lookaside.bMalloced ){
89315     sqlite3_free(db->lookaside.pStart);
89316   }
89317   /* The size of a lookaside slot needs to be larger than a pointer
89318   ** to be useful.
89319   */
89320   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
89321   if( cnt<0 ) cnt = 0;
89322   if( sz==0 || cnt==0 ){
89323     sz = 0;
89324     pStart = 0;
89325   }else if( pBuf==0 ){
89326     sz = (sz + 7)&~7;
89327     sqlite3BeginBenignMalloc();
89328     pStart = sqlite3Malloc( sz*cnt );
89329     sqlite3EndBenignMalloc();
89330   }else{
89331     sz = sz&~7;
89332     pStart = pBuf;
89333   }
89334   db->lookaside.pStart = pStart;
89335   db->lookaside.pFree = 0;
89336   db->lookaside.sz = (u16)sz;
89337   if( pStart ){
89338     int i;
89339     LookasideSlot *p;
89340     assert( sz > sizeof(LookasideSlot*) );
89341     p = (LookasideSlot*)pStart;
89342     for(i=cnt-1; i>=0; i--){
89343       p->pNext = db->lookaside.pFree;
89344       db->lookaside.pFree = p;
89345       p = (LookasideSlot*)&((u8*)p)[sz];
89346     }
89347     db->lookaside.pEnd = p;
89348     db->lookaside.bEnabled = 1;
89349     db->lookaside.bMalloced = pBuf==0 ?1:0;
89350   }else{
89351     db->lookaside.pEnd = 0;
89352     db->lookaside.bEnabled = 0;
89353     db->lookaside.bMalloced = 0;
89354   }
89355   return SQLITE_OK;
89356 }
89357
89358 /*
89359 ** Return the mutex associated with a database connection.
89360 */
89361 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
89362   return db->mutex;
89363 }
89364
89365 /*
89366 ** Configuration settings for an individual database connection
89367 */
89368 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
89369   va_list ap;
89370   int rc;
89371   va_start(ap, op);
89372   switch( op ){
89373     case SQLITE_DBCONFIG_LOOKASIDE: {
89374       void *pBuf = va_arg(ap, void*);
89375       int sz = va_arg(ap, int);
89376       int cnt = va_arg(ap, int);
89377       rc = setupLookaside(db, pBuf, sz, cnt);
89378       break;
89379     }
89380     default: {
89381       rc = SQLITE_ERROR;
89382       break;
89383     }
89384   }
89385   va_end(ap);
89386   return rc;
89387 }
89388
89389
89390 /*
89391 ** Return true if the buffer z[0..n-1] contains all spaces.
89392 */
89393 static int allSpaces(const char *z, int n){
89394   while( n>0 && z[n-1]==' ' ){ n--; }
89395   return n==0;
89396 }
89397
89398 /*
89399 ** This is the default collating function named "BINARY" which is always
89400 ** available.
89401 **
89402 ** If the padFlag argument is not NULL then space padding at the end
89403 ** of strings is ignored.  This implements the RTRIM collation.
89404 */
89405 static int binCollFunc(
89406   void *padFlag,
89407   int nKey1, const void *pKey1,
89408   int nKey2, const void *pKey2
89409 ){
89410   int rc, n;
89411   n = nKey1<nKey2 ? nKey1 : nKey2;
89412   rc = memcmp(pKey1, pKey2, n);
89413   if( rc==0 ){
89414     if( padFlag
89415      && allSpaces(((char*)pKey1)+n, nKey1-n)
89416      && allSpaces(((char*)pKey2)+n, nKey2-n)
89417     ){
89418       /* Leave rc unchanged at 0 */
89419     }else{
89420       rc = nKey1 - nKey2;
89421     }
89422   }
89423   return rc;
89424 }
89425
89426 /*
89427 ** Another built-in collating sequence: NOCASE. 
89428 **
89429 ** This collating sequence is intended to be used for "case independant
89430 ** comparison". SQLite's knowledge of upper and lower case equivalents
89431 ** extends only to the 26 characters used in the English language.
89432 **
89433 ** At the moment there is only a UTF-8 implementation.
89434 */
89435 static int nocaseCollatingFunc(
89436   void *NotUsed,
89437   int nKey1, const void *pKey1,
89438   int nKey2, const void *pKey2
89439 ){
89440   int r = sqlite3StrNICmp(
89441       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
89442   UNUSED_PARAMETER(NotUsed);
89443   if( 0==r ){
89444     r = nKey1-nKey2;
89445   }
89446   return r;
89447 }
89448
89449 /*
89450 ** Return the ROWID of the most recent insert
89451 */
89452 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
89453   return db->lastRowid;
89454 }
89455
89456 /*
89457 ** Return the number of changes in the most recent call to sqlite3_exec().
89458 */
89459 SQLITE_API int sqlite3_changes(sqlite3 *db){
89460   return db->nChange;
89461 }
89462
89463 /*
89464 ** Return the number of changes since the database handle was opened.
89465 */
89466 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
89467   return db->nTotalChange;
89468 }
89469
89470 /*
89471 ** Close all open savepoints. This function only manipulates fields of the
89472 ** database handle object, it does not close any savepoints that may be open
89473 ** at the b-tree/pager level.
89474 */
89475 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
89476   while( db->pSavepoint ){
89477     Savepoint *pTmp = db->pSavepoint;
89478     db->pSavepoint = pTmp->pNext;
89479     sqlite3DbFree(db, pTmp);
89480   }
89481   db->nSavepoint = 0;
89482   db->isTransactionSavepoint = 0;
89483 }
89484
89485 /*
89486 ** Close an existing SQLite database
89487 */
89488 SQLITE_API int sqlite3_close(sqlite3 *db){
89489   HashElem *i;
89490   int j;
89491
89492   if( !db ){
89493     return SQLITE_OK;
89494   }
89495   if( !sqlite3SafetyCheckSickOrOk(db) ){
89496     return SQLITE_MISUSE;
89497   }
89498   sqlite3_mutex_enter(db->mutex);
89499
89500 #ifdef SQLITE_SSE
89501   {
89502     extern void sqlite3SseCleanup(sqlite3*);
89503     sqlite3SseCleanup(db);
89504   }
89505 #endif 
89506
89507   sqlite3ResetInternalSchema(db, 0);
89508
89509   /* If a transaction is open, the ResetInternalSchema() call above
89510   ** will not have called the xDisconnect() method on any virtual
89511   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
89512   ** call will do so. We need to do this before the check for active
89513   ** SQL statements below, as the v-table implementation may be storing
89514   ** some prepared statements internally.
89515   */
89516   sqlite3VtabRollback(db);
89517
89518   /* If there are any outstanding VMs, return SQLITE_BUSY. */
89519   if( db->pVdbe ){
89520     sqlite3Error(db, SQLITE_BUSY, 
89521         "unable to close due to unfinalised statements");
89522     sqlite3_mutex_leave(db->mutex);
89523     return SQLITE_BUSY;
89524   }
89525   assert( sqlite3SafetyCheckSickOrOk(db) );
89526
89527   for(j=0; j<db->nDb; j++){
89528     Btree *pBt = db->aDb[j].pBt;
89529     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
89530       sqlite3Error(db, SQLITE_BUSY, 
89531           "unable to close due to unfinished backup operation");
89532       sqlite3_mutex_leave(db->mutex);
89533       return SQLITE_BUSY;
89534     }
89535   }
89536
89537   /* Free any outstanding Savepoint structures. */
89538   sqlite3CloseSavepoints(db);
89539
89540   for(j=0; j<db->nDb; j++){
89541     struct Db *pDb = &db->aDb[j];
89542     if( pDb->pBt ){
89543       sqlite3BtreeClose(pDb->pBt);
89544       pDb->pBt = 0;
89545       if( j!=1 ){
89546         pDb->pSchema = 0;
89547       }
89548     }
89549   }
89550   sqlite3ResetInternalSchema(db, 0);
89551   assert( db->nDb<=2 );
89552   assert( db->aDb==db->aDbStatic );
89553   for(j=0; j<ArraySize(db->aFunc.a); j++){
89554     FuncDef *pNext, *pHash, *p;
89555     for(p=db->aFunc.a[j]; p; p=pHash){
89556       pHash = p->pHash;
89557       while( p ){
89558         pNext = p->pNext;
89559         sqlite3DbFree(db, p);
89560         p = pNext;
89561       }
89562     }
89563   }
89564   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
89565     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
89566     /* Invoke any destructors registered for collation sequence user data. */
89567     for(j=0; j<3; j++){
89568       if( pColl[j].xDel ){
89569         pColl[j].xDel(pColl[j].pUser);
89570       }
89571     }
89572     sqlite3DbFree(db, pColl);
89573   }
89574   sqlite3HashClear(&db->aCollSeq);
89575 #ifndef SQLITE_OMIT_VIRTUALTABLE
89576   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
89577     Module *pMod = (Module *)sqliteHashData(i);
89578     if( pMod->xDestroy ){
89579       pMod->xDestroy(pMod->pAux);
89580     }
89581     sqlite3DbFree(db, pMod);
89582   }
89583   sqlite3HashClear(&db->aModule);
89584 #endif
89585
89586   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
89587   if( db->pErr ){
89588     sqlite3ValueFree(db->pErr);
89589   }
89590   sqlite3CloseExtensions(db);
89591
89592   db->magic = SQLITE_MAGIC_ERROR;
89593
89594   /* The temp-database schema is allocated differently from the other schema
89595   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
89596   ** So it needs to be freed here. Todo: Why not roll the temp schema into
89597   ** the same sqliteMalloc() as the one that allocates the database 
89598   ** structure?
89599   */
89600   sqlite3DbFree(db, db->aDb[1].pSchema);
89601   sqlite3_mutex_leave(db->mutex);
89602   db->magic = SQLITE_MAGIC_CLOSED;
89603   sqlite3_mutex_free(db->mutex);
89604   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
89605   if( db->lookaside.bMalloced ){
89606     sqlite3_free(db->lookaside.pStart);
89607   }
89608   sqlite3_free(db);
89609   return SQLITE_OK;
89610 }
89611
89612 /*
89613 ** Rollback all database files.
89614 */
89615 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
89616   int i;
89617   int inTrans = 0;
89618   assert( sqlite3_mutex_held(db->mutex) );
89619   sqlite3BeginBenignMalloc();
89620   for(i=0; i<db->nDb; i++){
89621     if( db->aDb[i].pBt ){
89622       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
89623         inTrans = 1;
89624       }
89625       sqlite3BtreeRollback(db->aDb[i].pBt);
89626       db->aDb[i].inTrans = 0;
89627     }
89628   }
89629   sqlite3VtabRollback(db);
89630   sqlite3EndBenignMalloc();
89631
89632   if( db->flags&SQLITE_InternChanges ){
89633     sqlite3ExpirePreparedStatements(db);
89634     sqlite3ResetInternalSchema(db, 0);
89635   }
89636
89637   /* If one has been configured, invoke the rollback-hook callback */
89638   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
89639     db->xRollbackCallback(db->pRollbackArg);
89640   }
89641 }
89642
89643 /*
89644 ** Return a static string that describes the kind of error specified in the
89645 ** argument.
89646 */
89647 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
89648   const char *z;
89649   switch( rc & 0xff ){
89650     case SQLITE_ROW:
89651     case SQLITE_DONE:
89652     case SQLITE_OK:         z = "not an error";                          break;
89653     case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
89654     case SQLITE_PERM:       z = "access permission denied";              break;
89655     case SQLITE_ABORT:      z = "callback requested query abort";        break;
89656     case SQLITE_BUSY:       z = "database is locked";                    break;
89657     case SQLITE_LOCKED:     z = "database table is locked";              break;
89658     case SQLITE_NOMEM:      z = "out of memory";                         break;
89659     case SQLITE_READONLY:   z = "attempt to write a readonly database";  break;
89660     case SQLITE_INTERRUPT:  z = "interrupted";                           break;
89661     case SQLITE_IOERR:      z = "disk I/O error";                        break;
89662     case SQLITE_CORRUPT:    z = "database disk image is malformed";      break;
89663     case SQLITE_FULL:       z = "database or disk is full";              break;
89664     case SQLITE_CANTOPEN:   z = "unable to open database file";          break;
89665     case SQLITE_EMPTY:      z = "table contains no data";                break;
89666     case SQLITE_SCHEMA:     z = "database schema has changed";           break;
89667     case SQLITE_TOOBIG:     z = "String or BLOB exceeded size limit";    break;
89668     case SQLITE_CONSTRAINT: z = "constraint failed";                     break;
89669     case SQLITE_MISMATCH:   z = "datatype mismatch";                     break;
89670     case SQLITE_MISUSE:     z = "library routine called out of sequence";break;
89671     case SQLITE_NOLFS:      z = "large file support is disabled";        break;
89672     case SQLITE_AUTH:       z = "authorization denied";                  break;
89673     case SQLITE_FORMAT:     z = "auxiliary database format error";       break;
89674     case SQLITE_RANGE:      z = "bind or column index out of range";     break;
89675     case SQLITE_NOTADB:     z = "file is encrypted or is not a database";break;
89676     default:                z = "unknown error";                         break;
89677   }
89678   return z;
89679 }
89680
89681 /*
89682 ** This routine implements a busy callback that sleeps and tries
89683 ** again until a timeout value is reached.  The timeout value is
89684 ** an integer number of milliseconds passed in as the first
89685 ** argument.
89686 */
89687 static int sqliteDefaultBusyCallback(
89688  void *ptr,               /* Database connection */
89689  int count                /* Number of times table has been busy */
89690 ){
89691 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
89692   static const u8 delays[] =
89693      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
89694   static const u8 totals[] =
89695      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
89696 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
89697   sqlite3 *db = (sqlite3 *)ptr;
89698   int timeout = db->busyTimeout;
89699   int delay, prior;
89700
89701   assert( count>=0 );
89702   if( count < NDELAY ){
89703     delay = delays[count];
89704     prior = totals[count];
89705   }else{
89706     delay = delays[NDELAY-1];
89707     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
89708   }
89709   if( prior + delay > timeout ){
89710     delay = timeout - prior;
89711     if( delay<=0 ) return 0;
89712   }
89713   sqlite3OsSleep(db->pVfs, delay*1000);
89714   return 1;
89715 #else
89716   sqlite3 *db = (sqlite3 *)ptr;
89717   int timeout = ((sqlite3 *)ptr)->busyTimeout;
89718   if( (count+1)*1000 > timeout ){
89719     return 0;
89720   }
89721   sqlite3OsSleep(db->pVfs, 1000000);
89722   return 1;
89723 #endif
89724 }
89725
89726 /*
89727 ** Invoke the given busy handler.
89728 **
89729 ** This routine is called when an operation failed with a lock.
89730 ** If this routine returns non-zero, the lock is retried.  If it
89731 ** returns 0, the operation aborts with an SQLITE_BUSY error.
89732 */
89733 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
89734   int rc;
89735   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
89736   rc = p->xFunc(p->pArg, p->nBusy);
89737   if( rc==0 ){
89738     p->nBusy = -1;
89739   }else{
89740     p->nBusy++;
89741   }
89742   return rc; 
89743 }
89744
89745 /*
89746 ** This routine sets the busy callback for an Sqlite database to the
89747 ** given callback function with the given argument.
89748 */
89749 SQLITE_API int sqlite3_busy_handler(
89750   sqlite3 *db,
89751   int (*xBusy)(void*,int),
89752   void *pArg
89753 ){
89754   sqlite3_mutex_enter(db->mutex);
89755   db->busyHandler.xFunc = xBusy;
89756   db->busyHandler.pArg = pArg;
89757   db->busyHandler.nBusy = 0;
89758   sqlite3_mutex_leave(db->mutex);
89759   return SQLITE_OK;
89760 }
89761
89762 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
89763 /*
89764 ** This routine sets the progress callback for an Sqlite database to the
89765 ** given callback function with the given argument. The progress callback will
89766 ** be invoked every nOps opcodes.
89767 */
89768 SQLITE_API void sqlite3_progress_handler(
89769   sqlite3 *db, 
89770   int nOps,
89771   int (*xProgress)(void*), 
89772   void *pArg
89773 ){
89774   sqlite3_mutex_enter(db->mutex);
89775   if( nOps>0 ){
89776     db->xProgress = xProgress;
89777     db->nProgressOps = nOps;
89778     db->pProgressArg = pArg;
89779   }else{
89780     db->xProgress = 0;
89781     db->nProgressOps = 0;
89782     db->pProgressArg = 0;
89783   }
89784   sqlite3_mutex_leave(db->mutex);
89785 }
89786 #endif
89787
89788
89789 /*
89790 ** This routine installs a default busy handler that waits for the
89791 ** specified number of milliseconds before returning 0.
89792 */
89793 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
89794   if( ms>0 ){
89795     db->busyTimeout = ms;
89796     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
89797   }else{
89798     sqlite3_busy_handler(db, 0, 0);
89799   }
89800   return SQLITE_OK;
89801 }
89802
89803 /*
89804 ** Cause any pending operation to stop at its earliest opportunity.
89805 */
89806 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
89807   db->u1.isInterrupted = 1;
89808 }
89809
89810
89811 /*
89812 ** This function is exactly the same as sqlite3_create_function(), except
89813 ** that it is designed to be called by internal code. The difference is
89814 ** that if a malloc() fails in sqlite3_create_function(), an error code
89815 ** is returned and the mallocFailed flag cleared. 
89816 */
89817 SQLITE_PRIVATE int sqlite3CreateFunc(
89818   sqlite3 *db,
89819   const char *zFunctionName,
89820   int nArg,
89821   int enc,
89822   void *pUserData,
89823   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
89824   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
89825   void (*xFinal)(sqlite3_context*)
89826 ){
89827   FuncDef *p;
89828   int nName;
89829
89830   assert( sqlite3_mutex_held(db->mutex) );
89831   if( zFunctionName==0 ||
89832       (xFunc && (xFinal || xStep)) || 
89833       (!xFunc && (xFinal && !xStep)) ||
89834       (!xFunc && (!xFinal && xStep)) ||
89835       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
89836       (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
89837     sqlite3Error(db, SQLITE_ERROR, "bad parameters");
89838     return SQLITE_ERROR;
89839   }
89840   
89841 #ifndef SQLITE_OMIT_UTF16
89842   /* If SQLITE_UTF16 is specified as the encoding type, transform this
89843   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
89844   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
89845   **
89846   ** If SQLITE_ANY is specified, add three versions of the function
89847   ** to the hash table.
89848   */
89849   if( enc==SQLITE_UTF16 ){
89850     enc = SQLITE_UTF16NATIVE;
89851   }else if( enc==SQLITE_ANY ){
89852     int rc;
89853     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
89854          pUserData, xFunc, xStep, xFinal);
89855     if( rc==SQLITE_OK ){
89856       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
89857           pUserData, xFunc, xStep, xFinal);
89858     }
89859     if( rc!=SQLITE_OK ){
89860       return rc;
89861     }
89862     enc = SQLITE_UTF16BE;
89863   }
89864 #else
89865   enc = SQLITE_UTF8;
89866 #endif
89867   
89868   /* Check if an existing function is being overridden or deleted. If so,
89869   ** and there are active VMs, then return SQLITE_BUSY. If a function
89870   ** is being overridden/deleted but there are no active VMs, allow the
89871   ** operation to continue but invalidate all precompiled statements.
89872   */
89873   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
89874   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
89875     if( db->activeVdbeCnt ){
89876       sqlite3Error(db, SQLITE_BUSY, 
89877         "unable to delete/modify user-function due to active statements");
89878       assert( !db->mallocFailed );
89879       return SQLITE_BUSY;
89880     }else{
89881       sqlite3ExpirePreparedStatements(db);
89882     }
89883   }
89884
89885   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
89886   assert(p || db->mallocFailed);
89887   if( !p ){
89888     return SQLITE_NOMEM;
89889   }
89890   p->flags = 0;
89891   p->xFunc = xFunc;
89892   p->xStep = xStep;
89893   p->xFinalize = xFinal;
89894   p->pUserData = pUserData;
89895   p->nArg = (u16)nArg;
89896   return SQLITE_OK;
89897 }
89898
89899 /*
89900 ** Create new user functions.
89901 */
89902 SQLITE_API int sqlite3_create_function(
89903   sqlite3 *db,
89904   const char *zFunctionName,
89905   int nArg,
89906   int enc,
89907   void *p,
89908   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
89909   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
89910   void (*xFinal)(sqlite3_context*)
89911 ){
89912   int rc;
89913   sqlite3_mutex_enter(db->mutex);
89914   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
89915   rc = sqlite3ApiExit(db, rc);
89916   sqlite3_mutex_leave(db->mutex);
89917   return rc;
89918 }
89919
89920 #ifndef SQLITE_OMIT_UTF16
89921 SQLITE_API int sqlite3_create_function16(
89922   sqlite3 *db,
89923   const void *zFunctionName,
89924   int nArg,
89925   int eTextRep,
89926   void *p,
89927   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
89928   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
89929   void (*xFinal)(sqlite3_context*)
89930 ){
89931   int rc;
89932   char *zFunc8;
89933   sqlite3_mutex_enter(db->mutex);
89934   assert( !db->mallocFailed );
89935   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
89936   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
89937   sqlite3DbFree(db, zFunc8);
89938   rc = sqlite3ApiExit(db, rc);
89939   sqlite3_mutex_leave(db->mutex);
89940   return rc;
89941 }
89942 #endif
89943
89944
89945 /*
89946 ** Declare that a function has been overloaded by a virtual table.
89947 **
89948 ** If the function already exists as a regular global function, then
89949 ** this routine is a no-op.  If the function does not exist, then create
89950 ** a new one that always throws a run-time error.  
89951 **
89952 ** When virtual tables intend to provide an overloaded function, they
89953 ** should call this routine to make sure the global function exists.
89954 ** A global function must exist in order for name resolution to work
89955 ** properly.
89956 */
89957 SQLITE_API int sqlite3_overload_function(
89958   sqlite3 *db,
89959   const char *zName,
89960   int nArg
89961 ){
89962   int nName = sqlite3Strlen(db, zName);
89963   int rc;
89964   sqlite3_mutex_enter(db->mutex);
89965   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
89966     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
89967                       0, sqlite3InvalidFunction, 0, 0);
89968   }
89969   rc = sqlite3ApiExit(db, SQLITE_OK);
89970   sqlite3_mutex_leave(db->mutex);
89971   return rc;
89972 }
89973
89974 #ifndef SQLITE_OMIT_TRACE
89975 /*
89976 ** Register a trace function.  The pArg from the previously registered trace
89977 ** is returned.  
89978 **
89979 ** A NULL trace function means that no tracing is executes.  A non-NULL
89980 ** trace is a pointer to a function that is invoked at the start of each
89981 ** SQL statement.
89982 */
89983 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
89984   void *pOld;
89985   sqlite3_mutex_enter(db->mutex);
89986   pOld = db->pTraceArg;
89987   db->xTrace = xTrace;
89988   db->pTraceArg = pArg;
89989   sqlite3_mutex_leave(db->mutex);
89990   return pOld;
89991 }
89992 /*
89993 ** Register a profile function.  The pArg from the previously registered 
89994 ** profile function is returned.  
89995 **
89996 ** A NULL profile function means that no profiling is executes.  A non-NULL
89997 ** profile is a pointer to a function that is invoked at the conclusion of
89998 ** each SQL statement that is run.
89999 */
90000 SQLITE_API void *sqlite3_profile(
90001   sqlite3 *db,
90002   void (*xProfile)(void*,const char*,sqlite_uint64),
90003   void *pArg
90004 ){
90005   void *pOld;
90006   sqlite3_mutex_enter(db->mutex);
90007   pOld = db->pProfileArg;
90008   db->xProfile = xProfile;
90009   db->pProfileArg = pArg;
90010   sqlite3_mutex_leave(db->mutex);
90011   return pOld;
90012 }
90013 #endif /* SQLITE_OMIT_TRACE */
90014
90015 /*** EXPERIMENTAL ***
90016 **
90017 ** Register a function to be invoked when a transaction comments.
90018 ** If the invoked function returns non-zero, then the commit becomes a
90019 ** rollback.
90020 */
90021 SQLITE_API void *sqlite3_commit_hook(
90022   sqlite3 *db,              /* Attach the hook to this database */
90023   int (*xCallback)(void*),  /* Function to invoke on each commit */
90024   void *pArg                /* Argument to the function */
90025 ){
90026   void *pOld;
90027   sqlite3_mutex_enter(db->mutex);
90028   pOld = db->pCommitArg;
90029   db->xCommitCallback = xCallback;
90030   db->pCommitArg = pArg;
90031   sqlite3_mutex_leave(db->mutex);
90032   return pOld;
90033 }
90034
90035 /*
90036 ** Register a callback to be invoked each time a row is updated,
90037 ** inserted or deleted using this database connection.
90038 */
90039 SQLITE_API void *sqlite3_update_hook(
90040   sqlite3 *db,              /* Attach the hook to this database */
90041   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
90042   void *pArg                /* Argument to the function */
90043 ){
90044   void *pRet;
90045   sqlite3_mutex_enter(db->mutex);
90046   pRet = db->pUpdateArg;
90047   db->xUpdateCallback = xCallback;
90048   db->pUpdateArg = pArg;
90049   sqlite3_mutex_leave(db->mutex);
90050   return pRet;
90051 }
90052
90053 /*
90054 ** Register a callback to be invoked each time a transaction is rolled
90055 ** back by this database connection.
90056 */
90057 SQLITE_API void *sqlite3_rollback_hook(
90058   sqlite3 *db,              /* Attach the hook to this database */
90059   void (*xCallback)(void*), /* Callback function */
90060   void *pArg                /* Argument to the function */
90061 ){
90062   void *pRet;
90063   sqlite3_mutex_enter(db->mutex);
90064   pRet = db->pRollbackArg;
90065   db->xRollbackCallback = xCallback;
90066   db->pRollbackArg = pArg;
90067   sqlite3_mutex_leave(db->mutex);
90068   return pRet;
90069 }
90070
90071 /*
90072 ** This routine is called to create a connection to a database BTree
90073 ** driver.  If zFilename is the name of a file, then that file is
90074 ** opened and used.  If zFilename is the magic name ":memory:" then
90075 ** the database is stored in memory (and is thus forgotten as soon as
90076 ** the connection is closed.)  If zFilename is NULL then the database
90077 ** is a "virtual" database for transient use only and is deleted as
90078 ** soon as the connection is closed.
90079 **
90080 ** A virtual database can be either a disk file (that is automatically
90081 ** deleted when the file is closed) or it an be held entirely in memory,
90082 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
90083 ** db->temp_store variable, according to the following chart:
90084 **
90085 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
90086 **   -----------------     --------------     ------------------------------
90087 **   0                     any                file
90088 **   1                     1                  file
90089 **   1                     2                  memory
90090 **   1                     0                  file
90091 **   2                     1                  file
90092 **   2                     2                  memory
90093 **   2                     0                  memory
90094 **   3                     any                memory
90095 */
90096 SQLITE_PRIVATE int sqlite3BtreeFactory(
90097   const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
90098   const char *zFilename,    /* Name of the file containing the BTree database */
90099   int omitJournal,          /* if TRUE then do not journal this file */
90100   int nCache,               /* How many pages in the page cache */
90101   int vfsFlags,             /* Flags passed through to vfsOpen */
90102   Btree **ppBtree           /* Pointer to new Btree object written here */
90103 ){
90104   int btFlags = 0;
90105   int rc;
90106   
90107   assert( sqlite3_mutex_held(db->mutex) );
90108   assert( ppBtree != 0);
90109   if( omitJournal ){
90110     btFlags |= BTREE_OMIT_JOURNAL;
90111   }
90112   if( db->flags & SQLITE_NoReadlock ){
90113     btFlags |= BTREE_NO_READLOCK;
90114   }
90115   if( zFilename==0 ){
90116 #if SQLITE_TEMP_STORE==0
90117     /* Do nothing */
90118 #endif
90119 #ifndef SQLITE_OMIT_MEMORYDB
90120 #if SQLITE_TEMP_STORE==1
90121     if( db->temp_store==2 ) zFilename = ":memory:";
90122 #endif
90123 #if SQLITE_TEMP_STORE==2
90124     if( db->temp_store!=1 ) zFilename = ":memory:";
90125 #endif
90126 #if SQLITE_TEMP_STORE==3
90127     zFilename = ":memory:";
90128 #endif
90129 #endif /* SQLITE_OMIT_MEMORYDB */
90130   }
90131
90132   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
90133     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
90134   }
90135   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
90136
90137   /* If the B-Tree was successfully opened, set the pager-cache size to the
90138   ** default value. Except, if the call to BtreeOpen() returned a handle
90139   ** open on an existing shared pager-cache, do not change the pager-cache 
90140   ** size.
90141   */
90142   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
90143     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
90144   }
90145   return rc;
90146 }
90147
90148 /*
90149 ** Return UTF-8 encoded English language explanation of the most recent
90150 ** error.
90151 */
90152 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
90153   const char *z;
90154   if( !db ){
90155     return sqlite3ErrStr(SQLITE_NOMEM);
90156   }
90157   if( !sqlite3SafetyCheckSickOrOk(db) ){
90158     return sqlite3ErrStr(SQLITE_MISUSE);
90159   }
90160   if( db->mallocFailed ){
90161     return sqlite3ErrStr(SQLITE_NOMEM);
90162   }
90163   sqlite3_mutex_enter(db->mutex);
90164   assert( !db->mallocFailed );
90165   z = (char*)sqlite3_value_text(db->pErr);
90166   assert( !db->mallocFailed );
90167   if( z==0 ){
90168     z = sqlite3ErrStr(db->errCode);
90169   }
90170   sqlite3_mutex_leave(db->mutex);
90171   return z;
90172 }
90173
90174 #ifndef SQLITE_OMIT_UTF16
90175 /*
90176 ** Return UTF-16 encoded English language explanation of the most recent
90177 ** error.
90178 */
90179 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
90180   /* Because all the characters in the string are in the unicode
90181   ** range 0x00-0xFF, if we pad the big-endian string with a 
90182   ** zero byte, we can obtain the little-endian string with
90183   ** &big_endian[1].
90184   */
90185   static const char outOfMemBe[] = {
90186     0, 'o', 0, 'u', 0, 't', 0, ' ', 
90187     0, 'o', 0, 'f', 0, ' ', 
90188     0, 'm', 0, 'e', 0, 'm', 0, 'o', 0, 'r', 0, 'y', 0, 0, 0
90189   };
90190   static const char misuseBe [] = {
90191     0, 'l', 0, 'i', 0, 'b', 0, 'r', 0, 'a', 0, 'r', 0, 'y', 0, ' ', 
90192     0, 'r', 0, 'o', 0, 'u', 0, 't', 0, 'i', 0, 'n', 0, 'e', 0, ' ', 
90193     0, 'c', 0, 'a', 0, 'l', 0, 'l', 0, 'e', 0, 'd', 0, ' ', 
90194     0, 'o', 0, 'u', 0, 't', 0, ' ', 
90195     0, 'o', 0, 'f', 0, ' ', 
90196     0, 's', 0, 'e', 0, 'q', 0, 'u', 0, 'e', 0, 'n', 0, 'c', 0, 'e', 0, 0, 0
90197   };
90198
90199   const void *z;
90200   if( !db ){
90201     return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
90202   }
90203   if( !sqlite3SafetyCheckSickOrOk(db) ){
90204     return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]);
90205   }
90206   sqlite3_mutex_enter(db->mutex);
90207   assert( !db->mallocFailed );
90208   z = sqlite3_value_text16(db->pErr);
90209   if( z==0 ){
90210     sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
90211          SQLITE_UTF8, SQLITE_STATIC);
90212     z = sqlite3_value_text16(db->pErr);
90213   }
90214   /* A malloc() may have failed within the call to sqlite3_value_text16()
90215   ** above. If this is the case, then the db->mallocFailed flag needs to
90216   ** be cleared before returning. Do this directly, instead of via
90217   ** sqlite3ApiExit(), to avoid setting the database handle error message.
90218   */
90219   db->mallocFailed = 0;
90220   sqlite3_mutex_leave(db->mutex);
90221   return z;
90222 }
90223 #endif /* SQLITE_OMIT_UTF16 */
90224
90225 /*
90226 ** Return the most recent error code generated by an SQLite routine. If NULL is
90227 ** passed to this function, we assume a malloc() failed during sqlite3_open().
90228 */
90229 SQLITE_API int sqlite3_errcode(sqlite3 *db){
90230   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
90231     return SQLITE_MISUSE;
90232   }
90233   if( !db || db->mallocFailed ){
90234     return SQLITE_NOMEM;
90235   }
90236   return db->errCode & db->errMask;
90237 }
90238 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
90239   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
90240     return SQLITE_MISUSE;
90241   }
90242   if( !db || db->mallocFailed ){
90243     return SQLITE_NOMEM;
90244   }
90245   return db->errCode;
90246 }
90247
90248 /*
90249 ** Create a new collating function for database "db".  The name is zName
90250 ** and the encoding is enc.
90251 */
90252 static int createCollation(
90253   sqlite3* db, 
90254   const char *zName, 
90255   int enc, 
90256   void* pCtx,
90257   int(*xCompare)(void*,int,const void*,int,const void*),
90258   void(*xDel)(void*)
90259 ){
90260   CollSeq *pColl;
90261   int enc2;
90262   int nName;
90263   
90264   assert( sqlite3_mutex_held(db->mutex) );
90265
90266   /* If SQLITE_UTF16 is specified as the encoding type, transform this
90267   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
90268   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
90269   */
90270   enc2 = enc & ~SQLITE_UTF16_ALIGNED;
90271   if( enc2==SQLITE_UTF16 ){
90272     enc2 = SQLITE_UTF16NATIVE;
90273   }
90274   if( (enc2&~3)!=0 ){
90275     return SQLITE_MISUSE;
90276   }
90277
90278   /* Check if this call is removing or replacing an existing collation 
90279   ** sequence. If so, and there are active VMs, return busy. If there
90280   ** are no active VMs, invalidate any pre-compiled statements.
90281   */
90282   nName = sqlite3Strlen(db, zName);
90283   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
90284   if( pColl && pColl->xCmp ){
90285     if( db->activeVdbeCnt ){
90286       sqlite3Error(db, SQLITE_BUSY, 
90287         "unable to delete/modify collation sequence due to active statements");
90288       return SQLITE_BUSY;
90289     }
90290     sqlite3ExpirePreparedStatements(db);
90291
90292     /* If collation sequence pColl was created directly by a call to
90293     ** sqlite3_create_collation, and not generated by synthCollSeq(),
90294     ** then any copies made by synthCollSeq() need to be invalidated.
90295     ** Also, collation destructor - CollSeq.xDel() - function may need
90296     ** to be called.
90297     */ 
90298     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
90299       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
90300       int j;
90301       for(j=0; j<3; j++){
90302         CollSeq *p = &aColl[j];
90303         if( p->enc==pColl->enc ){
90304           if( p->xDel ){
90305             p->xDel(p->pUser);
90306           }
90307           p->xCmp = 0;
90308         }
90309       }
90310     }
90311   }
90312
90313   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1);
90314   if( pColl ){
90315     pColl->xCmp = xCompare;
90316     pColl->pUser = pCtx;
90317     pColl->xDel = xDel;
90318     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
90319   }
90320   sqlite3Error(db, SQLITE_OK, 0);
90321   return SQLITE_OK;
90322 }
90323
90324
90325 /*
90326 ** This array defines hard upper bounds on limit values.  The
90327 ** initializer must be kept in sync with the SQLITE_LIMIT_*
90328 ** #defines in sqlite3.h.
90329 */
90330 static const int aHardLimit[] = {
90331   SQLITE_MAX_LENGTH,
90332   SQLITE_MAX_SQL_LENGTH,
90333   SQLITE_MAX_COLUMN,
90334   SQLITE_MAX_EXPR_DEPTH,
90335   SQLITE_MAX_COMPOUND_SELECT,
90336   SQLITE_MAX_VDBE_OP,
90337   SQLITE_MAX_FUNCTION_ARG,
90338   SQLITE_MAX_ATTACHED,
90339   SQLITE_MAX_LIKE_PATTERN_LENGTH,
90340   SQLITE_MAX_VARIABLE_NUMBER,
90341 };
90342
90343 /*
90344 ** Make sure the hard limits are set to reasonable values
90345 */
90346 #if SQLITE_MAX_LENGTH<100
90347 # error SQLITE_MAX_LENGTH must be at least 100
90348 #endif
90349 #if SQLITE_MAX_SQL_LENGTH<100
90350 # error SQLITE_MAX_SQL_LENGTH must be at least 100
90351 #endif
90352 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
90353 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
90354 #endif
90355 #if SQLITE_MAX_COMPOUND_SELECT<2
90356 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
90357 #endif
90358 #if SQLITE_MAX_VDBE_OP<40
90359 # error SQLITE_MAX_VDBE_OP must be at least 40
90360 #endif
90361 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
90362 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
90363 #endif
90364 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
90365 # error SQLITE_MAX_ATTACHED must be between 0 and 30
90366 #endif
90367 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
90368 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
90369 #endif
90370 #if SQLITE_MAX_VARIABLE_NUMBER<1
90371 # error SQLITE_MAX_VARIABLE_NUMBER must be at least 1
90372 #endif
90373 #if SQLITE_MAX_COLUMN>32767
90374 # error SQLITE_MAX_COLUMN must not exceed 32767
90375 #endif
90376
90377
90378 /*
90379 ** Change the value of a limit.  Report the old value.
90380 ** If an invalid limit index is supplied, report -1.
90381 ** Make no changes but still report the old value if the
90382 ** new limit is negative.
90383 **
90384 ** A new lower limit does not shrink existing constructs.
90385 ** It merely prevents new constructs that exceed the limit
90386 ** from forming.
90387 */
90388 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
90389   int oldLimit;
90390   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
90391     return -1;
90392   }
90393   oldLimit = db->aLimit[limitId];
90394   if( newLimit>=0 ){
90395     if( newLimit>aHardLimit[limitId] ){
90396       newLimit = aHardLimit[limitId];
90397     }
90398     db->aLimit[limitId] = newLimit;
90399   }
90400   return oldLimit;
90401 }
90402
90403 /*
90404 ** This routine does the work of opening a database on behalf of
90405 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
90406 ** is UTF-8 encoded.
90407 */
90408 static int openDatabase(
90409   const char *zFilename, /* Database filename UTF-8 encoded */
90410   sqlite3 **ppDb,        /* OUT: Returned database handle */
90411   unsigned flags,        /* Operational flags */
90412   const char *zVfs       /* Name of the VFS to use */
90413 ){
90414   sqlite3 *db;
90415   int rc;
90416   CollSeq *pColl;
90417   int isThreadsafe;
90418
90419 #ifndef SQLITE_OMIT_AUTOINIT
90420   rc = sqlite3_initialize();
90421   if( rc ) return rc;
90422 #endif
90423
90424   if( sqlite3GlobalConfig.bCoreMutex==0 ){
90425     isThreadsafe = 0;
90426   }else if( flags & SQLITE_OPEN_NOMUTEX ){
90427     isThreadsafe = 0;
90428   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
90429     isThreadsafe = 1;
90430   }else{
90431     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
90432   }
90433
90434   /* Remove harmful bits from the flags parameter */
90435   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
90436                SQLITE_OPEN_MAIN_DB |
90437                SQLITE_OPEN_TEMP_DB | 
90438                SQLITE_OPEN_TRANSIENT_DB | 
90439                SQLITE_OPEN_MAIN_JOURNAL | 
90440                SQLITE_OPEN_TEMP_JOURNAL | 
90441                SQLITE_OPEN_SUBJOURNAL | 
90442                SQLITE_OPEN_MASTER_JOURNAL |
90443                SQLITE_OPEN_NOMUTEX |
90444                SQLITE_OPEN_FULLMUTEX
90445              );
90446
90447   /* Allocate the sqlite data structure */
90448   db = sqlite3MallocZero( sizeof(sqlite3) );
90449   if( db==0 ) goto opendb_out;
90450   if( isThreadsafe ){
90451     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
90452     if( db->mutex==0 ){
90453       sqlite3_free(db);
90454       db = 0;
90455       goto opendb_out;
90456     }
90457   }
90458   sqlite3_mutex_enter(db->mutex);
90459   db->errMask = 0xff;
90460   db->priorNewRowid = 0;
90461   db->nDb = 2;
90462   db->magic = SQLITE_MAGIC_BUSY;
90463   db->aDb = db->aDbStatic;
90464
90465   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
90466   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
90467   db->autoCommit = 1;
90468   db->nextAutovac = -1;
90469   db->nextPagesize = 0;
90470   db->flags |= SQLITE_ShortColNames
90471 #if SQLITE_DEFAULT_FILE_FORMAT<4
90472                  | SQLITE_LegacyFileFmt
90473 #endif
90474 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
90475                  | SQLITE_LoadExtension
90476 #endif
90477       ;
90478   sqlite3HashInit(&db->aCollSeq, 0);
90479 #ifndef SQLITE_OMIT_VIRTUALTABLE
90480   sqlite3HashInit(&db->aModule, 0);
90481 #endif
90482
90483   db->pVfs = sqlite3_vfs_find(zVfs);
90484   if( !db->pVfs ){
90485     rc = SQLITE_ERROR;
90486     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
90487     goto opendb_out;
90488   }
90489
90490   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
90491   ** and UTF-16, so add a version for each to avoid any unnecessary
90492   ** conversions. The only error that can occur here is a malloc() failure.
90493   */
90494   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
90495   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
90496   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
90497   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
90498   if( db->mallocFailed ){
90499     goto opendb_out;
90500   }
90501   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0);
90502   assert( db->pDfltColl!=0 );
90503
90504   /* Also add a UTF-8 case-insensitive collation sequence. */
90505   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
90506
90507   /* Set flags on the built-in collating sequences */
90508   db->pDfltColl->type = SQLITE_COLL_BINARY;
90509   pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "NOCASE", 6, 0);
90510   if( pColl ){
90511     pColl->type = SQLITE_COLL_NOCASE;
90512   }
90513
90514   /* Open the backend database driver */
90515   db->openFlags = flags;
90516   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
90517                            flags | SQLITE_OPEN_MAIN_DB,
90518                            &db->aDb[0].pBt);
90519   if( rc!=SQLITE_OK ){
90520     if( rc==SQLITE_IOERR_NOMEM ){
90521       rc = SQLITE_NOMEM;
90522     }
90523     sqlite3Error(db, rc, 0);
90524     goto opendb_out;
90525   }
90526   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
90527   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
90528
90529
90530   /* The default safety_level for the main database is 'full'; for the temp
90531   ** database it is 'NONE'. This matches the pager layer defaults.  
90532   */
90533   db->aDb[0].zName = "main";
90534   db->aDb[0].safety_level = 3;
90535 #ifndef SQLITE_OMIT_TEMPDB
90536   db->aDb[1].zName = "temp";
90537   db->aDb[1].safety_level = 1;
90538 #endif
90539
90540   db->magic = SQLITE_MAGIC_OPEN;
90541   if( db->mallocFailed ){
90542     goto opendb_out;
90543   }
90544
90545   /* Register all built-in functions, but do not attempt to read the
90546   ** database schema yet. This is delayed until the first time the database
90547   ** is accessed.
90548   */
90549   sqlite3Error(db, SQLITE_OK, 0);
90550   sqlite3RegisterBuiltinFunctions(db);
90551
90552   /* Load automatic extensions - extensions that have been registered
90553   ** using the sqlite3_automatic_extension() API.
90554   */
90555   (void)sqlite3AutoLoadExtensions(db);
90556   if( sqlite3_errcode(db)!=SQLITE_OK ){
90557     goto opendb_out;
90558   }
90559
90560 #ifdef SQLITE_ENABLE_FTS1
90561   if( !db->mallocFailed ){
90562     extern int sqlite3Fts1Init(sqlite3*);
90563     rc = sqlite3Fts1Init(db);
90564   }
90565 #endif
90566
90567 #ifdef SQLITE_ENABLE_FTS2
90568   if( !db->mallocFailed && rc==SQLITE_OK ){
90569     extern int sqlite3Fts2Init(sqlite3*);
90570     rc = sqlite3Fts2Init(db);
90571   }
90572 #endif
90573
90574 #ifdef SQLITE_ENABLE_FTS3
90575   if( !db->mallocFailed && rc==SQLITE_OK ){
90576     rc = sqlite3Fts3Init(db);
90577   }
90578 #endif
90579
90580 #ifdef SQLITE_ENABLE_ICU
90581   if( !db->mallocFailed && rc==SQLITE_OK ){
90582     rc = sqlite3IcuInit(db);
90583   }
90584 #endif
90585
90586 #ifdef SQLITE_ENABLE_RTREE
90587   if( !db->mallocFailed && rc==SQLITE_OK){
90588     rc = sqlite3RtreeInit(db);
90589   }
90590 #endif
90591
90592   sqlite3Error(db, rc, 0);
90593
90594   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
90595   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
90596   ** mode.  Doing nothing at all also makes NORMAL the default.
90597   */
90598 #ifdef SQLITE_DEFAULT_LOCKING_MODE
90599   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
90600   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
90601                           SQLITE_DEFAULT_LOCKING_MODE);
90602 #endif
90603
90604   /* Enable the lookaside-malloc subsystem */
90605   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
90606                         sqlite3GlobalConfig.nLookaside);
90607
90608 opendb_out:
90609   if( db ){
90610     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
90611     sqlite3_mutex_leave(db->mutex);
90612   }
90613   rc = sqlite3_errcode(db);
90614   if( rc==SQLITE_NOMEM ){
90615     sqlite3_close(db);
90616     db = 0;
90617   }else if( rc!=SQLITE_OK ){
90618     db->magic = SQLITE_MAGIC_SICK;
90619   }
90620   *ppDb = db;
90621   return sqlite3ApiExit(0, rc);
90622 }
90623
90624 /*
90625 ** Open a new database handle.
90626 */
90627 SQLITE_API int sqlite3_open(
90628   const char *zFilename, 
90629   sqlite3 **ppDb 
90630 ){
90631   return openDatabase(zFilename, ppDb,
90632                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
90633 }
90634 SQLITE_API int sqlite3_open_v2(
90635   const char *filename,   /* Database filename (UTF-8) */
90636   sqlite3 **ppDb,         /* OUT: SQLite db handle */
90637   int flags,              /* Flags */
90638   const char *zVfs        /* Name of VFS module to use */
90639 ){
90640   return openDatabase(filename, ppDb, flags, zVfs);
90641 }
90642
90643 #ifndef SQLITE_OMIT_UTF16
90644 /*
90645 ** Open a new database handle.
90646 */
90647 SQLITE_API int sqlite3_open16(
90648   const void *zFilename, 
90649   sqlite3 **ppDb
90650 ){
90651   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
90652   sqlite3_value *pVal;
90653   int rc;
90654
90655   assert( zFilename );
90656   assert( ppDb );
90657   *ppDb = 0;
90658 #ifndef SQLITE_OMIT_AUTOINIT
90659   rc = sqlite3_initialize();
90660   if( rc ) return rc;
90661 #endif
90662   pVal = sqlite3ValueNew(0);
90663   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
90664   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
90665   if( zFilename8 ){
90666     rc = openDatabase(zFilename8, ppDb,
90667                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
90668     assert( *ppDb || rc==SQLITE_NOMEM );
90669     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
90670       ENC(*ppDb) = SQLITE_UTF16NATIVE;
90671     }
90672   }else{
90673     rc = SQLITE_NOMEM;
90674   }
90675   sqlite3ValueFree(pVal);
90676
90677   return sqlite3ApiExit(0, rc);
90678 }
90679 #endif /* SQLITE_OMIT_UTF16 */
90680
90681 /*
90682 ** Register a new collation sequence with the database handle db.
90683 */
90684 SQLITE_API int sqlite3_create_collation(
90685   sqlite3* db, 
90686   const char *zName, 
90687   int enc, 
90688   void* pCtx,
90689   int(*xCompare)(void*,int,const void*,int,const void*)
90690 ){
90691   int rc;
90692   sqlite3_mutex_enter(db->mutex);
90693   assert( !db->mallocFailed );
90694   rc = createCollation(db, zName, enc, pCtx, xCompare, 0);
90695   rc = sqlite3ApiExit(db, rc);
90696   sqlite3_mutex_leave(db->mutex);
90697   return rc;
90698 }
90699
90700 /*
90701 ** Register a new collation sequence with the database handle db.
90702 */
90703 SQLITE_API int sqlite3_create_collation_v2(
90704   sqlite3* db, 
90705   const char *zName, 
90706   int enc, 
90707   void* pCtx,
90708   int(*xCompare)(void*,int,const void*,int,const void*),
90709   void(*xDel)(void*)
90710 ){
90711   int rc;
90712   sqlite3_mutex_enter(db->mutex);
90713   assert( !db->mallocFailed );
90714   rc = createCollation(db, zName, enc, pCtx, xCompare, xDel);
90715   rc = sqlite3ApiExit(db, rc);
90716   sqlite3_mutex_leave(db->mutex);
90717   return rc;
90718 }
90719
90720 #ifndef SQLITE_OMIT_UTF16
90721 /*
90722 ** Register a new collation sequence with the database handle db.
90723 */
90724 SQLITE_API int sqlite3_create_collation16(
90725   sqlite3* db, 
90726   const void *zName,
90727   int enc, 
90728   void* pCtx,
90729   int(*xCompare)(void*,int,const void*,int,const void*)
90730 ){
90731   int rc = SQLITE_OK;
90732   char *zName8;
90733   sqlite3_mutex_enter(db->mutex);
90734   assert( !db->mallocFailed );
90735   zName8 = sqlite3Utf16to8(db, zName, -1);
90736   if( zName8 ){
90737     rc = createCollation(db, zName8, enc, pCtx, xCompare, 0);
90738     sqlite3DbFree(db, zName8);
90739   }
90740   rc = sqlite3ApiExit(db, rc);
90741   sqlite3_mutex_leave(db->mutex);
90742   return rc;
90743 }
90744 #endif /* SQLITE_OMIT_UTF16 */
90745
90746 /*
90747 ** Register a collation sequence factory callback with the database handle
90748 ** db. Replace any previously installed collation sequence factory.
90749 */
90750 SQLITE_API int sqlite3_collation_needed(
90751   sqlite3 *db, 
90752   void *pCollNeededArg, 
90753   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
90754 ){
90755   sqlite3_mutex_enter(db->mutex);
90756   db->xCollNeeded = xCollNeeded;
90757   db->xCollNeeded16 = 0;
90758   db->pCollNeededArg = pCollNeededArg;
90759   sqlite3_mutex_leave(db->mutex);
90760   return SQLITE_OK;
90761 }
90762
90763 #ifndef SQLITE_OMIT_UTF16
90764 /*
90765 ** Register a collation sequence factory callback with the database handle
90766 ** db. Replace any previously installed collation sequence factory.
90767 */
90768 SQLITE_API int sqlite3_collation_needed16(
90769   sqlite3 *db, 
90770   void *pCollNeededArg, 
90771   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
90772 ){
90773   sqlite3_mutex_enter(db->mutex);
90774   db->xCollNeeded = 0;
90775   db->xCollNeeded16 = xCollNeeded16;
90776   db->pCollNeededArg = pCollNeededArg;
90777   sqlite3_mutex_leave(db->mutex);
90778   return SQLITE_OK;
90779 }
90780 #endif /* SQLITE_OMIT_UTF16 */
90781
90782 #ifndef SQLITE_OMIT_GLOBALRECOVER
90783 #ifndef SQLITE_OMIT_DEPRECATED
90784 /*
90785 ** This function is now an anachronism. It used to be used to recover from a
90786 ** malloc() failure, but SQLite now does this automatically.
90787 */
90788 SQLITE_API int sqlite3_global_recover(void){
90789   return SQLITE_OK;
90790 }
90791 #endif
90792 #endif
90793
90794 /*
90795 ** Test to see whether or not the database connection is in autocommit
90796 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
90797 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
90798 ** by the next COMMIT or ROLLBACK.
90799 **
90800 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
90801 */
90802 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
90803   return db->autoCommit;
90804 }
90805
90806 #ifdef SQLITE_DEBUG
90807 /*
90808 ** The following routine is subtituted for constant SQLITE_CORRUPT in
90809 ** debugging builds.  This provides a way to set a breakpoint for when
90810 ** corruption is first detected.
90811 */
90812 SQLITE_PRIVATE int sqlite3Corrupt(void){
90813   return SQLITE_CORRUPT;
90814 }
90815 #endif
90816
90817 #ifndef SQLITE_OMIT_DEPRECATED
90818 /*
90819 ** This is a convenience routine that makes sure that all thread-specific
90820 ** data for this thread has been deallocated.
90821 **
90822 ** SQLite no longer uses thread-specific data so this routine is now a
90823 ** no-op.  It is retained for historical compatibility.
90824 */
90825 SQLITE_API void sqlite3_thread_cleanup(void){
90826 }
90827 #endif
90828
90829 /*
90830 ** Return meta information about a specific column of a database table.
90831 ** See comment in sqlite3.h (sqlite.h.in) for details.
90832 */
90833 #ifdef SQLITE_ENABLE_COLUMN_METADATA
90834 SQLITE_API int sqlite3_table_column_metadata(
90835   sqlite3 *db,                /* Connection handle */
90836   const char *zDbName,        /* Database name or NULL */
90837   const char *zTableName,     /* Table name */
90838   const char *zColumnName,    /* Column name */
90839   char const **pzDataType,    /* OUTPUT: Declared data type */
90840   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
90841   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
90842   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
90843   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
90844 ){
90845   int rc;
90846   char *zErrMsg = 0;
90847   Table *pTab = 0;
90848   Column *pCol = 0;
90849   int iCol;
90850
90851   char const *zDataType = 0;
90852   char const *zCollSeq = 0;
90853   int notnull = 0;
90854   int primarykey = 0;
90855   int autoinc = 0;
90856
90857   /* Ensure the database schema has been loaded */
90858   sqlite3_mutex_enter(db->mutex);
90859   (void)sqlite3SafetyOn(db);
90860   sqlite3BtreeEnterAll(db);
90861   rc = sqlite3Init(db, &zErrMsg);
90862   sqlite3BtreeLeaveAll(db);
90863   if( SQLITE_OK!=rc ){
90864     goto error_out;
90865   }
90866
90867   /* Locate the table in question */
90868   pTab = sqlite3FindTable(db, zTableName, zDbName);
90869   if( !pTab || pTab->pSelect ){
90870     pTab = 0;
90871     goto error_out;
90872   }
90873
90874   /* Find the column for which info is requested */
90875   if( sqlite3IsRowid(zColumnName) ){
90876     iCol = pTab->iPKey;
90877     if( iCol>=0 ){
90878       pCol = &pTab->aCol[iCol];
90879     }
90880   }else{
90881     for(iCol=0; iCol<pTab->nCol; iCol++){
90882       pCol = &pTab->aCol[iCol];
90883       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
90884         break;
90885       }
90886     }
90887     if( iCol==pTab->nCol ){
90888       pTab = 0;
90889       goto error_out;
90890     }
90891   }
90892
90893   /* The following block stores the meta information that will be returned
90894   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
90895   ** and autoinc. At this point there are two possibilities:
90896   ** 
90897   **     1. The specified column name was rowid", "oid" or "_rowid_" 
90898   **        and there is no explicitly declared IPK column. 
90899   **
90900   **     2. The table is not a view and the column name identified an 
90901   **        explicitly declared column. Copy meta information from *pCol.
90902   */ 
90903   if( pCol ){
90904     zDataType = pCol->zType;
90905     zCollSeq = pCol->zColl;
90906     notnull = pCol->notNull!=0;
90907     primarykey  = pCol->isPrimKey!=0;
90908     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
90909   }else{
90910     zDataType = "INTEGER";
90911     primarykey = 1;
90912   }
90913   if( !zCollSeq ){
90914     zCollSeq = "BINARY";
90915   }
90916
90917 error_out:
90918   (void)sqlite3SafetyOff(db);
90919
90920   /* Whether the function call succeeded or failed, set the output parameters
90921   ** to whatever their local counterparts contain. If an error did occur,
90922   ** this has the effect of zeroing all output parameters.
90923   */
90924   if( pzDataType ) *pzDataType = zDataType;
90925   if( pzCollSeq ) *pzCollSeq = zCollSeq;
90926   if( pNotNull ) *pNotNull = notnull;
90927   if( pPrimaryKey ) *pPrimaryKey = primarykey;
90928   if( pAutoinc ) *pAutoinc = autoinc;
90929
90930   if( SQLITE_OK==rc && !pTab ){
90931     sqlite3DbFree(db, zErrMsg);
90932     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
90933         zColumnName);
90934     rc = SQLITE_ERROR;
90935   }
90936   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
90937   sqlite3DbFree(db, zErrMsg);
90938   rc = sqlite3ApiExit(db, rc);
90939   sqlite3_mutex_leave(db->mutex);
90940   return rc;
90941 }
90942 #endif
90943
90944 /*
90945 ** Sleep for a little while.  Return the amount of time slept.
90946 */
90947 SQLITE_API int sqlite3_sleep(int ms){
90948   sqlite3_vfs *pVfs;
90949   int rc;
90950   pVfs = sqlite3_vfs_find(0);
90951   if( pVfs==0 ) return 0;
90952
90953   /* This function works in milliseconds, but the underlying OsSleep() 
90954   ** API uses microseconds. Hence the 1000's.
90955   */
90956   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
90957   return rc;
90958 }
90959
90960 /*
90961 ** Enable or disable the extended result codes.
90962 */
90963 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
90964   sqlite3_mutex_enter(db->mutex);
90965   db->errMask = onoff ? 0xffffffff : 0xff;
90966   sqlite3_mutex_leave(db->mutex);
90967   return SQLITE_OK;
90968 }
90969
90970 /*
90971 ** Invoke the xFileControl method on a particular database.
90972 */
90973 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
90974   int rc = SQLITE_ERROR;
90975   int iDb;
90976   sqlite3_mutex_enter(db->mutex);
90977   if( zDbName==0 ){
90978     iDb = 0;
90979   }else{
90980     for(iDb=0; iDb<db->nDb; iDb++){
90981       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
90982     }
90983   }
90984   if( iDb<db->nDb ){
90985     Btree *pBtree = db->aDb[iDb].pBt;
90986     if( pBtree ){
90987       Pager *pPager;
90988       sqlite3_file *fd;
90989       sqlite3BtreeEnter(pBtree);
90990       pPager = sqlite3BtreePager(pBtree);
90991       assert( pPager!=0 );
90992       fd = sqlite3PagerFile(pPager);
90993       assert( fd!=0 );
90994       if( fd->pMethods ){
90995         rc = sqlite3OsFileControl(fd, op, pArg);
90996       }
90997       sqlite3BtreeLeave(pBtree);
90998     }
90999   }
91000   sqlite3_mutex_leave(db->mutex);
91001   return rc;   
91002 }
91003
91004 /*
91005 ** Interface to the testing logic.
91006 */
91007 SQLITE_API int sqlite3_test_control(int op, ...){
91008   int rc = 0;
91009 #ifndef SQLITE_OMIT_BUILTIN_TEST
91010   va_list ap;
91011   va_start(ap, op);
91012   switch( op ){
91013
91014     /*
91015     ** Save the current state of the PRNG.
91016     */
91017     case SQLITE_TESTCTRL_PRNG_SAVE: {
91018       sqlite3PrngSaveState();
91019       break;
91020     }
91021
91022     /*
91023     ** Restore the state of the PRNG to the last state saved using
91024     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
91025     ** this verb acts like PRNG_RESET.
91026     */
91027     case SQLITE_TESTCTRL_PRNG_RESTORE: {
91028       sqlite3PrngRestoreState();
91029       break;
91030     }
91031
91032     /*
91033     ** Reset the PRNG back to its uninitialized state.  The next call
91034     ** to sqlite3_randomness() will reseed the PRNG using a single call
91035     ** to the xRandomness method of the default VFS.
91036     */
91037     case SQLITE_TESTCTRL_PRNG_RESET: {
91038       sqlite3PrngResetState();
91039       break;
91040     }
91041
91042     /*
91043     **  sqlite3_test_control(BITVEC_TEST, size, program)
91044     **
91045     ** Run a test against a Bitvec object of size.  The program argument
91046     ** is an array of integers that defines the test.  Return -1 on a
91047     ** memory allocation error, 0 on success, or non-zero for an error.
91048     ** See the sqlite3BitvecBuiltinTest() for additional information.
91049     */
91050     case SQLITE_TESTCTRL_BITVEC_TEST: {
91051       int sz = va_arg(ap, int);
91052       int *aProg = va_arg(ap, int*);
91053       rc = sqlite3BitvecBuiltinTest(sz, aProg);
91054       break;
91055     }
91056
91057     /*
91058     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
91059     **
91060     ** Register hooks to call to indicate which malloc() failures 
91061     ** are benign.
91062     */
91063     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
91064       typedef void (*void_function)(void);
91065       void_function xBenignBegin;
91066       void_function xBenignEnd;
91067       xBenignBegin = va_arg(ap, void_function);
91068       xBenignEnd = va_arg(ap, void_function);
91069       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
91070       break;
91071     }
91072
91073     /*
91074     **  sqlite3_test_control(PENDING_BYTE, unsigned int X)
91075     **
91076     ** Set the PENDING byte to the value in the argument, if X>0.
91077     ** Make no changes if X==0.  Return the value of the pending byte
91078     ** as it existing before this routine was called.
91079     **
91080     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
91081     ** an incompatible database file format.  Changing the PENDING byte
91082     ** while any database connection is open results in undefined and
91083     ** dileterious behavior.
91084     */
91085     case SQLITE_TESTCTRL_PENDING_BYTE: {
91086       unsigned int newVal = va_arg(ap, unsigned int);
91087       rc = sqlite3PendingByte;
91088       if( newVal ) sqlite3PendingByte = newVal;
91089       break;
91090     }
91091   }
91092   va_end(ap);
91093 #endif /* SQLITE_OMIT_BUILTIN_TEST */
91094   return rc;
91095 }
91096
91097 /************** End of main.c ************************************************/
91098 /************** Begin file fts3.c ********************************************/
91099 /*
91100 ** 2006 Oct 10
91101 **
91102 ** The author disclaims copyright to this source code.  In place of
91103 ** a legal notice, here is a blessing:
91104 **
91105 **    May you do good and not evil.
91106 **    May you find forgiveness for yourself and forgive others.
91107 **    May you share freely, never taking more than you give.
91108 **
91109 ******************************************************************************
91110 **
91111 ** This is an SQLite module implementing full-text search.
91112 */
91113
91114 /*
91115 ** The code in this file is only compiled if:
91116 **
91117 **     * The FTS3 module is being built as an extension
91118 **       (in which case SQLITE_CORE is not defined), or
91119 **
91120 **     * The FTS3 module is being built into the core of
91121 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
91122 */
91123
91124 /* TODO(shess) Consider exporting this comment to an HTML file or the
91125 ** wiki.
91126 */
91127 /* The full-text index is stored in a series of b+tree (-like)
91128 ** structures called segments which map terms to doclists.  The
91129 ** structures are like b+trees in layout, but are constructed from the
91130 ** bottom up in optimal fashion and are not updatable.  Since trees
91131 ** are built from the bottom up, things will be described from the
91132 ** bottom up.
91133 **
91134 **
91135 **** Varints ****
91136 ** The basic unit of encoding is a variable-length integer called a
91137 ** varint.  We encode variable-length integers in little-endian order
91138 ** using seven bits * per byte as follows:
91139 **
91140 ** KEY:
91141 **         A = 0xxxxxxx    7 bits of data and one flag bit
91142 **         B = 1xxxxxxx    7 bits of data and one flag bit
91143 **
91144 **  7 bits - A
91145 ** 14 bits - BA
91146 ** 21 bits - BBA
91147 ** and so on.
91148 **
91149 ** This is identical to how sqlite encodes varints (see util.c).
91150 **
91151 **
91152 **** Document lists ****
91153 ** A doclist (document list) holds a docid-sorted list of hits for a
91154 ** given term.  Doclists hold docids, and can optionally associate
91155 ** token positions and offsets with docids.
91156 **
91157 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
91158 **
91159 ** array {
91160 **   varint docid;
91161 **   array {                (position list for column 0)
91162 **     varint position;     (delta from previous position plus POS_BASE)
91163 **     varint startOffset;  (delta from previous startOffset)
91164 **     varint endOffset;    (delta from startOffset)
91165 **   }
91166 **   array {
91167 **     varint POS_COLUMN;   (marks start of position list for new column)
91168 **     varint column;       (index of new column)
91169 **     array {
91170 **       varint position;   (delta from previous position plus POS_BASE)
91171 **       varint startOffset;(delta from previous startOffset)
91172 **       varint endOffset;  (delta from startOffset)
91173 **     }
91174 **   }
91175 **   varint POS_END;        (marks end of positions for this document.
91176 ** }
91177 **
91178 ** Here, array { X } means zero or more occurrences of X, adjacent in
91179 ** memory.  A "position" is an index of a token in the token stream
91180 ** generated by the tokenizer, while an "offset" is a byte offset,
91181 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
91182 ** same logical place as the position element, and act as sentinals
91183 ** ending a position list array.
91184 **
91185 ** A DL_POSITIONS doclist omits the startOffset and endOffset
91186 ** information.  A DL_DOCIDS doclist omits both the position and
91187 ** offset information, becoming an array of varint-encoded docids.
91188 **
91189 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
91190 ** the type.  Due to how deletion is implemented in the segmentation
91191 ** system, on-disk doclists MUST store at least positions.
91192 **
91193 **
91194 **** Segment leaf nodes ****
91195 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
91196 ** nodes are written using LeafWriter, and read using LeafReader (to
91197 ** iterate through a single leaf node's data) and LeavesReader (to
91198 ** iterate through a segment's entire leaf layer).  Leaf nodes have
91199 ** the format:
91200 **
91201 ** varint iHeight;             (height from leaf level, always 0)
91202 ** varint nTerm;               (length of first term)
91203 ** char pTerm[nTerm];          (content of first term)
91204 ** varint nDoclist;            (length of term's associated doclist)
91205 ** char pDoclist[nDoclist];    (content of doclist)
91206 ** array {
91207 **                             (further terms are delta-encoded)
91208 **   varint nPrefix;           (length of prefix shared with previous term)
91209 **   varint nSuffix;           (length of unshared suffix)
91210 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
91211 **   varint nDoclist;          (length of term's associated doclist)
91212 **   char pDoclist[nDoclist];  (content of doclist)
91213 ** }
91214 **
91215 ** Here, array { X } means zero or more occurrences of X, adjacent in
91216 ** memory.
91217 **
91218 ** Leaf nodes are broken into blocks which are stored contiguously in
91219 ** the %_segments table in sorted order.  This means that when the end
91220 ** of a node is reached, the next term is in the node with the next
91221 ** greater node id.
91222 **
91223 ** New data is spilled to a new leaf node when the current node
91224 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
91225 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
91226 ** node (a leaf node with a single term and doclist).  The goal of
91227 ** these settings is to pack together groups of small doclists while
91228 ** making it efficient to directly access large doclists.  The
91229 ** assumption is that large doclists represent terms which are more
91230 ** likely to be query targets.
91231 **
91232 ** TODO(shess) It may be useful for blocking decisions to be more
91233 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
91234 ** node rather than splitting into 2k and .5k nodes.  My intuition is
91235 ** that this might extend through 2x or 4x the pagesize.
91236 **
91237 **
91238 **** Segment interior nodes ****
91239 ** Segment interior nodes store blockids for subtree nodes and terms
91240 ** to describe what data is stored by the each subtree.  Interior
91241 ** nodes are written using InteriorWriter, and read using
91242 ** InteriorReader.  InteriorWriters are created as needed when
91243 ** SegmentWriter creates new leaf nodes, or when an interior node
91244 ** itself grows too big and must be split.  The format of interior
91245 ** nodes:
91246 **
91247 ** varint iHeight;           (height from leaf level, always >0)
91248 ** varint iBlockid;          (block id of node's leftmost subtree)
91249 ** optional {
91250 **   varint nTerm;           (length of first term)
91251 **   char pTerm[nTerm];      (content of first term)
91252 **   array {
91253 **                                (further terms are delta-encoded)
91254 **     varint nPrefix;            (length of shared prefix with previous term)
91255 **     varint nSuffix;            (length of unshared suffix)
91256 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
91257 **   }
91258 ** }
91259 **
91260 ** Here, optional { X } means an optional element, while array { X }
91261 ** means zero or more occurrences of X, adjacent in memory.
91262 **
91263 ** An interior node encodes n terms separating n+1 subtrees.  The
91264 ** subtree blocks are contiguous, so only the first subtree's blockid
91265 ** is encoded.  The subtree at iBlockid will contain all terms less
91266 ** than the first term encoded (or all terms if no term is encoded).
91267 ** Otherwise, for terms greater than or equal to pTerm[i] but less
91268 ** than pTerm[i+1], the subtree for that term will be rooted at
91269 ** iBlockid+i.  Interior nodes only store enough term data to
91270 ** distinguish adjacent children (if the rightmost term of the left
91271 ** child is "something", and the leftmost term of the right child is
91272 ** "wicked", only "w" is stored).
91273 **
91274 ** New data is spilled to a new interior node at the same height when
91275 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
91276 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
91277 ** interior nodes and making the tree too skinny.  The interior nodes
91278 ** at a given height are naturally tracked by interior nodes at
91279 ** height+1, and so on.
91280 **
91281 **
91282 **** Segment directory ****
91283 ** The segment directory in table %_segdir stores meta-information for
91284 ** merging and deleting segments, and also the root node of the
91285 ** segment's tree.
91286 **
91287 ** The root node is the top node of the segment's tree after encoding
91288 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
91289 ** This could be either a leaf node or an interior node.  If the top
91290 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
91291 ** and a new root interior node is generated (which should always fit
91292 ** within ROOT_MAX because it only needs space for 2 varints, the
91293 ** height and the blockid of the previous root).
91294 **
91295 ** The meta-information in the segment directory is:
91296 **   level               - segment level (see below)
91297 **   idx                 - index within level
91298 **                       - (level,idx uniquely identify a segment)
91299 **   start_block         - first leaf node
91300 **   leaves_end_block    - last leaf node
91301 **   end_block           - last block (including interior nodes)
91302 **   root                - contents of root node
91303 **
91304 ** If the root node is a leaf node, then start_block,
91305 ** leaves_end_block, and end_block are all 0.
91306 **
91307 **
91308 **** Segment merging ****
91309 ** To amortize update costs, segments are grouped into levels and
91310 ** merged in batches.  Each increase in level represents exponentially
91311 ** more documents.
91312 **
91313 ** New documents (actually, document updates) are tokenized and
91314 ** written individually (using LeafWriter) to a level 0 segment, with
91315 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
91316 ** level 0 segments are merged into a single level 1 segment.  Level 1
91317 ** is populated like level 0, and eventually MERGE_COUNT level 1
91318 ** segments are merged to a single level 2 segment (representing
91319 ** MERGE_COUNT^2 updates), and so on.
91320 **
91321 ** A segment merge traverses all segments at a given level in
91322 ** parallel, performing a straightforward sorted merge.  Since segment
91323 ** leaf nodes are written in to the %_segments table in order, this
91324 ** merge traverses the underlying sqlite disk structures efficiently.
91325 ** After the merge, all segment blocks from the merged level are
91326 ** deleted.
91327 **
91328 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
91329 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
91330 ** very similar performance numbers to 16 on insertion, though they're
91331 ** a tiny bit slower (perhaps due to more overhead in merge-time
91332 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
91333 ** 16, 2 about 66% slower than 16.
91334 **
91335 ** At query time, high MERGE_COUNT increases the number of segments
91336 ** which need to be scanned and merged.  For instance, with 100k docs
91337 ** inserted:
91338 **
91339 **    MERGE_COUNT   segments
91340 **       16           25
91341 **        8           12
91342 **        4           10
91343 **        2            6
91344 **
91345 ** This appears to have only a moderate impact on queries for very
91346 ** frequent terms (which are somewhat dominated by segment merge
91347 ** costs), and infrequent and non-existent terms still seem to be fast
91348 ** even with many segments.
91349 **
91350 ** TODO(shess) That said, it would be nice to have a better query-side
91351 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
91352 ** optimizations to things like doclist merging will swing the sweet
91353 ** spot around.
91354 **
91355 **
91356 **
91357 **** Handling of deletions and updates ****
91358 ** Since we're using a segmented structure, with no docid-oriented
91359 ** index into the term index, we clearly cannot simply update the term
91360 ** index when a document is deleted or updated.  For deletions, we
91361 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
91362 ** we simply write the new doclist.  Segment merges overwrite older
91363 ** data for a particular docid with newer data, so deletes or updates
91364 ** will eventually overtake the earlier data and knock it out.  The
91365 ** query logic likewise merges doclists so that newer data knocks out
91366 ** older data.
91367 **
91368 ** TODO(shess) Provide a VACUUM type operation to clear out all
91369 ** deletions and duplications.  This would basically be a forced merge
91370 ** into a single segment.
91371 */
91372
91373 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
91374
91375 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
91376 # define SQLITE_CORE 1
91377 #endif
91378
91379
91380 /************** Include fts3_expr.h in the middle of fts3.c ******************/
91381 /************** Begin file fts3_expr.h ***************************************/
91382 /*
91383 ** 2008 Nov 28
91384 **
91385 ** The author disclaims copyright to this source code.  In place of
91386 ** a legal notice, here is a blessing:
91387 **
91388 **    May you do good and not evil.
91389 **    May you find forgiveness for yourself and forgive others.
91390 **    May you share freely, never taking more than you give.
91391 **
91392 ******************************************************************************
91393 **
91394 */
91395
91396 /************** Include fts3_tokenizer.h in the middle of fts3_expr.h ********/
91397 /************** Begin file fts3_tokenizer.h **********************************/
91398 /*
91399 ** 2006 July 10
91400 **
91401 ** The author disclaims copyright to this source code.
91402 **
91403 *************************************************************************
91404 ** Defines the interface to tokenizers used by fulltext-search.  There
91405 ** are three basic components:
91406 **
91407 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
91408 ** interface functions.  This is essentially the class structure for
91409 ** tokenizers.
91410 **
91411 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
91412 ** including customization information defined at creation time.
91413 **
91414 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
91415 ** tokens from a particular input.
91416 */
91417 #ifndef _FTS3_TOKENIZER_H_
91418 #define _FTS3_TOKENIZER_H_
91419
91420 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
91421 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
91422 ** we will need a way to register the API consistently.
91423 */
91424
91425 /*
91426 ** Structures used by the tokenizer interface. When a new tokenizer
91427 ** implementation is registered, the caller provides a pointer to
91428 ** an sqlite3_tokenizer_module containing pointers to the callback
91429 ** functions that make up an implementation.
91430 **
91431 ** When an fts3 table is created, it passes any arguments passed to
91432 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
91433 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
91434 ** implementation. The xCreate() function in turn returns an 
91435 ** sqlite3_tokenizer structure representing the specific tokenizer to
91436 ** be used for the fts3 table (customized by the tokenizer clause arguments).
91437 **
91438 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
91439 ** method is called. It returns an sqlite3_tokenizer_cursor object
91440 ** that may be used to tokenize a specific input buffer based on
91441 ** the tokenization rules supplied by a specific sqlite3_tokenizer
91442 ** object.
91443 */
91444 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
91445 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
91446 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
91447
91448 struct sqlite3_tokenizer_module {
91449
91450   /*
91451   ** Structure version. Should always be set to 0.
91452   */
91453   int iVersion;
91454
91455   /*
91456   ** Create a new tokenizer. The values in the argv[] array are the
91457   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
91458   ** TABLE statement that created the fts3 table. For example, if
91459   ** the following SQL is executed:
91460   **
91461   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
91462   **
91463   ** then argc is set to 2, and the argv[] array contains pointers
91464   ** to the strings "arg1" and "arg2".
91465   **
91466   ** This method should return either SQLITE_OK (0), or an SQLite error 
91467   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
91468   ** to point at the newly created tokenizer structure. The generic
91469   ** sqlite3_tokenizer.pModule variable should not be initialised by
91470   ** this callback. The caller will do so.
91471   */
91472   int (*xCreate)(
91473     int argc,                           /* Size of argv array */
91474     const char *const*argv,             /* Tokenizer argument strings */
91475     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
91476   );
91477
91478   /*
91479   ** Destroy an existing tokenizer. The fts3 module calls this method
91480   ** exactly once for each successful call to xCreate().
91481   */
91482   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
91483
91484   /*
91485   ** Create a tokenizer cursor to tokenize an input buffer. The caller
91486   ** is responsible for ensuring that the input buffer remains valid
91487   ** until the cursor is closed (using the xClose() method). 
91488   */
91489   int (*xOpen)(
91490     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
91491     const char *pInput, int nBytes,      /* Input buffer */
91492     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
91493   );
91494
91495   /*
91496   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
91497   ** method exactly once for each successful call to xOpen().
91498   */
91499   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
91500
91501   /*
91502   ** Retrieve the next token from the tokenizer cursor pCursor. This
91503   ** method should either return SQLITE_OK and set the values of the
91504   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
91505   ** the end of the buffer has been reached, or an SQLite error code.
91506   **
91507   ** *ppToken should be set to point at a buffer containing the 
91508   ** normalized version of the token (i.e. after any case-folding and/or
91509   ** stemming has been performed). *pnBytes should be set to the length
91510   ** of this buffer in bytes. The input text that generated the token is
91511   ** identified by the byte offsets returned in *piStartOffset and
91512   ** *piEndOffset. *piStartOffset should be set to the index of the first
91513   ** byte of the token in the input buffer. *piEndOffset should be set
91514   ** to the index of the first byte just past the end of the token in
91515   ** the input buffer.
91516   **
91517   ** The buffer *ppToken is set to point at is managed by the tokenizer
91518   ** implementation. It is only required to be valid until the next call
91519   ** to xNext() or xClose(). 
91520   */
91521   /* TODO(shess) current implementation requires pInput to be
91522   ** nul-terminated.  This should either be fixed, or pInput/nBytes
91523   ** should be converted to zInput.
91524   */
91525   int (*xNext)(
91526     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
91527     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
91528     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
91529     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
91530     int *piPosition      /* OUT: Number of tokens returned before this one */
91531   );
91532 };
91533
91534 struct sqlite3_tokenizer {
91535   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
91536   /* Tokenizer implementations will typically add additional fields */
91537 };
91538
91539 struct sqlite3_tokenizer_cursor {
91540   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
91541   /* Tokenizer implementations will typically add additional fields */
91542 };
91543
91544 #endif /* _FTS3_TOKENIZER_H_ */
91545
91546 /************** End of fts3_tokenizer.h **************************************/
91547 /************** Continuing where we left off in fts3_expr.h ******************/
91548
91549 /*
91550 ** The following describes the syntax supported by the fts3 MATCH
91551 ** operator in a similar format to that used by the lemon parser
91552 ** generator. This module does not use actually lemon, it uses a
91553 ** custom parser.
91554 **
91555 **   query ::= andexpr (OR andexpr)*.
91556 **
91557 **   andexpr ::= notexpr (AND? notexpr)*.
91558 **
91559 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
91560 **   notexpr ::= LP query RP.
91561 **
91562 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
91563 **
91564 **   distance_opt ::= .
91565 **   distance_opt ::= / INTEGER.
91566 **
91567 **   phrase ::= TOKEN.
91568 **   phrase ::= COLUMN:TOKEN.
91569 **   phrase ::= "TOKEN TOKEN TOKEN...".
91570 */
91571
91572 typedef struct Fts3Expr Fts3Expr;
91573 typedef struct Fts3Phrase Fts3Phrase;
91574
91575 /*
91576 ** A "phrase" is a sequence of one or more tokens that must match in
91577 ** sequence.  A single token is the base case and the most common case.
91578 ** For a sequence of tokens contained in "...", nToken will be the number
91579 ** of tokens in the string.
91580 */
91581 struct Fts3Phrase {
91582   int nToken;          /* Number of tokens in the phrase */
91583   int iColumn;         /* Index of column this phrase must match */
91584   int isNot;           /* Phrase prefixed by unary not (-) operator */
91585   struct PhraseToken {
91586     char *z;              /* Text of the token */
91587     int n;                /* Number of bytes in buffer pointed to by z */
91588     int isPrefix;         /* True if token ends in with a "*" character */
91589   } aToken[1];         /* One entry for each token in the phrase */
91590 };
91591
91592 /*
91593 ** A tree of these objects forms the RHS of a MATCH operator.
91594 */
91595 struct Fts3Expr {
91596   int eType;                 /* One of the FTSQUERY_XXX values defined below */
91597   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
91598   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
91599   Fts3Expr *pLeft;           /* Left operand */
91600   Fts3Expr *pRight;          /* Right operand */
91601   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
91602 };
91603
91604 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, char **, int, int, 
91605                          const char *, int, Fts3Expr **);
91606 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
91607
91608 /*
91609 ** Candidate values for Fts3Query.eType. Note that the order of the first
91610 ** four values is in order of precedence when parsing expressions. For 
91611 ** example, the following:
91612 **
91613 **   "a OR b AND c NOT d NEAR e"
91614 **
91615 ** is equivalent to:
91616 **
91617 **   "a OR (b AND (c NOT (d NEAR e)))"
91618 */
91619 #define FTSQUERY_NEAR   1
91620 #define FTSQUERY_NOT    2
91621 #define FTSQUERY_AND    3
91622 #define FTSQUERY_OR     4
91623 #define FTSQUERY_PHRASE 5
91624
91625 #ifdef SQLITE_TEST
91626 SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
91627 #endif
91628
91629 /************** End of fts3_expr.h *******************************************/
91630 /************** Continuing where we left off in fts3.c ***********************/
91631 /************** Include fts3_hash.h in the middle of fts3.c ******************/
91632 /************** Begin file fts3_hash.h ***************************************/
91633 /*
91634 ** 2001 September 22
91635 **
91636 ** The author disclaims copyright to this source code.  In place of
91637 ** a legal notice, here is a blessing:
91638 **
91639 **    May you do good and not evil.
91640 **    May you find forgiveness for yourself and forgive others.
91641 **    May you share freely, never taking more than you give.
91642 **
91643 *************************************************************************
91644 ** This is the header file for the generic hash-table implemenation
91645 ** used in SQLite.  We've modified it slightly to serve as a standalone
91646 ** hash table implementation for the full-text indexing module.
91647 **
91648 */
91649 #ifndef _FTS3_HASH_H_
91650 #define _FTS3_HASH_H_
91651
91652 /* Forward declarations of structures. */
91653 typedef struct fts3Hash fts3Hash;
91654 typedef struct fts3HashElem fts3HashElem;
91655
91656 /* A complete hash table is an instance of the following structure.
91657 ** The internals of this structure are intended to be opaque -- client
91658 ** code should not attempt to access or modify the fields of this structure
91659 ** directly.  Change this structure only by using the routines below.
91660 ** However, many of the "procedures" and "functions" for modifying and
91661 ** accessing this structure are really macros, so we can't really make
91662 ** this structure opaque.
91663 */
91664 struct fts3Hash {
91665   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
91666   char copyKey;           /* True if copy of key made on insert */
91667   int count;              /* Number of entries in this table */
91668   fts3HashElem *first;    /* The first element of the array */
91669   int htsize;             /* Number of buckets in the hash table */
91670   struct _fts3ht {        /* the hash table */
91671     int count;               /* Number of entries with this hash */
91672     fts3HashElem *chain;     /* Pointer to first entry with this hash */
91673   } *ht;
91674 };
91675
91676 /* Each element in the hash table is an instance of the following 
91677 ** structure.  All elements are stored on a single doubly-linked list.
91678 **
91679 ** Again, this structure is intended to be opaque, but it can't really
91680 ** be opaque because it is used by macros.
91681 */
91682 struct fts3HashElem {
91683   fts3HashElem *next, *prev; /* Next and previous elements in the table */
91684   void *data;                /* Data associated with this element */
91685   void *pKey; int nKey;      /* Key associated with this element */
91686 };
91687
91688 /*
91689 ** There are 2 different modes of operation for a hash table:
91690 **
91691 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
91692 **                           (including the null-terminator, if any).  Case
91693 **                           is respected in comparisons.
91694 **
91695 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
91696 **                           memcmp() is used to compare keys.
91697 **
91698 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
91699 */
91700 #define FTS3_HASH_STRING    1
91701 #define FTS3_HASH_BINARY    2
91702
91703 /*
91704 ** Access routines.  To delete, insert a NULL pointer.
91705 */
91706 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey);
91707 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData);
91708 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey);
91709 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*);
91710
91711 /*
91712 ** Shorthand for the functions above
91713 */
91714 #define fts3HashInit   sqlite3Fts3HashInit
91715 #define fts3HashInsert sqlite3Fts3HashInsert
91716 #define fts3HashFind   sqlite3Fts3HashFind
91717 #define fts3HashClear  sqlite3Fts3HashClear
91718
91719 /*
91720 ** Macros for looping over all elements of a hash table.  The idiom is
91721 ** like this:
91722 **
91723 **   fts3Hash h;
91724 **   fts3HashElem *p;
91725 **   ...
91726 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
91727 **     SomeStructure *pData = fts3HashData(p);
91728 **     // do something with pData
91729 **   }
91730 */
91731 #define fts3HashFirst(H)  ((H)->first)
91732 #define fts3HashNext(E)   ((E)->next)
91733 #define fts3HashData(E)   ((E)->data)
91734 #define fts3HashKey(E)    ((E)->pKey)
91735 #define fts3HashKeysize(E) ((E)->nKey)
91736
91737 /*
91738 ** Number of entries in a hash table
91739 */
91740 #define fts3HashCount(H)  ((H)->count)
91741
91742 #endif /* _FTS3_HASH_H_ */
91743
91744 /************** End of fts3_hash.h *******************************************/
91745 /************** Continuing where we left off in fts3.c ***********************/
91746 #ifndef SQLITE_CORE 
91747   SQLITE_EXTENSION_INIT1
91748 #endif
91749
91750
91751 /* TODO(shess) MAN, this thing needs some refactoring.  At minimum, it
91752 ** would be nice to order the file better, perhaps something along the
91753 ** lines of:
91754 **
91755 **  - utility functions
91756 **  - table setup functions
91757 **  - table update functions
91758 **  - table query functions
91759 **
91760 ** Put the query functions last because they're likely to reference
91761 ** typedefs or functions from the table update section.
91762 */
91763
91764 #if 0
91765 # define FTSTRACE(A)  printf A; fflush(stdout)
91766 #else
91767 # define FTSTRACE(A)
91768 #endif
91769
91770 /* It is not safe to call isspace(), tolower(), or isalnum() on
91771 ** hi-bit-set characters.  This is the same solution used in the
91772 ** tokenizer.
91773 */
91774 /* TODO(shess) The snippet-generation code should be using the
91775 ** tokenizer-generated tokens rather than doing its own local
91776 ** tokenization.
91777 */
91778 /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
91779 static int safe_isspace(char c){
91780   return (c&0x80)==0 ? isspace(c) : 0;
91781 }
91782 static int safe_tolower(char c){
91783   return (c&0x80)==0 ? tolower(c) : c;
91784 }
91785 static int safe_isalnum(char c){
91786   return (c&0x80)==0 ? isalnum(c) : 0;
91787 }
91788
91789 typedef enum DocListType {
91790   DL_DOCIDS,              /* docids only */
91791   DL_POSITIONS,           /* docids + positions */
91792   DL_POSITIONS_OFFSETS    /* docids + positions + offsets */
91793 } DocListType;
91794
91795 /*
91796 ** By default, only positions and not offsets are stored in the doclists.
91797 ** To change this so that offsets are stored too, compile with
91798 **
91799 **          -DDL_DEFAULT=DL_POSITIONS_OFFSETS
91800 **
91801 ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
91802 ** into (no deletes or updates).
91803 */
91804 #ifndef DL_DEFAULT
91805 # define DL_DEFAULT DL_POSITIONS
91806 #endif
91807
91808 enum {
91809   POS_END = 0,        /* end of this position list */
91810   POS_COLUMN,         /* followed by new column number */
91811   POS_BASE
91812 };
91813
91814 /* MERGE_COUNT controls how often we merge segments (see comment at
91815 ** top of file).
91816 */
91817 #define MERGE_COUNT 16
91818
91819 /* utility functions */
91820
91821 /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
91822 ** record to prevent errors of the form:
91823 **
91824 ** my_function(SomeType *b){
91825 **   memset(b, '\0', sizeof(b));  // sizeof(b)!=sizeof(*b)
91826 ** }
91827 */
91828 /* TODO(shess) Obvious candidates for a header file. */
91829 #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
91830
91831 #ifndef NDEBUG
91832 #  define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
91833 #else
91834 #  define SCRAMBLE(b)
91835 #endif
91836
91837 /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
91838 #define VARINT_MAX 10
91839
91840 /* Write a 64-bit variable-length integer to memory starting at p[0].
91841  * The length of data written will be between 1 and VARINT_MAX bytes.
91842  * The number of bytes written is returned. */
91843 static int fts3PutVarint(char *p, sqlite_int64 v){
91844   unsigned char *q = (unsigned char *) p;
91845   sqlite_uint64 vu = v;
91846   do{
91847     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
91848     vu >>= 7;
91849   }while( vu!=0 );
91850   q[-1] &= 0x7f;  /* turn off high bit in final byte */
91851   assert( q - (unsigned char *)p <= VARINT_MAX );
91852   return (int) (q - (unsigned char *)p);
91853 }
91854
91855 /* Read a 64-bit variable-length integer from memory starting at p[0].
91856  * Return the number of bytes read, or 0 on error.
91857  * The value is stored in *v. */
91858 static int fts3GetVarint(const char *p, sqlite_int64 *v){
91859   const unsigned char *q = (const unsigned char *) p;
91860   sqlite_uint64 x = 0, y = 1;
91861   while( (*q & 0x80) == 0x80 ){
91862     x += y * (*q++ & 0x7f);
91863     y <<= 7;
91864     if( q - (unsigned char *)p >= VARINT_MAX ){  /* bad data */
91865       assert( 0 );
91866       return 0;
91867     }
91868   }
91869   x += y * (*q++);
91870   *v = (sqlite_int64) x;
91871   return (int) (q - (unsigned char *)p);
91872 }
91873
91874 static int fts3GetVarint32(const char *p, int *pi){
91875  sqlite_int64 i;
91876  int ret = fts3GetVarint(p, &i);
91877  *pi = (int) i;
91878  assert( *pi==i );
91879  return ret;
91880 }
91881
91882 /*******************************************************************/
91883 /* DataBuffer is used to collect data into a buffer in piecemeal
91884 ** fashion.  It implements the usual distinction between amount of
91885 ** data currently stored (nData) and buffer capacity (nCapacity).
91886 **
91887 ** dataBufferInit - create a buffer with given initial capacity.
91888 ** dataBufferReset - forget buffer's data, retaining capacity.
91889 ** dataBufferDestroy - free buffer's data.
91890 ** dataBufferSwap - swap contents of two buffers.
91891 ** dataBufferExpand - expand capacity without adding data.
91892 ** dataBufferAppend - append data.
91893 ** dataBufferAppend2 - append two pieces of data at once.
91894 ** dataBufferReplace - replace buffer's data.
91895 */
91896 typedef struct DataBuffer {
91897   char *pData;          /* Pointer to malloc'ed buffer. */
91898   int nCapacity;        /* Size of pData buffer. */
91899   int nData;            /* End of data loaded into pData. */
91900 } DataBuffer;
91901
91902 static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
91903   assert( nCapacity>=0 );
91904   pBuffer->nData = 0;
91905   pBuffer->nCapacity = nCapacity;
91906   pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
91907 }
91908 static void dataBufferReset(DataBuffer *pBuffer){
91909   pBuffer->nData = 0;
91910 }
91911 static void dataBufferDestroy(DataBuffer *pBuffer){
91912   if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
91913   SCRAMBLE(pBuffer);
91914 }
91915 static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
91916   DataBuffer tmp = *pBuffer1;
91917   *pBuffer1 = *pBuffer2;
91918   *pBuffer2 = tmp;
91919 }
91920 static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
91921   assert( nAddCapacity>0 );
91922   /* TODO(shess) Consider expanding more aggressively.  Note that the
91923   ** underlying malloc implementation may take care of such things for
91924   ** us already.
91925   */
91926   if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
91927     pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
91928     pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
91929   }
91930 }
91931 static void dataBufferAppend(DataBuffer *pBuffer,
91932                              const char *pSource, int nSource){
91933   assert( nSource>0 && pSource!=NULL );
91934   dataBufferExpand(pBuffer, nSource);
91935   memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
91936   pBuffer->nData += nSource;
91937 }
91938 static void dataBufferAppend2(DataBuffer *pBuffer,
91939                               const char *pSource1, int nSource1,
91940                               const char *pSource2, int nSource2){
91941   assert( nSource1>0 && pSource1!=NULL );
91942   assert( nSource2>0 && pSource2!=NULL );
91943   dataBufferExpand(pBuffer, nSource1+nSource2);
91944   memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
91945   memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
91946   pBuffer->nData += nSource1+nSource2;
91947 }
91948 static void dataBufferReplace(DataBuffer *pBuffer,
91949                               const char *pSource, int nSource){
91950   dataBufferReset(pBuffer);
91951   dataBufferAppend(pBuffer, pSource, nSource);
91952 }
91953
91954 /* StringBuffer is a null-terminated version of DataBuffer. */
91955 typedef struct StringBuffer {
91956   DataBuffer b;            /* Includes null terminator. */
91957 } StringBuffer;
91958
91959 static void initStringBuffer(StringBuffer *sb){
91960   dataBufferInit(&sb->b, 100);
91961   dataBufferReplace(&sb->b, "", 1);
91962 }
91963 static int stringBufferLength(StringBuffer *sb){
91964   return sb->b.nData-1;
91965 }
91966 static char *stringBufferData(StringBuffer *sb){
91967   return sb->b.pData;
91968 }
91969 static void stringBufferDestroy(StringBuffer *sb){
91970   dataBufferDestroy(&sb->b);
91971 }
91972
91973 static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
91974   assert( sb->b.nData>0 );
91975   if( nFrom>0 ){
91976     sb->b.nData--;
91977     dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
91978   }
91979 }
91980 static void append(StringBuffer *sb, const char *zFrom){
91981   nappend(sb, zFrom, strlen(zFrom));
91982 }
91983
91984 /* Append a list of strings separated by commas. */
91985 static void appendList(StringBuffer *sb, int nString, char **azString){
91986   int i;
91987   for(i=0; i<nString; ++i){
91988     if( i>0 ) append(sb, ", ");
91989     append(sb, azString[i]);
91990   }
91991 }
91992
91993 static int endsInWhiteSpace(StringBuffer *p){
91994   return stringBufferLength(p)>0 &&
91995     safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
91996 }
91997
91998 /* If the StringBuffer ends in something other than white space, add a
91999 ** single space character to the end.
92000 */
92001 static void appendWhiteSpace(StringBuffer *p){
92002   if( stringBufferLength(p)==0 ) return;
92003   if( !endsInWhiteSpace(p) ) append(p, " ");
92004 }
92005
92006 /* Remove white space from the end of the StringBuffer */
92007 static void trimWhiteSpace(StringBuffer *p){
92008   while( endsInWhiteSpace(p) ){
92009     p->b.pData[--p->b.nData-1] = '\0';
92010   }
92011 }
92012
92013 /*******************************************************************/
92014 /* DLReader is used to read document elements from a doclist.  The
92015 ** current docid is cached, so dlrDocid() is fast.  DLReader does not
92016 ** own the doclist buffer.
92017 **
92018 ** dlrAtEnd - true if there's no more data to read.
92019 ** dlrDocid - docid of current document.
92020 ** dlrDocData - doclist data for current document (including docid).
92021 ** dlrDocDataBytes - length of same.
92022 ** dlrAllDataBytes - length of all remaining data.
92023 ** dlrPosData - position data for current document.
92024 ** dlrPosDataLen - length of pos data for current document (incl POS_END).
92025 ** dlrStep - step to current document.
92026 ** dlrInit - initial for doclist of given type against given data.
92027 ** dlrDestroy - clean up.
92028 **
92029 ** Expected usage is something like:
92030 **
92031 **   DLReader reader;
92032 **   dlrInit(&reader, pData, nData);
92033 **   while( !dlrAtEnd(&reader) ){
92034 **     // calls to dlrDocid() and kin.
92035 **     dlrStep(&reader);
92036 **   }
92037 **   dlrDestroy(&reader);
92038 */
92039 typedef struct DLReader {
92040   DocListType iType;
92041   const char *pData;
92042   int nData;
92043
92044   sqlite_int64 iDocid;
92045   int nElement;
92046 } DLReader;
92047
92048 static int dlrAtEnd(DLReader *pReader){
92049   assert( pReader->nData>=0 );
92050   return pReader->nData==0;
92051 }
92052 static sqlite_int64 dlrDocid(DLReader *pReader){
92053   assert( !dlrAtEnd(pReader) );
92054   return pReader->iDocid;
92055 }
92056 static const char *dlrDocData(DLReader *pReader){
92057   assert( !dlrAtEnd(pReader) );
92058   return pReader->pData;
92059 }
92060 static int dlrDocDataBytes(DLReader *pReader){
92061   assert( !dlrAtEnd(pReader) );
92062   return pReader->nElement;
92063 }
92064 static int dlrAllDataBytes(DLReader *pReader){
92065   assert( !dlrAtEnd(pReader) );
92066   return pReader->nData;
92067 }
92068 /* TODO(shess) Consider adding a field to track iDocid varint length
92069 ** to make these two functions faster.  This might matter (a tiny bit)
92070 ** for queries.
92071 */
92072 static const char *dlrPosData(DLReader *pReader){
92073   sqlite_int64 iDummy;
92074   int n = fts3GetVarint(pReader->pData, &iDummy);
92075   assert( !dlrAtEnd(pReader) );
92076   return pReader->pData+n;
92077 }
92078 static int dlrPosDataLen(DLReader *pReader){
92079   sqlite_int64 iDummy;
92080   int n = fts3GetVarint(pReader->pData, &iDummy);
92081   assert( !dlrAtEnd(pReader) );
92082   return pReader->nElement-n;
92083 }
92084 static void dlrStep(DLReader *pReader){
92085   assert( !dlrAtEnd(pReader) );
92086
92087   /* Skip past current doclist element. */
92088   assert( pReader->nElement<=pReader->nData );
92089   pReader->pData += pReader->nElement;
92090   pReader->nData -= pReader->nElement;
92091
92092   /* If there is more data, read the next doclist element. */
92093   if( pReader->nData!=0 ){
92094     sqlite_int64 iDocidDelta;
92095     int iDummy, n = fts3GetVarint(pReader->pData, &iDocidDelta);
92096     pReader->iDocid += iDocidDelta;
92097     if( pReader->iType>=DL_POSITIONS ){
92098       assert( n<pReader->nData );
92099       while( 1 ){
92100         n += fts3GetVarint32(pReader->pData+n, &iDummy);
92101         assert( n<=pReader->nData );
92102         if( iDummy==POS_END ) break;
92103         if( iDummy==POS_COLUMN ){
92104           n += fts3GetVarint32(pReader->pData+n, &iDummy);
92105           assert( n<pReader->nData );
92106         }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
92107           n += fts3GetVarint32(pReader->pData+n, &iDummy);
92108           n += fts3GetVarint32(pReader->pData+n, &iDummy);
92109           assert( n<pReader->nData );
92110         }
92111       }
92112     }
92113     pReader->nElement = n;
92114     assert( pReader->nElement<=pReader->nData );
92115   }
92116 }
92117 static void dlrInit(DLReader *pReader, DocListType iType,
92118                     const char *pData, int nData){
92119   assert( pData!=NULL && nData!=0 );
92120   pReader->iType = iType;
92121   pReader->pData = pData;
92122   pReader->nData = nData;
92123   pReader->nElement = 0;
92124   pReader->iDocid = 0;
92125
92126   /* Load the first element's data.  There must be a first element. */
92127   dlrStep(pReader);
92128 }
92129 static void dlrDestroy(DLReader *pReader){
92130   SCRAMBLE(pReader);
92131 }
92132
92133 #ifndef NDEBUG
92134 /* Verify that the doclist can be validly decoded.  Also returns the
92135 ** last docid found because it is convenient in other assertions for
92136 ** DLWriter.
92137 */
92138 static void docListValidate(DocListType iType, const char *pData, int nData,
92139                             sqlite_int64 *pLastDocid){
92140   sqlite_int64 iPrevDocid = 0;
92141   assert( nData>0 );
92142   assert( pData!=0 );
92143   assert( pData+nData>pData );
92144   while( nData!=0 ){
92145     sqlite_int64 iDocidDelta;
92146     int n = fts3GetVarint(pData, &iDocidDelta);
92147     iPrevDocid += iDocidDelta;
92148     if( iType>DL_DOCIDS ){
92149       int iDummy;
92150       while( 1 ){
92151         n += fts3GetVarint32(pData+n, &iDummy);
92152         if( iDummy==POS_END ) break;
92153         if( iDummy==POS_COLUMN ){
92154           n += fts3GetVarint32(pData+n, &iDummy);
92155         }else if( iType>DL_POSITIONS ){
92156           n += fts3GetVarint32(pData+n, &iDummy);
92157           n += fts3GetVarint32(pData+n, &iDummy);
92158         }
92159         assert( n<=nData );
92160       }
92161     }
92162     assert( n<=nData );
92163     pData += n;
92164     nData -= n;
92165   }
92166   if( pLastDocid ) *pLastDocid = iPrevDocid;
92167 }
92168 #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
92169 #else
92170 #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
92171 #endif
92172
92173 /*******************************************************************/
92174 /* DLWriter is used to write doclist data to a DataBuffer.  DLWriter
92175 ** always appends to the buffer and does not own it.
92176 **
92177 ** dlwInit - initialize to write a given type doclistto a buffer.
92178 ** dlwDestroy - clear the writer's memory.  Does not free buffer.
92179 ** dlwAppend - append raw doclist data to buffer.
92180 ** dlwCopy - copy next doclist from reader to writer.
92181 ** dlwAdd - construct doclist element and append to buffer.
92182 **    Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
92183 */
92184 typedef struct DLWriter {
92185   DocListType iType;
92186   DataBuffer *b;
92187   sqlite_int64 iPrevDocid;
92188 #ifndef NDEBUG
92189   int has_iPrevDocid;
92190 #endif
92191 } DLWriter;
92192
92193 static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
92194   pWriter->b = b;
92195   pWriter->iType = iType;
92196   pWriter->iPrevDocid = 0;
92197 #ifndef NDEBUG
92198   pWriter->has_iPrevDocid = 0;
92199 #endif
92200 }
92201 static void dlwDestroy(DLWriter *pWriter){
92202   SCRAMBLE(pWriter);
92203 }
92204 /* iFirstDocid is the first docid in the doclist in pData.  It is
92205 ** needed because pData may point within a larger doclist, in which
92206 ** case the first item would be delta-encoded.
92207 **
92208 ** iLastDocid is the final docid in the doclist in pData.  It is
92209 ** needed to create the new iPrevDocid for future delta-encoding.  The
92210 ** code could decode the passed doclist to recreate iLastDocid, but
92211 ** the only current user (docListMerge) already has decoded this
92212 ** information.
92213 */
92214 /* TODO(shess) This has become just a helper for docListMerge.
92215 ** Consider a refactor to make this cleaner.
92216 */
92217 static void dlwAppend(DLWriter *pWriter,
92218                       const char *pData, int nData,
92219                       sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
92220   sqlite_int64 iDocid = 0;
92221   char c[VARINT_MAX];
92222   int nFirstOld, nFirstNew;     /* Old and new varint len of first docid. */
92223 #ifndef NDEBUG
92224   sqlite_int64 iLastDocidDelta;
92225 #endif
92226
92227   /* Recode the initial docid as delta from iPrevDocid. */
92228   nFirstOld = fts3GetVarint(pData, &iDocid);
92229   assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
92230   nFirstNew = fts3PutVarint(c, iFirstDocid-pWriter->iPrevDocid);
92231
92232   /* Verify that the incoming doclist is valid AND that it ends with
92233   ** the expected docid.  This is essential because we'll trust this
92234   ** docid in future delta-encoding.
92235   */
92236   ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
92237   assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
92238
92239   /* Append recoded initial docid and everything else.  Rest of docids
92240   ** should have been delta-encoded from previous initial docid.
92241   */
92242   if( nFirstOld<nData ){
92243     dataBufferAppend2(pWriter->b, c, nFirstNew,
92244                       pData+nFirstOld, nData-nFirstOld);
92245   }else{
92246     dataBufferAppend(pWriter->b, c, nFirstNew);
92247   }
92248   pWriter->iPrevDocid = iLastDocid;
92249 }
92250 static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
92251   dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
92252             dlrDocid(pReader), dlrDocid(pReader));
92253 }
92254 static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
92255   char c[VARINT_MAX];
92256   int n = fts3PutVarint(c, iDocid-pWriter->iPrevDocid);
92257
92258   /* Docids must ascend. */
92259   assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
92260   assert( pWriter->iType==DL_DOCIDS );
92261
92262   dataBufferAppend(pWriter->b, c, n);
92263   pWriter->iPrevDocid = iDocid;
92264 #ifndef NDEBUG
92265   pWriter->has_iPrevDocid = 1;
92266 #endif
92267 }
92268
92269 /*******************************************************************/
92270 /* PLReader is used to read data from a document's position list.  As
92271 ** the caller steps through the list, data is cached so that varints
92272 ** only need to be decoded once.
92273 **
92274 ** plrInit, plrDestroy - create/destroy a reader.
92275 ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
92276 ** plrAtEnd - at end of stream, only call plrDestroy once true.
92277 ** plrStep - step to the next element.
92278 */
92279 typedef struct PLReader {
92280   /* These refer to the next position's data.  nData will reach 0 when
92281   ** reading the last position, so plrStep() signals EOF by setting
92282   ** pData to NULL.
92283   */
92284   const char *pData;
92285   int nData;
92286
92287   DocListType iType;
92288   int iColumn;         /* the last column read */
92289   int iPosition;       /* the last position read */
92290   int iStartOffset;    /* the last start offset read */
92291   int iEndOffset;      /* the last end offset read */
92292 } PLReader;
92293
92294 static int plrAtEnd(PLReader *pReader){
92295   return pReader->pData==NULL;
92296 }
92297 static int plrColumn(PLReader *pReader){
92298   assert( !plrAtEnd(pReader) );
92299   return pReader->iColumn;
92300 }
92301 static int plrPosition(PLReader *pReader){
92302   assert( !plrAtEnd(pReader) );
92303   return pReader->iPosition;
92304 }
92305 static int plrStartOffset(PLReader *pReader){
92306   assert( !plrAtEnd(pReader) );
92307   return pReader->iStartOffset;
92308 }
92309 static int plrEndOffset(PLReader *pReader){
92310   assert( !plrAtEnd(pReader) );
92311   return pReader->iEndOffset;
92312 }
92313 static void plrStep(PLReader *pReader){
92314   int i, n;
92315
92316   assert( !plrAtEnd(pReader) );
92317
92318   if( pReader->nData==0 ){
92319     pReader->pData = NULL;
92320     return;
92321   }
92322
92323   n = fts3GetVarint32(pReader->pData, &i);
92324   if( i==POS_COLUMN ){
92325     n += fts3GetVarint32(pReader->pData+n, &pReader->iColumn);
92326     pReader->iPosition = 0;
92327     pReader->iStartOffset = 0;
92328     n += fts3GetVarint32(pReader->pData+n, &i);
92329   }
92330   /* Should never see adjacent column changes. */
92331   assert( i!=POS_COLUMN );
92332
92333   if( i==POS_END ){
92334     pReader->nData = 0;
92335     pReader->pData = NULL;
92336     return;
92337   }
92338
92339   pReader->iPosition += i-POS_BASE;
92340   if( pReader->iType==DL_POSITIONS_OFFSETS ){
92341     n += fts3GetVarint32(pReader->pData+n, &i);
92342     pReader->iStartOffset += i;
92343     n += fts3GetVarint32(pReader->pData+n, &i);
92344     pReader->iEndOffset = pReader->iStartOffset+i;
92345   }
92346   assert( n<=pReader->nData );
92347   pReader->pData += n;
92348   pReader->nData -= n;
92349 }
92350
92351 static void plrInit(PLReader *pReader, DLReader *pDLReader){
92352   pReader->pData = dlrPosData(pDLReader);
92353   pReader->nData = dlrPosDataLen(pDLReader);
92354   pReader->iType = pDLReader->iType;
92355   pReader->iColumn = 0;
92356   pReader->iPosition = 0;
92357   pReader->iStartOffset = 0;
92358   pReader->iEndOffset = 0;
92359   plrStep(pReader);
92360 }
92361 static void plrDestroy(PLReader *pReader){
92362   SCRAMBLE(pReader);
92363 }
92364
92365 /*******************************************************************/
92366 /* PLWriter is used in constructing a document's position list.  As a
92367 ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
92368 ** PLWriter writes to the associated DLWriter's buffer.
92369 **
92370 ** plwInit - init for writing a document's poslist.
92371 ** plwDestroy - clear a writer.
92372 ** plwAdd - append position and offset information.
92373 ** plwCopy - copy next position's data from reader to writer.
92374 ** plwTerminate - add any necessary doclist terminator.
92375 **
92376 ** Calling plwAdd() after plwTerminate() may result in a corrupt
92377 ** doclist.
92378 */
92379 /* TODO(shess) Until we've written the second item, we can cache the
92380 ** first item's information.  Then we'd have three states:
92381 **
92382 ** - initialized with docid, no positions.
92383 ** - docid and one position.
92384 ** - docid and multiple positions.
92385 **
92386 ** Only the last state needs to actually write to dlw->b, which would
92387 ** be an improvement in the DLCollector case.
92388 */
92389 typedef struct PLWriter {
92390   DLWriter *dlw;
92391
92392   int iColumn;    /* the last column written */
92393   int iPos;       /* the last position written */
92394   int iOffset;    /* the last start offset written */
92395 } PLWriter;
92396
92397 /* TODO(shess) In the case where the parent is reading these values
92398 ** from a PLReader, we could optimize to a copy if that PLReader has
92399 ** the same type as pWriter.
92400 */
92401 static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
92402                    int iStartOffset, int iEndOffset){
92403   /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
92404   ** iStartOffsetDelta, and iEndOffsetDelta.
92405   */
92406   char c[5*VARINT_MAX];
92407   int n = 0;
92408
92409   /* Ban plwAdd() after plwTerminate(). */
92410   assert( pWriter->iPos!=-1 );
92411
92412   if( pWriter->dlw->iType==DL_DOCIDS ) return;
92413
92414   if( iColumn!=pWriter->iColumn ){
92415     n += fts3PutVarint(c+n, POS_COLUMN);
92416     n += fts3PutVarint(c+n, iColumn);
92417     pWriter->iColumn = iColumn;
92418     pWriter->iPos = 0;
92419     pWriter->iOffset = 0;
92420   }
92421   assert( iPos>=pWriter->iPos );
92422   n += fts3PutVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
92423   pWriter->iPos = iPos;
92424   if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
92425     assert( iStartOffset>=pWriter->iOffset );
92426     n += fts3PutVarint(c+n, iStartOffset-pWriter->iOffset);
92427     pWriter->iOffset = iStartOffset;
92428     assert( iEndOffset>=iStartOffset );
92429     n += fts3PutVarint(c+n, iEndOffset-iStartOffset);
92430   }
92431   dataBufferAppend(pWriter->dlw->b, c, n);
92432 }
92433 static void plwCopy(PLWriter *pWriter, PLReader *pReader){
92434   plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
92435          plrStartOffset(pReader), plrEndOffset(pReader));
92436 }
92437 static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
92438   char c[VARINT_MAX];
92439   int n;
92440
92441   pWriter->dlw = dlw;
92442
92443   /* Docids must ascend. */
92444   assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
92445   n = fts3PutVarint(c, iDocid-pWriter->dlw->iPrevDocid);
92446   dataBufferAppend(pWriter->dlw->b, c, n);
92447   pWriter->dlw->iPrevDocid = iDocid;
92448 #ifndef NDEBUG
92449   pWriter->dlw->has_iPrevDocid = 1;
92450 #endif
92451
92452   pWriter->iColumn = 0;
92453   pWriter->iPos = 0;
92454   pWriter->iOffset = 0;
92455 }
92456 /* TODO(shess) Should plwDestroy() also terminate the doclist?  But
92457 ** then plwDestroy() would no longer be just a destructor, it would
92458 ** also be doing work, which isn't consistent with the overall idiom.
92459 ** Another option would be for plwAdd() to always append any necessary
92460 ** terminator, so that the output is always correct.  But that would
92461 ** add incremental work to the common case with the only benefit being
92462 ** API elegance.  Punt for now.
92463 */
92464 static void plwTerminate(PLWriter *pWriter){
92465   if( pWriter->dlw->iType>DL_DOCIDS ){
92466     char c[VARINT_MAX];
92467     int n = fts3PutVarint(c, POS_END);
92468     dataBufferAppend(pWriter->dlw->b, c, n);
92469   }
92470 #ifndef NDEBUG
92471   /* Mark as terminated for assert in plwAdd(). */
92472   pWriter->iPos = -1;
92473 #endif
92474 }
92475 static void plwDestroy(PLWriter *pWriter){
92476   SCRAMBLE(pWriter);
92477 }
92478
92479 /*******************************************************************/
92480 /* DLCollector wraps PLWriter and DLWriter to provide a
92481 ** dynamically-allocated doclist area to use during tokenization.
92482 **
92483 ** dlcNew - malloc up and initialize a collector.
92484 ** dlcDelete - destroy a collector and all contained items.
92485 ** dlcAddPos - append position and offset information.
92486 ** dlcAddDoclist - add the collected doclist to the given buffer.
92487 ** dlcNext - terminate the current document and open another.
92488 */
92489 typedef struct DLCollector {
92490   DataBuffer b;
92491   DLWriter dlw;
92492   PLWriter plw;
92493 } DLCollector;
92494
92495 /* TODO(shess) This could also be done by calling plwTerminate() and
92496 ** dataBufferAppend().  I tried that, expecting nominal performance
92497 ** differences, but it seemed to pretty reliably be worth 1% to code
92498 ** it this way.  I suspect it is the incremental malloc overhead (some
92499 ** percentage of the plwTerminate() calls will cause a realloc), so
92500 ** this might be worth revisiting if the DataBuffer implementation
92501 ** changes.
92502 */
92503 static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
92504   if( pCollector->dlw.iType>DL_DOCIDS ){
92505     char c[VARINT_MAX];
92506     int n = fts3PutVarint(c, POS_END);
92507     dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
92508   }else{
92509     dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
92510   }
92511 }
92512 static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
92513   plwTerminate(&pCollector->plw);
92514   plwDestroy(&pCollector->plw);
92515   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
92516 }
92517 static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
92518                       int iStartOffset, int iEndOffset){
92519   plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
92520 }
92521
92522 static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
92523   DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
92524   dataBufferInit(&pCollector->b, 0);
92525   dlwInit(&pCollector->dlw, iType, &pCollector->b);
92526   plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
92527   return pCollector;
92528 }
92529 static void dlcDelete(DLCollector *pCollector){
92530   plwDestroy(&pCollector->plw);
92531   dlwDestroy(&pCollector->dlw);
92532   dataBufferDestroy(&pCollector->b);
92533   SCRAMBLE(pCollector);
92534   sqlite3_free(pCollector);
92535 }
92536
92537
92538 /* Copy the doclist data of iType in pData/nData into *out, trimming
92539 ** unnecessary data as we go.  Only columns matching iColumn are
92540 ** copied, all columns copied if iColumn is -1.  Elements with no
92541 ** matching columns are dropped.  The output is an iOutType doclist.
92542 */
92543 /* NOTE(shess) This code is only valid after all doclists are merged.
92544 ** If this is run before merges, then doclist items which represent
92545 ** deletion will be trimmed, and will thus not effect a deletion
92546 ** during the merge.
92547 */
92548 static void docListTrim(DocListType iType, const char *pData, int nData,
92549                         int iColumn, DocListType iOutType, DataBuffer *out){
92550   DLReader dlReader;
92551   DLWriter dlWriter;
92552
92553   assert( iOutType<=iType );
92554
92555   dlrInit(&dlReader, iType, pData, nData);
92556   dlwInit(&dlWriter, iOutType, out);
92557
92558   while( !dlrAtEnd(&dlReader) ){
92559     PLReader plReader;
92560     PLWriter plWriter;
92561     int match = 0;
92562
92563     plrInit(&plReader, &dlReader);
92564
92565     while( !plrAtEnd(&plReader) ){
92566       if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
92567         if( !match ){
92568           plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
92569           match = 1;
92570         }
92571         plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
92572                plrStartOffset(&plReader), plrEndOffset(&plReader));
92573       }
92574       plrStep(&plReader);
92575     }
92576     if( match ){
92577       plwTerminate(&plWriter);
92578       plwDestroy(&plWriter);
92579     }
92580
92581     plrDestroy(&plReader);
92582     dlrStep(&dlReader);
92583   }
92584   dlwDestroy(&dlWriter);
92585   dlrDestroy(&dlReader);
92586 }
92587
92588 /* Used by docListMerge() to keep doclists in the ascending order by
92589 ** docid, then ascending order by age (so the newest comes first).
92590 */
92591 typedef struct OrderedDLReader {
92592   DLReader *pReader;
92593
92594   /* TODO(shess) If we assume that docListMerge pReaders is ordered by
92595   ** age (which we do), then we could use pReader comparisons to break
92596   ** ties.
92597   */
92598   int idx;
92599 } OrderedDLReader;
92600
92601 /* Order eof to end, then by docid asc, idx desc. */
92602 static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
92603   if( dlrAtEnd(r1->pReader) ){
92604     if( dlrAtEnd(r2->pReader) ) return 0;  /* Both atEnd(). */
92605     return 1;                              /* Only r1 atEnd(). */
92606   }
92607   if( dlrAtEnd(r2->pReader) ) return -1;   /* Only r2 atEnd(). */
92608
92609   if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
92610   if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
92611
92612   /* Descending on idx. */
92613   return r2->idx-r1->idx;
92614 }
92615
92616 /* Bubble p[0] to appropriate place in p[1..n-1].  Assumes that
92617 ** p[1..n-1] is already sorted.
92618 */
92619 /* TODO(shess) Is this frequent enough to warrant a binary search?
92620 ** Before implementing that, instrument the code to check.  In most
92621 ** current usage, I expect that p[0] will be less than p[1] a very
92622 ** high proportion of the time.
92623 */
92624 static void orderedDLReaderReorder(OrderedDLReader *p, int n){
92625   while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
92626     OrderedDLReader tmp = p[0];
92627     p[0] = p[1];
92628     p[1] = tmp;
92629     n--;
92630     p++;
92631   }
92632 }
92633
92634 /* Given an array of doclist readers, merge their doclist elements
92635 ** into out in sorted order (by docid), dropping elements from older
92636 ** readers when there is a duplicate docid.  pReaders is assumed to be
92637 ** ordered by age, oldest first.
92638 */
92639 /* TODO(shess) nReaders must be <= MERGE_COUNT.  This should probably
92640 ** be fixed.
92641 */
92642 static void docListMerge(DataBuffer *out,
92643                          DLReader *pReaders, int nReaders){
92644   OrderedDLReader readers[MERGE_COUNT];
92645   DLWriter writer;
92646   int i, n;
92647   const char *pStart = 0;
92648   int nStart = 0;
92649   sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
92650
92651   assert( nReaders>0 );
92652   if( nReaders==1 ){
92653     dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
92654     return;
92655   }
92656
92657   assert( nReaders<=MERGE_COUNT );
92658   n = 0;
92659   for(i=0; i<nReaders; i++){
92660     assert( pReaders[i].iType==pReaders[0].iType );
92661     readers[i].pReader = pReaders+i;
92662     readers[i].idx = i;
92663     n += dlrAllDataBytes(&pReaders[i]);
92664   }
92665   /* Conservatively size output to sum of inputs.  Output should end
92666   ** up strictly smaller than input.
92667   */
92668   dataBufferExpand(out, n);
92669
92670   /* Get the readers into sorted order. */
92671   while( i-->0 ){
92672     orderedDLReaderReorder(readers+i, nReaders-i);
92673   }
92674
92675   dlwInit(&writer, pReaders[0].iType, out);
92676   while( !dlrAtEnd(readers[0].pReader) ){
92677     sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
92678
92679     /* If this is a continuation of the current buffer to copy, extend
92680     ** that buffer.  memcpy() seems to be more efficient if it has a
92681     ** lots of data to copy.
92682     */
92683     if( dlrDocData(readers[0].pReader)==pStart+nStart ){
92684       nStart += dlrDocDataBytes(readers[0].pReader);
92685     }else{
92686       if( pStart!=0 ){
92687         dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
92688       }
92689       pStart = dlrDocData(readers[0].pReader);
92690       nStart = dlrDocDataBytes(readers[0].pReader);
92691       iFirstDocid = iDocid;
92692     }
92693     iLastDocid = iDocid;
92694     dlrStep(readers[0].pReader);
92695
92696     /* Drop all of the older elements with the same docid. */
92697     for(i=1; i<nReaders &&
92698              !dlrAtEnd(readers[i].pReader) &&
92699              dlrDocid(readers[i].pReader)==iDocid; i++){
92700       dlrStep(readers[i].pReader);
92701     }
92702
92703     /* Get the readers back into order. */
92704     while( i-->0 ){
92705       orderedDLReaderReorder(readers+i, nReaders-i);
92706     }
92707   }
92708
92709   /* Copy over any remaining elements. */
92710   if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
92711   dlwDestroy(&writer);
92712 }
92713
92714 /* Helper function for posListUnion().  Compares the current position
92715 ** between left and right, returning as standard C idiom of <0 if
92716 ** left<right, >0 if left>right, and 0 if left==right.  "End" always
92717 ** compares greater.
92718 */
92719 static int posListCmp(PLReader *pLeft, PLReader *pRight){
92720   assert( pLeft->iType==pRight->iType );
92721   if( pLeft->iType==DL_DOCIDS ) return 0;
92722
92723   if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
92724   if( plrAtEnd(pRight) ) return -1;
92725
92726   if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
92727   if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
92728
92729   if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
92730   if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
92731   if( pLeft->iType==DL_POSITIONS ) return 0;
92732
92733   if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
92734   if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
92735
92736   if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
92737   if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
92738
92739   return 0;
92740 }
92741
92742 /* Write the union of position lists in pLeft and pRight to pOut.
92743 ** "Union" in this case meaning "All unique position tuples".  Should
92744 ** work with any doclist type, though both inputs and the output
92745 ** should be the same type.
92746 */
92747 static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
92748   PLReader left, right;
92749   PLWriter writer;
92750
92751   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
92752   assert( pLeft->iType==pRight->iType );
92753   assert( pLeft->iType==pOut->iType );
92754
92755   plrInit(&left, pLeft);
92756   plrInit(&right, pRight);
92757   plwInit(&writer, pOut, dlrDocid(pLeft));
92758
92759   while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
92760     int c = posListCmp(&left, &right);
92761     if( c<0 ){
92762       plwCopy(&writer, &left);
92763       plrStep(&left);
92764     }else if( c>0 ){
92765       plwCopy(&writer, &right);
92766       plrStep(&right);
92767     }else{
92768       plwCopy(&writer, &left);
92769       plrStep(&left);
92770       plrStep(&right);
92771     }
92772   }
92773
92774   plwTerminate(&writer);
92775   plwDestroy(&writer);
92776   plrDestroy(&left);
92777   plrDestroy(&right);
92778 }
92779
92780 /* Write the union of doclists in pLeft and pRight to pOut.  For
92781 ** docids in common between the inputs, the union of the position
92782 ** lists is written.  Inputs and outputs are always type DL_DEFAULT.
92783 */
92784 static void docListUnion(
92785   const char *pLeft, int nLeft,
92786   const char *pRight, int nRight,
92787   DataBuffer *pOut      /* Write the combined doclist here */
92788 ){
92789   DLReader left, right;
92790   DLWriter writer;
92791
92792   if( nLeft==0 ){
92793     if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
92794     return;
92795   }
92796   if( nRight==0 ){
92797     dataBufferAppend(pOut, pLeft, nLeft);
92798     return;
92799   }
92800
92801   dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
92802   dlrInit(&right, DL_DEFAULT, pRight, nRight);
92803   dlwInit(&writer, DL_DEFAULT, pOut);
92804
92805   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
92806     if( dlrAtEnd(&right) ){
92807       dlwCopy(&writer, &left);
92808       dlrStep(&left);
92809     }else if( dlrAtEnd(&left) ){
92810       dlwCopy(&writer, &right);
92811       dlrStep(&right);
92812     }else if( dlrDocid(&left)<dlrDocid(&right) ){
92813       dlwCopy(&writer, &left);
92814       dlrStep(&left);
92815     }else if( dlrDocid(&left)>dlrDocid(&right) ){
92816       dlwCopy(&writer, &right);
92817       dlrStep(&right);
92818     }else{
92819       posListUnion(&left, &right, &writer);
92820       dlrStep(&left);
92821       dlrStep(&right);
92822     }
92823   }
92824
92825   dlrDestroy(&left);
92826   dlrDestroy(&right);
92827   dlwDestroy(&writer);
92828 }
92829
92830 /* 
92831 ** This function is used as part of the implementation of phrase and
92832 ** NEAR matching.
92833 **
92834 ** pLeft and pRight are DLReaders positioned to the same docid in
92835 ** lists of type DL_POSITION. This function writes an entry to the
92836 ** DLWriter pOut for each position in pRight that is less than
92837 ** (nNear+1) greater (but not equal to or smaller) than a position 
92838 ** in pLeft. For example, if nNear is 0, and the positions contained
92839 ** by pLeft and pRight are:
92840 **
92841 **    pLeft:  5 10 15 20
92842 **    pRight: 6  9 17 21
92843 **
92844 ** then the docid is added to pOut. If pOut is of type DL_POSITIONS,
92845 ** then a positionids "6" and "21" are also added to pOut.
92846 **
92847 ** If boolean argument isSaveLeft is true, then positionids are copied
92848 ** from pLeft instead of pRight. In the example above, the positions "5"
92849 ** and "20" would be added instead of "6" and "21".
92850 */
92851 static void posListPhraseMerge(
92852   DLReader *pLeft, 
92853   DLReader *pRight,
92854   int nNear,
92855   int isSaveLeft,
92856   DLWriter *pOut
92857 ){
92858   PLReader left, right;
92859   PLWriter writer;
92860   int match = 0;
92861
92862   assert( dlrDocid(pLeft)==dlrDocid(pRight) );
92863   assert( pOut->iType!=DL_POSITIONS_OFFSETS );
92864
92865   plrInit(&left, pLeft);
92866   plrInit(&right, pRight);
92867
92868   while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
92869     if( plrColumn(&left)<plrColumn(&right) ){
92870       plrStep(&left);
92871     }else if( plrColumn(&left)>plrColumn(&right) ){
92872       plrStep(&right);
92873     }else if( plrPosition(&left)>=plrPosition(&right) ){
92874       plrStep(&right);
92875     }else{
92876       if( (plrPosition(&right)-plrPosition(&left))<=(nNear+1) ){
92877         if( !match ){
92878           plwInit(&writer, pOut, dlrDocid(pLeft));
92879           match = 1;
92880         }
92881         if( !isSaveLeft ){
92882           plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
92883         }else{
92884           plwAdd(&writer, plrColumn(&left), plrPosition(&left), 0, 0);
92885         }
92886         plrStep(&right);
92887       }else{
92888         plrStep(&left);
92889       }
92890     }
92891   }
92892
92893   if( match ){
92894     plwTerminate(&writer);
92895     plwDestroy(&writer);
92896   }
92897
92898   plrDestroy(&left);
92899   plrDestroy(&right);
92900 }
92901
92902 /*
92903 ** Compare the values pointed to by the PLReaders passed as arguments. 
92904 ** Return -1 if the value pointed to by pLeft is considered less than
92905 ** the value pointed to by pRight, +1 if it is considered greater
92906 ** than it, or 0 if it is equal. i.e.
92907 **
92908 **     (*pLeft - *pRight)
92909 **
92910 ** A PLReader that is in the EOF condition is considered greater than
92911 ** any other. If neither argument is in EOF state, the return value of
92912 ** plrColumn() is used. If the plrColumn() values are equal, the
92913 ** comparison is on the basis of plrPosition().
92914 */
92915 static int plrCompare(PLReader *pLeft, PLReader *pRight){
92916   assert(!plrAtEnd(pLeft) || !plrAtEnd(pRight));
92917
92918   if( plrAtEnd(pRight) || plrAtEnd(pLeft) ){
92919     return (plrAtEnd(pRight) ? -1 : 1);
92920   }
92921   if( plrColumn(pLeft)!=plrColumn(pRight) ){
92922     return ((plrColumn(pLeft)<plrColumn(pRight)) ? -1 : 1);
92923   }
92924   if( plrPosition(pLeft)!=plrPosition(pRight) ){
92925     return ((plrPosition(pLeft)<plrPosition(pRight)) ? -1 : 1);
92926   }
92927   return 0;
92928 }
92929
92930 /* We have two doclists with positions:  pLeft and pRight. Depending
92931 ** on the value of the nNear parameter, perform either a phrase
92932 ** intersection (if nNear==0) or a NEAR intersection (if nNear>0)
92933 ** and write the results into pOut.
92934 **
92935 ** A phrase intersection means that two documents only match
92936 ** if pLeft.iPos+1==pRight.iPos.
92937 **
92938 ** A NEAR intersection means that two documents only match if 
92939 ** (abs(pLeft.iPos-pRight.iPos)<nNear).
92940 **
92941 ** If a NEAR intersection is requested, then the nPhrase argument should
92942 ** be passed the number of tokens in the two operands to the NEAR operator
92943 ** combined. For example:
92944 **
92945 **       Query syntax               nPhrase
92946 **      ------------------------------------
92947 **       "A B C" NEAR "D E"         5
92948 **       A NEAR B                   2
92949 **
92950 ** iType controls the type of data written to pOut.  If iType is
92951 ** DL_POSITIONS, the positions are those from pRight.
92952 */
92953 static void docListPhraseMerge(
92954   const char *pLeft, int nLeft,
92955   const char *pRight, int nRight,
92956   int nNear,            /* 0 for a phrase merge, non-zero for a NEAR merge */
92957   int nPhrase,          /* Number of tokens in left+right operands to NEAR */
92958   DocListType iType,    /* Type of doclist to write to pOut */
92959   DataBuffer *pOut      /* Write the combined doclist here */
92960 ){
92961   DLReader left, right;
92962   DLWriter writer;
92963
92964   if( nLeft==0 || nRight==0 ) return;
92965
92966   assert( iType!=DL_POSITIONS_OFFSETS );
92967
92968   dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
92969   dlrInit(&right, DL_POSITIONS, pRight, nRight);
92970   dlwInit(&writer, iType, pOut);
92971
92972   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
92973     if( dlrDocid(&left)<dlrDocid(&right) ){
92974       dlrStep(&left);
92975     }else if( dlrDocid(&right)<dlrDocid(&left) ){
92976       dlrStep(&right);
92977     }else{
92978       if( nNear==0 ){
92979         posListPhraseMerge(&left, &right, 0, 0, &writer);
92980       }else{
92981         /* This case occurs when two terms (simple terms or phrases) are
92982          * connected by a NEAR operator, span (nNear+1). i.e.
92983          *
92984          *     '"terrible company" NEAR widget'
92985          */
92986         DataBuffer one = {0, 0, 0};
92987         DataBuffer two = {0, 0, 0};
92988
92989         DLWriter dlwriter2;
92990         DLReader dr1 = {0, 0, 0, 0, 0}; 
92991         DLReader dr2 = {0, 0, 0, 0, 0};
92992
92993         dlwInit(&dlwriter2, iType, &one);
92994         posListPhraseMerge(&right, &left, nNear-3+nPhrase, 1, &dlwriter2);
92995         dlwInit(&dlwriter2, iType, &two);
92996         posListPhraseMerge(&left, &right, nNear-1, 0, &dlwriter2);
92997
92998         if( one.nData) dlrInit(&dr1, iType, one.pData, one.nData);
92999         if( two.nData) dlrInit(&dr2, iType, two.pData, two.nData);
93000
93001         if( !dlrAtEnd(&dr1) || !dlrAtEnd(&dr2) ){
93002           PLReader pr1 = {0};
93003           PLReader pr2 = {0};
93004
93005           PLWriter plwriter;
93006           plwInit(&plwriter, &writer, dlrDocid(dlrAtEnd(&dr1)?&dr2:&dr1));
93007
93008           if( one.nData ) plrInit(&pr1, &dr1);
93009           if( two.nData ) plrInit(&pr2, &dr2);
93010           while( !plrAtEnd(&pr1) || !plrAtEnd(&pr2) ){
93011             int iCompare = plrCompare(&pr1, &pr2);
93012             switch( iCompare ){
93013               case -1:
93014                 plwCopy(&plwriter, &pr1);
93015                 plrStep(&pr1);
93016                 break;
93017               case 1:
93018                 plwCopy(&plwriter, &pr2);
93019                 plrStep(&pr2);
93020                 break;
93021               case 0:
93022                 plwCopy(&plwriter, &pr1);
93023                 plrStep(&pr1);
93024                 plrStep(&pr2);
93025                 break;
93026             }
93027           }
93028           plwTerminate(&plwriter);
93029         }
93030         dataBufferDestroy(&one);
93031         dataBufferDestroy(&two);
93032       }
93033       dlrStep(&left);
93034       dlrStep(&right);
93035     }
93036   }
93037
93038   dlrDestroy(&left);
93039   dlrDestroy(&right);
93040   dlwDestroy(&writer);
93041 }
93042
93043 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
93044 ** Write the intersection of these two doclists into pOut as a
93045 ** DL_DOCIDS doclist.
93046 */
93047 static void docListAndMerge(
93048   const char *pLeft, int nLeft,
93049   const char *pRight, int nRight,
93050   DataBuffer *pOut      /* Write the combined doclist here */
93051 ){
93052   DLReader left, right;
93053   DLWriter writer;
93054
93055   if( nLeft==0 || nRight==0 ) return;
93056
93057   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
93058   dlrInit(&right, DL_DOCIDS, pRight, nRight);
93059   dlwInit(&writer, DL_DOCIDS, pOut);
93060
93061   while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
93062     if( dlrDocid(&left)<dlrDocid(&right) ){
93063       dlrStep(&left);
93064     }else if( dlrDocid(&right)<dlrDocid(&left) ){
93065       dlrStep(&right);
93066     }else{
93067       dlwAdd(&writer, dlrDocid(&left));
93068       dlrStep(&left);
93069       dlrStep(&right);
93070     }
93071   }
93072
93073   dlrDestroy(&left);
93074   dlrDestroy(&right);
93075   dlwDestroy(&writer);
93076 }
93077
93078 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
93079 ** Write the union of these two doclists into pOut as a
93080 ** DL_DOCIDS doclist.
93081 */
93082 static void docListOrMerge(
93083   const char *pLeft, int nLeft,
93084   const char *pRight, int nRight,
93085   DataBuffer *pOut      /* Write the combined doclist here */
93086 ){
93087   DLReader left, right;
93088   DLWriter writer;
93089
93090   if( nLeft==0 ){
93091     if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
93092     return;
93093   }
93094   if( nRight==0 ){
93095     dataBufferAppend(pOut, pLeft, nLeft);
93096     return;
93097   }
93098
93099   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
93100   dlrInit(&right, DL_DOCIDS, pRight, nRight);
93101   dlwInit(&writer, DL_DOCIDS, pOut);
93102
93103   while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
93104     if( dlrAtEnd(&right) ){
93105       dlwAdd(&writer, dlrDocid(&left));
93106       dlrStep(&left);
93107     }else if( dlrAtEnd(&left) ){
93108       dlwAdd(&writer, dlrDocid(&right));
93109       dlrStep(&right);
93110     }else if( dlrDocid(&left)<dlrDocid(&right) ){
93111       dlwAdd(&writer, dlrDocid(&left));
93112       dlrStep(&left);
93113     }else if( dlrDocid(&right)<dlrDocid(&left) ){
93114       dlwAdd(&writer, dlrDocid(&right));
93115       dlrStep(&right);
93116     }else{
93117       dlwAdd(&writer, dlrDocid(&left));
93118       dlrStep(&left);
93119       dlrStep(&right);
93120     }
93121   }
93122
93123   dlrDestroy(&left);
93124   dlrDestroy(&right);
93125   dlwDestroy(&writer);
93126 }
93127
93128 /* We have two DL_DOCIDS doclists:  pLeft and pRight.
93129 ** Write into pOut as DL_DOCIDS doclist containing all documents that
93130 ** occur in pLeft but not in pRight.
93131 */
93132 static void docListExceptMerge(
93133   const char *pLeft, int nLeft,
93134   const char *pRight, int nRight,
93135   DataBuffer *pOut      /* Write the combined doclist here */
93136 ){
93137   DLReader left, right;
93138   DLWriter writer;
93139
93140   if( nLeft==0 ) return;
93141   if( nRight==0 ){
93142     dataBufferAppend(pOut, pLeft, nLeft);
93143     return;
93144   }
93145
93146   dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
93147   dlrInit(&right, DL_DOCIDS, pRight, nRight);
93148   dlwInit(&writer, DL_DOCIDS, pOut);
93149
93150   while( !dlrAtEnd(&left) ){
93151     while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
93152       dlrStep(&right);
93153     }
93154     if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
93155       dlwAdd(&writer, dlrDocid(&left));
93156     }
93157     dlrStep(&left);
93158   }
93159
93160   dlrDestroy(&left);
93161   dlrDestroy(&right);
93162   dlwDestroy(&writer);
93163 }
93164
93165 static char *string_dup_n(const char *s, int n){
93166   char *str = sqlite3_malloc(n + 1);
93167   memcpy(str, s, n);
93168   str[n] = '\0';
93169   return str;
93170 }
93171
93172 /* Duplicate a string; the caller must free() the returned string.
93173  * (We don't use strdup() since it is not part of the standard C library and
93174  * may not be available everywhere.) */
93175 static char *string_dup(const char *s){
93176   return string_dup_n(s, strlen(s));
93177 }
93178
93179 /* Format a string, replacing each occurrence of the % character with
93180  * zDb.zName.  This may be more convenient than sqlite_mprintf()
93181  * when one string is used repeatedly in a format string.
93182  * The caller must free() the returned string. */
93183 static char *string_format(const char *zFormat,
93184                            const char *zDb, const char *zName){
93185   const char *p;
93186   size_t len = 0;
93187   size_t nDb = strlen(zDb);
93188   size_t nName = strlen(zName);
93189   size_t nFullTableName = nDb+1+nName;
93190   char *result;
93191   char *r;
93192
93193   /* first compute length needed */
93194   for(p = zFormat ; *p ; ++p){
93195     len += (*p=='%' ? nFullTableName : 1);
93196   }
93197   len += 1;  /* for null terminator */
93198
93199   r = result = sqlite3_malloc(len);
93200   for(p = zFormat; *p; ++p){
93201     if( *p=='%' ){
93202       memcpy(r, zDb, nDb);
93203       r += nDb;
93204       *r++ = '.';
93205       memcpy(r, zName, nName);
93206       r += nName;
93207     } else {
93208       *r++ = *p;
93209     }
93210   }
93211   *r++ = '\0';
93212   assert( r == result + len );
93213   return result;
93214 }
93215
93216 static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
93217                     const char *zFormat){
93218   char *zCommand = string_format(zFormat, zDb, zName);
93219   int rc;
93220   FTSTRACE(("FTS3 sql: %s\n", zCommand));
93221   rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
93222   sqlite3_free(zCommand);
93223   return rc;
93224 }
93225
93226 static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
93227                        sqlite3_stmt **ppStmt, const char *zFormat){
93228   char *zCommand = string_format(zFormat, zDb, zName);
93229   int rc;
93230   FTSTRACE(("FTS3 prepare: %s\n", zCommand));
93231   rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
93232   sqlite3_free(zCommand);
93233   return rc;
93234 }
93235
93236 /* end utility functions */
93237
93238 /* Forward reference */
93239 typedef struct fulltext_vtab fulltext_vtab;
93240
93241 /*
93242 ** An instance of the following structure keeps track of generated
93243 ** matching-word offset information and snippets.
93244 */
93245 typedef struct Snippet {
93246   int nMatch;     /* Total number of matches */
93247   int nAlloc;     /* Space allocated for aMatch[] */
93248   struct snippetMatch { /* One entry for each matching term */
93249     char snStatus;       /* Status flag for use while constructing snippets */
93250     short int iCol;      /* The column that contains the match */
93251     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
93252     int iToken;          /* The index of the matching document token */
93253     short int nByte;     /* Number of bytes in the term */
93254     int iStart;          /* The offset to the first character of the term */
93255   } *aMatch;      /* Points to space obtained from malloc */
93256   char *zOffset;  /* Text rendering of aMatch[] */
93257   int nOffset;    /* strlen(zOffset) */
93258   char *zSnippet; /* Snippet text */
93259   int nSnippet;   /* strlen(zSnippet) */
93260 } Snippet;
93261
93262
93263 typedef enum QueryType {
93264   QUERY_GENERIC,   /* table scan */
93265   QUERY_DOCID,     /* lookup by docid */
93266   QUERY_FULLTEXT   /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
93267 } QueryType;
93268
93269 typedef enum fulltext_statement {
93270   CONTENT_INSERT_STMT,
93271   CONTENT_SELECT_STMT,
93272   CONTENT_UPDATE_STMT,
93273   CONTENT_DELETE_STMT,
93274   CONTENT_EXISTS_STMT,
93275
93276   BLOCK_INSERT_STMT,
93277   BLOCK_SELECT_STMT,
93278   BLOCK_DELETE_STMT,
93279   BLOCK_DELETE_ALL_STMT,
93280
93281   SEGDIR_MAX_INDEX_STMT,
93282   SEGDIR_SET_STMT,
93283   SEGDIR_SELECT_LEVEL_STMT,
93284   SEGDIR_SPAN_STMT,
93285   SEGDIR_DELETE_STMT,
93286   SEGDIR_SELECT_SEGMENT_STMT,
93287   SEGDIR_SELECT_ALL_STMT,
93288   SEGDIR_DELETE_ALL_STMT,
93289   SEGDIR_COUNT_STMT,
93290
93291   MAX_STMT                     /* Always at end! */
93292 } fulltext_statement;
93293
93294 /* These must exactly match the enum above. */
93295 /* TODO(shess): Is there some risk that a statement will be used in two
93296 ** cursors at once, e.g.  if a query joins a virtual table to itself?
93297 ** If so perhaps we should move some of these to the cursor object.
93298 */
93299 static const char *const fulltext_zStatement[MAX_STMT] = {
93300   /* CONTENT_INSERT */ NULL,  /* generated in contentInsertStatement() */
93301   /* CONTENT_SELECT */ NULL,  /* generated in contentSelectStatement() */
93302   /* CONTENT_UPDATE */ NULL,  /* generated in contentUpdateStatement() */
93303   /* CONTENT_DELETE */ "delete from %_content where docid = ?",
93304   /* CONTENT_EXISTS */ "select docid from %_content limit 1",
93305
93306   /* BLOCK_INSERT */
93307   "insert into %_segments (blockid, block) values (null, ?)",
93308   /* BLOCK_SELECT */ "select block from %_segments where blockid = ?",
93309   /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?",
93310   /* BLOCK_DELETE_ALL */ "delete from %_segments",
93311
93312   /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
93313   /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
93314   /* SEGDIR_SELECT_LEVEL */
93315   "select start_block, leaves_end_block, root from %_segdir "
93316   " where level = ? order by idx",
93317   /* SEGDIR_SPAN */
93318   "select min(start_block), max(end_block) from %_segdir "
93319   " where level = ? and start_block <> 0",
93320   /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
93321
93322   /* NOTE(shess): The first three results of the following two
93323   ** statements must match.
93324   */
93325   /* SEGDIR_SELECT_SEGMENT */
93326   "select start_block, leaves_end_block, root from %_segdir "
93327   " where level = ? and idx = ?",
93328   /* SEGDIR_SELECT_ALL */
93329   "select start_block, leaves_end_block, root from %_segdir "
93330   " order by level desc, idx asc",
93331   /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
93332   /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
93333 };
93334
93335 /*
93336 ** A connection to a fulltext index is an instance of the following
93337 ** structure.  The xCreate and xConnect methods create an instance
93338 ** of this structure and xDestroy and xDisconnect free that instance.
93339 ** All other methods receive a pointer to the structure as one of their
93340 ** arguments.
93341 */
93342 struct fulltext_vtab {
93343   sqlite3_vtab base;               /* Base class used by SQLite core */
93344   sqlite3 *db;                     /* The database connection */
93345   const char *zDb;                 /* logical database name */
93346   const char *zName;               /* virtual table name */
93347   int nColumn;                     /* number of columns in virtual table */
93348   char **azColumn;                 /* column names.  malloced */
93349   char **azContentColumn;          /* column names in content table; malloced */
93350   sqlite3_tokenizer *pTokenizer;   /* tokenizer for inserts and queries */
93351
93352   /* Precompiled statements which we keep as long as the table is
93353   ** open.
93354   */
93355   sqlite3_stmt *pFulltextStatements[MAX_STMT];
93356
93357   /* Precompiled statements used for segment merges.  We run a
93358   ** separate select across the leaf level of each tree being merged.
93359   */
93360   sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
93361   /* The statement used to prepare pLeafSelectStmts. */
93362 #define LEAF_SELECT \
93363   "select block from %_segments where blockid between ? and ? order by blockid"
93364
93365   /* These buffer pending index updates during transactions.
93366   ** nPendingData estimates the memory size of the pending data.  It
93367   ** doesn't include the hash-bucket overhead, nor any malloc
93368   ** overhead.  When nPendingData exceeds kPendingThreshold, the
93369   ** buffer is flushed even before the transaction closes.
93370   ** pendingTerms stores the data, and is only valid when nPendingData
93371   ** is >=0 (nPendingData<0 means pendingTerms has not been
93372   ** initialized).  iPrevDocid is the last docid written, used to make
93373   ** certain we're inserting in sorted order.
93374   */
93375   int nPendingData;
93376 #define kPendingThreshold (1*1024*1024)
93377   sqlite_int64 iPrevDocid;
93378   fts3Hash pendingTerms;
93379 };
93380
93381 /*
93382 ** When the core wants to do a query, it create a cursor using a
93383 ** call to xOpen.  This structure is an instance of a cursor.  It
93384 ** is destroyed by xClose.
93385 */
93386 typedef struct fulltext_cursor {
93387   sqlite3_vtab_cursor base;        /* Base class used by SQLite core */
93388   QueryType iCursorType;           /* Copy of sqlite3_index_info.idxNum */
93389   sqlite3_stmt *pStmt;             /* Prepared statement in use by the cursor */
93390   int eof;                         /* True if at End Of Results */
93391   Fts3Expr *pExpr;                 /* Parsed MATCH query string */
93392   Snippet snippet;                 /* Cached snippet for the current row */
93393   int iColumn;                     /* Column being searched */
93394   DataBuffer result;               /* Doclist results from fulltextQuery */
93395   DLReader reader;                 /* Result reader if result not empty */
93396 } fulltext_cursor;
93397
93398 static fulltext_vtab *cursor_vtab(fulltext_cursor *c){
93399   return (fulltext_vtab *) c->base.pVtab;
93400 }
93401
93402 static const sqlite3_module fts3Module;   /* forward declaration */
93403
93404 /* Return a dynamically generated statement of the form
93405  *   insert into %_content (docid, ...) values (?, ...)
93406  */
93407 static const char *contentInsertStatement(fulltext_vtab *v){
93408   StringBuffer sb;
93409   int i;
93410
93411   initStringBuffer(&sb);
93412   append(&sb, "insert into %_content (docid, ");
93413   appendList(&sb, v->nColumn, v->azContentColumn);
93414   append(&sb, ") values (?");
93415   for(i=0; i<v->nColumn; ++i)
93416     append(&sb, ", ?");
93417   append(&sb, ")");
93418   return stringBufferData(&sb);
93419 }
93420
93421 /* Return a dynamically generated statement of the form
93422  *   select <content columns> from %_content where docid = ?
93423  */
93424 static const char *contentSelectStatement(fulltext_vtab *v){
93425   StringBuffer sb;
93426   initStringBuffer(&sb);
93427   append(&sb, "SELECT ");
93428   appendList(&sb, v->nColumn, v->azContentColumn);
93429   append(&sb, " FROM %_content WHERE docid = ?");
93430   return stringBufferData(&sb);
93431 }
93432
93433 /* Return a dynamically generated statement of the form
93434  *   update %_content set [col_0] = ?, [col_1] = ?, ...
93435  *                    where docid = ?
93436  */
93437 static const char *contentUpdateStatement(fulltext_vtab *v){
93438   StringBuffer sb;
93439   int i;
93440
93441   initStringBuffer(&sb);
93442   append(&sb, "update %_content set ");
93443   for(i=0; i<v->nColumn; ++i) {
93444     if( i>0 ){
93445       append(&sb, ", ");
93446     }
93447     append(&sb, v->azContentColumn[i]);
93448     append(&sb, " = ?");
93449   }
93450   append(&sb, " where docid = ?");
93451   return stringBufferData(&sb);
93452 }
93453
93454 /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
93455 ** If the indicated statement has never been prepared, it is prepared
93456 ** and cached, otherwise the cached version is reset.
93457 */
93458 static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
93459                              sqlite3_stmt **ppStmt){
93460   assert( iStmt<MAX_STMT );
93461   if( v->pFulltextStatements[iStmt]==NULL ){
93462     const char *zStmt;
93463     int rc;
93464     switch( iStmt ){
93465       case CONTENT_INSERT_STMT:
93466         zStmt = contentInsertStatement(v); break;
93467       case CONTENT_SELECT_STMT:
93468         zStmt = contentSelectStatement(v); break;
93469       case CONTENT_UPDATE_STMT:
93470         zStmt = contentUpdateStatement(v); break;
93471       default:
93472         zStmt = fulltext_zStatement[iStmt];
93473     }
93474     rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
93475                          zStmt);
93476     if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
93477     if( rc!=SQLITE_OK ) return rc;
93478   } else {
93479     int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
93480     if( rc!=SQLITE_OK ) return rc;
93481   }
93482
93483   *ppStmt = v->pFulltextStatements[iStmt];
93484   return SQLITE_OK;
93485 }
93486
93487 /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
93488 ** SQLITE_ROW to SQLITE_ERROR.  Useful for statements like UPDATE,
93489 ** where we expect no results.
93490 */
93491 static int sql_single_step(sqlite3_stmt *s){
93492   int rc = sqlite3_step(s);
93493   return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
93494 }
93495
93496 /* Like sql_get_statement(), but for special replicated LEAF_SELECT
93497 ** statements.  idx -1 is a special case for an uncached version of
93498 ** the statement (used in the optimize implementation).
93499 */
93500 /* TODO(shess) Write version for generic statements and then share
93501 ** that between the cached-statement functions.
93502 */
93503 static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
93504                                   sqlite3_stmt **ppStmt){
93505   assert( idx>=-1 && idx<MERGE_COUNT );
93506   if( idx==-1 ){
93507     return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
93508   }else if( v->pLeafSelectStmts[idx]==NULL ){
93509     int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
93510                          LEAF_SELECT);
93511     if( rc!=SQLITE_OK ) return rc;
93512   }else{
93513     int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
93514     if( rc!=SQLITE_OK ) return rc;
93515   }
93516
93517   *ppStmt = v->pLeafSelectStmts[idx];
93518   return SQLITE_OK;
93519 }
93520
93521 /* insert into %_content (docid, ...) values ([docid], [pValues])
93522 ** If the docid contains SQL NULL, then a unique docid will be
93523 ** generated.
93524 */
93525 static int content_insert(fulltext_vtab *v, sqlite3_value *docid,
93526                           sqlite3_value **pValues){
93527   sqlite3_stmt *s;
93528   int i;
93529   int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
93530   if( rc!=SQLITE_OK ) return rc;
93531
93532   rc = sqlite3_bind_value(s, 1, docid);
93533   if( rc!=SQLITE_OK ) return rc;
93534
93535   for(i=0; i<v->nColumn; ++i){
93536     rc = sqlite3_bind_value(s, 2+i, pValues[i]);
93537     if( rc!=SQLITE_OK ) return rc;
93538   }
93539
93540   return sql_single_step(s);
93541 }
93542
93543 /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
93544  *                  where docid = [iDocid] */
93545 static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
93546                           sqlite_int64 iDocid){
93547   sqlite3_stmt *s;
93548   int i;
93549   int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
93550   if( rc!=SQLITE_OK ) return rc;
93551
93552   for(i=0; i<v->nColumn; ++i){
93553     rc = sqlite3_bind_value(s, 1+i, pValues[i]);
93554     if( rc!=SQLITE_OK ) return rc;
93555   }
93556
93557   rc = sqlite3_bind_int64(s, 1+v->nColumn, iDocid);
93558   if( rc!=SQLITE_OK ) return rc;
93559
93560   return sql_single_step(s);
93561 }
93562
93563 static void freeStringArray(int nString, const char **pString){
93564   int i;
93565
93566   for (i=0 ; i < nString ; ++i) {
93567     if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
93568   }
93569   sqlite3_free((void *) pString);
93570 }
93571
93572 /* select * from %_content where docid = [iDocid]
93573  * The caller must delete the returned array and all strings in it.
93574  * null fields will be NULL in the returned array.
93575  *
93576  * TODO: Perhaps we should return pointer/length strings here for consistency
93577  * with other code which uses pointer/length. */
93578 static int content_select(fulltext_vtab *v, sqlite_int64 iDocid,
93579                           const char ***pValues){
93580   sqlite3_stmt *s;
93581   const char **values;
93582   int i;
93583   int rc;
93584
93585   *pValues = NULL;
93586
93587   rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
93588   if( rc!=SQLITE_OK ) return rc;
93589
93590   rc = sqlite3_bind_int64(s, 1, iDocid);
93591   if( rc!=SQLITE_OK ) return rc;
93592
93593   rc = sqlite3_step(s);
93594   if( rc!=SQLITE_ROW ) return rc;
93595
93596   values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
93597   for(i=0; i<v->nColumn; ++i){
93598     if( sqlite3_column_type(s, i)==SQLITE_NULL ){
93599       values[i] = NULL;
93600     }else{
93601       values[i] = string_dup((char*)sqlite3_column_text(s, i));
93602     }
93603   }
93604
93605   /* We expect only one row.  We must execute another sqlite3_step()
93606    * to complete the iteration; otherwise the table will remain locked. */
93607   rc = sqlite3_step(s);
93608   if( rc==SQLITE_DONE ){
93609     *pValues = values;
93610     return SQLITE_OK;
93611   }
93612
93613   freeStringArray(v->nColumn, values);
93614   return rc;
93615 }
93616
93617 /* delete from %_content where docid = [iDocid ] */
93618 static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){
93619   sqlite3_stmt *s;
93620   int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
93621   if( rc!=SQLITE_OK ) return rc;
93622
93623   rc = sqlite3_bind_int64(s, 1, iDocid);
93624   if( rc!=SQLITE_OK ) return rc;
93625
93626   return sql_single_step(s);
93627 }
93628
93629 /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
93630 ** no rows exist, and any error in case of failure.
93631 */
93632 static int content_exists(fulltext_vtab *v){
93633   sqlite3_stmt *s;
93634   int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
93635   if( rc!=SQLITE_OK ) return rc;
93636
93637   rc = sqlite3_step(s);
93638   if( rc!=SQLITE_ROW ) return rc;
93639
93640   /* We expect only one row.  We must execute another sqlite3_step()
93641    * to complete the iteration; otherwise the table will remain locked. */
93642   rc = sqlite3_step(s);
93643   if( rc==SQLITE_DONE ) return SQLITE_ROW;
93644   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93645   return rc;
93646 }
93647
93648 /* insert into %_segments values ([pData])
93649 **   returns assigned blockid in *piBlockid
93650 */
93651 static int block_insert(fulltext_vtab *v, const char *pData, int nData,
93652                         sqlite_int64 *piBlockid){
93653   sqlite3_stmt *s;
93654   int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
93655   if( rc!=SQLITE_OK ) return rc;
93656
93657   rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
93658   if( rc!=SQLITE_OK ) return rc;
93659
93660   rc = sqlite3_step(s);
93661   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93662   if( rc!=SQLITE_DONE ) return rc;
93663
93664   /* blockid column is an alias for rowid. */
93665   *piBlockid = sqlite3_last_insert_rowid(v->db);
93666   return SQLITE_OK;
93667 }
93668
93669 /* delete from %_segments
93670 **   where blockid between [iStartBlockid] and [iEndBlockid]
93671 **
93672 ** Deletes the range of blocks, inclusive, used to delete the blocks
93673 ** which form a segment.
93674 */
93675 static int block_delete(fulltext_vtab *v,
93676                         sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
93677   sqlite3_stmt *s;
93678   int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
93679   if( rc!=SQLITE_OK ) return rc;
93680
93681   rc = sqlite3_bind_int64(s, 1, iStartBlockid);
93682   if( rc!=SQLITE_OK ) return rc;
93683
93684   rc = sqlite3_bind_int64(s, 2, iEndBlockid);
93685   if( rc!=SQLITE_OK ) return rc;
93686
93687   return sql_single_step(s);
93688 }
93689
93690 /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
93691 ** at iLevel.  Returns SQLITE_DONE if there are no segments at
93692 ** iLevel.  Otherwise returns an error.
93693 */
93694 static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
93695   sqlite3_stmt *s;
93696   int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
93697   if( rc!=SQLITE_OK ) return rc;
93698
93699   rc = sqlite3_bind_int(s, 1, iLevel);
93700   if( rc!=SQLITE_OK ) return rc;
93701
93702   rc = sqlite3_step(s);
93703   /* Should always get at least one row due to how max() works. */
93704   if( rc==SQLITE_DONE ) return SQLITE_DONE;
93705   if( rc!=SQLITE_ROW ) return rc;
93706
93707   /* NULL means that there were no inputs to max(). */
93708   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
93709     rc = sqlite3_step(s);
93710     if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93711     return rc;
93712   }
93713
93714   *pidx = sqlite3_column_int(s, 0);
93715
93716   /* We expect only one row.  We must execute another sqlite3_step()
93717    * to complete the iteration; otherwise the table will remain locked. */
93718   rc = sqlite3_step(s);
93719   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93720   if( rc!=SQLITE_DONE ) return rc;
93721   return SQLITE_ROW;
93722 }
93723
93724 /* insert into %_segdir values (
93725 **   [iLevel], [idx],
93726 **   [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
93727 **   [pRootData]
93728 ** )
93729 */
93730 static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
93731                       sqlite_int64 iStartBlockid,
93732                       sqlite_int64 iLeavesEndBlockid,
93733                       sqlite_int64 iEndBlockid,
93734                       const char *pRootData, int nRootData){
93735   sqlite3_stmt *s;
93736   int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
93737   if( rc!=SQLITE_OK ) return rc;
93738
93739   rc = sqlite3_bind_int(s, 1, iLevel);
93740   if( rc!=SQLITE_OK ) return rc;
93741
93742   rc = sqlite3_bind_int(s, 2, idx);
93743   if( rc!=SQLITE_OK ) return rc;
93744
93745   rc = sqlite3_bind_int64(s, 3, iStartBlockid);
93746   if( rc!=SQLITE_OK ) return rc;
93747
93748   rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
93749   if( rc!=SQLITE_OK ) return rc;
93750
93751   rc = sqlite3_bind_int64(s, 5, iEndBlockid);
93752   if( rc!=SQLITE_OK ) return rc;
93753
93754   rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
93755   if( rc!=SQLITE_OK ) return rc;
93756
93757   return sql_single_step(s);
93758 }
93759
93760 /* Queries %_segdir for the block span of the segments in level
93761 ** iLevel.  Returns SQLITE_DONE if there are no blocks for iLevel,
93762 ** SQLITE_ROW if there are blocks, else an error.
93763 */
93764 static int segdir_span(fulltext_vtab *v, int iLevel,
93765                        sqlite_int64 *piStartBlockid,
93766                        sqlite_int64 *piEndBlockid){
93767   sqlite3_stmt *s;
93768   int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
93769   if( rc!=SQLITE_OK ) return rc;
93770
93771   rc = sqlite3_bind_int(s, 1, iLevel);
93772   if( rc!=SQLITE_OK ) return rc;
93773
93774   rc = sqlite3_step(s);
93775   if( rc==SQLITE_DONE ) return SQLITE_DONE;  /* Should never happen */
93776   if( rc!=SQLITE_ROW ) return rc;
93777
93778   /* This happens if all segments at this level are entirely inline. */
93779   if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
93780     /* We expect only one row.  We must execute another sqlite3_step()
93781      * to complete the iteration; otherwise the table will remain locked. */
93782     int rc2 = sqlite3_step(s);
93783     if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
93784     return rc2;
93785   }
93786
93787   *piStartBlockid = sqlite3_column_int64(s, 0);
93788   *piEndBlockid = sqlite3_column_int64(s, 1);
93789
93790   /* We expect only one row.  We must execute another sqlite3_step()
93791    * to complete the iteration; otherwise the table will remain locked. */
93792   rc = sqlite3_step(s);
93793   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93794   if( rc!=SQLITE_DONE ) return rc;
93795   return SQLITE_ROW;
93796 }
93797
93798 /* Delete the segment blocks and segment directory records for all
93799 ** segments at iLevel.
93800 */
93801 static int segdir_delete(fulltext_vtab *v, int iLevel){
93802   sqlite3_stmt *s;
93803   sqlite_int64 iStartBlockid, iEndBlockid;
93804   int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
93805   if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
93806
93807   if( rc==SQLITE_ROW ){
93808     rc = block_delete(v, iStartBlockid, iEndBlockid);
93809     if( rc!=SQLITE_OK ) return rc;
93810   }
93811
93812   /* Delete the segment directory itself. */
93813   rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
93814   if( rc!=SQLITE_OK ) return rc;
93815
93816   rc = sqlite3_bind_int64(s, 1, iLevel);
93817   if( rc!=SQLITE_OK ) return rc;
93818
93819   return sql_single_step(s);
93820 }
93821
93822 /* Delete entire fts index, SQLITE_OK on success, relevant error on
93823 ** failure.
93824 */
93825 static int segdir_delete_all(fulltext_vtab *v){
93826   sqlite3_stmt *s;
93827   int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
93828   if( rc!=SQLITE_OK ) return rc;
93829
93830   rc = sql_single_step(s);
93831   if( rc!=SQLITE_OK ) return rc;
93832
93833   rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
93834   if( rc!=SQLITE_OK ) return rc;
93835
93836   return sql_single_step(s);
93837 }
93838
93839 /* Returns SQLITE_OK with *pnSegments set to the number of entries in
93840 ** %_segdir and *piMaxLevel set to the highest level which has a
93841 ** segment.  Otherwise returns the SQLite error which caused failure.
93842 */
93843 static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
93844   sqlite3_stmt *s;
93845   int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
93846   if( rc!=SQLITE_OK ) return rc;
93847
93848   rc = sqlite3_step(s);
93849   /* TODO(shess): This case should not be possible?  Should stronger
93850   ** measures be taken if it happens?
93851   */
93852   if( rc==SQLITE_DONE ){
93853     *pnSegments = 0;
93854     *piMaxLevel = 0;
93855     return SQLITE_OK;
93856   }
93857   if( rc!=SQLITE_ROW ) return rc;
93858
93859   *pnSegments = sqlite3_column_int(s, 0);
93860   *piMaxLevel = sqlite3_column_int(s, 1);
93861
93862   /* We expect only one row.  We must execute another sqlite3_step()
93863    * to complete the iteration; otherwise the table will remain locked. */
93864   rc = sqlite3_step(s);
93865   if( rc==SQLITE_DONE ) return SQLITE_OK;
93866   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
93867   return rc;
93868 }
93869
93870 /* TODO(shess) clearPendingTerms() is far down the file because
93871 ** writeZeroSegment() is far down the file because LeafWriter is far
93872 ** down the file.  Consider refactoring the code to move the non-vtab
93873 ** code above the vtab code so that we don't need this forward
93874 ** reference.
93875 */
93876 static int clearPendingTerms(fulltext_vtab *v);
93877
93878 /*
93879 ** Free the memory used to contain a fulltext_vtab structure.
93880 */
93881 static void fulltext_vtab_destroy(fulltext_vtab *v){
93882   int iStmt, i;
93883
93884   FTSTRACE(("FTS3 Destroy %p\n", v));
93885   for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
93886     if( v->pFulltextStatements[iStmt]!=NULL ){
93887       sqlite3_finalize(v->pFulltextStatements[iStmt]);
93888       v->pFulltextStatements[iStmt] = NULL;
93889     }
93890   }
93891
93892   for( i=0; i<MERGE_COUNT; i++ ){
93893     if( v->pLeafSelectStmts[i]!=NULL ){
93894       sqlite3_finalize(v->pLeafSelectStmts[i]);
93895       v->pLeafSelectStmts[i] = NULL;
93896     }
93897   }
93898
93899   if( v->pTokenizer!=NULL ){
93900     v->pTokenizer->pModule->xDestroy(v->pTokenizer);
93901     v->pTokenizer = NULL;
93902   }
93903
93904   clearPendingTerms(v);
93905
93906   sqlite3_free(v->azColumn);
93907   for(i = 0; i < v->nColumn; ++i) {
93908     sqlite3_free(v->azContentColumn[i]);
93909   }
93910   sqlite3_free(v->azContentColumn);
93911   sqlite3_free(v);
93912 }
93913
93914 /*
93915 ** Token types for parsing the arguments to xConnect or xCreate.
93916 */
93917 #define TOKEN_EOF         0    /* End of file */
93918 #define TOKEN_SPACE       1    /* Any kind of whitespace */
93919 #define TOKEN_ID          2    /* An identifier */
93920 #define TOKEN_STRING      3    /* A string literal */
93921 #define TOKEN_PUNCT       4    /* A single punctuation character */
93922
93923 /*
93924 ** If X is a character that can be used in an identifier then
93925 ** ftsIdChar(X) will be true.  Otherwise it is false.
93926 **
93927 ** For ASCII, any character with the high-order bit set is
93928 ** allowed in an identifier.  For 7-bit characters, 
93929 ** isFtsIdChar[X] must be 1.
93930 **
93931 ** Ticket #1066.  the SQL standard does not allow '$' in the
93932 ** middle of identfiers.  But many SQL implementations do. 
93933 ** SQLite will allow '$' in identifiers for compatibility.
93934 ** But the feature is undocumented.
93935 */
93936 static const char isFtsIdChar[] = {
93937 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
93938     0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
93939     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
93940     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
93941     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
93942     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
93943     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
93944 };
93945 #define ftsIdChar(C)  (((c=C)&0x80)!=0 || (c>0x1f && isFtsIdChar[c-0x20]))
93946
93947
93948 /*
93949 ** Return the length of the token that begins at z[0]. 
93950 ** Store the token type in *tokenType before returning.
93951 */
93952 static int ftsGetToken(const char *z, int *tokenType){
93953   int i, c;
93954   switch( *z ){
93955     case 0: {
93956       *tokenType = TOKEN_EOF;
93957       return 0;
93958     }
93959     case ' ': case '\t': case '\n': case '\f': case '\r': {
93960       for(i=1; safe_isspace(z[i]); i++){}
93961       *tokenType = TOKEN_SPACE;
93962       return i;
93963     }
93964     case '`':
93965     case '\'':
93966     case '"': {
93967       int delim = z[0];
93968       for(i=1; (c=z[i])!=0; i++){
93969         if( c==delim ){
93970           if( z[i+1]==delim ){
93971             i++;
93972           }else{
93973             break;
93974           }
93975         }
93976       }
93977       *tokenType = TOKEN_STRING;
93978       return i + (c!=0);
93979     }
93980     case '[': {
93981       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
93982       *tokenType = TOKEN_ID;
93983       return i;
93984     }
93985     default: {
93986       if( !ftsIdChar(*z) ){
93987         break;
93988       }
93989       for(i=1; ftsIdChar(z[i]); i++){}
93990       *tokenType = TOKEN_ID;
93991       return i;
93992     }
93993   }
93994   *tokenType = TOKEN_PUNCT;
93995   return 1;
93996 }
93997
93998 /*
93999 ** A token extracted from a string is an instance of the following
94000 ** structure.
94001 */
94002 typedef struct FtsToken {
94003   const char *z;       /* Pointer to token text.  Not '\000' terminated */
94004   short int n;         /* Length of the token text in bytes. */
94005 } FtsToken;
94006
94007 /*
94008 ** Given a input string (which is really one of the argv[] parameters
94009 ** passed into xConnect or xCreate) split the string up into tokens.
94010 ** Return an array of pointers to '\000' terminated strings, one string
94011 ** for each non-whitespace token.
94012 **
94013 ** The returned array is terminated by a single NULL pointer.
94014 **
94015 ** Space to hold the returned array is obtained from a single
94016 ** malloc and should be freed by passing the return value to free().
94017 ** The individual strings within the token list are all a part of
94018 ** the single memory allocation and will all be freed at once.
94019 */
94020 static char **tokenizeString(const char *z, int *pnToken){
94021   int nToken = 0;
94022   FtsToken *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
94023   int n = 1;
94024   int e, i;
94025   int totalSize = 0;
94026   char **azToken;
94027   char *zCopy;
94028   while( n>0 ){
94029     n = ftsGetToken(z, &e);
94030     if( e!=TOKEN_SPACE ){
94031       aToken[nToken].z = z;
94032       aToken[nToken].n = n;
94033       nToken++;
94034       totalSize += n+1;
94035     }
94036     z += n;
94037   }
94038   azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
94039   zCopy = (char*)&azToken[nToken];
94040   nToken--;
94041   for(i=0; i<nToken; i++){
94042     azToken[i] = zCopy;
94043     n = aToken[i].n;
94044     memcpy(zCopy, aToken[i].z, n);
94045     zCopy[n] = 0;
94046     zCopy += n+1;
94047   }
94048   azToken[nToken] = 0;
94049   sqlite3_free(aToken);
94050   *pnToken = nToken;
94051   return azToken;
94052 }
94053
94054 /*
94055 ** Convert an SQL-style quoted string into a normal string by removing
94056 ** the quote characters.  The conversion is done in-place.  If the
94057 ** input does not begin with a quote character, then this routine
94058 ** is a no-op.
94059 **
94060 ** Examples:
94061 **
94062 **     "abc"   becomes   abc
94063 **     'xyz'   becomes   xyz
94064 **     [pqr]   becomes   pqr
94065 **     `mno`   becomes   mno
94066 */
94067 static void dequoteString(char *z){
94068   int quote;
94069   int i, j;
94070   if( z==0 ) return;
94071   quote = z[0];
94072   switch( quote ){
94073     case '\'':  break;
94074     case '"':   break;
94075     case '`':   break;                /* For MySQL compatibility */
94076     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
94077     default:    return;
94078   }
94079   for(i=1, j=0; z[i]; i++){
94080     if( z[i]==quote ){
94081       if( z[i+1]==quote ){
94082         z[j++] = quote;
94083         i++;
94084       }else{
94085         z[j++] = 0;
94086         break;
94087       }
94088     }else{
94089       z[j++] = z[i];
94090     }
94091   }
94092 }
94093
94094 /*
94095 ** The input azIn is a NULL-terminated list of tokens.  Remove the first
94096 ** token and all punctuation tokens.  Remove the quotes from
94097 ** around string literal tokens.
94098 **
94099 ** Example:
94100 **
94101 **     input:      tokenize chinese ( 'simplifed' , 'mixed' )
94102 **     output:     chinese simplifed mixed
94103 **
94104 ** Another example:
94105 **
94106 **     input:      delimiters ( '[' , ']' , '...' )
94107 **     output:     [ ] ...
94108 */
94109 static void tokenListToIdList(char **azIn){
94110   int i, j;
94111   if( azIn ){
94112     for(i=0, j=-1; azIn[i]; i++){
94113       if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
94114         dequoteString(azIn[i]);
94115         if( j>=0 ){
94116           azIn[j] = azIn[i];
94117         }
94118         j++;
94119       }
94120     }
94121     azIn[j] = 0;
94122   }
94123 }
94124
94125
94126 /*
94127 ** Find the first alphanumeric token in the string zIn.  Null-terminate
94128 ** this token.  Remove any quotation marks.  And return a pointer to
94129 ** the result.
94130 */
94131 static char *firstToken(char *zIn, char **pzTail){
94132   int n, ttype;
94133   while(1){
94134     n = ftsGetToken(zIn, &ttype);
94135     if( ttype==TOKEN_SPACE ){
94136       zIn += n;
94137     }else if( ttype==TOKEN_EOF ){
94138       *pzTail = zIn;
94139       return 0;
94140     }else{
94141       zIn[n] = 0;
94142       *pzTail = &zIn[1];
94143       dequoteString(zIn);
94144       return zIn;
94145     }
94146   }
94147   /*NOTREACHED*/
94148 }
94149
94150 /* Return true if...
94151 **
94152 **   *  s begins with the string t, ignoring case
94153 **   *  s is longer than t
94154 **   *  The first character of s beyond t is not a alphanumeric
94155 ** 
94156 ** Ignore leading space in *s.
94157 **
94158 ** To put it another way, return true if the first token of
94159 ** s[] is t[].
94160 */
94161 static int startsWith(const char *s, const char *t){
94162   while( safe_isspace(*s) ){ s++; }
94163   while( *t ){
94164     if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
94165   }
94166   return *s!='_' && !safe_isalnum(*s);
94167 }
94168
94169 /*
94170 ** An instance of this structure defines the "spec" of a
94171 ** full text index.  This structure is populated by parseSpec
94172 ** and use by fulltextConnect and fulltextCreate.
94173 */
94174 typedef struct TableSpec {
94175   const char *zDb;         /* Logical database name */
94176   const char *zName;       /* Name of the full-text index */
94177   int nColumn;             /* Number of columns to be indexed */
94178   char **azColumn;         /* Original names of columns to be indexed */
94179   char **azContentColumn;  /* Column names for %_content */
94180   char **azTokenizer;      /* Name of tokenizer and its arguments */
94181 } TableSpec;
94182
94183 /*
94184 ** Reclaim all of the memory used by a TableSpec
94185 */
94186 static void clearTableSpec(TableSpec *p) {
94187   sqlite3_free(p->azColumn);
94188   sqlite3_free(p->azContentColumn);
94189   sqlite3_free(p->azTokenizer);
94190 }
94191
94192 /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
94193  *
94194  * CREATE VIRTUAL TABLE email
94195  *        USING fts3(subject, body, tokenize mytokenizer(myarg))
94196  *
94197  * We return parsed information in a TableSpec structure.
94198  * 
94199  */
94200 static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
94201                      char**pzErr){
94202   int i, n;
94203   char *z, *zDummy;
94204   char **azArg;
94205   const char *zTokenizer = 0;    /* argv[] entry describing the tokenizer */
94206
94207   assert( argc>=3 );
94208   /* Current interface:
94209   ** argv[0] - module name
94210   ** argv[1] - database name
94211   ** argv[2] - table name
94212   ** argv[3..] - columns, optionally followed by tokenizer specification
94213   **             and snippet delimiters specification.
94214   */
94215
94216   /* Make a copy of the complete argv[][] array in a single allocation.
94217   ** The argv[][] array is read-only and transient.  We can write to the
94218   ** copy in order to modify things and the copy is persistent.
94219   */
94220   CLEAR(pSpec);
94221   for(i=n=0; i<argc; i++){
94222     n += strlen(argv[i]) + 1;
94223   }
94224   azArg = sqlite3_malloc( sizeof(char*)*argc + n );
94225   if( azArg==0 ){
94226     return SQLITE_NOMEM;
94227   }
94228   z = (char*)&azArg[argc];
94229   for(i=0; i<argc; i++){
94230     azArg[i] = z;
94231     strcpy(z, argv[i]);
94232     z += strlen(z)+1;
94233   }
94234
94235   /* Identify the column names and the tokenizer and delimiter arguments
94236   ** in the argv[][] array.
94237   */
94238   pSpec->zDb = azArg[1];
94239   pSpec->zName = azArg[2];
94240   pSpec->nColumn = 0;
94241   pSpec->azColumn = azArg;
94242   zTokenizer = "tokenize simple";
94243   for(i=3; i<argc; ++i){
94244     if( startsWith(azArg[i],"tokenize") ){
94245       zTokenizer = azArg[i];
94246     }else{
94247       z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
94248       pSpec->nColumn++;
94249     }
94250   }
94251   if( pSpec->nColumn==0 ){
94252     azArg[0] = "content";
94253     pSpec->nColumn = 1;
94254   }
94255
94256   /*
94257   ** Construct the list of content column names.
94258   **
94259   ** Each content column name will be of the form cNNAAAA
94260   ** where NN is the column number and AAAA is the sanitized
94261   ** column name.  "sanitized" means that special characters are
94262   ** converted to "_".  The cNN prefix guarantees that all column
94263   ** names are unique.
94264   **
94265   ** The AAAA suffix is not strictly necessary.  It is included
94266   ** for the convenience of people who might examine the generated
94267   ** %_content table and wonder what the columns are used for.
94268   */
94269   pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
94270   if( pSpec->azContentColumn==0 ){
94271     clearTableSpec(pSpec);
94272     return SQLITE_NOMEM;
94273   }
94274   for(i=0; i<pSpec->nColumn; i++){
94275     char *p;
94276     pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
94277     for (p = pSpec->azContentColumn[i]; *p ; ++p) {
94278       if( !safe_isalnum(*p) ) *p = '_';
94279     }
94280   }
94281
94282   /*
94283   ** Parse the tokenizer specification string.
94284   */
94285   pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
94286   tokenListToIdList(pSpec->azTokenizer);
94287
94288   return SQLITE_OK;
94289 }
94290
94291 /*
94292 ** Generate a CREATE TABLE statement that describes the schema of
94293 ** the virtual table.  Return a pointer to this schema string.
94294 **
94295 ** Space is obtained from sqlite3_mprintf() and should be freed
94296 ** using sqlite3_free().
94297 */
94298 static char *fulltextSchema(
94299   int nColumn,                  /* Number of columns */
94300   const char *const* azColumn,  /* List of columns */
94301   const char *zTableName        /* Name of the table */
94302 ){
94303   int i;
94304   char *zSchema, *zNext;
94305   const char *zSep = "(";
94306   zSchema = sqlite3_mprintf("CREATE TABLE x");
94307   for(i=0; i<nColumn; i++){
94308     zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
94309     sqlite3_free(zSchema);
94310     zSchema = zNext;
94311     zSep = ",";
94312   }
94313   zNext = sqlite3_mprintf("%s,%Q HIDDEN", zSchema, zTableName);
94314   sqlite3_free(zSchema);
94315   zSchema = zNext;
94316   zNext = sqlite3_mprintf("%s,docid HIDDEN)", zSchema);
94317   sqlite3_free(zSchema);
94318   return zNext;
94319 }
94320
94321 /*
94322 ** Build a new sqlite3_vtab structure that will describe the
94323 ** fulltext index defined by spec.
94324 */
94325 static int constructVtab(
94326   sqlite3 *db,              /* The SQLite database connection */
94327   fts3Hash *pHash,          /* Hash table containing tokenizers */
94328   TableSpec *spec,          /* Parsed spec information from parseSpec() */
94329   sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
94330   char **pzErr              /* Write any error message here */
94331 ){
94332   int rc;
94333   int n;
94334   fulltext_vtab *v = 0;
94335   const sqlite3_tokenizer_module *m = NULL;
94336   char *schema;
94337
94338   char const *zTok;         /* Name of tokenizer to use for this fts table */
94339   int nTok;                 /* Length of zTok, including nul terminator */
94340
94341   v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
94342   if( v==0 ) return SQLITE_NOMEM;
94343   CLEAR(v);
94344   /* sqlite will initialize v->base */
94345   v->db = db;
94346   v->zDb = spec->zDb;       /* Freed when azColumn is freed */
94347   v->zName = spec->zName;   /* Freed when azColumn is freed */
94348   v->nColumn = spec->nColumn;
94349   v->azContentColumn = spec->azContentColumn;
94350   spec->azContentColumn = 0;
94351   v->azColumn = spec->azColumn;
94352   spec->azColumn = 0;
94353
94354   if( spec->azTokenizer==0 ){
94355     return SQLITE_NOMEM;
94356   }
94357
94358   zTok = spec->azTokenizer[0]; 
94359   if( !zTok ){
94360     zTok = "simple";
94361   }
94362   nTok = strlen(zTok)+1;
94363
94364   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zTok, nTok);
94365   if( !m ){
94366     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
94367     rc = SQLITE_ERROR;
94368     goto err;
94369   }
94370
94371   for(n=0; spec->azTokenizer[n]; n++){}
94372   if( n ){
94373     rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
94374                     &v->pTokenizer);
94375   }else{
94376     rc = m->xCreate(0, 0, &v->pTokenizer);
94377   }
94378   if( rc!=SQLITE_OK ) goto err;
94379   v->pTokenizer->pModule = m;
94380
94381   /* TODO: verify the existence of backing tables foo_content, foo_term */
94382
94383   schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
94384                           spec->zName);
94385   rc = sqlite3_declare_vtab(db, schema);
94386   sqlite3_free(schema);
94387   if( rc!=SQLITE_OK ) goto err;
94388
94389   memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
94390
94391   /* Indicate that the buffer is not live. */
94392   v->nPendingData = -1;
94393
94394   *ppVTab = &v->base;
94395   FTSTRACE(("FTS3 Connect %p\n", v));
94396
94397   return rc;
94398
94399 err:
94400   fulltext_vtab_destroy(v);
94401   return rc;
94402 }
94403
94404 static int fulltextConnect(
94405   sqlite3 *db,
94406   void *pAux,
94407   int argc, const char *const*argv,
94408   sqlite3_vtab **ppVTab,
94409   char **pzErr
94410 ){
94411   TableSpec spec;
94412   int rc = parseSpec(&spec, argc, argv, pzErr);
94413   if( rc!=SQLITE_OK ) return rc;
94414
94415   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
94416   clearTableSpec(&spec);
94417   return rc;
94418 }
94419
94420 /* The %_content table holds the text of each document, with
94421 ** the docid column exposed as the SQLite rowid for the table.
94422 */
94423 /* TODO(shess) This comment needs elaboration to match the updated
94424 ** code.  Work it into the top-of-file comment at that time.
94425 */
94426 static int fulltextCreate(sqlite3 *db, void *pAux,
94427                           int argc, const char * const *argv,
94428                           sqlite3_vtab **ppVTab, char **pzErr){
94429   int rc;
94430   TableSpec spec;
94431   StringBuffer schema;
94432   FTSTRACE(("FTS3 Create\n"));
94433
94434   rc = parseSpec(&spec, argc, argv, pzErr);
94435   if( rc!=SQLITE_OK ) return rc;
94436
94437   initStringBuffer(&schema);
94438   append(&schema, "CREATE TABLE %_content(");
94439   append(&schema, "  docid INTEGER PRIMARY KEY,");
94440   appendList(&schema, spec.nColumn, spec.azContentColumn);
94441   append(&schema, ")");
94442   rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
94443   stringBufferDestroy(&schema);
94444   if( rc!=SQLITE_OK ) goto out;
94445
94446   rc = sql_exec(db, spec.zDb, spec.zName,
94447                 "create table %_segments("
94448                 "  blockid INTEGER PRIMARY KEY,"
94449                 "  block blob"
94450                 ");"
94451                 );
94452   if( rc!=SQLITE_OK ) goto out;
94453
94454   rc = sql_exec(db, spec.zDb, spec.zName,
94455                 "create table %_segdir("
94456                 "  level integer,"
94457                 "  idx integer,"
94458                 "  start_block integer,"
94459                 "  leaves_end_block integer,"
94460                 "  end_block integer,"
94461                 "  root blob,"
94462                 "  primary key(level, idx)"
94463                 ");");
94464   if( rc!=SQLITE_OK ) goto out;
94465
94466   rc = constructVtab(db, (fts3Hash *)pAux, &spec, ppVTab, pzErr);
94467
94468 out:
94469   clearTableSpec(&spec);
94470   return rc;
94471 }
94472
94473 /* Decide how to handle an SQL query. */
94474 static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
94475   fulltext_vtab *v = (fulltext_vtab *)pVTab;
94476   int i;
94477   FTSTRACE(("FTS3 BestIndex\n"));
94478
94479   for(i=0; i<pInfo->nConstraint; ++i){
94480     const struct sqlite3_index_constraint *pConstraint;
94481     pConstraint = &pInfo->aConstraint[i];
94482     if( pConstraint->usable ) {
94483       if( (pConstraint->iColumn==-1 || pConstraint->iColumn==v->nColumn+1) &&
94484           pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
94485         pInfo->idxNum = QUERY_DOCID;      /* lookup by docid */
94486         FTSTRACE(("FTS3 QUERY_DOCID\n"));
94487       } else if( pConstraint->iColumn>=0 && pConstraint->iColumn<=v->nColumn &&
94488                  pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
94489         /* full-text search */
94490         pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
94491         FTSTRACE(("FTS3 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
94492       } else continue;
94493
94494       pInfo->aConstraintUsage[i].argvIndex = 1;
94495       pInfo->aConstraintUsage[i].omit = 1;
94496
94497       /* An arbitrary value for now.
94498        * TODO: Perhaps docid matches should be considered cheaper than
94499        * full-text searches. */
94500       pInfo->estimatedCost = 1.0;   
94501
94502       return SQLITE_OK;
94503     }
94504   }
94505   pInfo->idxNum = QUERY_GENERIC;
94506   return SQLITE_OK;
94507 }
94508
94509 static int fulltextDisconnect(sqlite3_vtab *pVTab){
94510   FTSTRACE(("FTS3 Disconnect %p\n", pVTab));
94511   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
94512   return SQLITE_OK;
94513 }
94514
94515 static int fulltextDestroy(sqlite3_vtab *pVTab){
94516   fulltext_vtab *v = (fulltext_vtab *)pVTab;
94517   int rc;
94518
94519   FTSTRACE(("FTS3 Destroy %p\n", pVTab));
94520   rc = sql_exec(v->db, v->zDb, v->zName,
94521                 "drop table if exists %_content;"
94522                 "drop table if exists %_segments;"
94523                 "drop table if exists %_segdir;"
94524                 );
94525   if( rc!=SQLITE_OK ) return rc;
94526
94527   fulltext_vtab_destroy((fulltext_vtab *)pVTab);
94528   return SQLITE_OK;
94529 }
94530
94531 static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
94532   fulltext_cursor *c;
94533
94534   c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
94535   if( c ){
94536     memset(c, 0, sizeof(fulltext_cursor));
94537     /* sqlite will initialize c->base */
94538     *ppCursor = &c->base;
94539     FTSTRACE(("FTS3 Open %p: %p\n", pVTab, c));
94540     return SQLITE_OK;
94541   }else{
94542     return SQLITE_NOMEM;
94543   }
94544 }
94545
94546 /* Free all of the dynamically allocated memory held by the
94547 ** Snippet
94548 */
94549 static void snippetClear(Snippet *p){
94550   sqlite3_free(p->aMatch);
94551   sqlite3_free(p->zOffset);
94552   sqlite3_free(p->zSnippet);
94553   CLEAR(p);
94554 }
94555
94556 /*
94557 ** Append a single entry to the p->aMatch[] log.
94558 */
94559 static void snippetAppendMatch(
94560   Snippet *p,               /* Append the entry to this snippet */
94561   int iCol, int iTerm,      /* The column and query term */
94562   int iToken,               /* Matching token in document */
94563   int iStart, int nByte     /* Offset and size of the match */
94564 ){
94565   int i;
94566   struct snippetMatch *pMatch;
94567   if( p->nMatch+1>=p->nAlloc ){
94568     p->nAlloc = p->nAlloc*2 + 10;
94569     p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
94570     if( p->aMatch==0 ){
94571       p->nMatch = 0;
94572       p->nAlloc = 0;
94573       return;
94574     }
94575   }
94576   i = p->nMatch++;
94577   pMatch = &p->aMatch[i];
94578   pMatch->iCol = iCol;
94579   pMatch->iTerm = iTerm;
94580   pMatch->iToken = iToken;
94581   pMatch->iStart = iStart;
94582   pMatch->nByte = nByte;
94583 }
94584
94585 /*
94586 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
94587 */
94588 #define FTS3_ROTOR_SZ   (32)
94589 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
94590
94591 /*
94592 ** Function to iterate through the tokens of a compiled expression.
94593 **
94594 ** Except, skip all tokens on the right-hand side of a NOT operator.
94595 ** This function is used to find tokens as part of snippet and offset
94596 ** generation and we do nt want snippets and offsets to report matches
94597 ** for tokens on the RHS of a NOT.
94598 */
94599 static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
94600   Fts3Expr *p = *ppExpr;
94601   int iToken = *piToken;
94602   if( iToken<0 ){
94603     /* In this case the expression p is the root of an expression tree.
94604     ** Move to the first token in the expression tree.
94605     */
94606     while( p->pLeft ){
94607       p = p->pLeft;
94608     }
94609     iToken = 0;
94610   }else{
94611     assert(p && p->eType==FTSQUERY_PHRASE );
94612     if( iToken<(p->pPhrase->nToken-1) ){
94613       iToken++;
94614     }else{
94615       iToken = 0;
94616       while( p->pParent && p->pParent->pLeft!=p ){
94617         assert( p->pParent->pRight==p );
94618         p = p->pParent;
94619       }
94620       p = p->pParent;
94621       if( p ){
94622         assert( p->pRight!=0 );
94623         p = p->pRight;
94624         while( p->pLeft ){
94625           p = p->pLeft;
94626         }
94627       }
94628     }
94629   }
94630
94631   *ppExpr = p;
94632   *piToken = iToken;
94633   return p?1:0;
94634 }
94635
94636 /*
94637 ** Return TRUE if the expression node pExpr is located beneath the
94638 ** RHS of a NOT operator.
94639 */
94640 static int fts3ExprBeneathNot(Fts3Expr *p){
94641   Fts3Expr *pParent;
94642   while( p ){
94643     pParent = p->pParent;
94644     if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
94645       return 1;
94646     }
94647     p = pParent;
94648   }
94649   return 0;
94650 }
94651
94652 /*
94653 ** Add entries to pSnippet->aMatch[] for every match that occurs against
94654 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
94655 */
94656 static void snippetOffsetsOfColumn(
94657   fulltext_cursor *pCur,         /* The fulltest search cursor */
94658   Snippet *pSnippet,             /* The Snippet object to be filled in */
94659   int iColumn,                   /* Index of fulltext table column */
94660   const char *zDoc,              /* Text of the fulltext table column */
94661   int nDoc                       /* Length of zDoc in bytes */
94662 ){
94663   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
94664   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
94665   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
94666   fulltext_vtab *pVtab;                /* The full text index */
94667   int nColumn;                         /* Number of columns in the index */
94668   int i, j;                            /* Loop counters */
94669   int rc;                              /* Return code */
94670   unsigned int match, prevMatch;       /* Phrase search bitmasks */
94671   const char *zToken;                  /* Next token from the tokenizer */
94672   int nToken;                          /* Size of zToken */
94673   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
94674
94675   /* The following variables keep a circular buffer of the last
94676   ** few tokens */
94677   unsigned int iRotor = 0;             /* Index of current token */
94678   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
94679   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
94680
94681   pVtab = cursor_vtab(pCur);
94682   nColumn = pVtab->nColumn;
94683   pTokenizer = pVtab->pTokenizer;
94684   pTModule = pTokenizer->pModule;
94685   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
94686   if( rc ) return;
94687   pTCursor->pTokenizer = pTokenizer;
94688
94689   prevMatch = 0;
94690   while( !pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos) ){
94691     Fts3Expr *pIter = pCur->pExpr;
94692     int iIter = -1;
94693     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
94694     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
94695     match = 0;
94696     for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
94697       int nPhrase;                    /* Number of tokens in current phrase */
94698       struct PhraseToken *pToken;     /* Current token */
94699       int iCol;                       /* Column index */
94700
94701       if( fts3ExprBeneathNot(pIter) ) continue;
94702       nPhrase = pIter->pPhrase->nToken;
94703       pToken = &pIter->pPhrase->aToken[iIter];
94704       iCol = pIter->pPhrase->iColumn;
94705       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
94706       if( pToken->n>nToken ) continue;
94707       if( !pToken->isPrefix && pToken->n<nToken ) continue;
94708       assert( pToken->n<=nToken );
94709       if( memcmp(pToken->z, zToken, pToken->n) ) continue;
94710       if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
94711       match |= 1<<i;
94712       if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
94713         for(j=nPhrase-1; j>=0; j--){
94714           int k = (iRotor-j) & FTS3_ROTOR_MASK;
94715           snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
94716                 iRotorBegin[k], iRotorLen[k]);
94717         }
94718       }
94719     }
94720     prevMatch = match<<1;
94721     iRotor++;
94722   }
94723   pTModule->xClose(pTCursor);  
94724 }
94725
94726 /*
94727 ** Remove entries from the pSnippet structure to account for the NEAR
94728 ** operator. When this is called, pSnippet contains the list of token 
94729 ** offsets produced by treating all NEAR operators as AND operators.
94730 ** This function removes any entries that should not be present after
94731 ** accounting for the NEAR restriction. For example, if the queried
94732 ** document is:
94733 **
94734 **     "A B C D E A"
94735 **
94736 ** and the query is:
94737 ** 
94738 **     A NEAR/0 E
94739 **
94740 ** then when this function is called the Snippet contains token offsets
94741 ** 0, 4 and 5. This function removes the "0" entry (because the first A
94742 ** is not near enough to an E).
94743 **
94744 ** When this function is called, the value pointed to by parameter piLeft is
94745 ** the integer id of the left-most token in the expression tree headed by
94746 ** pExpr. This function increments *piLeft by the total number of tokens
94747 ** in the expression tree headed by pExpr.
94748 **
94749 ** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
94750 */
94751 static int trimSnippetOffsets(
94752   Fts3Expr *pExpr,      /* The search expression */
94753   Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
94754   int *piLeft           /* Index of left-most token in pExpr */
94755 ){
94756   if( pExpr ){
94757     if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
94758       return 1;
94759     }
94760
94761     switch( pExpr->eType ){
94762       case FTSQUERY_PHRASE:
94763         *piLeft += pExpr->pPhrase->nToken;
94764         break;
94765       case FTSQUERY_NEAR: {
94766         /* The right-hand-side of a NEAR operator is always a phrase. The
94767         ** left-hand-side is either a phrase or an expression tree that is 
94768         ** itself headed by a NEAR operator. The following initializations
94769         ** set local variable iLeft to the token number of the left-most
94770         ** token in the right-hand phrase, and iRight to the right most
94771         ** token in the same phrase. For example, if we had:
94772         **
94773         **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
94774         **
94775         ** then iLeft will be set to 2 (token number of ghi) and nToken will
94776         ** be set to 4.
94777         */
94778         Fts3Expr *pLeft = pExpr->pLeft;
94779         Fts3Expr *pRight = pExpr->pRight;
94780         int iLeft = *piLeft;
94781         int nNear = pExpr->nNear;
94782         int nToken = pRight->pPhrase->nToken;
94783         int jj, ii;
94784         if( pLeft->eType==FTSQUERY_NEAR ){
94785           pLeft = pLeft->pRight;
94786         }
94787         assert( pRight->eType==FTSQUERY_PHRASE );
94788         assert( pLeft->eType==FTSQUERY_PHRASE );
94789         nToken += pLeft->pPhrase->nToken;
94790
94791         for(ii=0; ii<pSnippet->nMatch; ii++){
94792           struct snippetMatch *p = &pSnippet->aMatch[ii];
94793           if( p->iTerm==iLeft ){
94794             int isOk = 0;
94795             /* Snippet ii is an occurence of query term iLeft in the document.
94796             ** It occurs at position (p->iToken) of the document. We now
94797             ** search for an instance of token (iLeft-1) somewhere in the 
94798             ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within 
94799             ** the set of snippetMatch structures. If one is found, proceed. 
94800             ** If one cannot be found, then remove snippets ii..(ii+N-1) 
94801             ** from the matching snippets, where N is the number of tokens 
94802             ** in phrase pRight->pPhrase.
94803             */
94804             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
94805               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
94806               if( p2->iTerm==(iLeft-1) ){
94807                 if( p2->iToken>=(p->iToken-nNear-1) 
94808                  && p2->iToken<(p->iToken+nNear+nToken) 
94809                 ){
94810                   isOk = 1;
94811                 }
94812               }
94813             }
94814             if( !isOk ){
94815               int kk;
94816               for(kk=0; kk<pRight->pPhrase->nToken; kk++){
94817                 pSnippet->aMatch[kk+ii].iTerm = -2;
94818               }
94819               return 1;
94820             }
94821           }
94822           if( p->iTerm==(iLeft-1) ){
94823             int isOk = 0;
94824             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
94825               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
94826               if( p2->iTerm==iLeft ){
94827                 if( p2->iToken<=(p->iToken+nNear+1) 
94828                  && p2->iToken>(p->iToken-nNear-nToken) 
94829                 ){
94830                   isOk = 1;
94831                 }
94832               }
94833             }
94834             if( !isOk ){
94835               int kk;
94836               for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
94837                 pSnippet->aMatch[ii-kk].iTerm = -2;
94838               }
94839               return 1;
94840             }
94841           }
94842         }
94843         break;
94844       }
94845     }
94846
94847     if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
94848       return 1;
94849     }
94850   }
94851   return 0;
94852 }
94853
94854 /*
94855 ** Compute all offsets for the current row of the query.  
94856 ** If the offsets have already been computed, this routine is a no-op.
94857 */
94858 static void snippetAllOffsets(fulltext_cursor *p){
94859   int nColumn;
94860   int iColumn, i;
94861   int iFirst, iLast;
94862   int iTerm = 0;
94863   fulltext_vtab *pFts = cursor_vtab(p);
94864
94865   if( p->snippet.nMatch || p->pExpr==0 ){
94866     return;
94867   }
94868   nColumn = pFts->nColumn;
94869   iColumn = (p->iCursorType - QUERY_FULLTEXT);
94870   if( iColumn<0 || iColumn>=nColumn ){
94871     /* Look for matches over all columns of the full-text index */
94872     iFirst = 0;
94873     iLast = nColumn-1;
94874   }else{
94875     /* Look for matches in the iColumn-th column of the index only */
94876     iFirst = iColumn;
94877     iLast = iColumn;
94878   }
94879   for(i=iFirst; i<=iLast; i++){
94880     const char *zDoc;
94881     int nDoc;
94882     zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
94883     nDoc = sqlite3_column_bytes(p->pStmt, i+1);
94884     snippetOffsetsOfColumn(p, &p->snippet, i, zDoc, nDoc);
94885   }
94886
94887   while( trimSnippetOffsets(p->pExpr, &p->snippet, &iTerm) ){
94888     iTerm = 0;
94889   }
94890 }
94891
94892 /*
94893 ** Convert the information in the aMatch[] array of the snippet
94894 ** into the string zOffset[0..nOffset-1]. This string is used as
94895 ** the return of the SQL offsets() function.
94896 */
94897 static void snippetOffsetText(Snippet *p){
94898   int i;
94899   int cnt = 0;
94900   StringBuffer sb;
94901   char zBuf[200];
94902   if( p->zOffset ) return;
94903   initStringBuffer(&sb);
94904   for(i=0; i<p->nMatch; i++){
94905     struct snippetMatch *pMatch = &p->aMatch[i];
94906     if( pMatch->iTerm>=0 ){
94907       /* If snippetMatch.iTerm is less than 0, then the match was 
94908       ** discarded as part of processing the NEAR operator (see the 
94909       ** trimSnippetOffsetsForNear() function for details). Ignore 
94910       ** it in this case
94911       */
94912       zBuf[0] = ' ';
94913       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
94914           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
94915       append(&sb, zBuf);
94916       cnt++;
94917     }
94918   }
94919   p->zOffset = stringBufferData(&sb);
94920   p->nOffset = stringBufferLength(&sb);
94921 }
94922
94923 /*
94924 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
94925 ** of matching words some of which might be in zDoc.  zDoc is column
94926 ** number iCol.
94927 **
94928 ** iBreak is suggested spot in zDoc where we could begin or end an
94929 ** excerpt.  Return a value similar to iBreak but possibly adjusted
94930 ** to be a little left or right so that the break point is better.
94931 */
94932 static int wordBoundary(
94933   int iBreak,                   /* The suggested break point */
94934   const char *zDoc,             /* Document text */
94935   int nDoc,                     /* Number of bytes in zDoc[] */
94936   struct snippetMatch *aMatch,  /* Matching words */
94937   int nMatch,                   /* Number of entries in aMatch[] */
94938   int iCol                      /* The column number for zDoc[] */
94939 ){
94940   int i;
94941   if( iBreak<=10 ){
94942     return 0;
94943   }
94944   if( iBreak>=nDoc-10 ){
94945     return nDoc;
94946   }
94947   for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
94948   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
94949   if( i<nMatch ){
94950     if( aMatch[i].iStart<iBreak+10 ){
94951       return aMatch[i].iStart;
94952     }
94953     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
94954       return aMatch[i-1].iStart;
94955     }
94956   }
94957   for(i=1; i<=10; i++){
94958     if( safe_isspace(zDoc[iBreak-i]) ){
94959       return iBreak - i + 1;
94960     }
94961     if( safe_isspace(zDoc[iBreak+i]) ){
94962       return iBreak + i + 1;
94963     }
94964   }
94965   return iBreak;
94966 }
94967
94968
94969
94970 /*
94971 ** Allowed values for Snippet.aMatch[].snStatus
94972 */
94973 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
94974 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
94975
94976 /*
94977 ** Generate the text of a snippet.
94978 */
94979 static void snippetText(
94980   fulltext_cursor *pCursor,   /* The cursor we need the snippet for */
94981   const char *zStartMark,     /* Markup to appear before each match */
94982   const char *zEndMark,       /* Markup to appear after each match */
94983   const char *zEllipsis       /* Ellipsis mark */
94984 ){
94985   int i, j;
94986   struct snippetMatch *aMatch;
94987   int nMatch;
94988   int nDesired;
94989   StringBuffer sb;
94990   int tailCol;
94991   int tailOffset;
94992   int iCol;
94993   int nDoc;
94994   const char *zDoc;
94995   int iStart, iEnd;
94996   int tailEllipsis = 0;
94997   int iMatch;
94998   
94999
95000   sqlite3_free(pCursor->snippet.zSnippet);
95001   pCursor->snippet.zSnippet = 0;
95002   aMatch = pCursor->snippet.aMatch;
95003   nMatch = pCursor->snippet.nMatch;
95004   initStringBuffer(&sb);
95005
95006   for(i=0; i<nMatch; i++){
95007     aMatch[i].snStatus = SNIPPET_IGNORE;
95008   }
95009   nDesired = 0;
95010   for(i=0; i<FTS3_ROTOR_SZ; i++){
95011     for(j=0; j<nMatch; j++){
95012       if( aMatch[j].iTerm==i ){
95013         aMatch[j].snStatus = SNIPPET_DESIRED;
95014         nDesired++;
95015         break;
95016       }
95017     }
95018   }
95019
95020   iMatch = 0;
95021   tailCol = -1;
95022   tailOffset = 0;
95023   for(i=0; i<nMatch && nDesired>0; i++){
95024     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
95025     nDesired--;
95026     iCol = aMatch[i].iCol;
95027     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
95028     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
95029     iStart = aMatch[i].iStart - 40;
95030     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
95031     if( iStart<=10 ){
95032       iStart = 0;
95033     }
95034     if( iCol==tailCol && iStart<=tailOffset+20 ){
95035       iStart = tailOffset;
95036     }
95037     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
95038       trimWhiteSpace(&sb);
95039       appendWhiteSpace(&sb);
95040       append(&sb, zEllipsis);
95041       appendWhiteSpace(&sb);
95042     }
95043     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
95044     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
95045     if( iEnd>=nDoc-10 ){
95046       iEnd = nDoc;
95047       tailEllipsis = 0;
95048     }else{
95049       tailEllipsis = 1;
95050     }
95051     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
95052     while( iStart<iEnd ){
95053       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
95054              && aMatch[iMatch].iCol<=iCol ){
95055         iMatch++;
95056       }
95057       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
95058              && aMatch[iMatch].iCol==iCol ){
95059         nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
95060         iStart = aMatch[iMatch].iStart;
95061         append(&sb, zStartMark);
95062         nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
95063         append(&sb, zEndMark);
95064         iStart += aMatch[iMatch].nByte;
95065         for(j=iMatch+1; j<nMatch; j++){
95066           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
95067               && aMatch[j].snStatus==SNIPPET_DESIRED ){
95068             nDesired--;
95069             aMatch[j].snStatus = SNIPPET_IGNORE;
95070           }
95071         }
95072       }else{
95073         nappend(&sb, &zDoc[iStart], iEnd - iStart);
95074         iStart = iEnd;
95075       }
95076     }
95077     tailCol = iCol;
95078     tailOffset = iEnd;
95079   }
95080   trimWhiteSpace(&sb);
95081   if( tailEllipsis ){
95082     appendWhiteSpace(&sb);
95083     append(&sb, zEllipsis);
95084   }
95085   pCursor->snippet.zSnippet = stringBufferData(&sb);
95086   pCursor->snippet.nSnippet = stringBufferLength(&sb);
95087 }
95088
95089
95090 /*
95091 ** Close the cursor.  For additional information see the documentation
95092 ** on the xClose method of the virtual table interface.
95093 */
95094 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
95095   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95096   FTSTRACE(("FTS3 Close %p\n", c));
95097   sqlite3_finalize(c->pStmt);
95098   sqlite3Fts3ExprFree(c->pExpr);
95099   snippetClear(&c->snippet);
95100   if( c->result.nData!=0 ){
95101     dlrDestroy(&c->reader);
95102   }
95103   dataBufferDestroy(&c->result);
95104   sqlite3_free(c);
95105   return SQLITE_OK;
95106 }
95107
95108 static int fulltextNext(sqlite3_vtab_cursor *pCursor){
95109   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95110   int rc;
95111
95112   FTSTRACE(("FTS3 Next %p\n", pCursor));
95113   snippetClear(&c->snippet);
95114   if( c->iCursorType < QUERY_FULLTEXT ){
95115     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
95116     rc = sqlite3_step(c->pStmt);
95117     switch( rc ){
95118       case SQLITE_ROW:
95119         c->eof = 0;
95120         return SQLITE_OK;
95121       case SQLITE_DONE:
95122         c->eof = 1;
95123         return SQLITE_OK;
95124       default:
95125         c->eof = 1;
95126         return rc;
95127     }
95128   } else {  /* full-text query */
95129     rc = sqlite3_reset(c->pStmt);
95130     if( rc!=SQLITE_OK ) return rc;
95131
95132     if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
95133       c->eof = 1;
95134       return SQLITE_OK;
95135     }
95136     rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
95137     dlrStep(&c->reader);
95138     if( rc!=SQLITE_OK ) return rc;
95139     /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
95140     rc = sqlite3_step(c->pStmt);
95141     if( rc==SQLITE_ROW ){   /* the case we expect */
95142       c->eof = 0;
95143       return SQLITE_OK;
95144     }
95145     /* an error occurred; abort */
95146     return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
95147   }
95148 }
95149
95150
95151 /* TODO(shess) If we pushed LeafReader to the top of the file, or to
95152 ** another file, term_select() could be pushed above
95153 ** docListOfTerm().
95154 */
95155 static int termSelect(fulltext_vtab *v, int iColumn,
95156                       const char *pTerm, int nTerm, int isPrefix,
95157                       DocListType iType, DataBuffer *out);
95158
95159 /* 
95160 ** Return a DocList corresponding to the phrase *pPhrase.
95161 **
95162 ** The resulting DL_DOCIDS doclist is stored in pResult, which is
95163 ** overwritten.
95164 */
95165 static int docListOfPhrase(
95166   fulltext_vtab *pTab,   /* The full text index */
95167   Fts3Phrase *pPhrase,   /* Phrase to return a doclist corresponding to */
95168   DocListType eListType, /* Either DL_DOCIDS or DL_POSITIONS */
95169   DataBuffer *pResult    /* Write the result here */
95170 ){
95171   int ii;
95172   int rc = SQLITE_OK;
95173   int iCol = pPhrase->iColumn;
95174   DocListType eType = eListType;
95175   assert( eType==DL_POSITIONS || eType==DL_DOCIDS );
95176   if( pPhrase->nToken>1 ){
95177     eType = DL_POSITIONS;
95178   }
95179
95180   /* This code should never be called with buffered updates. */
95181   assert( pTab->nPendingData<0 );
95182
95183   for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
95184     DataBuffer tmp;
95185     struct PhraseToken *p = &pPhrase->aToken[ii];
95186     rc = termSelect(pTab, iCol, p->z, p->n, p->isPrefix, eType, &tmp);
95187     if( rc==SQLITE_OK ){
95188       if( ii==0 ){
95189         *pResult = tmp;
95190       }else{
95191         DataBuffer res = *pResult;
95192         dataBufferInit(pResult, 0);
95193         if( ii==(pPhrase->nToken-1) ){
95194           eType = eListType;
95195         }
95196         docListPhraseMerge(
95197           res.pData, res.nData, tmp.pData, tmp.nData, 0, 0, eType, pResult
95198         );
95199         dataBufferDestroy(&res);
95200         dataBufferDestroy(&tmp);
95201       }
95202     }
95203   }
95204
95205   return rc;
95206 }
95207
95208 /*
95209 ** Evaluate the full-text expression pExpr against fts3 table pTab. Write
95210 ** the results into pRes.
95211 */
95212 static int evalFts3Expr(
95213   fulltext_vtab *pTab,           /* Fts3 Virtual table object */
95214   Fts3Expr *pExpr,               /* Parsed fts3 expression */
95215   DataBuffer *pRes               /* OUT: Write results of the expression here */
95216 ){
95217   int rc = SQLITE_OK;
95218
95219   /* Initialize the output buffer. If this is an empty query (pExpr==0), 
95220   ** this is all that needs to be done. Empty queries produce empty 
95221   ** result sets.
95222   */
95223   dataBufferInit(pRes, 0);
95224
95225   if( pExpr ){
95226     if( pExpr->eType==FTSQUERY_PHRASE ){
95227       DocListType eType = DL_DOCIDS;
95228       if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
95229         eType = DL_POSITIONS;
95230       }
95231       rc = docListOfPhrase(pTab, pExpr->pPhrase, eType, pRes);
95232     }else{
95233       DataBuffer lhs;
95234       DataBuffer rhs;
95235
95236       dataBufferInit(&rhs, 0);
95237       if( SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pLeft, &lhs)) 
95238        && SQLITE_OK==(rc = evalFts3Expr(pTab, pExpr->pRight, &rhs)) 
95239       ){
95240         switch( pExpr->eType ){
95241           case FTSQUERY_NEAR: {
95242             int nToken;
95243             Fts3Expr *pLeft;
95244             DocListType eType = DL_DOCIDS;
95245             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
95246               eType = DL_POSITIONS;
95247             }
95248             pLeft = pExpr->pLeft;
95249             while( pLeft->eType==FTSQUERY_NEAR ){ 
95250               pLeft=pLeft->pRight;
95251             }
95252             assert( pExpr->pRight->eType==FTSQUERY_PHRASE );
95253             assert( pLeft->eType==FTSQUERY_PHRASE );
95254             nToken = pLeft->pPhrase->nToken + pExpr->pRight->pPhrase->nToken;
95255             docListPhraseMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, 
95256                 pExpr->nNear+1, nToken, eType, pRes
95257             );
95258             break;
95259           }
95260           case FTSQUERY_NOT: {
95261             docListExceptMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData,pRes);
95262             break;
95263           }
95264           case FTSQUERY_AND: {
95265             docListAndMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
95266             break;
95267           }
95268           case FTSQUERY_OR: {
95269             docListOrMerge(lhs.pData, lhs.nData, rhs.pData, rhs.nData, pRes);
95270             break;
95271           }
95272         }
95273       }
95274       dataBufferDestroy(&lhs);
95275       dataBufferDestroy(&rhs);
95276     }
95277   }
95278
95279   return rc;
95280 }
95281
95282 /* TODO(shess) Refactor the code to remove this forward decl. */
95283 static int flushPendingTerms(fulltext_vtab *v);
95284
95285 /* Perform a full-text query using the search expression in
95286 ** zInput[0..nInput-1].  Return a list of matching documents
95287 ** in pResult.
95288 **
95289 ** Queries must match column iColumn.  Or if iColumn>=nColumn
95290 ** they are allowed to match against any column.
95291 */
95292 static int fulltextQuery(
95293   fulltext_vtab *v,      /* The full text index */
95294   int iColumn,           /* Match against this column by default */
95295   const char *zInput,    /* The query string */
95296   int nInput,            /* Number of bytes in zInput[] */
95297   DataBuffer *pResult,   /* Write the result doclist here */
95298   Fts3Expr **ppExpr        /* Put parsed query string here */
95299 ){
95300   int rc;
95301
95302   /* TODO(shess) Instead of flushing pendingTerms, we could query for
95303   ** the relevant term and merge the doclist into what we receive from
95304   ** the database.  Wait and see if this is a common issue, first.
95305   **
95306   ** A good reason not to flush is to not generate update-related
95307   ** error codes from here.
95308   */
95309
95310   /* Flush any buffered updates before executing the query. */
95311   rc = flushPendingTerms(v);
95312   if( rc!=SQLITE_OK ){
95313     return rc;
95314   }
95315
95316   /* Parse the query passed to the MATCH operator. */
95317   rc = sqlite3Fts3ExprParse(v->pTokenizer, 
95318       v->azColumn, v->nColumn, iColumn, zInput, nInput, ppExpr
95319   );
95320   if( rc!=SQLITE_OK ){
95321     assert( 0==(*ppExpr) );
95322     return rc;
95323   }
95324
95325   return evalFts3Expr(v, *ppExpr, pResult);
95326 }
95327
95328 /*
95329 ** This is the xFilter interface for the virtual table.  See
95330 ** the virtual table xFilter method documentation for additional
95331 ** information.
95332 **
95333 ** If idxNum==QUERY_GENERIC then do a full table scan against
95334 ** the %_content table.
95335 **
95336 ** If idxNum==QUERY_DOCID then do a docid lookup for a single entry
95337 ** in the %_content table.
95338 **
95339 ** If idxNum>=QUERY_FULLTEXT then use the full text index.  The
95340 ** column on the left-hand side of the MATCH operator is column
95341 ** number idxNum-QUERY_FULLTEXT, 0 indexed.  argv[0] is the right-hand
95342 ** side of the MATCH operator.
95343 */
95344 /* TODO(shess) Upgrade the cursor initialization and destruction to
95345 ** account for fulltextFilter() being called multiple times on the
95346 ** same cursor.  The current solution is very fragile.  Apply fix to
95347 ** fts3 as appropriate.
95348 */
95349 static int fulltextFilter(
95350   sqlite3_vtab_cursor *pCursor,     /* The cursor used for this query */
95351   int idxNum, const char *idxStr,   /* Which indexing scheme to use */
95352   int argc, sqlite3_value **argv    /* Arguments for the indexing scheme */
95353 ){
95354   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95355   fulltext_vtab *v = cursor_vtab(c);
95356   int rc;
95357
95358   FTSTRACE(("FTS3 Filter %p\n",pCursor));
95359
95360   /* If the cursor has a statement that was not prepared according to
95361   ** idxNum, clear it.  I believe all calls to fulltextFilter with a
95362   ** given cursor will have the same idxNum , but in this case it's
95363   ** easy to be safe.
95364   */
95365   if( c->pStmt && c->iCursorType!=idxNum ){
95366     sqlite3_finalize(c->pStmt);
95367     c->pStmt = NULL;
95368   }
95369
95370   /* Get a fresh statement appropriate to idxNum. */
95371   /* TODO(shess): Add a prepared-statement cache in the vt structure.
95372   ** The cache must handle multiple open cursors.  Easier to cache the
95373   ** statement variants at the vt to reduce malloc/realloc/free here.
95374   ** Or we could have a StringBuffer variant which allowed stack
95375   ** construction for small values.
95376   */
95377   if( !c->pStmt ){
95378     StringBuffer sb;
95379     initStringBuffer(&sb);
95380     append(&sb, "SELECT docid, ");
95381     appendList(&sb, v->nColumn, v->azContentColumn);
95382     append(&sb, " FROM %_content");
95383     if( idxNum!=QUERY_GENERIC ) append(&sb, " WHERE docid = ?");
95384     rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt,
95385                      stringBufferData(&sb));
95386     stringBufferDestroy(&sb);
95387     if( rc!=SQLITE_OK ) return rc;
95388     c->iCursorType = idxNum;
95389   }else{
95390     sqlite3_reset(c->pStmt);
95391     assert( c->iCursorType==idxNum );
95392   }
95393
95394   switch( idxNum ){
95395     case QUERY_GENERIC:
95396       break;
95397
95398     case QUERY_DOCID:
95399       rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
95400       if( rc!=SQLITE_OK ) return rc;
95401       break;
95402
95403     default:   /* full-text search */
95404     {
95405       int iCol = idxNum-QUERY_FULLTEXT;
95406       const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
95407       assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
95408       assert( argc==1 );
95409       if( c->result.nData!=0 ){
95410         /* This case happens if the same cursor is used repeatedly. */
95411         dlrDestroy(&c->reader);
95412         dataBufferReset(&c->result);
95413       }else{
95414         dataBufferInit(&c->result, 0);
95415       }
95416       rc = fulltextQuery(v, iCol, zQuery, -1, &c->result, &c->pExpr);
95417       if( rc!=SQLITE_OK ) return rc;
95418       if( c->result.nData!=0 ){
95419         dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
95420       }
95421       break;
95422     }
95423   }
95424
95425   return fulltextNext(pCursor);
95426 }
95427
95428 /* This is the xEof method of the virtual table.  The SQLite core
95429 ** calls this routine to find out if it has reached the end of
95430 ** a query's results set.
95431 */
95432 static int fulltextEof(sqlite3_vtab_cursor *pCursor){
95433   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95434   return c->eof;
95435 }
95436
95437 /* This is the xColumn method of the virtual table.  The SQLite
95438 ** core calls this method during a query when it needs the value
95439 ** of a column from the virtual table.  This method needs to use
95440 ** one of the sqlite3_result_*() routines to store the requested
95441 ** value back in the pContext.
95442 */
95443 static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
95444                           sqlite3_context *pContext, int idxCol){
95445   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95446   fulltext_vtab *v = cursor_vtab(c);
95447
95448   if( idxCol<v->nColumn ){
95449     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
95450     sqlite3_result_value(pContext, pVal);
95451   }else if( idxCol==v->nColumn ){
95452     /* The extra column whose name is the same as the table.
95453     ** Return a blob which is a pointer to the cursor
95454     */
95455     sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
95456   }else if( idxCol==v->nColumn+1 ){
95457     /* The docid column, which is an alias for rowid. */
95458     sqlite3_value *pVal = sqlite3_column_value(c->pStmt, 0);
95459     sqlite3_result_value(pContext, pVal);
95460   }
95461   return SQLITE_OK;
95462 }
95463
95464 /* This is the xRowid method.  The SQLite core calls this routine to
95465 ** retrieve the rowid for the current row of the result set.  fts3
95466 ** exposes %_content.docid as the rowid for the virtual table.  The
95467 ** rowid should be written to *pRowid.
95468 */
95469 static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
95470   fulltext_cursor *c = (fulltext_cursor *) pCursor;
95471
95472   *pRowid = sqlite3_column_int64(c->pStmt, 0);
95473   return SQLITE_OK;
95474 }
95475
95476 /* Add all terms in [zText] to pendingTerms table.  If [iColumn] > 0,
95477 ** we also store positions and offsets in the hash table using that
95478 ** column number.
95479 */
95480 static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
95481                       const char *zText, int iColumn){
95482   sqlite3_tokenizer *pTokenizer = v->pTokenizer;
95483   sqlite3_tokenizer_cursor *pCursor;
95484   const char *pToken;
95485   int nTokenBytes;
95486   int iStartOffset, iEndOffset, iPosition;
95487   int rc;
95488
95489   rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
95490   if( rc!=SQLITE_OK ) return rc;
95491
95492   pCursor->pTokenizer = pTokenizer;
95493   while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
95494                                                    &pToken, &nTokenBytes,
95495                                                    &iStartOffset, &iEndOffset,
95496                                                    &iPosition)) ){
95497     DLCollector *p;
95498     int nData;                   /* Size of doclist before our update. */
95499
95500     /* Positions can't be negative; we use -1 as a terminator
95501      * internally.  Token can't be NULL or empty. */
95502     if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
95503       rc = SQLITE_ERROR;
95504       break;
95505     }
95506
95507     p = fts3HashFind(&v->pendingTerms, pToken, nTokenBytes);
95508     if( p==NULL ){
95509       nData = 0;
95510       p = dlcNew(iDocid, DL_DEFAULT);
95511       fts3HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
95512
95513       /* Overhead for our hash table entry, the key, and the value. */
95514       v->nPendingData += sizeof(struct fts3HashElem)+sizeof(*p)+nTokenBytes;
95515     }else{
95516       nData = p->b.nData;
95517       if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
95518     }
95519     if( iColumn>=0 ){
95520       dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
95521     }
95522
95523     /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
95524     v->nPendingData += p->b.nData-nData;
95525   }
95526
95527   /* TODO(shess) Check return?  Should this be able to cause errors at
95528   ** this point?  Actually, same question about sqlite3_finalize(),
95529   ** though one could argue that failure there means that the data is
95530   ** not durable.  *ponder*
95531   */
95532   pTokenizer->pModule->xClose(pCursor);
95533   if( SQLITE_DONE == rc ) return SQLITE_OK;
95534   return rc;
95535 }
95536
95537 /* Add doclists for all terms in [pValues] to pendingTerms table. */
95538 static int insertTerms(fulltext_vtab *v, sqlite_int64 iDocid,
95539                        sqlite3_value **pValues){
95540   int i;
95541   for(i = 0; i < v->nColumn ; ++i){
95542     char *zText = (char*)sqlite3_value_text(pValues[i]);
95543     int rc = buildTerms(v, iDocid, zText, i);
95544     if( rc!=SQLITE_OK ) return rc;
95545   }
95546   return SQLITE_OK;
95547 }
95548
95549 /* Add empty doclists for all terms in the given row's content to
95550 ** pendingTerms.
95551 */
95552 static int deleteTerms(fulltext_vtab *v, sqlite_int64 iDocid){
95553   const char **pValues;
95554   int i, rc;
95555
95556   /* TODO(shess) Should we allow such tables at all? */
95557   if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
95558
95559   rc = content_select(v, iDocid, &pValues);
95560   if( rc!=SQLITE_OK ) return rc;
95561
95562   for(i = 0 ; i < v->nColumn; ++i) {
95563     rc = buildTerms(v, iDocid, pValues[i], -1);
95564     if( rc!=SQLITE_OK ) break;
95565   }
95566
95567   freeStringArray(v->nColumn, pValues);
95568   return SQLITE_OK;
95569 }
95570
95571 /* TODO(shess) Refactor the code to remove this forward decl. */
95572 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
95573
95574 /* Insert a row into the %_content table; set *piDocid to be the ID of the
95575 ** new row.  Add doclists for terms to pendingTerms.
95576 */
95577 static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestDocid,
95578                         sqlite3_value **pValues, sqlite_int64 *piDocid){
95579   int rc;
95580
95581   rc = content_insert(v, pRequestDocid, pValues);  /* execute an SQL INSERT */
95582   if( rc!=SQLITE_OK ) return rc;
95583
95584   /* docid column is an alias for rowid. */
95585   *piDocid = sqlite3_last_insert_rowid(v->db);
95586   rc = initPendingTerms(v, *piDocid);
95587   if( rc!=SQLITE_OK ) return rc;
95588
95589   return insertTerms(v, *piDocid, pValues);
95590 }
95591
95592 /* Delete a row from the %_content table; add empty doclists for terms
95593 ** to pendingTerms.
95594 */
95595 static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
95596   int rc = initPendingTerms(v, iRow);
95597   if( rc!=SQLITE_OK ) return rc;
95598
95599   rc = deleteTerms(v, iRow);
95600   if( rc!=SQLITE_OK ) return rc;
95601
95602   return content_delete(v, iRow);  /* execute an SQL DELETE */
95603 }
95604
95605 /* Update a row in the %_content table; add delete doclists to
95606 ** pendingTerms for old terms not in the new data, add insert doclists
95607 ** to pendingTerms for terms in the new data.
95608 */
95609 static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
95610                         sqlite3_value **pValues){
95611   int rc = initPendingTerms(v, iRow);
95612   if( rc!=SQLITE_OK ) return rc;
95613
95614   /* Generate an empty doclist for each term that previously appeared in this
95615    * row. */
95616   rc = deleteTerms(v, iRow);
95617   if( rc!=SQLITE_OK ) return rc;
95618
95619   rc = content_update(v, pValues, iRow);  /* execute an SQL UPDATE */
95620   if( rc!=SQLITE_OK ) return rc;
95621
95622   /* Now add positions for terms which appear in the updated row. */
95623   return insertTerms(v, iRow, pValues);
95624 }
95625
95626 /*******************************************************************/
95627 /* InteriorWriter is used to collect terms and block references into
95628 ** interior nodes in %_segments.  See commentary at top of file for
95629 ** format.
95630 */
95631
95632 /* How large interior nodes can grow. */
95633 #define INTERIOR_MAX 2048
95634
95635 /* Minimum number of terms per interior node (except the root). This
95636 ** prevents large terms from making the tree too skinny - must be >0
95637 ** so that the tree always makes progress.  Note that the min tree
95638 ** fanout will be INTERIOR_MIN_TERMS+1.
95639 */
95640 #define INTERIOR_MIN_TERMS 7
95641 #if INTERIOR_MIN_TERMS<1
95642 # error INTERIOR_MIN_TERMS must be greater than 0.
95643 #endif
95644
95645 /* ROOT_MAX controls how much data is stored inline in the segment
95646 ** directory.
95647 */
95648 /* TODO(shess) Push ROOT_MAX down to whoever is writing things.  It's
95649 ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
95650 ** can both see it, but if the caller passed it in, we wouldn't even
95651 ** need a define.
95652 */
95653 #define ROOT_MAX 1024
95654 #if ROOT_MAX<VARINT_MAX*2
95655 # error ROOT_MAX must have enough space for a header.
95656 #endif
95657
95658 /* InteriorBlock stores a linked-list of interior blocks while a lower
95659 ** layer is being constructed.
95660 */
95661 typedef struct InteriorBlock {
95662   DataBuffer term;           /* Leftmost term in block's subtree. */
95663   DataBuffer data;           /* Accumulated data for the block. */
95664   struct InteriorBlock *next;
95665 } InteriorBlock;
95666
95667 static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
95668                                        const char *pTerm, int nTerm){
95669   InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
95670   char c[VARINT_MAX+VARINT_MAX];
95671   int n;
95672
95673   if( block ){
95674     memset(block, 0, sizeof(*block));
95675     dataBufferInit(&block->term, 0);
95676     dataBufferReplace(&block->term, pTerm, nTerm);
95677
95678     n = fts3PutVarint(c, iHeight);
95679     n += fts3PutVarint(c+n, iChildBlock);
95680     dataBufferInit(&block->data, INTERIOR_MAX);
95681     dataBufferReplace(&block->data, c, n);
95682   }
95683   return block;
95684 }
95685
95686 #ifndef NDEBUG
95687 /* Verify that the data is readable as an interior node. */
95688 static void interiorBlockValidate(InteriorBlock *pBlock){
95689   const char *pData = pBlock->data.pData;
95690   int nData = pBlock->data.nData;
95691   int n, iDummy;
95692   sqlite_int64 iBlockid;
95693
95694   assert( nData>0 );
95695   assert( pData!=0 );
95696   assert( pData+nData>pData );
95697
95698   /* Must lead with height of node as a varint(n), n>0 */
95699   n = fts3GetVarint32(pData, &iDummy);
95700   assert( n>0 );
95701   assert( iDummy>0 );
95702   assert( n<nData );
95703   pData += n;
95704   nData -= n;
95705
95706   /* Must contain iBlockid. */
95707   n = fts3GetVarint(pData, &iBlockid);
95708   assert( n>0 );
95709   assert( n<=nData );
95710   pData += n;
95711   nData -= n;
95712
95713   /* Zero or more terms of positive length */
95714   if( nData!=0 ){
95715     /* First term is not delta-encoded. */
95716     n = fts3GetVarint32(pData, &iDummy);
95717     assert( n>0 );
95718     assert( iDummy>0 );
95719     assert( n+iDummy>0);
95720     assert( n+iDummy<=nData );
95721     pData += n+iDummy;
95722     nData -= n+iDummy;
95723
95724     /* Following terms delta-encoded. */
95725     while( nData!=0 ){
95726       /* Length of shared prefix. */
95727       n = fts3GetVarint32(pData, &iDummy);
95728       assert( n>0 );
95729       assert( iDummy>=0 );
95730       assert( n<nData );
95731       pData += n;
95732       nData -= n;
95733
95734       /* Length and data of distinct suffix. */
95735       n = fts3GetVarint32(pData, &iDummy);
95736       assert( n>0 );
95737       assert( iDummy>0 );
95738       assert( n+iDummy>0);
95739       assert( n+iDummy<=nData );
95740       pData += n+iDummy;
95741       nData -= n+iDummy;
95742     }
95743   }
95744 }
95745 #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
95746 #else
95747 #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
95748 #endif
95749
95750 typedef struct InteriorWriter {
95751   int iHeight;                   /* from 0 at leaves. */
95752   InteriorBlock *first, *last;
95753   struct InteriorWriter *parentWriter;
95754
95755   DataBuffer term;               /* Last term written to block "last". */
95756   sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
95757 #ifndef NDEBUG
95758   sqlite_int64 iLastChildBlock;  /* for consistency checks. */
95759 #endif
95760 } InteriorWriter;
95761
95762 /* Initialize an interior node where pTerm[nTerm] marks the leftmost
95763 ** term in the tree.  iChildBlock is the leftmost child block at the
95764 ** next level down the tree.
95765 */
95766 static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
95767                                sqlite_int64 iChildBlock,
95768                                InteriorWriter *pWriter){
95769   InteriorBlock *block;
95770   assert( iHeight>0 );
95771   CLEAR(pWriter);
95772
95773   pWriter->iHeight = iHeight;
95774   pWriter->iOpeningChildBlock = iChildBlock;
95775 #ifndef NDEBUG
95776   pWriter->iLastChildBlock = iChildBlock;
95777 #endif
95778   block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
95779   pWriter->last = pWriter->first = block;
95780   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
95781   dataBufferInit(&pWriter->term, 0);
95782 }
95783
95784 /* Append the child node rooted at iChildBlock to the interior node,
95785 ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
95786 */
95787 static void interiorWriterAppend(InteriorWriter *pWriter,
95788                                  const char *pTerm, int nTerm,
95789                                  sqlite_int64 iChildBlock){
95790   char c[VARINT_MAX+VARINT_MAX];
95791   int n, nPrefix = 0;
95792
95793   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
95794
95795   /* The first term written into an interior node is actually
95796   ** associated with the second child added (the first child was added
95797   ** in interiorWriterInit, or in the if clause at the bottom of this
95798   ** function).  That term gets encoded straight up, with nPrefix left
95799   ** at 0.
95800   */
95801   if( pWriter->term.nData==0 ){
95802     n = fts3PutVarint(c, nTerm);
95803   }else{
95804     while( nPrefix<pWriter->term.nData &&
95805            pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
95806       nPrefix++;
95807     }
95808
95809     n = fts3PutVarint(c, nPrefix);
95810     n += fts3PutVarint(c+n, nTerm-nPrefix);
95811   }
95812
95813 #ifndef NDEBUG
95814   pWriter->iLastChildBlock++;
95815 #endif
95816   assert( pWriter->iLastChildBlock==iChildBlock );
95817
95818   /* Overflow to a new block if the new term makes the current block
95819   ** too big, and the current block already has enough terms.
95820   */
95821   if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
95822       iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
95823     pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
95824                                            pTerm, nTerm);
95825     pWriter->last = pWriter->last->next;
95826     pWriter->iOpeningChildBlock = iChildBlock;
95827     dataBufferReset(&pWriter->term);
95828   }else{
95829     dataBufferAppend2(&pWriter->last->data, c, n,
95830                       pTerm+nPrefix, nTerm-nPrefix);
95831     dataBufferReplace(&pWriter->term, pTerm, nTerm);
95832   }
95833   ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
95834 }
95835
95836 /* Free the space used by pWriter, including the linked-list of
95837 ** InteriorBlocks, and parentWriter, if present.
95838 */
95839 static int interiorWriterDestroy(InteriorWriter *pWriter){
95840   InteriorBlock *block = pWriter->first;
95841
95842   while( block!=NULL ){
95843     InteriorBlock *b = block;
95844     block = block->next;
95845     dataBufferDestroy(&b->term);
95846     dataBufferDestroy(&b->data);
95847     sqlite3_free(b);
95848   }
95849   if( pWriter->parentWriter!=NULL ){
95850     interiorWriterDestroy(pWriter->parentWriter);
95851     sqlite3_free(pWriter->parentWriter);
95852   }
95853   dataBufferDestroy(&pWriter->term);
95854   SCRAMBLE(pWriter);
95855   return SQLITE_OK;
95856 }
95857
95858 /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
95859 ** directly, leaving *piEndBlockid unchanged.  Otherwise, flush
95860 ** pWriter to %_segments, building a new layer of interior nodes, and
95861 ** recursively ask for their root into.
95862 */
95863 static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
95864                                   char **ppRootInfo, int *pnRootInfo,
95865                                   sqlite_int64 *piEndBlockid){
95866   InteriorBlock *block = pWriter->first;
95867   sqlite_int64 iBlockid = 0;
95868   int rc;
95869
95870   /* If we can fit the segment inline */
95871   if( block==pWriter->last && block->data.nData<ROOT_MAX ){
95872     *ppRootInfo = block->data.pData;
95873     *pnRootInfo = block->data.nData;
95874     return SQLITE_OK;
95875   }
95876
95877   /* Flush the first block to %_segments, and create a new level of
95878   ** interior node.
95879   */
95880   ASSERT_VALID_INTERIOR_BLOCK(block);
95881   rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
95882   if( rc!=SQLITE_OK ) return rc;
95883   *piEndBlockid = iBlockid;
95884
95885   pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
95886   interiorWriterInit(pWriter->iHeight+1,
95887                      block->term.pData, block->term.nData,
95888                      iBlockid, pWriter->parentWriter);
95889
95890   /* Flush additional blocks and append to the higher interior
95891   ** node.
95892   */
95893   for(block=block->next; block!=NULL; block=block->next){
95894     ASSERT_VALID_INTERIOR_BLOCK(block);
95895     rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
95896     if( rc!=SQLITE_OK ) return rc;
95897     *piEndBlockid = iBlockid;
95898
95899     interiorWriterAppend(pWriter->parentWriter,
95900                          block->term.pData, block->term.nData, iBlockid);
95901   }
95902
95903   /* Parent node gets the chance to be the root. */
95904   return interiorWriterRootInfo(v, pWriter->parentWriter,
95905                                 ppRootInfo, pnRootInfo, piEndBlockid);
95906 }
95907
95908 /****************************************************************/
95909 /* InteriorReader is used to read off the data from an interior node
95910 ** (see comment at top of file for the format).
95911 */
95912 typedef struct InteriorReader {
95913   const char *pData;
95914   int nData;
95915
95916   DataBuffer term;          /* previous term, for decoding term delta. */
95917
95918   sqlite_int64 iBlockid;
95919 } InteriorReader;
95920
95921 static void interiorReaderDestroy(InteriorReader *pReader){
95922   dataBufferDestroy(&pReader->term);
95923   SCRAMBLE(pReader);
95924 }
95925
95926 /* TODO(shess) The assertions are great, but what if we're in NDEBUG
95927 ** and the blob is empty or otherwise contains suspect data?
95928 */
95929 static void interiorReaderInit(const char *pData, int nData,
95930                                InteriorReader *pReader){
95931   int n, nTerm;
95932
95933   /* Require at least the leading flag byte */
95934   assert( nData>0 );
95935   assert( pData[0]!='\0' );
95936
95937   CLEAR(pReader);
95938
95939   /* Decode the base blockid, and set the cursor to the first term. */
95940   n = fts3GetVarint(pData+1, &pReader->iBlockid);
95941   assert( 1+n<=nData );
95942   pReader->pData = pData+1+n;
95943   pReader->nData = nData-(1+n);
95944
95945   /* A single-child interior node (such as when a leaf node was too
95946   ** large for the segment directory) won't have any terms.
95947   ** Otherwise, decode the first term.
95948   */
95949   if( pReader->nData==0 ){
95950     dataBufferInit(&pReader->term, 0);
95951   }else{
95952     n = fts3GetVarint32(pReader->pData, &nTerm);
95953     dataBufferInit(&pReader->term, nTerm);
95954     dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
95955     assert( n+nTerm<=pReader->nData );
95956     pReader->pData += n+nTerm;
95957     pReader->nData -= n+nTerm;
95958   }
95959 }
95960
95961 static int interiorReaderAtEnd(InteriorReader *pReader){
95962   return pReader->term.nData==0;
95963 }
95964
95965 static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
95966   return pReader->iBlockid;
95967 }
95968
95969 static int interiorReaderTermBytes(InteriorReader *pReader){
95970   assert( !interiorReaderAtEnd(pReader) );
95971   return pReader->term.nData;
95972 }
95973 static const char *interiorReaderTerm(InteriorReader *pReader){
95974   assert( !interiorReaderAtEnd(pReader) );
95975   return pReader->term.pData;
95976 }
95977
95978 /* Step forward to the next term in the node. */
95979 static void interiorReaderStep(InteriorReader *pReader){
95980   assert( !interiorReaderAtEnd(pReader) );
95981
95982   /* If the last term has been read, signal eof, else construct the
95983   ** next term.
95984   */
95985   if( pReader->nData==0 ){
95986     dataBufferReset(&pReader->term);
95987   }else{
95988     int n, nPrefix, nSuffix;
95989
95990     n = fts3GetVarint32(pReader->pData, &nPrefix);
95991     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
95992
95993     /* Truncate the current term and append suffix data. */
95994     pReader->term.nData = nPrefix;
95995     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
95996
95997     assert( n+nSuffix<=pReader->nData );
95998     pReader->pData += n+nSuffix;
95999     pReader->nData -= n+nSuffix;
96000   }
96001   pReader->iBlockid++;
96002 }
96003
96004 /* Compare the current term to pTerm[nTerm], returning strcmp-style
96005 ** results.  If isPrefix, equality means equal through nTerm bytes.
96006 */
96007 static int interiorReaderTermCmp(InteriorReader *pReader,
96008                                  const char *pTerm, int nTerm, int isPrefix){
96009   const char *pReaderTerm = interiorReaderTerm(pReader);
96010   int nReaderTerm = interiorReaderTermBytes(pReader);
96011   int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
96012
96013   if( n==0 ){
96014     if( nReaderTerm>0 ) return -1;
96015     if( nTerm>0 ) return 1;
96016     return 0;
96017   }
96018
96019   c = memcmp(pReaderTerm, pTerm, n);
96020   if( c!=0 ) return c;
96021   if( isPrefix && n==nTerm ) return 0;
96022   return nReaderTerm - nTerm;
96023 }
96024
96025 /****************************************************************/
96026 /* LeafWriter is used to collect terms and associated doclist data
96027 ** into leaf blocks in %_segments (see top of file for format info).
96028 ** Expected usage is:
96029 **
96030 ** LeafWriter writer;
96031 ** leafWriterInit(0, 0, &writer);
96032 ** while( sorted_terms_left_to_process ){
96033 **   // data is doclist data for that term.
96034 **   rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
96035 **   if( rc!=SQLITE_OK ) goto err;
96036 ** }
96037 ** rc = leafWriterFinalize(v, &writer);
96038 **err:
96039 ** leafWriterDestroy(&writer);
96040 ** return rc;
96041 **
96042 ** leafWriterStep() may write a collected leaf out to %_segments.
96043 ** leafWriterFinalize() finishes writing any buffered data and stores
96044 ** a root node in %_segdir.  leafWriterDestroy() frees all buffers and
96045 ** InteriorWriters allocated as part of writing this segment.
96046 **
96047 ** TODO(shess) Document leafWriterStepMerge().
96048 */
96049
96050 /* Put terms with data this big in their own block. */
96051 #define STANDALONE_MIN 1024
96052
96053 /* Keep leaf blocks below this size. */
96054 #define LEAF_MAX 2048
96055
96056 typedef struct LeafWriter {
96057   int iLevel;
96058   int idx;
96059   sqlite_int64 iStartBlockid;     /* needed to create the root info */
96060   sqlite_int64 iEndBlockid;       /* when we're done writing. */
96061
96062   DataBuffer term;                /* previous encoded term */
96063   DataBuffer data;                /* encoding buffer */
96064
96065   /* bytes of first term in the current node which distinguishes that
96066   ** term from the last term of the previous node.
96067   */
96068   int nTermDistinct;
96069
96070   InteriorWriter parentWriter;    /* if we overflow */
96071   int has_parent;
96072 } LeafWriter;
96073
96074 static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
96075   CLEAR(pWriter);
96076   pWriter->iLevel = iLevel;
96077   pWriter->idx = idx;
96078
96079   dataBufferInit(&pWriter->term, 32);
96080
96081   /* Start out with a reasonably sized block, though it can grow. */
96082   dataBufferInit(&pWriter->data, LEAF_MAX);
96083 }
96084
96085 #ifndef NDEBUG
96086 /* Verify that the data is readable as a leaf node. */
96087 static void leafNodeValidate(const char *pData, int nData){
96088   int n, iDummy;
96089
96090   if( nData==0 ) return;
96091   assert( nData>0 );
96092   assert( pData!=0 );
96093   assert( pData+nData>pData );
96094
96095   /* Must lead with a varint(0) */
96096   n = fts3GetVarint32(pData, &iDummy);
96097   assert( iDummy==0 );
96098   assert( n>0 );
96099   assert( n<nData );
96100   pData += n;
96101   nData -= n;
96102
96103   /* Leading term length and data must fit in buffer. */
96104   n = fts3GetVarint32(pData, &iDummy);
96105   assert( n>0 );
96106   assert( iDummy>0 );
96107   assert( n+iDummy>0 );
96108   assert( n+iDummy<nData );
96109   pData += n+iDummy;
96110   nData -= n+iDummy;
96111
96112   /* Leading term's doclist length and data must fit. */
96113   n = fts3GetVarint32(pData, &iDummy);
96114   assert( n>0 );
96115   assert( iDummy>0 );
96116   assert( n+iDummy>0 );
96117   assert( n+iDummy<=nData );
96118   ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
96119   pData += n+iDummy;
96120   nData -= n+iDummy;
96121
96122   /* Verify that trailing terms and doclists also are readable. */
96123   while( nData!=0 ){
96124     n = fts3GetVarint32(pData, &iDummy);
96125     assert( n>0 );
96126     assert( iDummy>=0 );
96127     assert( n<nData );
96128     pData += n;
96129     nData -= n;
96130     n = fts3GetVarint32(pData, &iDummy);
96131     assert( n>0 );
96132     assert( iDummy>0 );
96133     assert( n+iDummy>0 );
96134     assert( n+iDummy<nData );
96135     pData += n+iDummy;
96136     nData -= n+iDummy;
96137
96138     n = fts3GetVarint32(pData, &iDummy);
96139     assert( n>0 );
96140     assert( iDummy>0 );
96141     assert( n+iDummy>0 );
96142     assert( n+iDummy<=nData );
96143     ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
96144     pData += n+iDummy;
96145     nData -= n+iDummy;
96146   }
96147 }
96148 #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
96149 #else
96150 #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
96151 #endif
96152
96153 /* Flush the current leaf node to %_segments, and adding the resulting
96154 ** blockid and the starting term to the interior node which will
96155 ** contain it.
96156 */
96157 static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
96158                                    int iData, int nData){
96159   sqlite_int64 iBlockid = 0;
96160   const char *pStartingTerm;
96161   int nStartingTerm, rc, n;
96162
96163   /* Must have the leading varint(0) flag, plus at least some
96164   ** valid-looking data.
96165   */
96166   assert( nData>2 );
96167   assert( iData>=0 );
96168   assert( iData+nData<=pWriter->data.nData );
96169   ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
96170
96171   rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
96172   if( rc!=SQLITE_OK ) return rc;
96173   assert( iBlockid!=0 );
96174
96175   /* Reconstruct the first term in the leaf for purposes of building
96176   ** the interior node.
96177   */
96178   n = fts3GetVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
96179   pStartingTerm = pWriter->data.pData+iData+1+n;
96180   assert( pWriter->data.nData>iData+1+n+nStartingTerm );
96181   assert( pWriter->nTermDistinct>0 );
96182   assert( pWriter->nTermDistinct<=nStartingTerm );
96183   nStartingTerm = pWriter->nTermDistinct;
96184
96185   if( pWriter->has_parent ){
96186     interiorWriterAppend(&pWriter->parentWriter,
96187                          pStartingTerm, nStartingTerm, iBlockid);
96188   }else{
96189     interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
96190                        &pWriter->parentWriter);
96191     pWriter->has_parent = 1;
96192   }
96193
96194   /* Track the span of this segment's leaf nodes. */
96195   if( pWriter->iEndBlockid==0 ){
96196     pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
96197   }else{
96198     pWriter->iEndBlockid++;
96199     assert( iBlockid==pWriter->iEndBlockid );
96200   }
96201
96202   return SQLITE_OK;
96203 }
96204 static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
96205   int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
96206   if( rc!=SQLITE_OK ) return rc;
96207
96208   /* Re-initialize the output buffer. */
96209   dataBufferReset(&pWriter->data);
96210
96211   return SQLITE_OK;
96212 }
96213
96214 /* Fetch the root info for the segment.  If the entire leaf fits
96215 ** within ROOT_MAX, then it will be returned directly, otherwise it
96216 ** will be flushed and the root info will be returned from the
96217 ** interior node.  *piEndBlockid is set to the blockid of the last
96218 ** interior or leaf node written to disk (0 if none are written at
96219 ** all).
96220 */
96221 static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
96222                               char **ppRootInfo, int *pnRootInfo,
96223                               sqlite_int64 *piEndBlockid){
96224   /* we can fit the segment entirely inline */
96225   if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
96226     *ppRootInfo = pWriter->data.pData;
96227     *pnRootInfo = pWriter->data.nData;
96228     *piEndBlockid = 0;
96229     return SQLITE_OK;
96230   }
96231
96232   /* Flush remaining leaf data. */
96233   if( pWriter->data.nData>0 ){
96234     int rc = leafWriterFlush(v, pWriter);
96235     if( rc!=SQLITE_OK ) return rc;
96236   }
96237
96238   /* We must have flushed a leaf at some point. */
96239   assert( pWriter->has_parent );
96240
96241   /* Tenatively set the end leaf blockid as the end blockid.  If the
96242   ** interior node can be returned inline, this will be the final
96243   ** blockid, otherwise it will be overwritten by
96244   ** interiorWriterRootInfo().
96245   */
96246   *piEndBlockid = pWriter->iEndBlockid;
96247
96248   return interiorWriterRootInfo(v, &pWriter->parentWriter,
96249                                 ppRootInfo, pnRootInfo, piEndBlockid);
96250 }
96251
96252 /* Collect the rootInfo data and store it into the segment directory.
96253 ** This has the effect of flushing the segment's leaf data to
96254 ** %_segments, and also flushing any interior nodes to %_segments.
96255 */
96256 static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
96257   sqlite_int64 iEndBlockid;
96258   char *pRootInfo;
96259   int rc, nRootInfo;
96260
96261   rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
96262   if( rc!=SQLITE_OK ) return rc;
96263
96264   /* Don't bother storing an entirely empty segment. */
96265   if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
96266
96267   return segdir_set(v, pWriter->iLevel, pWriter->idx,
96268                     pWriter->iStartBlockid, pWriter->iEndBlockid,
96269                     iEndBlockid, pRootInfo, nRootInfo);
96270 }
96271
96272 static void leafWriterDestroy(LeafWriter *pWriter){
96273   if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
96274   dataBufferDestroy(&pWriter->term);
96275   dataBufferDestroy(&pWriter->data);
96276 }
96277
96278 /* Encode a term into the leafWriter, delta-encoding as appropriate.
96279 ** Returns the length of the new term which distinguishes it from the
96280 ** previous term, which can be used to set nTermDistinct when a node
96281 ** boundary is crossed.
96282 */
96283 static int leafWriterEncodeTerm(LeafWriter *pWriter,
96284                                 const char *pTerm, int nTerm){
96285   char c[VARINT_MAX+VARINT_MAX];
96286   int n, nPrefix = 0;
96287
96288   assert( nTerm>0 );
96289   while( nPrefix<pWriter->term.nData &&
96290          pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
96291     nPrefix++;
96292     /* Failing this implies that the terms weren't in order. */
96293     assert( nPrefix<nTerm );
96294   }
96295
96296   if( pWriter->data.nData==0 ){
96297     /* Encode the node header and leading term as:
96298     **  varint(0)
96299     **  varint(nTerm)
96300     **  char pTerm[nTerm]
96301     */
96302     n = fts3PutVarint(c, '\0');
96303     n += fts3PutVarint(c+n, nTerm);
96304     dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
96305   }else{
96306     /* Delta-encode the term as:
96307     **  varint(nPrefix)
96308     **  varint(nSuffix)
96309     **  char pTermSuffix[nSuffix]
96310     */
96311     n = fts3PutVarint(c, nPrefix);
96312     n += fts3PutVarint(c+n, nTerm-nPrefix);
96313     dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
96314   }
96315   dataBufferReplace(&pWriter->term, pTerm, nTerm);
96316
96317   return nPrefix+1;
96318 }
96319
96320 /* Used to avoid a memmove when a large amount of doclist data is in
96321 ** the buffer.  This constructs a node and term header before
96322 ** iDoclistData and flushes the resulting complete node using
96323 ** leafWriterInternalFlush().
96324 */
96325 static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
96326                                  const char *pTerm, int nTerm,
96327                                  int iDoclistData){
96328   char c[VARINT_MAX+VARINT_MAX];
96329   int iData, n = fts3PutVarint(c, 0);
96330   n += fts3PutVarint(c+n, nTerm);
96331
96332   /* There should always be room for the header.  Even if pTerm shared
96333   ** a substantial prefix with the previous term, the entire prefix
96334   ** could be constructed from earlier data in the doclist, so there
96335   ** should be room.
96336   */
96337   assert( iDoclistData>=n+nTerm );
96338
96339   iData = iDoclistData-(n+nTerm);
96340   memcpy(pWriter->data.pData+iData, c, n);
96341   memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
96342
96343   return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
96344 }
96345
96346 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
96347 ** %_segments.
96348 */
96349 static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
96350                                const char *pTerm, int nTerm,
96351                                DLReader *pReaders, int nReaders){
96352   char c[VARINT_MAX+VARINT_MAX];
96353   int iTermData = pWriter->data.nData, iDoclistData;
96354   int i, nData, n, nActualData, nActual, rc, nTermDistinct;
96355
96356   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
96357   nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
96358
96359   /* Remember nTermDistinct if opening a new node. */
96360   if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
96361
96362   iDoclistData = pWriter->data.nData;
96363
96364   /* Estimate the length of the merged doclist so we can leave space
96365   ** to encode it.
96366   */
96367   for(i=0, nData=0; i<nReaders; i++){
96368     nData += dlrAllDataBytes(&pReaders[i]);
96369   }
96370   n = fts3PutVarint(c, nData);
96371   dataBufferAppend(&pWriter->data, c, n);
96372
96373   docListMerge(&pWriter->data, pReaders, nReaders);
96374   ASSERT_VALID_DOCLIST(DL_DEFAULT,
96375                        pWriter->data.pData+iDoclistData+n,
96376                        pWriter->data.nData-iDoclistData-n, NULL);
96377
96378   /* The actual amount of doclist data at this point could be smaller
96379   ** than the length we encoded.  Additionally, the space required to
96380   ** encode this length could be smaller.  For small doclists, this is
96381   ** not a big deal, we can just use memmove() to adjust things.
96382   */
96383   nActualData = pWriter->data.nData-(iDoclistData+n);
96384   nActual = fts3PutVarint(c, nActualData);
96385   assert( nActualData<=nData );
96386   assert( nActual<=n );
96387
96388   /* If the new doclist is big enough for force a standalone leaf
96389   ** node, we can immediately flush it inline without doing the
96390   ** memmove().
96391   */
96392   /* TODO(shess) This test matches leafWriterStep(), which does this
96393   ** test before it knows the cost to varint-encode the term and
96394   ** doclist lengths.  At some point, change to
96395   ** pWriter->data.nData-iTermData>STANDALONE_MIN.
96396   */
96397   if( nTerm+nActualData>STANDALONE_MIN ){
96398     /* Push leaf node from before this term. */
96399     if( iTermData>0 ){
96400       rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
96401       if( rc!=SQLITE_OK ) return rc;
96402
96403       pWriter->nTermDistinct = nTermDistinct;
96404     }
96405
96406     /* Fix the encoded doclist length. */
96407     iDoclistData += n - nActual;
96408     memcpy(pWriter->data.pData+iDoclistData, c, nActual);
96409
96410     /* Push the standalone leaf node. */
96411     rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
96412     if( rc!=SQLITE_OK ) return rc;
96413
96414     /* Leave the node empty. */
96415     dataBufferReset(&pWriter->data);
96416
96417     return rc;
96418   }
96419
96420   /* At this point, we know that the doclist was small, so do the
96421   ** memmove if indicated.
96422   */
96423   if( nActual<n ){
96424     memmove(pWriter->data.pData+iDoclistData+nActual,
96425             pWriter->data.pData+iDoclistData+n,
96426             pWriter->data.nData-(iDoclistData+n));
96427     pWriter->data.nData -= n-nActual;
96428   }
96429
96430   /* Replace written length with actual length. */
96431   memcpy(pWriter->data.pData+iDoclistData, c, nActual);
96432
96433   /* If the node is too large, break things up. */
96434   /* TODO(shess) This test matches leafWriterStep(), which does this
96435   ** test before it knows the cost to varint-encode the term and
96436   ** doclist lengths.  At some point, change to
96437   ** pWriter->data.nData>LEAF_MAX.
96438   */
96439   if( iTermData+nTerm+nActualData>LEAF_MAX ){
96440     /* Flush out the leading data as a node */
96441     rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
96442     if( rc!=SQLITE_OK ) return rc;
96443
96444     pWriter->nTermDistinct = nTermDistinct;
96445
96446     /* Rebuild header using the current term */
96447     n = fts3PutVarint(pWriter->data.pData, 0);
96448     n += fts3PutVarint(pWriter->data.pData+n, nTerm);
96449     memcpy(pWriter->data.pData+n, pTerm, nTerm);
96450     n += nTerm;
96451
96452     /* There should always be room, because the previous encoding
96453     ** included all data necessary to construct the term.
96454     */
96455     assert( n<iDoclistData );
96456     /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
96457     ** following memcpy() is safe (as opposed to needing a memmove).
96458     */
96459     assert( 2*STANDALONE_MIN<=LEAF_MAX );
96460     assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
96461     memcpy(pWriter->data.pData+n,
96462            pWriter->data.pData+iDoclistData,
96463            pWriter->data.nData-iDoclistData);
96464     pWriter->data.nData -= iDoclistData-n;
96465   }
96466   ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
96467
96468   return SQLITE_OK;
96469 }
96470
96471 /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
96472 ** %_segments.
96473 */
96474 /* TODO(shess) Revise writeZeroSegment() so that doclists are
96475 ** constructed directly in pWriter->data.
96476 */
96477 static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
96478                           const char *pTerm, int nTerm,
96479                           const char *pData, int nData){
96480   int rc;
96481   DLReader reader;
96482
96483   dlrInit(&reader, DL_DEFAULT, pData, nData);
96484   rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
96485   dlrDestroy(&reader);
96486
96487   return rc;
96488 }
96489
96490
96491 /****************************************************************/
96492 /* LeafReader is used to iterate over an individual leaf node. */
96493 typedef struct LeafReader {
96494   DataBuffer term;          /* copy of current term. */
96495
96496   const char *pData;        /* data for current term. */
96497   int nData;
96498 } LeafReader;
96499
96500 static void leafReaderDestroy(LeafReader *pReader){
96501   dataBufferDestroy(&pReader->term);
96502   SCRAMBLE(pReader);
96503 }
96504
96505 static int leafReaderAtEnd(LeafReader *pReader){
96506   return pReader->nData<=0;
96507 }
96508
96509 /* Access the current term. */
96510 static int leafReaderTermBytes(LeafReader *pReader){
96511   return pReader->term.nData;
96512 }
96513 static const char *leafReaderTerm(LeafReader *pReader){
96514   assert( pReader->term.nData>0 );
96515   return pReader->term.pData;
96516 }
96517
96518 /* Access the doclist data for the current term. */
96519 static int leafReaderDataBytes(LeafReader *pReader){
96520   int nData;
96521   assert( pReader->term.nData>0 );
96522   fts3GetVarint32(pReader->pData, &nData);
96523   return nData;
96524 }
96525 static const char *leafReaderData(LeafReader *pReader){
96526   int n, nData;
96527   assert( pReader->term.nData>0 );
96528   n = fts3GetVarint32(pReader->pData, &nData);
96529   return pReader->pData+n;
96530 }
96531
96532 static void leafReaderInit(const char *pData, int nData,
96533                            LeafReader *pReader){
96534   int nTerm, n;
96535
96536   assert( nData>0 );
96537   assert( pData[0]=='\0' );
96538
96539   CLEAR(pReader);
96540
96541   /* Read the first term, skipping the header byte. */
96542   n = fts3GetVarint32(pData+1, &nTerm);
96543   dataBufferInit(&pReader->term, nTerm);
96544   dataBufferReplace(&pReader->term, pData+1+n, nTerm);
96545
96546   /* Position after the first term. */
96547   assert( 1+n+nTerm<nData );
96548   pReader->pData = pData+1+n+nTerm;
96549   pReader->nData = nData-1-n-nTerm;
96550 }
96551
96552 /* Step the reader forward to the next term. */
96553 static void leafReaderStep(LeafReader *pReader){
96554   int n, nData, nPrefix, nSuffix;
96555   assert( !leafReaderAtEnd(pReader) );
96556
96557   /* Skip previous entry's data block. */
96558   n = fts3GetVarint32(pReader->pData, &nData);
96559   assert( n+nData<=pReader->nData );
96560   pReader->pData += n+nData;
96561   pReader->nData -= n+nData;
96562
96563   if( !leafReaderAtEnd(pReader) ){
96564     /* Construct the new term using a prefix from the old term plus a
96565     ** suffix from the leaf data.
96566     */
96567     n = fts3GetVarint32(pReader->pData, &nPrefix);
96568     n += fts3GetVarint32(pReader->pData+n, &nSuffix);
96569     assert( n+nSuffix<pReader->nData );
96570     pReader->term.nData = nPrefix;
96571     dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
96572
96573     pReader->pData += n+nSuffix;
96574     pReader->nData -= n+nSuffix;
96575   }
96576 }
96577
96578 /* strcmp-style comparison of pReader's current term against pTerm.
96579 ** If isPrefix, equality means equal through nTerm bytes.
96580 */
96581 static int leafReaderTermCmp(LeafReader *pReader,
96582                              const char *pTerm, int nTerm, int isPrefix){
96583   int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
96584   if( n==0 ){
96585     if( pReader->term.nData>0 ) return -1;
96586     if(nTerm>0 ) return 1;
96587     return 0;
96588   }
96589
96590   c = memcmp(pReader->term.pData, pTerm, n);
96591   if( c!=0 ) return c;
96592   if( isPrefix && n==nTerm ) return 0;
96593   return pReader->term.nData - nTerm;
96594 }
96595
96596
96597 /****************************************************************/
96598 /* LeavesReader wraps LeafReader to allow iterating over the entire
96599 ** leaf layer of the tree.
96600 */
96601 typedef struct LeavesReader {
96602   int idx;                  /* Index within the segment. */
96603
96604   sqlite3_stmt *pStmt;      /* Statement we're streaming leaves from. */
96605   int eof;                  /* we've seen SQLITE_DONE from pStmt. */
96606
96607   LeafReader leafReader;    /* reader for the current leaf. */
96608   DataBuffer rootData;      /* root data for inline. */
96609 } LeavesReader;
96610
96611 /* Access the current term. */
96612 static int leavesReaderTermBytes(LeavesReader *pReader){
96613   assert( !pReader->eof );
96614   return leafReaderTermBytes(&pReader->leafReader);
96615 }
96616 static const char *leavesReaderTerm(LeavesReader *pReader){
96617   assert( !pReader->eof );
96618   return leafReaderTerm(&pReader->leafReader);
96619 }
96620
96621 /* Access the doclist data for the current term. */
96622 static int leavesReaderDataBytes(LeavesReader *pReader){
96623   assert( !pReader->eof );
96624   return leafReaderDataBytes(&pReader->leafReader);
96625 }
96626 static const char *leavesReaderData(LeavesReader *pReader){
96627   assert( !pReader->eof );
96628   return leafReaderData(&pReader->leafReader);
96629 }
96630
96631 static int leavesReaderAtEnd(LeavesReader *pReader){
96632   return pReader->eof;
96633 }
96634
96635 /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
96636 ** leaving the statement handle open, which locks the table.
96637 */
96638 /* TODO(shess) This "solution" is not satisfactory.  Really, there
96639 ** should be check-in function for all statement handles which
96640 ** arranges to call sqlite3_reset().  This most likely will require
96641 ** modification to control flow all over the place, though, so for now
96642 ** just punt.
96643 **
96644 ** Note the the current system assumes that segment merges will run to
96645 ** completion, which is why this particular probably hasn't arisen in
96646 ** this case.  Probably a brittle assumption.
96647 */
96648 static int leavesReaderReset(LeavesReader *pReader){
96649   return sqlite3_reset(pReader->pStmt);
96650 }
96651
96652 static void leavesReaderDestroy(LeavesReader *pReader){
96653   /* If idx is -1, that means we're using a non-cached statement
96654   ** handle in the optimize() case, so we need to release it.
96655   */
96656   if( pReader->pStmt!=NULL && pReader->idx==-1 ){
96657     sqlite3_finalize(pReader->pStmt);
96658   }
96659   leafReaderDestroy(&pReader->leafReader);
96660   dataBufferDestroy(&pReader->rootData);
96661   SCRAMBLE(pReader);
96662 }
96663
96664 /* Initialize pReader with the given root data (if iStartBlockid==0
96665 ** the leaf data was entirely contained in the root), or from the
96666 ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
96667 */
96668 static int leavesReaderInit(fulltext_vtab *v,
96669                             int idx,
96670                             sqlite_int64 iStartBlockid,
96671                             sqlite_int64 iEndBlockid,
96672                             const char *pRootData, int nRootData,
96673                             LeavesReader *pReader){
96674   CLEAR(pReader);
96675   pReader->idx = idx;
96676
96677   dataBufferInit(&pReader->rootData, 0);
96678   if( iStartBlockid==0 ){
96679     /* Entire leaf level fit in root data. */
96680     dataBufferReplace(&pReader->rootData, pRootData, nRootData);
96681     leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
96682                    &pReader->leafReader);
96683   }else{
96684     sqlite3_stmt *s;
96685     int rc = sql_get_leaf_statement(v, idx, &s);
96686     if( rc!=SQLITE_OK ) return rc;
96687
96688     rc = sqlite3_bind_int64(s, 1, iStartBlockid);
96689     if( rc!=SQLITE_OK ) return rc;
96690
96691     rc = sqlite3_bind_int64(s, 2, iEndBlockid);
96692     if( rc!=SQLITE_OK ) return rc;
96693
96694     rc = sqlite3_step(s);
96695     if( rc==SQLITE_DONE ){
96696       pReader->eof = 1;
96697       return SQLITE_OK;
96698     }
96699     if( rc!=SQLITE_ROW ) return rc;
96700
96701     pReader->pStmt = s;
96702     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
96703                    sqlite3_column_bytes(pReader->pStmt, 0),
96704                    &pReader->leafReader);
96705   }
96706   return SQLITE_OK;
96707 }
96708
96709 /* Step the current leaf forward to the next term.  If we reach the
96710 ** end of the current leaf, step forward to the next leaf block.
96711 */
96712 static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
96713   assert( !leavesReaderAtEnd(pReader) );
96714   leafReaderStep(&pReader->leafReader);
96715
96716   if( leafReaderAtEnd(&pReader->leafReader) ){
96717     int rc;
96718     if( pReader->rootData.pData ){
96719       pReader->eof = 1;
96720       return SQLITE_OK;
96721     }
96722     rc = sqlite3_step(pReader->pStmt);
96723     if( rc!=SQLITE_ROW ){
96724       pReader->eof = 1;
96725       return rc==SQLITE_DONE ? SQLITE_OK : rc;
96726     }
96727     leafReaderDestroy(&pReader->leafReader);
96728     leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
96729                    sqlite3_column_bytes(pReader->pStmt, 0),
96730                    &pReader->leafReader);
96731   }
96732   return SQLITE_OK;
96733 }
96734
96735 /* Order LeavesReaders by their term, ignoring idx.  Readers at eof
96736 ** always sort to the end.
96737 */
96738 static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
96739   if( leavesReaderAtEnd(lr1) ){
96740     if( leavesReaderAtEnd(lr2) ) return 0;
96741     return 1;
96742   }
96743   if( leavesReaderAtEnd(lr2) ) return -1;
96744
96745   return leafReaderTermCmp(&lr1->leafReader,
96746                            leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
96747                            0);
96748 }
96749
96750 /* Similar to leavesReaderTermCmp(), with additional ordering by idx
96751 ** so that older segments sort before newer segments.
96752 */
96753 static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
96754   int c = leavesReaderTermCmp(lr1, lr2);
96755   if( c!=0 ) return c;
96756   return lr1->idx-lr2->idx;
96757 }
96758
96759 /* Assume that pLr[1]..pLr[nLr] are sorted.  Bubble pLr[0] into its
96760 ** sorted position.
96761 */
96762 static void leavesReaderReorder(LeavesReader *pLr, int nLr){
96763   while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
96764     LeavesReader tmp = pLr[0];
96765     pLr[0] = pLr[1];
96766     pLr[1] = tmp;
96767     nLr--;
96768     pLr++;
96769   }
96770 }
96771
96772 /* Initializes pReaders with the segments from level iLevel, returning
96773 ** the number of segments in *piReaders.  Leaves pReaders in sorted
96774 ** order.
96775 */
96776 static int leavesReadersInit(fulltext_vtab *v, int iLevel,
96777                              LeavesReader *pReaders, int *piReaders){
96778   sqlite3_stmt *s;
96779   int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
96780   if( rc!=SQLITE_OK ) return rc;
96781
96782   rc = sqlite3_bind_int(s, 1, iLevel);
96783   if( rc!=SQLITE_OK ) return rc;
96784
96785   i = 0;
96786   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
96787     sqlite_int64 iStart = sqlite3_column_int64(s, 0);
96788     sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
96789     const char *pRootData = sqlite3_column_blob(s, 2);
96790     int nRootData = sqlite3_column_bytes(s, 2);
96791
96792     assert( i<MERGE_COUNT );
96793     rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
96794                           &pReaders[i]);
96795     if( rc!=SQLITE_OK ) break;
96796
96797     i++;
96798   }
96799   if( rc!=SQLITE_DONE ){
96800     while( i-->0 ){
96801       leavesReaderDestroy(&pReaders[i]);
96802     }
96803     return rc;
96804   }
96805
96806   *piReaders = i;
96807
96808   /* Leave our results sorted by term, then age. */
96809   while( i-- ){
96810     leavesReaderReorder(pReaders+i, *piReaders-i);
96811   }
96812   return SQLITE_OK;
96813 }
96814
96815 /* Merge doclists from pReaders[nReaders] into a single doclist, which
96816 ** is written to pWriter.  Assumes pReaders is ordered oldest to
96817 ** newest.
96818 */
96819 /* TODO(shess) Consider putting this inline in segmentMerge(). */
96820 static int leavesReadersMerge(fulltext_vtab *v,
96821                               LeavesReader *pReaders, int nReaders,
96822                               LeafWriter *pWriter){
96823   DLReader dlReaders[MERGE_COUNT];
96824   const char *pTerm = leavesReaderTerm(pReaders);
96825   int i, nTerm = leavesReaderTermBytes(pReaders);
96826
96827   assert( nReaders<=MERGE_COUNT );
96828
96829   for(i=0; i<nReaders; i++){
96830     dlrInit(&dlReaders[i], DL_DEFAULT,
96831             leavesReaderData(pReaders+i),
96832             leavesReaderDataBytes(pReaders+i));
96833   }
96834
96835   return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
96836 }
96837
96838 /* Forward ref due to mutual recursion with segdirNextIndex(). */
96839 static int segmentMerge(fulltext_vtab *v, int iLevel);
96840
96841 /* Put the next available index at iLevel into *pidx.  If iLevel
96842 ** already has MERGE_COUNT segments, they are merged to a higher
96843 ** level to make room.
96844 */
96845 static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
96846   int rc = segdir_max_index(v, iLevel, pidx);
96847   if( rc==SQLITE_DONE ){              /* No segments at iLevel. */
96848     *pidx = 0;
96849   }else if( rc==SQLITE_ROW ){
96850     if( *pidx==(MERGE_COUNT-1) ){
96851       rc = segmentMerge(v, iLevel);
96852       if( rc!=SQLITE_OK ) return rc;
96853       *pidx = 0;
96854     }else{
96855       (*pidx)++;
96856     }
96857   }else{
96858     return rc;
96859   }
96860   return SQLITE_OK;
96861 }
96862
96863 /* Merge MERGE_COUNT segments at iLevel into a new segment at
96864 ** iLevel+1.  If iLevel+1 is already full of segments, those will be
96865 ** merged to make room.
96866 */
96867 static int segmentMerge(fulltext_vtab *v, int iLevel){
96868   LeafWriter writer;
96869   LeavesReader lrs[MERGE_COUNT];
96870   int i, rc, idx = 0;
96871
96872   /* Determine the next available segment index at the next level,
96873   ** merging as necessary.
96874   */
96875   rc = segdirNextIndex(v, iLevel+1, &idx);
96876   if( rc!=SQLITE_OK ) return rc;
96877
96878   /* TODO(shess) This assumes that we'll always see exactly
96879   ** MERGE_COUNT segments to merge at a given level.  That will be
96880   ** broken if we allow the developer to request preemptive or
96881   ** deferred merging.
96882   */
96883   memset(&lrs, '\0', sizeof(lrs));
96884   rc = leavesReadersInit(v, iLevel, lrs, &i);
96885   if( rc!=SQLITE_OK ) return rc;
96886   assert( i==MERGE_COUNT );
96887
96888   leafWriterInit(iLevel+1, idx, &writer);
96889
96890   /* Since leavesReaderReorder() pushes readers at eof to the end,
96891   ** when the first reader is empty, all will be empty.
96892   */
96893   while( !leavesReaderAtEnd(lrs) ){
96894     /* Figure out how many readers share their next term. */
96895     for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
96896       if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
96897     }
96898
96899     rc = leavesReadersMerge(v, lrs, i, &writer);
96900     if( rc!=SQLITE_OK ) goto err;
96901
96902     /* Step forward those that were merged. */
96903     while( i-->0 ){
96904       rc = leavesReaderStep(v, lrs+i);
96905       if( rc!=SQLITE_OK ) goto err;
96906
96907       /* Reorder by term, then by age. */
96908       leavesReaderReorder(lrs+i, MERGE_COUNT-i);
96909     }
96910   }
96911
96912   for(i=0; i<MERGE_COUNT; i++){
96913     leavesReaderDestroy(&lrs[i]);
96914   }
96915
96916   rc = leafWriterFinalize(v, &writer);
96917   leafWriterDestroy(&writer);
96918   if( rc!=SQLITE_OK ) return rc;
96919
96920   /* Delete the merged segment data. */
96921   return segdir_delete(v, iLevel);
96922
96923  err:
96924   for(i=0; i<MERGE_COUNT; i++){
96925     leavesReaderDestroy(&lrs[i]);
96926   }
96927   leafWriterDestroy(&writer);
96928   return rc;
96929 }
96930
96931 /* Accumulate the union of *acc and *pData into *acc. */
96932 static void docListAccumulateUnion(DataBuffer *acc,
96933                                    const char *pData, int nData) {
96934   DataBuffer tmp = *acc;
96935   dataBufferInit(acc, tmp.nData+nData);
96936   docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
96937   dataBufferDestroy(&tmp);
96938 }
96939
96940 /* TODO(shess) It might be interesting to explore different merge
96941 ** strategies, here.  For instance, since this is a sorted merge, we
96942 ** could easily merge many doclists in parallel.  With some
96943 ** comprehension of the storage format, we could merge all of the
96944 ** doclists within a leaf node directly from the leaf node's storage.
96945 ** It may be worthwhile to merge smaller doclists before larger
96946 ** doclists, since they can be traversed more quickly - but the
96947 ** results may have less overlap, making them more expensive in a
96948 ** different way.
96949 */
96950
96951 /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
96952 ** *out (any doclists with duplicate docids overwrite those in *out).
96953 ** Internal function for loadSegmentLeaf().
96954 */
96955 static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
96956                                 const char *pTerm, int nTerm, int isPrefix,
96957                                 DataBuffer *out){
96958   /* doclist data is accumulated into pBuffers similar to how one does
96959   ** increment in binary arithmetic.  If index 0 is empty, the data is
96960   ** stored there.  If there is data there, it is merged and the
96961   ** results carried into position 1, with further merge-and-carry
96962   ** until an empty position is found.
96963   */
96964   DataBuffer *pBuffers = NULL;
96965   int nBuffers = 0, nMaxBuffers = 0, rc;
96966
96967   assert( nTerm>0 );
96968
96969   for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
96970       rc=leavesReaderStep(v, pReader)){
96971     /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
96972     ** already taken to compare the terms of two LeavesReaders.  Think
96973     ** on a better name.  [Meanwhile, break encapsulation rather than
96974     ** use a confusing name.]
96975     */
96976     int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
96977     if( c>0 ) break;      /* Past any possible matches. */
96978     if( c==0 ){
96979       const char *pData = leavesReaderData(pReader);
96980       int iBuffer, nData = leavesReaderDataBytes(pReader);
96981
96982       /* Find the first empty buffer. */
96983       for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
96984         if( 0==pBuffers[iBuffer].nData ) break;
96985       }
96986
96987       /* Out of buffers, add an empty one. */
96988       if( iBuffer==nBuffers ){
96989         if( nBuffers==nMaxBuffers ){
96990           DataBuffer *p;
96991           nMaxBuffers += 20;
96992
96993           /* Manual realloc so we can handle NULL appropriately. */
96994           p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
96995           if( p==NULL ){
96996             rc = SQLITE_NOMEM;
96997             break;
96998           }
96999
97000           if( nBuffers>0 ){
97001             assert(pBuffers!=NULL);
97002             memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
97003             sqlite3_free(pBuffers);
97004           }
97005           pBuffers = p;
97006         }
97007         dataBufferInit(&(pBuffers[nBuffers]), 0);
97008         nBuffers++;
97009       }
97010
97011       /* At this point, must have an empty at iBuffer. */
97012       assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
97013
97014       /* If empty was first buffer, no need for merge logic. */
97015       if( iBuffer==0 ){
97016         dataBufferReplace(&(pBuffers[0]), pData, nData);
97017       }else{
97018         /* pAcc is the empty buffer the merged data will end up in. */
97019         DataBuffer *pAcc = &(pBuffers[iBuffer]);
97020         DataBuffer *p = &(pBuffers[0]);
97021
97022         /* Handle position 0 specially to avoid need to prime pAcc
97023         ** with pData/nData.
97024         */
97025         dataBufferSwap(p, pAcc);
97026         docListAccumulateUnion(pAcc, pData, nData);
97027
97028         /* Accumulate remaining doclists into pAcc. */
97029         for(++p; p<pAcc; ++p){
97030           docListAccumulateUnion(pAcc, p->pData, p->nData);
97031
97032           /* dataBufferReset() could allow a large doclist to blow up
97033           ** our memory requirements.
97034           */
97035           if( p->nCapacity<1024 ){
97036             dataBufferReset(p);
97037           }else{
97038             dataBufferDestroy(p);
97039             dataBufferInit(p, 0);
97040           }
97041         }
97042       }
97043     }
97044   }
97045
97046   /* Union all the doclists together into *out. */
97047   /* TODO(shess) What if *out is big?  Sigh. */
97048   if( rc==SQLITE_OK && nBuffers>0 ){
97049     int iBuffer;
97050     for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
97051       if( pBuffers[iBuffer].nData>0 ){
97052         if( out->nData==0 ){
97053           dataBufferSwap(out, &(pBuffers[iBuffer]));
97054         }else{
97055           docListAccumulateUnion(out, pBuffers[iBuffer].pData,
97056                                  pBuffers[iBuffer].nData);
97057         }
97058       }
97059     }
97060   }
97061
97062   while( nBuffers-- ){
97063     dataBufferDestroy(&(pBuffers[nBuffers]));
97064   }
97065   if( pBuffers!=NULL ) sqlite3_free(pBuffers);
97066
97067   return rc;
97068 }
97069
97070 /* Call loadSegmentLeavesInt() with pData/nData as input. */
97071 static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
97072                            const char *pTerm, int nTerm, int isPrefix,
97073                            DataBuffer *out){
97074   LeavesReader reader;
97075   int rc;
97076
97077   assert( nData>1 );
97078   assert( *pData=='\0' );
97079   rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
97080   if( rc!=SQLITE_OK ) return rc;
97081
97082   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
97083   leavesReaderReset(&reader);
97084   leavesReaderDestroy(&reader);
97085   return rc;
97086 }
97087
97088 /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
97089 ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
97090 ** out.
97091 */
97092 static int loadSegmentLeaves(fulltext_vtab *v,
97093                              sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
97094                              const char *pTerm, int nTerm, int isPrefix,
97095                              DataBuffer *out){
97096   int rc;
97097   LeavesReader reader;
97098
97099   assert( iStartLeaf<=iEndLeaf );
97100   rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
97101   if( rc!=SQLITE_OK ) return rc;
97102
97103   rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
97104   leavesReaderReset(&reader);
97105   leavesReaderDestroy(&reader);
97106   return rc;
97107 }
97108
97109 /* Taking pData/nData as an interior node, find the sequence of child
97110 ** nodes which could include pTerm/nTerm/isPrefix.  Note that the
97111 ** interior node terms logically come between the blocks, so there is
97112 ** one more blockid than there are terms (that block contains terms >=
97113 ** the last interior-node term).
97114 */
97115 /* TODO(shess) The calling code may already know that the end child is
97116 ** not worth calculating, because the end may be in a later sibling
97117 ** node.  Consider whether breaking symmetry is worthwhile.  I suspect
97118 ** it is not worthwhile.
97119 */
97120 static void getChildrenContaining(const char *pData, int nData,
97121                                   const char *pTerm, int nTerm, int isPrefix,
97122                                   sqlite_int64 *piStartChild,
97123                                   sqlite_int64 *piEndChild){
97124   InteriorReader reader;
97125
97126   assert( nData>1 );
97127   assert( *pData!='\0' );
97128   interiorReaderInit(pData, nData, &reader);
97129
97130   /* Scan for the first child which could contain pTerm/nTerm. */
97131   while( !interiorReaderAtEnd(&reader) ){
97132     if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
97133     interiorReaderStep(&reader);
97134   }
97135   *piStartChild = interiorReaderCurrentBlockid(&reader);
97136
97137   /* Keep scanning to find a term greater than our term, using prefix
97138   ** comparison if indicated.  If isPrefix is false, this will be the
97139   ** same blockid as the starting block.
97140   */
97141   while( !interiorReaderAtEnd(&reader) ){
97142     if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
97143     interiorReaderStep(&reader);
97144   }
97145   *piEndChild = interiorReaderCurrentBlockid(&reader);
97146
97147   interiorReaderDestroy(&reader);
97148
97149   /* Children must ascend, and if !prefix, both must be the same. */
97150   assert( *piEndChild>=*piStartChild );
97151   assert( isPrefix || *piStartChild==*piEndChild );
97152 }
97153
97154 /* Read block at iBlockid and pass it with other params to
97155 ** getChildrenContaining().
97156 */
97157 static int loadAndGetChildrenContaining(
97158   fulltext_vtab *v,
97159   sqlite_int64 iBlockid,
97160   const char *pTerm, int nTerm, int isPrefix,
97161   sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
97162 ){
97163   sqlite3_stmt *s = NULL;
97164   int rc;
97165
97166   assert( iBlockid!=0 );
97167   assert( pTerm!=NULL );
97168   assert( nTerm!=0 );        /* TODO(shess) Why not allow this? */
97169   assert( piStartChild!=NULL );
97170   assert( piEndChild!=NULL );
97171
97172   rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
97173   if( rc!=SQLITE_OK ) return rc;
97174
97175   rc = sqlite3_bind_int64(s, 1, iBlockid);
97176   if( rc!=SQLITE_OK ) return rc;
97177
97178   rc = sqlite3_step(s);
97179   if( rc==SQLITE_DONE ) return SQLITE_ERROR;
97180   if( rc!=SQLITE_ROW ) return rc;
97181
97182   getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
97183                         pTerm, nTerm, isPrefix, piStartChild, piEndChild);
97184
97185   /* We expect only one row.  We must execute another sqlite3_step()
97186    * to complete the iteration; otherwise the table will remain
97187    * locked. */
97188   rc = sqlite3_step(s);
97189   if( rc==SQLITE_ROW ) return SQLITE_ERROR;
97190   if( rc!=SQLITE_DONE ) return rc;
97191
97192   return SQLITE_OK;
97193 }
97194
97195 /* Traverse the tree represented by pData[nData] looking for
97196 ** pTerm[nTerm], placing its doclist into *out.  This is internal to
97197 ** loadSegment() to make error-handling cleaner.
97198 */
97199 static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
97200                           sqlite_int64 iLeavesEnd,
97201                           const char *pTerm, int nTerm, int isPrefix,
97202                           DataBuffer *out){
97203   /* Special case where root is a leaf. */
97204   if( *pData=='\0' ){
97205     return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
97206   }else{
97207     int rc;
97208     sqlite_int64 iStartChild, iEndChild;
97209
97210     /* Process pData as an interior node, then loop down the tree
97211     ** until we find the set of leaf nodes to scan for the term.
97212     */
97213     getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
97214                           &iStartChild, &iEndChild);
97215     while( iStartChild>iLeavesEnd ){
97216       sqlite_int64 iNextStart, iNextEnd;
97217       rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
97218                                         &iNextStart, &iNextEnd);
97219       if( rc!=SQLITE_OK ) return rc;
97220
97221       /* If we've branched, follow the end branch, too. */
97222       if( iStartChild!=iEndChild ){
97223         sqlite_int64 iDummy;
97224         rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
97225                                           &iDummy, &iNextEnd);
97226         if( rc!=SQLITE_OK ) return rc;
97227       }
97228
97229       assert( iNextStart<=iNextEnd );
97230       iStartChild = iNextStart;
97231       iEndChild = iNextEnd;
97232     }
97233     assert( iStartChild<=iLeavesEnd );
97234     assert( iEndChild<=iLeavesEnd );
97235
97236     /* Scan through the leaf segments for doclists. */
97237     return loadSegmentLeaves(v, iStartChild, iEndChild,
97238                              pTerm, nTerm, isPrefix, out);
97239   }
97240 }
97241
97242 /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
97243 ** merge its doclist over *out (any duplicate doclists read from the
97244 ** segment rooted at pData will overwrite those in *out).
97245 */
97246 /* TODO(shess) Consider changing this to determine the depth of the
97247 ** leaves using either the first characters of interior nodes (when
97248 ** ==1, we're one level above the leaves), or the first character of
97249 ** the root (which will describe the height of the tree directly).
97250 ** Either feels somewhat tricky to me.
97251 */
97252 /* TODO(shess) The current merge is likely to be slow for large
97253 ** doclists (though it should process from newest/smallest to
97254 ** oldest/largest, so it may not be that bad).  It might be useful to
97255 ** modify things to allow for N-way merging.  This could either be
97256 ** within a segment, with pairwise merges across segments, or across
97257 ** all segments at once.
97258 */
97259 static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
97260                        sqlite_int64 iLeavesEnd,
97261                        const char *pTerm, int nTerm, int isPrefix,
97262                        DataBuffer *out){
97263   DataBuffer result;
97264   int rc;
97265
97266   assert( nData>1 );
97267
97268   /* This code should never be called with buffered updates. */
97269   assert( v->nPendingData<0 );
97270
97271   dataBufferInit(&result, 0);
97272   rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
97273                       pTerm, nTerm, isPrefix, &result);
97274   if( rc==SQLITE_OK && result.nData>0 ){
97275     if( out->nData==0 ){
97276       DataBuffer tmp = *out;
97277       *out = result;
97278       result = tmp;
97279     }else{
97280       DataBuffer merged;
97281       DLReader readers[2];
97282
97283       dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
97284       dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
97285       dataBufferInit(&merged, out->nData+result.nData);
97286       docListMerge(&merged, readers, 2);
97287       dataBufferDestroy(out);
97288       *out = merged;
97289       dlrDestroy(&readers[0]);
97290       dlrDestroy(&readers[1]);
97291     }
97292   }
97293   dataBufferDestroy(&result);
97294   return rc;
97295 }
97296
97297 /* Scan the database and merge together the posting lists for the term
97298 ** into *out.
97299 */
97300 static int termSelect(
97301   fulltext_vtab *v, 
97302   int iColumn,
97303   const char *pTerm, int nTerm,             /* Term to query for */
97304   int isPrefix,                             /* True for a prefix search */
97305   DocListType iType, 
97306   DataBuffer *out                           /* Write results here */
97307 ){
97308   DataBuffer doclist;
97309   sqlite3_stmt *s;
97310   int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
97311   if( rc!=SQLITE_OK ) return rc;
97312
97313   /* This code should never be called with buffered updates. */
97314   assert( v->nPendingData<0 );
97315
97316   dataBufferInit(&doclist, 0);
97317   dataBufferInit(out, 0);
97318
97319   /* Traverse the segments from oldest to newest so that newer doclist
97320   ** elements for given docids overwrite older elements.
97321   */
97322   while( (rc = sqlite3_step(s))==SQLITE_ROW ){
97323     const char *pData = sqlite3_column_blob(s, 2);
97324     const int nData = sqlite3_column_bytes(s, 2);
97325     const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
97326     rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
97327                      &doclist);
97328     if( rc!=SQLITE_OK ) goto err;
97329   }
97330   if( rc==SQLITE_DONE ){
97331     if( doclist.nData!=0 ){
97332       /* TODO(shess) The old term_select_all() code applied the column
97333       ** restrict as we merged segments, leading to smaller buffers.
97334       ** This is probably worthwhile to bring back, once the new storage
97335       ** system is checked in.
97336       */
97337       if( iColumn==v->nColumn) iColumn = -1;
97338       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
97339                   iColumn, iType, out);
97340     }
97341     rc = SQLITE_OK;
97342   }
97343
97344  err:
97345   dataBufferDestroy(&doclist);
97346   return rc;
97347 }
97348
97349 /****************************************************************/
97350 /* Used to hold hashtable data for sorting. */
97351 typedef struct TermData {
97352   const char *pTerm;
97353   int nTerm;
97354   DLCollector *pCollector;
97355 } TermData;
97356
97357 /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
97358 ** for equal, >0 for greater-than).
97359 */
97360 static int termDataCmp(const void *av, const void *bv){
97361   const TermData *a = (const TermData *)av;
97362   const TermData *b = (const TermData *)bv;
97363   int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
97364   int c = memcmp(a->pTerm, b->pTerm, n);
97365   if( c!=0 ) return c;
97366   return a->nTerm-b->nTerm;
97367 }
97368
97369 /* Order pTerms data by term, then write a new level 0 segment using
97370 ** LeafWriter.
97371 */
97372 static int writeZeroSegment(fulltext_vtab *v, fts3Hash *pTerms){
97373   fts3HashElem *e;
97374   int idx, rc, i, n;
97375   TermData *pData;
97376   LeafWriter writer;
97377   DataBuffer dl;
97378
97379   /* Determine the next index at level 0, merging as necessary. */
97380   rc = segdirNextIndex(v, 0, &idx);
97381   if( rc!=SQLITE_OK ) return rc;
97382
97383   n = fts3HashCount(pTerms);
97384   pData = sqlite3_malloc(n*sizeof(TermData));
97385
97386   for(i = 0, e = fts3HashFirst(pTerms); e; i++, e = fts3HashNext(e)){
97387     assert( i<n );
97388     pData[i].pTerm = fts3HashKey(e);
97389     pData[i].nTerm = fts3HashKeysize(e);
97390     pData[i].pCollector = fts3HashData(e);
97391   }
97392   assert( i==n );
97393
97394   /* TODO(shess) Should we allow user-defined collation sequences,
97395   ** here?  I think we only need that once we support prefix searches.
97396   */
97397   if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
97398
97399   /* TODO(shess) Refactor so that we can write directly to the segment
97400   ** DataBuffer, as happens for segment merges.
97401   */
97402   leafWriterInit(0, idx, &writer);
97403   dataBufferInit(&dl, 0);
97404   for(i=0; i<n; i++){
97405     dataBufferReset(&dl);
97406     dlcAddDoclist(pData[i].pCollector, &dl);
97407     rc = leafWriterStep(v, &writer,
97408                         pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
97409     if( rc!=SQLITE_OK ) goto err;
97410   }
97411   rc = leafWriterFinalize(v, &writer);
97412
97413  err:
97414   dataBufferDestroy(&dl);
97415   sqlite3_free(pData);
97416   leafWriterDestroy(&writer);
97417   return rc;
97418 }
97419
97420 /* If pendingTerms has data, free it. */
97421 static int clearPendingTerms(fulltext_vtab *v){
97422   if( v->nPendingData>=0 ){
97423     fts3HashElem *e;
97424     for(e=fts3HashFirst(&v->pendingTerms); e; e=fts3HashNext(e)){
97425       dlcDelete(fts3HashData(e));
97426     }
97427     fts3HashClear(&v->pendingTerms);
97428     v->nPendingData = -1;
97429   }
97430   return SQLITE_OK;
97431 }
97432
97433 /* If pendingTerms has data, flush it to a level-zero segment, and
97434 ** free it.
97435 */
97436 static int flushPendingTerms(fulltext_vtab *v){
97437   if( v->nPendingData>=0 ){
97438     int rc = writeZeroSegment(v, &v->pendingTerms);
97439     if( rc==SQLITE_OK ) clearPendingTerms(v);
97440     return rc;
97441   }
97442   return SQLITE_OK;
97443 }
97444
97445 /* If pendingTerms is "too big", or docid is out of order, flush it.
97446 ** Regardless, be certain that pendingTerms is initialized for use.
97447 */
97448 static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
97449   /* TODO(shess) Explore whether partially flushing the buffer on
97450   ** forced-flush would provide better performance.  I suspect that if
97451   ** we ordered the doclists by size and flushed the largest until the
97452   ** buffer was half empty, that would let the less frequent terms
97453   ** generate longer doclists.
97454   */
97455   if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
97456     int rc = flushPendingTerms(v);
97457     if( rc!=SQLITE_OK ) return rc;
97458   }
97459   if( v->nPendingData<0 ){
97460     fts3HashInit(&v->pendingTerms, FTS3_HASH_STRING, 1);
97461     v->nPendingData = 0;
97462   }
97463   v->iPrevDocid = iDocid;
97464   return SQLITE_OK;
97465 }
97466
97467 /* This function implements the xUpdate callback; it is the top-level entry
97468  * point for inserting, deleting or updating a row in a full-text table. */
97469 static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
97470                           sqlite_int64 *pRowid){
97471   fulltext_vtab *v = (fulltext_vtab *) pVtab;
97472   int rc;
97473
97474   FTSTRACE(("FTS3 Update %p\n", pVtab));
97475
97476   if( nArg<2 ){
97477     rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
97478     if( rc==SQLITE_OK ){
97479       /* If we just deleted the last row in the table, clear out the
97480       ** index data.
97481       */
97482       rc = content_exists(v);
97483       if( rc==SQLITE_ROW ){
97484         rc = SQLITE_OK;
97485       }else if( rc==SQLITE_DONE ){
97486         /* Clear the pending terms so we don't flush a useless level-0
97487         ** segment when the transaction closes.
97488         */
97489         rc = clearPendingTerms(v);
97490         if( rc==SQLITE_OK ){
97491           rc = segdir_delete_all(v);
97492         }
97493       }
97494     }
97495   } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
97496     /* An update:
97497      * ppArg[0] = old rowid
97498      * ppArg[1] = new rowid
97499      * ppArg[2..2+v->nColumn-1] = values
97500      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
97501      * ppArg[2+v->nColumn+1] = value for docid
97502      */
97503     sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
97504     if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
97505         sqlite3_value_int64(ppArg[1]) != rowid ){
97506       rc = SQLITE_ERROR;  /* we don't allow changing the rowid */
97507     }else if( sqlite3_value_type(ppArg[2+v->nColumn+1]) != SQLITE_INTEGER ||
97508               sqlite3_value_int64(ppArg[2+v->nColumn+1]) != rowid ){
97509       rc = SQLITE_ERROR;  /* we don't allow changing the docid */
97510     }else{
97511       assert( nArg==2+v->nColumn+2);
97512       rc = index_update(v, rowid, &ppArg[2]);
97513     }
97514   } else {
97515     /* An insert:
97516      * ppArg[1] = requested rowid
97517      * ppArg[2..2+v->nColumn-1] = values
97518      * ppArg[2+v->nColumn] = value for magic column (we ignore this)
97519      * ppArg[2+v->nColumn+1] = value for docid
97520      */
97521     sqlite3_value *pRequestDocid = ppArg[2+v->nColumn+1];
97522     assert( nArg==2+v->nColumn+2);
97523     if( SQLITE_NULL != sqlite3_value_type(pRequestDocid) &&
97524         SQLITE_NULL != sqlite3_value_type(ppArg[1]) ){
97525       /* TODO(shess) Consider allowing this to work if the values are
97526       ** identical.  I'm inclined to discourage that usage, though,
97527       ** given that both rowid and docid are special columns.  Better
97528       ** would be to define one or the other as the default winner,
97529       ** but should it be fts3-centric (docid) or SQLite-centric
97530       ** (rowid)?
97531       */
97532       rc = SQLITE_ERROR;
97533     }else{
97534       if( SQLITE_NULL == sqlite3_value_type(pRequestDocid) ){
97535         pRequestDocid = ppArg[1];
97536       }
97537       rc = index_insert(v, pRequestDocid, &ppArg[2], pRowid);
97538     }
97539   }
97540
97541   return rc;
97542 }
97543
97544 static int fulltextSync(sqlite3_vtab *pVtab){
97545   FTSTRACE(("FTS3 xSync()\n"));
97546   return flushPendingTerms((fulltext_vtab *)pVtab);
97547 }
97548
97549 static int fulltextBegin(sqlite3_vtab *pVtab){
97550   fulltext_vtab *v = (fulltext_vtab *) pVtab;
97551   FTSTRACE(("FTS3 xBegin()\n"));
97552
97553   /* Any buffered updates should have been cleared by the previous
97554   ** transaction.
97555   */
97556   assert( v->nPendingData<0 );
97557   return clearPendingTerms(v);
97558 }
97559
97560 static int fulltextCommit(sqlite3_vtab *pVtab){
97561   fulltext_vtab *v = (fulltext_vtab *) pVtab;
97562   FTSTRACE(("FTS3 xCommit()\n"));
97563
97564   /* Buffered updates should have been cleared by fulltextSync(). */
97565   assert( v->nPendingData<0 );
97566   return clearPendingTerms(v);
97567 }
97568
97569 static int fulltextRollback(sqlite3_vtab *pVtab){
97570   FTSTRACE(("FTS3 xRollback()\n"));
97571   return clearPendingTerms((fulltext_vtab *)pVtab);
97572 }
97573
97574 /*
97575 ** Implementation of the snippet() function for FTS3
97576 */
97577 static void snippetFunc(
97578   sqlite3_context *pContext,
97579   int argc,
97580   sqlite3_value **argv
97581 ){
97582   fulltext_cursor *pCursor;
97583   if( argc<1 ) return;
97584   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
97585       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
97586     sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
97587   }else{
97588     const char *zStart = "<b>";
97589     const char *zEnd = "</b>";
97590     const char *zEllipsis = "<b>...</b>";
97591     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
97592     if( argc>=2 ){
97593       zStart = (const char*)sqlite3_value_text(argv[1]);
97594       if( argc>=3 ){
97595         zEnd = (const char*)sqlite3_value_text(argv[2]);
97596         if( argc>=4 ){
97597           zEllipsis = (const char*)sqlite3_value_text(argv[3]);
97598         }
97599       }
97600     }
97601     snippetAllOffsets(pCursor);
97602     snippetText(pCursor, zStart, zEnd, zEllipsis);
97603     sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
97604                         pCursor->snippet.nSnippet, SQLITE_STATIC);
97605   }
97606 }
97607
97608 /*
97609 ** Implementation of the offsets() function for FTS3
97610 */
97611 static void snippetOffsetsFunc(
97612   sqlite3_context *pContext,
97613   int argc,
97614   sqlite3_value **argv
97615 ){
97616   fulltext_cursor *pCursor;
97617   if( argc<1 ) return;
97618   if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
97619       sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
97620     sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
97621   }else{
97622     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
97623     snippetAllOffsets(pCursor);
97624     snippetOffsetText(&pCursor->snippet);
97625     sqlite3_result_text(pContext,
97626                         pCursor->snippet.zOffset, pCursor->snippet.nOffset,
97627                         SQLITE_STATIC);
97628   }
97629 }
97630
97631 /* OptLeavesReader is nearly identical to LeavesReader, except that
97632 ** where LeavesReader is geared towards the merging of complete
97633 ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
97634 ** is geared towards implementation of the optimize() function, and
97635 ** can merge all segments simultaneously.  This version may be
97636 ** somewhat less efficient than LeavesReader because it merges into an
97637 ** accumulator rather than doing an N-way merge, but since segment
97638 ** size grows exponentially (so segment count logrithmically) this is
97639 ** probably not an immediate problem.
97640 */
97641 /* TODO(shess): Prove that assertion, or extend the merge code to
97642 ** merge tree fashion (like the prefix-searching code does).
97643 */
97644 /* TODO(shess): OptLeavesReader and LeavesReader could probably be
97645 ** merged with little or no loss of performance for LeavesReader.  The
97646 ** merged code would need to handle >MERGE_COUNT segments, and would
97647 ** also need to be able to optionally optimize away deletes.
97648 */
97649 typedef struct OptLeavesReader {
97650   /* Segment number, to order readers by age. */
97651   int segment;
97652   LeavesReader reader;
97653 } OptLeavesReader;
97654
97655 static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
97656   return leavesReaderAtEnd(&pReader->reader);
97657 }
97658 static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
97659   return leavesReaderTermBytes(&pReader->reader);
97660 }
97661 static const char *optLeavesReaderData(OptLeavesReader *pReader){
97662   return leavesReaderData(&pReader->reader);
97663 }
97664 static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
97665   return leavesReaderDataBytes(&pReader->reader);
97666 }
97667 static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
97668   return leavesReaderTerm(&pReader->reader);
97669 }
97670 static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
97671   return leavesReaderStep(v, &pReader->reader);
97672 }
97673 static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
97674   return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
97675 }
97676 /* Order by term ascending, segment ascending (oldest to newest), with
97677 ** exhausted readers to the end.
97678 */
97679 static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
97680   int c = optLeavesReaderTermCmp(lr1, lr2);
97681   if( c!=0 ) return c;
97682   return lr1->segment-lr2->segment;
97683 }
97684 /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1].  Assumes that
97685 ** pLr[1..nLr-1] is already sorted.
97686 */
97687 static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
97688   while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
97689     OptLeavesReader tmp = pLr[0];
97690     pLr[0] = pLr[1];
97691     pLr[1] = tmp;
97692     nLr--;
97693     pLr++;
97694   }
97695 }
97696
97697 /* optimize() helper function.  Put the readers in order and iterate
97698 ** through them, merging doclists for matching terms into pWriter.
97699 ** Returns SQLITE_OK on success, or the SQLite error code which
97700 ** prevented success.
97701 */
97702 static int optimizeInternal(fulltext_vtab *v,
97703                             OptLeavesReader *readers, int nReaders,
97704                             LeafWriter *pWriter){
97705   int i, rc = SQLITE_OK;
97706   DataBuffer doclist, merged, tmp;
97707
97708   /* Order the readers. */
97709   i = nReaders;
97710   while( i-- > 0 ){
97711     optLeavesReaderReorder(&readers[i], nReaders-i);
97712   }
97713
97714   dataBufferInit(&doclist, LEAF_MAX);
97715   dataBufferInit(&merged, LEAF_MAX);
97716
97717   /* Exhausted readers bubble to the end, so when the first reader is
97718   ** at eof, all are at eof.
97719   */
97720   while( !optLeavesReaderAtEnd(&readers[0]) ){
97721
97722     /* Figure out how many readers share the next term. */
97723     for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
97724       if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
97725     }
97726
97727     /* Special-case for no merge. */
97728     if( i==1 ){
97729       /* Trim deletions from the doclist. */
97730       dataBufferReset(&merged);
97731       docListTrim(DL_DEFAULT,
97732                   optLeavesReaderData(&readers[0]),
97733                   optLeavesReaderDataBytes(&readers[0]),
97734                   -1, DL_DEFAULT, &merged);
97735     }else{
97736       DLReader dlReaders[MERGE_COUNT];
97737       int iReader, nReaders;
97738
97739       /* Prime the pipeline with the first reader's doclist.  After
97740       ** one pass index 0 will reference the accumulated doclist.
97741       */
97742       dlrInit(&dlReaders[0], DL_DEFAULT,
97743               optLeavesReaderData(&readers[0]),
97744               optLeavesReaderDataBytes(&readers[0]));
97745       iReader = 1;
97746
97747       assert( iReader<i );  /* Must execute the loop at least once. */
97748       while( iReader<i ){
97749         /* Merge 16 inputs per pass. */
97750         for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
97751              iReader++, nReaders++ ){
97752           dlrInit(&dlReaders[nReaders], DL_DEFAULT,
97753                   optLeavesReaderData(&readers[iReader]),
97754                   optLeavesReaderDataBytes(&readers[iReader]));
97755         }
97756
97757         /* Merge doclists and swap result into accumulator. */
97758         dataBufferReset(&merged);
97759         docListMerge(&merged, dlReaders, nReaders);
97760         tmp = merged;
97761         merged = doclist;
97762         doclist = tmp;
97763
97764         while( nReaders-- > 0 ){
97765           dlrDestroy(&dlReaders[nReaders]);
97766         }
97767
97768         /* Accumulated doclist to reader 0 for next pass. */
97769         dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
97770       }
97771
97772       /* Destroy reader that was left in the pipeline. */
97773       dlrDestroy(&dlReaders[0]);
97774
97775       /* Trim deletions from the doclist. */
97776       dataBufferReset(&merged);
97777       docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
97778                   -1, DL_DEFAULT, &merged);
97779     }
97780
97781     /* Only pass doclists with hits (skip if all hits deleted). */
97782     if( merged.nData>0 ){
97783       rc = leafWriterStep(v, pWriter,
97784                           optLeavesReaderTerm(&readers[0]),
97785                           optLeavesReaderTermBytes(&readers[0]),
97786                           merged.pData, merged.nData);
97787       if( rc!=SQLITE_OK ) goto err;
97788     }
97789
97790     /* Step merged readers to next term and reorder. */
97791     while( i-- > 0 ){
97792       rc = optLeavesReaderStep(v, &readers[i]);
97793       if( rc!=SQLITE_OK ) goto err;
97794
97795       optLeavesReaderReorder(&readers[i], nReaders-i);
97796     }
97797   }
97798
97799  err:
97800   dataBufferDestroy(&doclist);
97801   dataBufferDestroy(&merged);
97802   return rc;
97803 }
97804
97805 /* Implement optimize() function for FTS3.  optimize(t) merges all
97806 ** segments in the fts index into a single segment.  't' is the magic
97807 ** table-named column.
97808 */
97809 static void optimizeFunc(sqlite3_context *pContext,
97810                          int argc, sqlite3_value **argv){
97811   fulltext_cursor *pCursor;
97812   if( argc>1 ){
97813     sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
97814   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
97815             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
97816     sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
97817   }else{
97818     fulltext_vtab *v;
97819     int i, rc, iMaxLevel;
97820     OptLeavesReader *readers;
97821     int nReaders;
97822     LeafWriter writer;
97823     sqlite3_stmt *s;
97824
97825     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
97826     v = cursor_vtab(pCursor);
97827
97828     /* Flush any buffered updates before optimizing. */
97829     rc = flushPendingTerms(v);
97830     if( rc!=SQLITE_OK ) goto err;
97831
97832     rc = segdir_count(v, &nReaders, &iMaxLevel);
97833     if( rc!=SQLITE_OK ) goto err;
97834     if( nReaders==0 || nReaders==1 ){
97835       sqlite3_result_text(pContext, "Index already optimal", -1,
97836                           SQLITE_STATIC);
97837       return;
97838     }
97839
97840     rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
97841     if( rc!=SQLITE_OK ) goto err;
97842
97843     readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
97844     if( readers==NULL ) goto err;
97845
97846     /* Note that there will already be a segment at this position
97847     ** until we call segdir_delete() on iMaxLevel.
97848     */
97849     leafWriterInit(iMaxLevel, 0, &writer);
97850
97851     i = 0;
97852     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
97853       sqlite_int64 iStart = sqlite3_column_int64(s, 0);
97854       sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
97855       const char *pRootData = sqlite3_column_blob(s, 2);
97856       int nRootData = sqlite3_column_bytes(s, 2);
97857
97858       assert( i<nReaders );
97859       rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
97860                             &readers[i].reader);
97861       if( rc!=SQLITE_OK ) break;
97862
97863       readers[i].segment = i;
97864       i++;
97865     }
97866
97867     /* If we managed to succesfully read them all, optimize them. */
97868     if( rc==SQLITE_DONE ){
97869       assert( i==nReaders );
97870       rc = optimizeInternal(v, readers, nReaders, &writer);
97871     }
97872
97873     while( i-- > 0 ){
97874       leavesReaderDestroy(&readers[i].reader);
97875     }
97876     sqlite3_free(readers);
97877
97878     /* If we've successfully gotten to here, delete the old segments
97879     ** and flush the interior structure of the new segment.
97880     */
97881     if( rc==SQLITE_OK ){
97882       for( i=0; i<=iMaxLevel; i++ ){
97883         rc = segdir_delete(v, i);
97884         if( rc!=SQLITE_OK ) break;
97885       }
97886
97887       if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
97888     }
97889
97890     leafWriterDestroy(&writer);
97891
97892     if( rc!=SQLITE_OK ) goto err;
97893
97894     sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
97895     return;
97896
97897     /* TODO(shess): Error-handling needs to be improved along the
97898     ** lines of the dump_ functions.
97899     */
97900  err:
97901     {
97902       char buf[512];
97903       sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
97904                        sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
97905       sqlite3_result_error(pContext, buf, -1);
97906     }
97907   }
97908 }
97909
97910 #ifdef SQLITE_TEST
97911 /* Generate an error of the form "<prefix>: <msg>".  If msg is NULL,
97912 ** pull the error from the context's db handle.
97913 */
97914 static void generateError(sqlite3_context *pContext,
97915                           const char *prefix, const char *msg){
97916   char buf[512];
97917   if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
97918   sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
97919   sqlite3_result_error(pContext, buf, -1);
97920 }
97921
97922 /* Helper function to collect the set of terms in the segment into
97923 ** pTerms.  The segment is defined by the leaf nodes between
97924 ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
97925 ** pRootData if iStartBlockid is 0 (in which case the entire segment
97926 ** fit in a leaf).
97927 */
97928 static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
97929                                fts3Hash *pTerms){
97930   const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
97931   const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
97932   const char *pRootData = sqlite3_column_blob(s, 2);
97933   const int nRootData = sqlite3_column_bytes(s, 2);
97934   LeavesReader reader;
97935   int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
97936                             pRootData, nRootData, &reader);
97937   if( rc!=SQLITE_OK ) return rc;
97938
97939   while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
97940     const char *pTerm = leavesReaderTerm(&reader);
97941     const int nTerm = leavesReaderTermBytes(&reader);
97942     void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm);
97943     void *newValue = (void *)((char *)oldValue+1);
97944
97945     /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c,
97946     ** the data value passed is returned in case of malloc failure.
97947     */
97948     if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){
97949       rc = SQLITE_NOMEM;
97950     }else{
97951       rc = leavesReaderStep(v, &reader);
97952     }
97953   }
97954
97955   leavesReaderDestroy(&reader);
97956   return rc;
97957 }
97958
97959 /* Helper function to build the result string for dump_terms(). */
97960 static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){
97961   int iTerm, nTerms, nResultBytes, iByte;
97962   char *result;
97963   TermData *pData;
97964   fts3HashElem *e;
97965
97966   /* Iterate pTerms to generate an array of terms in pData for
97967   ** sorting.
97968   */
97969   nTerms = fts3HashCount(pTerms);
97970   assert( nTerms>0 );
97971   pData = sqlite3_malloc(nTerms*sizeof(TermData));
97972   if( pData==NULL ) return SQLITE_NOMEM;
97973
97974   nResultBytes = 0;
97975   for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){
97976     nResultBytes += fts3HashKeysize(e)+1;   /* Term plus trailing space */
97977     assert( iTerm<nTerms );
97978     pData[iTerm].pTerm = fts3HashKey(e);
97979     pData[iTerm].nTerm = fts3HashKeysize(e);
97980     pData[iTerm].pCollector = fts3HashData(e);  /* unused */
97981   }
97982   assert( iTerm==nTerms );
97983
97984   assert( nResultBytes>0 );   /* nTerms>0, nResultsBytes must be, too. */
97985   result = sqlite3_malloc(nResultBytes);
97986   if( result==NULL ){
97987     sqlite3_free(pData);
97988     return SQLITE_NOMEM;
97989   }
97990
97991   if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
97992
97993   /* Read the terms in order to build the result. */
97994   iByte = 0;
97995   for(iTerm=0; iTerm<nTerms; ++iTerm){
97996     memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
97997     iByte += pData[iTerm].nTerm;
97998     result[iByte++] = ' ';
97999   }
98000   assert( iByte==nResultBytes );
98001   assert( result[nResultBytes-1]==' ' );
98002   result[nResultBytes-1] = '\0';
98003
98004   /* Passes away ownership of result. */
98005   sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
98006   sqlite3_free(pData);
98007   return SQLITE_OK;
98008 }
98009
98010 /* Implements dump_terms() for use in inspecting the fts3 index from
98011 ** tests.  TEXT result containing the ordered list of terms joined by
98012 ** spaces.  dump_terms(t, level, idx) dumps the terms for the segment
98013 ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
98014 ** all terms in the index.  In both cases t is the fts table's magic
98015 ** table-named column.
98016 */
98017 static void dumpTermsFunc(
98018   sqlite3_context *pContext,
98019   int argc, sqlite3_value **argv
98020 ){
98021   fulltext_cursor *pCursor;
98022   if( argc!=3 && argc!=1 ){
98023     generateError(pContext, "dump_terms", "incorrect arguments");
98024   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
98025             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
98026     generateError(pContext, "dump_terms", "illegal first argument");
98027   }else{
98028     fulltext_vtab *v;
98029     fts3Hash terms;
98030     sqlite3_stmt *s = NULL;
98031     int rc;
98032
98033     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
98034     v = cursor_vtab(pCursor);
98035
98036     /* If passed only the cursor column, get all segments.  Otherwise
98037     ** get the segment described by the following two arguments.
98038     */
98039     if( argc==1 ){
98040       rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
98041     }else{
98042       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
98043       if( rc==SQLITE_OK ){
98044         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
98045         if( rc==SQLITE_OK ){
98046           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
98047         }
98048       }
98049     }
98050
98051     if( rc!=SQLITE_OK ){
98052       generateError(pContext, "dump_terms", NULL);
98053       return;
98054     }
98055
98056     /* Collect the terms for each segment. */
98057     sqlite3Fts3HashInit(&terms, FTS3_HASH_STRING, 1);
98058     while( (rc = sqlite3_step(s))==SQLITE_ROW ){
98059       rc = collectSegmentTerms(v, s, &terms);
98060       if( rc!=SQLITE_OK ) break;
98061     }
98062
98063     if( rc!=SQLITE_DONE ){
98064       sqlite3_reset(s);
98065       generateError(pContext, "dump_terms", NULL);
98066     }else{
98067       const int nTerms = fts3HashCount(&terms);
98068       if( nTerms>0 ){
98069         rc = generateTermsResult(pContext, &terms);
98070         if( rc==SQLITE_NOMEM ){
98071           generateError(pContext, "dump_terms", "out of memory");
98072         }else{
98073           assert( rc==SQLITE_OK );
98074         }
98075       }else if( argc==3 ){
98076         /* The specific segment asked for could not be found. */
98077         generateError(pContext, "dump_terms", "segment not found");
98078       }else{
98079         /* No segments found. */
98080         /* TODO(shess): It should be impossible to reach this.  This
98081         ** case can only happen for an empty table, in which case
98082         ** SQLite has no rows to call this function on.
98083         */
98084         sqlite3_result_null(pContext);
98085       }
98086     }
98087     sqlite3Fts3HashClear(&terms);
98088   }
98089 }
98090
98091 /* Expand the DL_DEFAULT doclist in pData into a text result in
98092 ** pContext.
98093 */
98094 static void createDoclistResult(sqlite3_context *pContext,
98095                                 const char *pData, int nData){
98096   DataBuffer dump;
98097   DLReader dlReader;
98098
98099   assert( pData!=NULL && nData>0 );
98100
98101   dataBufferInit(&dump, 0);
98102   dlrInit(&dlReader, DL_DEFAULT, pData, nData);
98103   for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
98104     char buf[256];
98105     PLReader plReader;
98106
98107     plrInit(&plReader, &dlReader);
98108     if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
98109       sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
98110       dataBufferAppend(&dump, buf, strlen(buf));
98111     }else{
98112       int iColumn = plrColumn(&plReader);
98113
98114       sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
98115                        dlrDocid(&dlReader), iColumn);
98116       dataBufferAppend(&dump, buf, strlen(buf));
98117
98118       for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
98119         if( plrColumn(&plReader)!=iColumn ){
98120           iColumn = plrColumn(&plReader);
98121           sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
98122           assert( dump.nData>0 );
98123           dump.nData--;                     /* Overwrite trailing space. */
98124           assert( dump.pData[dump.nData]==' ');
98125           dataBufferAppend(&dump, buf, strlen(buf));
98126         }
98127         if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
98128           sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
98129                            plrPosition(&plReader),
98130                            plrStartOffset(&plReader), plrEndOffset(&plReader));
98131         }else if( DL_DEFAULT==DL_POSITIONS ){
98132           sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
98133         }else{
98134           assert( NULL=="Unhandled DL_DEFAULT value");
98135         }
98136         dataBufferAppend(&dump, buf, strlen(buf));
98137       }
98138       plrDestroy(&plReader);
98139
98140       assert( dump.nData>0 );
98141       dump.nData--;                     /* Overwrite trailing space. */
98142       assert( dump.pData[dump.nData]==' ');
98143       dataBufferAppend(&dump, "]] ", 3);
98144     }
98145   }
98146   dlrDestroy(&dlReader);
98147
98148   assert( dump.nData>0 );
98149   dump.nData--;                     /* Overwrite trailing space. */
98150   assert( dump.pData[dump.nData]==' ');
98151   dump.pData[dump.nData] = '\0';
98152   assert( dump.nData>0 );
98153
98154   /* Passes ownership of dump's buffer to pContext. */
98155   sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
98156   dump.pData = NULL;
98157   dump.nData = dump.nCapacity = 0;
98158 }
98159
98160 /* Implements dump_doclist() for use in inspecting the fts3 index from
98161 ** tests.  TEXT result containing a string representation of the
98162 ** doclist for the indicated term.  dump_doclist(t, term, level, idx)
98163 ** dumps the doclist for term from the segment specified by level, idx
98164 ** (in %_segdir), while dump_doclist(t, term) dumps the logical
98165 ** doclist for the term across all segments.  The per-segment doclist
98166 ** can contain deletions, while the full-index doclist will not
98167 ** (deletions are omitted).
98168 **
98169 ** Result formats differ with the setting of DL_DEFAULTS.  Examples:
98170 **
98171 ** DL_DOCIDS: [1] [3] [7]
98172 ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
98173 ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
98174 **
98175 ** In each case the number after the outer '[' is the docid.  In the
98176 ** latter two cases, the number before the inner '[' is the column
98177 ** associated with the values within.  For DL_POSITIONS the numbers
98178 ** within are the positions, for DL_POSITIONS_OFFSETS they are the
98179 ** position, the start offset, and the end offset.
98180 */
98181 static void dumpDoclistFunc(
98182   sqlite3_context *pContext,
98183   int argc, sqlite3_value **argv
98184 ){
98185   fulltext_cursor *pCursor;
98186   if( argc!=2 && argc!=4 ){
98187     generateError(pContext, "dump_doclist", "incorrect arguments");
98188   }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
98189             sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
98190     generateError(pContext, "dump_doclist", "illegal first argument");
98191   }else if( sqlite3_value_text(argv[1])==NULL ||
98192             sqlite3_value_text(argv[1])[0]=='\0' ){
98193     generateError(pContext, "dump_doclist", "empty second argument");
98194   }else{
98195     const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
98196     const int nTerm = strlen(pTerm);
98197     fulltext_vtab *v;
98198     int rc;
98199     DataBuffer doclist;
98200
98201     memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
98202     v = cursor_vtab(pCursor);
98203
98204     dataBufferInit(&doclist, 0);
98205
98206     /* termSelect() yields the same logical doclist that queries are
98207     ** run against.
98208     */
98209     if( argc==2 ){
98210       rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
98211     }else{
98212       sqlite3_stmt *s = NULL;
98213
98214       /* Get our specific segment's information. */
98215       rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
98216       if( rc==SQLITE_OK ){
98217         rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
98218         if( rc==SQLITE_OK ){
98219           rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
98220         }
98221       }
98222
98223       if( rc==SQLITE_OK ){
98224         rc = sqlite3_step(s);
98225
98226         if( rc==SQLITE_DONE ){
98227           dataBufferDestroy(&doclist);
98228           generateError(pContext, "dump_doclist", "segment not found");
98229           return;
98230         }
98231
98232         /* Found a segment, load it into doclist. */
98233         if( rc==SQLITE_ROW ){
98234           const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
98235           const char *pData = sqlite3_column_blob(s, 2);
98236           const int nData = sqlite3_column_bytes(s, 2);
98237
98238           /* loadSegment() is used by termSelect() to load each
98239           ** segment's data.
98240           */
98241           rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
98242                            &doclist);
98243           if( rc==SQLITE_OK ){
98244             rc = sqlite3_step(s);
98245
98246             /* Should not have more than one matching segment. */
98247             if( rc!=SQLITE_DONE ){
98248               sqlite3_reset(s);
98249               dataBufferDestroy(&doclist);
98250               generateError(pContext, "dump_doclist", "invalid segdir");
98251               return;
98252             }
98253             rc = SQLITE_OK;
98254           }
98255         }
98256       }
98257
98258       sqlite3_reset(s);
98259     }
98260
98261     if( rc==SQLITE_OK ){
98262       if( doclist.nData>0 ){
98263         createDoclistResult(pContext, doclist.pData, doclist.nData);
98264       }else{
98265         /* TODO(shess): This can happen if the term is not present, or
98266         ** if all instances of the term have been deleted and this is
98267         ** an all-index dump.  It may be interesting to distinguish
98268         ** these cases.
98269         */
98270         sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
98271       }
98272     }else if( rc==SQLITE_NOMEM ){
98273       /* Handle out-of-memory cases specially because if they are
98274       ** generated in fts3 code they may not be reflected in the db
98275       ** handle.
98276       */
98277       /* TODO(shess): Handle this more comprehensively.
98278       ** sqlite3ErrStr() has what I need, but is internal.
98279       */
98280       generateError(pContext, "dump_doclist", "out of memory");
98281     }else{
98282       generateError(pContext, "dump_doclist", NULL);
98283     }
98284
98285     dataBufferDestroy(&doclist);
98286   }
98287 }
98288 #endif
98289
98290 /*
98291 ** This routine implements the xFindFunction method for the FTS3
98292 ** virtual table.
98293 */
98294 static int fulltextFindFunction(
98295   sqlite3_vtab *pVtab,
98296   int nArg,
98297   const char *zName,
98298   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
98299   void **ppArg
98300 ){
98301   if( strcmp(zName,"snippet")==0 ){
98302     *pxFunc = snippetFunc;
98303     return 1;
98304   }else if( strcmp(zName,"offsets")==0 ){
98305     *pxFunc = snippetOffsetsFunc;
98306     return 1;
98307   }else if( strcmp(zName,"optimize")==0 ){
98308     *pxFunc = optimizeFunc;
98309     return 1;
98310 #ifdef SQLITE_TEST
98311     /* NOTE(shess): These functions are present only for testing
98312     ** purposes.  No particular effort is made to optimize their
98313     ** execution or how they build their results.
98314     */
98315   }else if( strcmp(zName,"dump_terms")==0 ){
98316     /* fprintf(stderr, "Found dump_terms\n"); */
98317     *pxFunc = dumpTermsFunc;
98318     return 1;
98319   }else if( strcmp(zName,"dump_doclist")==0 ){
98320     /* fprintf(stderr, "Found dump_doclist\n"); */
98321     *pxFunc = dumpDoclistFunc;
98322     return 1;
98323 #endif
98324   }
98325   return 0;
98326 }
98327
98328 /*
98329 ** Rename an fts3 table.
98330 */
98331 static int fulltextRename(
98332   sqlite3_vtab *pVtab,
98333   const char *zName
98334 ){
98335   fulltext_vtab *p = (fulltext_vtab *)pVtab;
98336   int rc = SQLITE_NOMEM;
98337   char *zSql = sqlite3_mprintf(
98338     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
98339     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
98340     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
98341     , p->zDb, p->zName, zName 
98342     , p->zDb, p->zName, zName 
98343     , p->zDb, p->zName, zName
98344   );
98345   if( zSql ){
98346     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98347     sqlite3_free(zSql);
98348   }
98349   return rc;
98350 }
98351
98352 static const sqlite3_module fts3Module = {
98353   /* iVersion      */ 0,
98354   /* xCreate       */ fulltextCreate,
98355   /* xConnect      */ fulltextConnect,
98356   /* xBestIndex    */ fulltextBestIndex,
98357   /* xDisconnect   */ fulltextDisconnect,
98358   /* xDestroy      */ fulltextDestroy,
98359   /* xOpen         */ fulltextOpen,
98360   /* xClose        */ fulltextClose,
98361   /* xFilter       */ fulltextFilter,
98362   /* xNext         */ fulltextNext,
98363   /* xEof          */ fulltextEof,
98364   /* xColumn       */ fulltextColumn,
98365   /* xRowid        */ fulltextRowid,
98366   /* xUpdate       */ fulltextUpdate,
98367   /* xBegin        */ fulltextBegin,
98368   /* xSync         */ fulltextSync,
98369   /* xCommit       */ fulltextCommit,
98370   /* xRollback     */ fulltextRollback,
98371   /* xFindFunction */ fulltextFindFunction,
98372   /* xRename */       fulltextRename,
98373 };
98374
98375 static void hashDestroy(void *p){
98376   fts3Hash *pHash = (fts3Hash *)p;
98377   sqlite3Fts3HashClear(pHash);
98378   sqlite3_free(pHash);
98379 }
98380
98381 /*
98382 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
98383 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
98384 ** two forward declarations are for functions declared in these files
98385 ** used to retrieve the respective implementations.
98386 **
98387 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
98388 ** to by the argument to point a the "simple" tokenizer implementation.
98389 ** Function ...PorterTokenizerModule() sets *pModule to point to the
98390 ** porter tokenizer/stemmer implementation.
98391 */
98392 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
98393 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
98394 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
98395
98396 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *);
98397
98398 /*
98399 ** Initialise the fts3 extension. If this extension is built as part
98400 ** of the sqlite library, then this function is called directly by
98401 ** SQLite. If fts3 is built as a dynamically loadable extension, this
98402 ** function is called by the sqlite3_extension_init() entry point.
98403 */
98404 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
98405   int rc = SQLITE_OK;
98406   fts3Hash *pHash = 0;
98407   const sqlite3_tokenizer_module *pSimple = 0;
98408   const sqlite3_tokenizer_module *pPorter = 0;
98409   const sqlite3_tokenizer_module *pIcu = 0;
98410
98411   sqlite3Fts3SimpleTokenizerModule(&pSimple);
98412   sqlite3Fts3PorterTokenizerModule(&pPorter);
98413 #ifdef SQLITE_ENABLE_ICU
98414   sqlite3Fts3IcuTokenizerModule(&pIcu);
98415 #endif
98416
98417   /* Allocate and initialise the hash-table used to store tokenizers. */
98418   pHash = sqlite3_malloc(sizeof(fts3Hash));
98419   if( !pHash ){
98420     rc = SQLITE_NOMEM;
98421   }else{
98422     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
98423   }
98424
98425   /* Load the built-in tokenizers into the hash table */
98426   if( rc==SQLITE_OK ){
98427     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
98428      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
98429      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
98430     ){
98431       rc = SQLITE_NOMEM;
98432     }
98433   }
98434
98435 #ifdef SQLITE_TEST
98436   sqlite3Fts3ExprInitTestInterface(db);
98437 #endif
98438
98439   /* Create the virtual table wrapper around the hash-table and overload 
98440   ** the two scalar functions. If this is successful, register the
98441   ** module with sqlite.
98442   */
98443   if( SQLITE_OK==rc 
98444    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
98445    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
98446    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
98447    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
98448 #ifdef SQLITE_TEST
98449    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
98450    && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
98451 #endif
98452   ){
98453     return sqlite3_create_module_v2(
98454         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
98455     );
98456   }
98457
98458   /* An error has occured. Delete the hash table and return the error code. */
98459   assert( rc!=SQLITE_OK );
98460   if( pHash ){
98461     sqlite3Fts3HashClear(pHash);
98462     sqlite3_free(pHash);
98463   }
98464   return rc;
98465 }
98466
98467 #if !SQLITE_CORE
98468 SQLITE_API int sqlite3_extension_init(
98469   sqlite3 *db, 
98470   char **pzErrMsg,
98471   const sqlite3_api_routines *pApi
98472 ){
98473   SQLITE_EXTENSION_INIT2(pApi)
98474   return sqlite3Fts3Init(db);
98475 }
98476 #endif
98477
98478 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
98479
98480 /************** End of fts3.c ************************************************/
98481 /************** Begin file fts3_expr.c ***************************************/
98482 /*
98483 ** 2008 Nov 28
98484 **
98485 ** The author disclaims copyright to this source code.  In place of
98486 ** a legal notice, here is a blessing:
98487 **
98488 **    May you do good and not evil.
98489 **    May you find forgiveness for yourself and forgive others.
98490 **    May you share freely, never taking more than you give.
98491 **
98492 ******************************************************************************
98493 **
98494 ** This module contains code that implements a parser for fts3 query strings
98495 ** (the right-hand argument to the MATCH operator). Because the supported 
98496 ** syntax is relatively simple, the whole tokenizer/parser system is
98497 ** hand-coded. The public interface to this module is declared in source
98498 ** code file "fts3_expr.h".
98499 */
98500 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98501
98502 /*
98503 ** By default, this module parses the legacy syntax that has been 
98504 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
98505 ** is defined, then it uses the new syntax. The differences between
98506 ** the new and the old syntaxes are:
98507 **
98508 **  a) The new syntax supports parenthesis. The old does not.
98509 **
98510 **  b) The new syntax supports the AND and NOT operators. The old does not.
98511 **
98512 **  c) The old syntax supports the "-" token qualifier. This is not 
98513 **     supported by the new syntax (it is replaced by the NOT operator).
98514 **
98515 **  d) When using the old syntax, the OR operator has a greater precedence
98516 **     than an implicit AND. When using the new, both implicity and explicit
98517 **     AND operators have a higher precedence than OR.
98518 **
98519 ** If compiled with SQLITE_TEST defined, then this module exports the
98520 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
98521 ** to zero causes the module to use the old syntax. If it is set to 
98522 ** non-zero the new syntax is activated. This is so both syntaxes can
98523 ** be tested using a single build of testfixture.
98524 */
98525 #ifdef SQLITE_TEST
98526 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
98527 #else
98528 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
98529 #  define sqlite3_fts3_enable_parentheses 1
98530 # else
98531 #  define sqlite3_fts3_enable_parentheses 0
98532 # endif
98533 #endif
98534
98535 /*
98536 ** Default span for NEAR operators.
98537 */
98538 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
98539
98540
98541 typedef struct ParseContext ParseContext;
98542 struct ParseContext {
98543   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
98544   const char **azCol;                 /* Array of column names for fts3 table */
98545   int nCol;                           /* Number of entries in azCol[] */
98546   int iDefaultCol;                    /* Default column to query */
98547   sqlite3_context *pCtx;              /* Write error message here */
98548   int nNest;                          /* Number of nested brackets */
98549 };
98550
98551 /*
98552 ** This function is equivalent to the standard isspace() function. 
98553 **
98554 ** The standard isspace() can be awkward to use safely, because although it
98555 ** is defined to accept an argument of type int, its behaviour when passed
98556 ** an integer that falls outside of the range of the unsigned char type
98557 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
98558 ** is defined to accept an argument of type char, and always returns 0 for
98559 ** any values that fall outside of the range of the unsigned char type (i.e.
98560 ** negative values).
98561 */
98562 static int fts3isspace(char c){
98563   return (c&0x80)==0 ? isspace(c) : 0;
98564 }
98565
98566 /*
98567 ** Extract the next token from buffer z (length n) using the tokenizer
98568 ** and other information (column names etc.) in pParse. Create an Fts3Expr
98569 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
98570 ** single token and set *ppExpr to point to it. If the end of the buffer is
98571 ** reached before a token is found, set *ppExpr to zero. It is the
98572 ** responsibility of the caller to eventually deallocate the allocated 
98573 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
98574 **
98575 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
98576 ** fails.
98577 */
98578 static int getNextToken(
98579   ParseContext *pParse,                   /* fts3 query parse context */
98580   int iCol,                               /* Value for Fts3Phrase.iColumn */
98581   const char *z, int n,                   /* Input string */
98582   Fts3Expr **ppExpr,                      /* OUT: expression */
98583   int *pnConsumed                         /* OUT: Number of bytes consumed */
98584 ){
98585   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
98586   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
98587   int rc;
98588   sqlite3_tokenizer_cursor *pCursor;
98589   Fts3Expr *pRet = 0;
98590   int nConsumed = 0;
98591
98592   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
98593   if( rc==SQLITE_OK ){
98594     const char *zToken;
98595     int nToken, iStart, iEnd, iPosition;
98596     int nByte;                               /* total space to allocate */
98597
98598     pCursor->pTokenizer = pTokenizer;
98599     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
98600
98601     if( rc==SQLITE_OK ){
98602       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
98603       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
98604       if( !pRet ){
98605         rc = SQLITE_NOMEM;
98606       }else{
98607         memset(pRet, 0, nByte);
98608         pRet->eType = FTSQUERY_PHRASE;
98609         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
98610         pRet->pPhrase->nToken = 1;
98611         pRet->pPhrase->iColumn = iCol;
98612         pRet->pPhrase->aToken[0].n = nToken;
98613         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
98614         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
98615
98616         if( iEnd<n && z[iEnd]=='*' ){
98617           pRet->pPhrase->aToken[0].isPrefix = 1;
98618           iEnd++;
98619         }
98620         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
98621           pRet->pPhrase->isNot = 1;
98622         }
98623       }
98624       nConsumed = iEnd;
98625     }
98626
98627     pModule->xClose(pCursor);
98628   }
98629   
98630   *pnConsumed = nConsumed;
98631   *ppExpr = pRet;
98632   return rc;
98633 }
98634
98635
98636 /*
98637 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
98638 ** then free the old allocation.
98639 */
98640 void *fts3ReallocOrFree(void *pOrig, int nNew){
98641   void *pRet = sqlite3_realloc(pOrig, nNew);
98642   if( !pRet ){
98643     sqlite3_free(pOrig);
98644   }
98645   return pRet;
98646 }
98647
98648 /*
98649 ** Buffer zInput, length nInput, contains the contents of a quoted string
98650 ** that appeared as part of an fts3 query expression. Neither quote character
98651 ** is included in the buffer. This function attempts to tokenize the entire
98652 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
98653 ** containing the results.
98654 **
98655 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
98656 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
98657 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
98658 ** to 0.
98659 */
98660 static int getNextString(
98661   ParseContext *pParse,                   /* fts3 query parse context */
98662   const char *zInput, int nInput,         /* Input string */
98663   Fts3Expr **ppExpr                       /* OUT: expression */
98664 ){
98665   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
98666   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
98667   int rc;
98668   Fts3Expr *p = 0;
98669   sqlite3_tokenizer_cursor *pCursor = 0;
98670   char *zTemp = 0;
98671   int nTemp = 0;
98672
98673   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
98674   if( rc==SQLITE_OK ){
98675     int ii;
98676     pCursor->pTokenizer = pTokenizer;
98677     for(ii=0; rc==SQLITE_OK; ii++){
98678       const char *zToken;
98679       int nToken, iBegin, iEnd, iPos;
98680       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
98681       if( rc==SQLITE_OK ){
98682         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
98683         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
98684         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
98685         if( !p || !zTemp ){
98686           goto no_mem;
98687         }
98688         if( ii==0 ){
98689           memset(p, 0, nByte);
98690           p->pPhrase = (Fts3Phrase *)&p[1];
98691           p->eType = FTSQUERY_PHRASE;
98692           p->pPhrase->iColumn = pParse->iDefaultCol;
98693         }
98694         p->pPhrase = (Fts3Phrase *)&p[1];
98695         p->pPhrase->nToken = ii+1;
98696         p->pPhrase->aToken[ii].n = nToken;
98697         memcpy(&zTemp[nTemp], zToken, nToken);
98698         nTemp += nToken;
98699         if( iEnd<nInput && zInput[iEnd]=='*' ){
98700           p->pPhrase->aToken[ii].isPrefix = 1;
98701         }else{
98702           p->pPhrase->aToken[ii].isPrefix = 0;
98703         }
98704       }
98705     }
98706
98707     pModule->xClose(pCursor);
98708     pCursor = 0;
98709   }
98710
98711   if( rc==SQLITE_DONE ){
98712     int jj;
98713     char *zNew;
98714     int nNew = 0;
98715     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
98716     nByte += (p->pPhrase->nToken-1) * sizeof(struct PhraseToken);
98717     p = fts3ReallocOrFree(p, nByte + nTemp);
98718     if( !p ){
98719       goto no_mem;
98720     }
98721     p->pPhrase = (Fts3Phrase *)&p[1];
98722     zNew = &(((char *)p)[nByte]);
98723     memcpy(zNew, zTemp, nTemp);
98724     for(jj=0; jj<p->pPhrase->nToken; jj++){
98725       p->pPhrase->aToken[jj].z = &zNew[nNew];
98726       nNew += p->pPhrase->aToken[jj].n;
98727     }
98728     sqlite3_free(zTemp);
98729     rc = SQLITE_OK;
98730   }
98731
98732   *ppExpr = p;
98733   return rc;
98734 no_mem:
98735
98736   if( pCursor ){
98737     pModule->xClose(pCursor);
98738   }
98739   sqlite3_free(zTemp);
98740   sqlite3_free(p);
98741   *ppExpr = 0;
98742   return SQLITE_NOMEM;
98743 }
98744
98745 /*
98746 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
98747 ** call fts3ExprParse(). So this forward declaration is required.
98748 */
98749 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
98750
98751 /*
98752 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
98753 ** structure, or set to 0 if the end of the input buffer is reached.
98754 **
98755 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
98756 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
98757 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
98758 */
98759 static int getNextNode(
98760   ParseContext *pParse,                   /* fts3 query parse context */
98761   const char *z, int n,                   /* Input string */
98762   Fts3Expr **ppExpr,                      /* OUT: expression */
98763   int *pnConsumed                         /* OUT: Number of bytes consumed */
98764 ){
98765   static const struct Fts3Keyword {
98766     char z[4];                            /* Keyword text */
98767     unsigned char n;                      /* Length of the keyword */
98768     unsigned char parenOnly;              /* Only valid in paren mode */
98769     unsigned char eType;                  /* Keyword code */
98770   } aKeyword[] = {
98771     { "OR" ,  2, 0, FTSQUERY_OR   },
98772     { "AND",  3, 1, FTSQUERY_AND  },
98773     { "NOT",  3, 1, FTSQUERY_NOT  },
98774     { "NEAR", 4, 0, FTSQUERY_NEAR }
98775   };
98776   int ii;
98777   int iCol;
98778   int iColLen;
98779   int rc;
98780   Fts3Expr *pRet = 0;
98781
98782   const char *zInput = z;
98783   int nInput = n;
98784
98785   /* Skip over any whitespace before checking for a keyword, an open or
98786   ** close bracket, or a quoted string. 
98787   */
98788   while( nInput>0 && fts3isspace(*zInput) ){
98789     nInput--;
98790     zInput++;
98791   }
98792   if( nInput==0 ){
98793     return SQLITE_DONE;
98794   }
98795
98796   /* See if we are dealing with a keyword. */
98797   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
98798     const struct Fts3Keyword *pKey = &aKeyword[ii];
98799
98800     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
98801       continue;
98802     }
98803
98804     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
98805       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
98806       int nKey = pKey->n;
98807       char cNext;
98808
98809       /* If this is a "NEAR" keyword, check for an explicit nearness. */
98810       if( pKey->eType==FTSQUERY_NEAR ){
98811         assert( nKey==4 );
98812         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
98813           nNear = 0;
98814           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
98815             nNear = nNear * 10 + (zInput[nKey] - '0');
98816           }
98817         }
98818       }
98819
98820       /* At this point this is probably a keyword. But for that to be true,
98821       ** the next byte must contain either whitespace, an open or close
98822       ** parenthesis, a quote character, or EOF. 
98823       */
98824       cNext = zInput[nKey];
98825       if( fts3isspace(cNext) 
98826        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
98827       ){
98828         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
98829         memset(pRet, 0, sizeof(Fts3Expr));
98830         pRet->eType = pKey->eType;
98831         pRet->nNear = nNear;
98832         *ppExpr = pRet;
98833         *pnConsumed = (zInput - z) + nKey;
98834         return SQLITE_OK;
98835       }
98836
98837       /* Turns out that wasn't a keyword after all. This happens if the
98838       ** user has supplied a token such as "ORacle". Continue.
98839       */
98840     }
98841   }
98842
98843   /* Check for an open bracket. */
98844   if( sqlite3_fts3_enable_parentheses ){
98845     if( *zInput=='(' ){
98846       int nConsumed;
98847       int rc;
98848       pParse->nNest++;
98849       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
98850       if( rc==SQLITE_OK && !*ppExpr ){
98851         rc = SQLITE_DONE;
98852       }
98853       *pnConsumed = (zInput - z) + 1 + nConsumed;
98854       return rc;
98855     }
98856   
98857     /* Check for a close bracket. */
98858     if( *zInput==')' ){
98859       pParse->nNest--;
98860       *pnConsumed = (zInput - z) + 1;
98861       return SQLITE_DONE;
98862     }
98863   }
98864
98865   /* See if we are dealing with a quoted phrase. If this is the case, then
98866   ** search for the closing quote and pass the whole string to getNextString()
98867   ** for processing. This is easy to do, as fts3 has no syntax for escaping
98868   ** a quote character embedded in a string.
98869   */
98870   if( *zInput=='"' ){
98871     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
98872     *pnConsumed = (zInput - z) + ii + 1;
98873     if( ii==nInput ){
98874       return SQLITE_ERROR;
98875     }
98876     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
98877   }
98878
98879
98880   /* If control flows to this point, this must be a regular token, or 
98881   ** the end of the input. Read a regular token using the sqlite3_tokenizer
98882   ** interface. Before doing so, figure out if there is an explicit
98883   ** column specifier for the token. 
98884   **
98885   ** TODO: Strangely, it is not possible to associate a column specifier
98886   ** with a quoted phrase, only with a single token. Not sure if this was
98887   ** an implementation artifact or an intentional decision when fts3 was
98888   ** first implemented. Whichever it was, this module duplicates the 
98889   ** limitation.
98890   */
98891   iCol = pParse->iDefaultCol;
98892   iColLen = 0;
98893   for(ii=0; ii<pParse->nCol; ii++){
98894     const char *zStr = pParse->azCol[ii];
98895     int nStr = strlen(zStr);
98896     if( nInput>nStr && zInput[nStr]==':' && memcmp(zStr, zInput, nStr)==0 ){
98897       iCol = ii;
98898       iColLen = ((zInput - z) + nStr + 1);
98899       break;
98900     }
98901   }
98902   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
98903   *pnConsumed += iColLen;
98904   return rc;
98905 }
98906
98907 /*
98908 ** The argument is an Fts3Expr structure for a binary operator (any type
98909 ** except an FTSQUERY_PHRASE). Return an integer value representing the
98910 ** precedence of the operator. Lower values have a higher precedence (i.e.
98911 ** group more tightly). For example, in the C language, the == operator
98912 ** groups more tightly than ||, and would therefore have a higher precedence.
98913 **
98914 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
98915 ** is defined), the order of the operators in precedence from highest to
98916 ** lowest is:
98917 **
98918 **   NEAR
98919 **   NOT
98920 **   AND (including implicit ANDs)
98921 **   OR
98922 **
98923 ** Note that when using the old query syntax, the OR operator has a higher
98924 ** precedence than the AND operator.
98925 */
98926 static int opPrecedence(Fts3Expr *p){
98927   assert( p->eType!=FTSQUERY_PHRASE );
98928   if( sqlite3_fts3_enable_parentheses ){
98929     return p->eType;
98930   }else if( p->eType==FTSQUERY_NEAR ){
98931     return 1;
98932   }else if( p->eType==FTSQUERY_OR ){
98933     return 2;
98934   }
98935   assert( p->eType==FTSQUERY_AND );
98936   return 3;
98937 }
98938
98939 /*
98940 ** Argument ppHead contains a pointer to the current head of a query 
98941 ** expression tree being parsed. pPrev is the expression node most recently
98942 ** inserted into the tree. This function adds pNew, which is always a binary
98943 ** operator node, into the expression tree based on the relative precedence
98944 ** of pNew and the existing nodes of the tree. This may result in the head
98945 ** of the tree changing, in which case *ppHead is set to the new root node.
98946 */
98947 static void insertBinaryOperator(
98948   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
98949   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
98950   Fts3Expr *pNew           /* New binary node to insert into expression tree */
98951 ){
98952   Fts3Expr *pSplit = pPrev;
98953   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
98954     pSplit = pSplit->pParent;
98955   }
98956
98957   if( pSplit->pParent ){
98958     assert( pSplit->pParent->pRight==pSplit );
98959     pSplit->pParent->pRight = pNew;
98960     pNew->pParent = pSplit->pParent;
98961   }else{
98962     *ppHead = pNew;
98963   }
98964   pNew->pLeft = pSplit;
98965   pSplit->pParent = pNew;
98966 }
98967
98968 /*
98969 ** Parse the fts3 query expression found in buffer z, length n. This function
98970 ** returns either when the end of the buffer is reached or an unmatched 
98971 ** closing bracket - ')' - is encountered.
98972 **
98973 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
98974 ** parsed form of the expression and *pnConsumed is set to the number of
98975 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
98976 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
98977 */
98978 static int fts3ExprParse(
98979   ParseContext *pParse,                   /* fts3 query parse context */
98980   const char *z, int n,                   /* Text of MATCH query */
98981   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
98982   int *pnConsumed                         /* OUT: Number of bytes consumed */
98983 ){
98984   Fts3Expr *pRet = 0;
98985   Fts3Expr *pPrev = 0;
98986   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
98987   int nIn = n;
98988   const char *zIn = z;
98989   int rc = SQLITE_OK;
98990   int isRequirePhrase = 1;
98991
98992   while( rc==SQLITE_OK ){
98993     Fts3Expr *p = 0;
98994     int nByte = 0;
98995     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
98996     if( rc==SQLITE_OK ){
98997       int isPhrase;
98998
98999       if( !sqlite3_fts3_enable_parentheses 
99000        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
99001       ){
99002         /* Create an implicit NOT operator. */
99003         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
99004         if( !pNot ){
99005           sqlite3Fts3ExprFree(p);
99006           rc = SQLITE_NOMEM;
99007           goto exprparse_out;
99008         }
99009         memset(pNot, 0, sizeof(Fts3Expr));
99010         pNot->eType = FTSQUERY_NOT;
99011         pNot->pRight = p;
99012         if( pNotBranch ){
99013           pNotBranch->pLeft = p;
99014           pNot->pRight = pNotBranch;
99015         }
99016         pNotBranch = pNot;
99017       }else{
99018         int eType = p->eType;
99019         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
99020         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
99021
99022         /* The isRequirePhrase variable is set to true if a phrase or
99023         ** an expression contained in parenthesis is required. If a
99024         ** binary operator (AND, OR, NOT or NEAR) is encounted when
99025         ** isRequirePhrase is set, this is a syntax error.
99026         */
99027         if( !isPhrase && isRequirePhrase ){
99028           sqlite3Fts3ExprFree(p);
99029           rc = SQLITE_ERROR;
99030           goto exprparse_out;
99031         }
99032   
99033         if( isPhrase && !isRequirePhrase ){
99034           /* Insert an implicit AND operator. */
99035           Fts3Expr *pAnd;
99036           assert( pRet && pPrev );
99037           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
99038           if( !pAnd ){
99039             sqlite3Fts3ExprFree(p);
99040             rc = SQLITE_NOMEM;
99041             goto exprparse_out;
99042           }
99043           memset(pAnd, 0, sizeof(Fts3Expr));
99044           pAnd->eType = FTSQUERY_AND;
99045           insertBinaryOperator(&pRet, pPrev, pAnd);
99046           pPrev = pAnd;
99047         }
99048
99049         /* This test catches attempts to make either operand of a NEAR
99050         ** operator something other than a phrase. For example, either of
99051         ** the following:
99052         **
99053         **    (bracketed expression) NEAR phrase
99054         **    phrase NEAR (bracketed expression)
99055         **
99056         ** Return an error in either case.
99057         */
99058         if( pPrev && (
99059             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
99060          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
99061         )){
99062           sqlite3Fts3ExprFree(p);
99063           rc = SQLITE_ERROR;
99064           goto exprparse_out;
99065         }
99066   
99067         if( isPhrase ){
99068           if( pRet ){
99069             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
99070             pPrev->pRight = p;
99071             p->pParent = pPrev;
99072           }else{
99073             pRet = p;
99074           }
99075         }else{
99076           insertBinaryOperator(&pRet, pPrev, p);
99077         }
99078         isRequirePhrase = !isPhrase;
99079       }
99080       assert( nByte>0 );
99081     }
99082     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
99083     nIn -= nByte;
99084     zIn += nByte;
99085     pPrev = p;
99086   }
99087
99088   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
99089     rc = SQLITE_ERROR;
99090   }
99091
99092   if( rc==SQLITE_DONE ){
99093     rc = SQLITE_OK;
99094     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
99095       if( !pRet ){
99096         rc = SQLITE_ERROR;
99097       }else{
99098         pNotBranch->pLeft = pRet;
99099         pRet = pNotBranch;
99100       }
99101     }
99102   }
99103   *pnConsumed = n - nIn;
99104
99105 exprparse_out:
99106   if( rc!=SQLITE_OK ){
99107     sqlite3Fts3ExprFree(pRet);
99108     sqlite3Fts3ExprFree(pNotBranch);
99109     pRet = 0;
99110   }
99111   *ppExpr = pRet;
99112   return rc;
99113 }
99114
99115 /*
99116 ** Parameters z and n contain a pointer to and length of a buffer containing
99117 ** an fts3 query expression, respectively. This function attempts to parse the
99118 ** query expression and create a tree of Fts3Expr structures representing the
99119 ** parsed expression. If successful, *ppExpr is set to point to the head
99120 ** of the parsed expression tree and SQLITE_OK is returned. If an error
99121 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
99122 ** error) is returned and *ppExpr is set to 0.
99123 **
99124 ** If parameter n is a negative number, then z is assumed to point to a
99125 ** nul-terminated string and the length is determined using strlen().
99126 **
99127 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
99128 ** use to normalize query tokens while parsing the expression. The azCol[]
99129 ** array, which is assumed to contain nCol entries, should contain the names
99130 ** of each column in the target fts3 table, in order from left to right. 
99131 ** Column names must be nul-terminated strings.
99132 **
99133 ** The iDefaultCol parameter should be passed the index of the table column
99134 ** that appears on the left-hand-side of the MATCH operator (the default
99135 ** column to match against for tokens for which a column name is not explicitly
99136 ** specified as part of the query string), or -1 if tokens may by default
99137 ** match any table column.
99138 */
99139 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
99140   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
99141   char **azCol,                       /* Array of column names for fts3 table */
99142   int nCol,                           /* Number of entries in azCol[] */
99143   int iDefaultCol,                    /* Default column to query */
99144   const char *z, int n,               /* Text of MATCH query */
99145   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
99146 ){
99147   int nParsed;
99148   int rc;
99149   ParseContext sParse;
99150   sParse.pTokenizer = pTokenizer;
99151   sParse.azCol = (const char **)azCol;
99152   sParse.nCol = nCol;
99153   sParse.iDefaultCol = iDefaultCol;
99154   sParse.nNest = 0;
99155   if( z==0 ){
99156     *ppExpr = 0;
99157     return SQLITE_OK;
99158   }
99159   if( n<0 ){
99160     n = strlen(z);
99161   }
99162   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
99163
99164   /* Check for mismatched parenthesis */
99165   if( rc==SQLITE_OK && sParse.nNest ){
99166     rc = SQLITE_ERROR;
99167     sqlite3Fts3ExprFree(*ppExpr);
99168     *ppExpr = 0;
99169   }
99170
99171   return rc;
99172 }
99173
99174 /*
99175 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
99176 */
99177 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
99178   if( p ){
99179     sqlite3Fts3ExprFree(p->pLeft);
99180     sqlite3Fts3ExprFree(p->pRight);
99181     sqlite3_free(p);
99182   }
99183 }
99184
99185 /****************************************************************************
99186 *****************************************************************************
99187 ** Everything after this point is just test code.
99188 */
99189
99190 #ifdef SQLITE_TEST
99191
99192
99193 /*
99194 ** Function to query the hash-table of tokenizers (see README.tokenizers).
99195 */
99196 static int queryTestTokenizer(
99197   sqlite3 *db, 
99198   const char *zName,  
99199   const sqlite3_tokenizer_module **pp
99200 ){
99201   int rc;
99202   sqlite3_stmt *pStmt;
99203   const char zSql[] = "SELECT fts3_tokenizer(?)";
99204
99205   *pp = 0;
99206   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
99207   if( rc!=SQLITE_OK ){
99208     return rc;
99209   }
99210
99211   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
99212   if( SQLITE_ROW==sqlite3_step(pStmt) ){
99213     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
99214       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
99215     }
99216   }
99217
99218   return sqlite3_finalize(pStmt);
99219 }
99220
99221 /*
99222 ** This function is part of the test interface for the query parser. It
99223 ** writes a text representation of the query expression pExpr into the
99224 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
99225 ** enough to store the required text representation.
99226 */
99227 static void exprToString(Fts3Expr *pExpr, char *zBuf){
99228   switch( pExpr->eType ){
99229     case FTSQUERY_PHRASE: {
99230       Fts3Phrase *pPhrase = pExpr->pPhrase;
99231       int i;
99232       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
99233       for(i=0; i<pPhrase->nToken; i++){
99234         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
99235         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
99236       }
99237       return;
99238     }
99239
99240     case FTSQUERY_NEAR:
99241       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
99242       break;
99243     case FTSQUERY_NOT:
99244       zBuf += sprintf(zBuf, "NOT ");
99245       break;
99246     case FTSQUERY_AND:
99247       zBuf += sprintf(zBuf, "AND ");
99248       break;
99249     case FTSQUERY_OR:
99250       zBuf += sprintf(zBuf, "OR ");
99251       break;
99252   }
99253
99254   zBuf += sprintf(zBuf, "{");
99255   exprToString(pExpr->pLeft, zBuf);
99256   zBuf += strlen(zBuf);
99257   zBuf += sprintf(zBuf, "} ");
99258
99259   zBuf += sprintf(zBuf, "{");
99260   exprToString(pExpr->pRight, zBuf);
99261   zBuf += strlen(zBuf);
99262   zBuf += sprintf(zBuf, "}");
99263 }
99264
99265 /*
99266 ** This is the implementation of a scalar SQL function used to test the 
99267 ** expression parser. It should be called as follows:
99268 **
99269 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
99270 **
99271 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
99272 ** to parse the query expression (see README.tokenizers). The second argument
99273 ** is the query expression to parse. Each subsequent argument is the name
99274 ** of a column of the fts3 table that the query expression may refer to.
99275 ** For example:
99276 **
99277 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
99278 */
99279 static void fts3ExprTest(
99280   sqlite3_context *context,
99281   int argc,
99282   sqlite3_value **argv
99283 ){
99284   sqlite3_tokenizer_module const *pModule = 0;
99285   sqlite3_tokenizer *pTokenizer = 0;
99286   int rc;
99287   char **azCol = 0;
99288   const char *zExpr;
99289   int nExpr;
99290   int nCol;
99291   int ii;
99292   Fts3Expr *pExpr;
99293   sqlite3 *db = sqlite3_context_db_handle(context);
99294
99295   if( argc<3 ){
99296     sqlite3_result_error(context, 
99297         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
99298     );
99299     return;
99300   }
99301
99302   rc = queryTestTokenizer(db,
99303                           (const char *)sqlite3_value_text(argv[0]), &pModule);
99304   if( rc==SQLITE_NOMEM ){
99305     sqlite3_result_error_nomem(context);
99306     goto exprtest_out;
99307   }else if( !pModule ){
99308     sqlite3_result_error(context, "No such tokenizer module", -1);
99309     goto exprtest_out;
99310   }
99311
99312   rc = pModule->xCreate(0, 0, &pTokenizer);
99313   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
99314   if( rc==SQLITE_NOMEM ){
99315     sqlite3_result_error_nomem(context);
99316     goto exprtest_out;
99317   }
99318   pTokenizer->pModule = pModule;
99319
99320   zExpr = (const char *)sqlite3_value_text(argv[1]);
99321   nExpr = sqlite3_value_bytes(argv[1]);
99322   nCol = argc-2;
99323   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
99324   if( !azCol ){
99325     sqlite3_result_error_nomem(context);
99326     goto exprtest_out;
99327   }
99328   for(ii=0; ii<nCol; ii++){
99329     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
99330   }
99331
99332   rc = sqlite3Fts3ExprParse(
99333       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
99334   );
99335   if( rc==SQLITE_NOMEM ){
99336     sqlite3_result_error_nomem(context);
99337     goto exprtest_out;
99338   }else if( rc==SQLITE_OK ){
99339     char zBuf[4096];
99340     exprToString(pExpr, zBuf);
99341     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
99342     sqlite3Fts3ExprFree(pExpr);
99343   }else{
99344     sqlite3_result_error(context, "Error parsing expression", -1);
99345   }
99346
99347 exprtest_out:
99348   if( pModule && pTokenizer ){
99349     rc = pModule->xDestroy(pTokenizer);
99350   }
99351   sqlite3_free(azCol);
99352 }
99353
99354 /*
99355 ** Register the query expression parser test function fts3_exprtest() 
99356 ** with database connection db. 
99357 */
99358 SQLITE_PRIVATE void sqlite3Fts3ExprInitTestInterface(sqlite3* db){
99359   sqlite3_create_function(
99360       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
99361   );
99362 }
99363
99364 #endif
99365 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
99366
99367 /************** End of fts3_expr.c *******************************************/
99368 /************** Begin file fts3_hash.c ***************************************/
99369 /*
99370 ** 2001 September 22
99371 **
99372 ** The author disclaims copyright to this source code.  In place of
99373 ** a legal notice, here is a blessing:
99374 **
99375 **    May you do good and not evil.
99376 **    May you find forgiveness for yourself and forgive others.
99377 **    May you share freely, never taking more than you give.
99378 **
99379 *************************************************************************
99380 ** This is the implementation of generic hash-tables used in SQLite.
99381 ** We've modified it slightly to serve as a standalone hash table
99382 ** implementation for the full-text indexing module.
99383 */
99384
99385 /*
99386 ** The code in this file is only compiled if:
99387 **
99388 **     * The FTS3 module is being built as an extension
99389 **       (in which case SQLITE_CORE is not defined), or
99390 **
99391 **     * The FTS3 module is being built into the core of
99392 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
99393 */
99394 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
99395
99396
99397
99398 /*
99399 ** Malloc and Free functions
99400 */
99401 static void *fts3HashMalloc(int n){
99402   void *p = sqlite3_malloc(n);
99403   if( p ){
99404     memset(p, 0, n);
99405   }
99406   return p;
99407 }
99408 static void fts3HashFree(void *p){
99409   sqlite3_free(p);
99410 }
99411
99412 /* Turn bulk memory into a hash table object by initializing the
99413 ** fields of the Hash structure.
99414 **
99415 ** "pNew" is a pointer to the hash table that is to be initialized.
99416 ** keyClass is one of the constants 
99417 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
99418 ** determines what kind of key the hash table will use.  "copyKey" is
99419 ** true if the hash table should make its own private copy of keys and
99420 ** false if it should just use the supplied pointer.
99421 */
99422 SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){
99423   assert( pNew!=0 );
99424   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
99425   pNew->keyClass = keyClass;
99426   pNew->copyKey = copyKey;
99427   pNew->first = 0;
99428   pNew->count = 0;
99429   pNew->htsize = 0;
99430   pNew->ht = 0;
99431 }
99432
99433 /* Remove all entries from a hash table.  Reclaim all memory.
99434 ** Call this routine to delete a hash table or to reset a hash table
99435 ** to the empty state.
99436 */
99437 SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){
99438   fts3HashElem *elem;         /* For looping over all elements of the table */
99439
99440   assert( pH!=0 );
99441   elem = pH->first;
99442   pH->first = 0;
99443   fts3HashFree(pH->ht);
99444   pH->ht = 0;
99445   pH->htsize = 0;
99446   while( elem ){
99447     fts3HashElem *next_elem = elem->next;
99448     if( pH->copyKey && elem->pKey ){
99449       fts3HashFree(elem->pKey);
99450     }
99451     fts3HashFree(elem);
99452     elem = next_elem;
99453   }
99454   pH->count = 0;
99455 }
99456
99457 /*
99458 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
99459 */
99460 static int fts3StrHash(const void *pKey, int nKey){
99461   const char *z = (const char *)pKey;
99462   int h = 0;
99463   if( nKey<=0 ) nKey = (int) strlen(z);
99464   while( nKey > 0  ){
99465     h = (h<<3) ^ h ^ *z++;
99466     nKey--;
99467   }
99468   return h & 0x7fffffff;
99469 }
99470 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
99471   if( n1!=n2 ) return 1;
99472   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
99473 }
99474
99475 /*
99476 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
99477 */
99478 static int fts3BinHash(const void *pKey, int nKey){
99479   int h = 0;
99480   const char *z = (const char *)pKey;
99481   while( nKey-- > 0 ){
99482     h = (h<<3) ^ h ^ *(z++);
99483   }
99484   return h & 0x7fffffff;
99485 }
99486 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
99487   if( n1!=n2 ) return 1;
99488   return memcmp(pKey1,pKey2,n1);
99489 }
99490
99491 /*
99492 ** Return a pointer to the appropriate hash function given the key class.
99493 **
99494 ** The C syntax in this function definition may be unfamilar to some 
99495 ** programmers, so we provide the following additional explanation:
99496 **
99497 ** The name of the function is "ftsHashFunction".  The function takes a
99498 ** single parameter "keyClass".  The return value of ftsHashFunction()
99499 ** is a pointer to another function.  Specifically, the return value
99500 ** of ftsHashFunction() is a pointer to a function that takes two parameters
99501 ** with types "const void*" and "int" and returns an "int".
99502 */
99503 static int (*ftsHashFunction(int keyClass))(const void*,int){
99504   if( keyClass==FTS3_HASH_STRING ){
99505     return &fts3StrHash;
99506   }else{
99507     assert( keyClass==FTS3_HASH_BINARY );
99508     return &fts3BinHash;
99509   }
99510 }
99511
99512 /*
99513 ** Return a pointer to the appropriate hash function given the key class.
99514 **
99515 ** For help in interpreted the obscure C code in the function definition,
99516 ** see the header comment on the previous function.
99517 */
99518 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
99519   if( keyClass==FTS3_HASH_STRING ){
99520     return &fts3StrCompare;
99521   }else{
99522     assert( keyClass==FTS3_HASH_BINARY );
99523     return &fts3BinCompare;
99524   }
99525 }
99526
99527 /* Link an element into the hash table
99528 */
99529 static void fts3HashInsertElement(
99530   fts3Hash *pH,            /* The complete hash table */
99531   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
99532   fts3HashElem *pNew       /* The element to be inserted */
99533 ){
99534   fts3HashElem *pHead;     /* First element already in pEntry */
99535   pHead = pEntry->chain;
99536   if( pHead ){
99537     pNew->next = pHead;
99538     pNew->prev = pHead->prev;
99539     if( pHead->prev ){ pHead->prev->next = pNew; }
99540     else             { pH->first = pNew; }
99541     pHead->prev = pNew;
99542   }else{
99543     pNew->next = pH->first;
99544     if( pH->first ){ pH->first->prev = pNew; }
99545     pNew->prev = 0;
99546     pH->first = pNew;
99547   }
99548   pEntry->count++;
99549   pEntry->chain = pNew;
99550 }
99551
99552
99553 /* Resize the hash table so that it cantains "new_size" buckets.
99554 ** "new_size" must be a power of 2.  The hash table might fail 
99555 ** to resize if sqliteMalloc() fails.
99556 */
99557 static void fts3Rehash(fts3Hash *pH, int new_size){
99558   struct _fts3ht *new_ht;          /* The new hash table */
99559   fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
99560   int (*xHash)(const void*,int);   /* The hash function */
99561
99562   assert( (new_size & (new_size-1))==0 );
99563   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
99564   if( new_ht==0 ) return;
99565   fts3HashFree(pH->ht);
99566   pH->ht = new_ht;
99567   pH->htsize = new_size;
99568   xHash = ftsHashFunction(pH->keyClass);
99569   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
99570     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
99571     next_elem = elem->next;
99572     fts3HashInsertElement(pH, &new_ht[h], elem);
99573   }
99574 }
99575
99576 /* This function (for internal use only) locates an element in an
99577 ** hash table that matches the given key.  The hash for this key has
99578 ** already been computed and is passed as the 4th parameter.
99579 */
99580 static fts3HashElem *fts3FindElementByHash(
99581   const fts3Hash *pH, /* The pH to be searched */
99582   const void *pKey,   /* The key we are searching for */
99583   int nKey,
99584   int h               /* The hash for this key. */
99585 ){
99586   fts3HashElem *elem;            /* Used to loop thru the element list */
99587   int count;                     /* Number of elements left to test */
99588   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
99589
99590   if( pH->ht ){
99591     struct _fts3ht *pEntry = &pH->ht[h];
99592     elem = pEntry->chain;
99593     count = pEntry->count;
99594     xCompare = ftsCompareFunction(pH->keyClass);
99595     while( count-- && elem ){
99596       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
99597         return elem;
99598       }
99599       elem = elem->next;
99600     }
99601   }
99602   return 0;
99603 }
99604
99605 /* Remove a single entry from the hash table given a pointer to that
99606 ** element and a hash on the element's key.
99607 */
99608 static void fts3RemoveElementByHash(
99609   fts3Hash *pH,         /* The pH containing "elem" */
99610   fts3HashElem* elem,   /* The element to be removed from the pH */
99611   int h                 /* Hash value for the element */
99612 ){
99613   struct _fts3ht *pEntry;
99614   if( elem->prev ){
99615     elem->prev->next = elem->next; 
99616   }else{
99617     pH->first = elem->next;
99618   }
99619   if( elem->next ){
99620     elem->next->prev = elem->prev;
99621   }
99622   pEntry = &pH->ht[h];
99623   if( pEntry->chain==elem ){
99624     pEntry->chain = elem->next;
99625   }
99626   pEntry->count--;
99627   if( pEntry->count<=0 ){
99628     pEntry->chain = 0;
99629   }
99630   if( pH->copyKey && elem->pKey ){
99631     fts3HashFree(elem->pKey);
99632   }
99633   fts3HashFree( elem );
99634   pH->count--;
99635   if( pH->count<=0 ){
99636     assert( pH->first==0 );
99637     assert( pH->count==0 );
99638     fts3HashClear(pH);
99639   }
99640 }
99641
99642 /* Attempt to locate an element of the hash table pH with a key
99643 ** that matches pKey,nKey.  Return the data for this element if it is
99644 ** found, or NULL if there is no match.
99645 */
99646 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){
99647   int h;                 /* A hash on key */
99648   fts3HashElem *elem;    /* The element that matches key */
99649   int (*xHash)(const void*,int);  /* The hash function */
99650
99651   if( pH==0 || pH->ht==0 ) return 0;
99652   xHash = ftsHashFunction(pH->keyClass);
99653   assert( xHash!=0 );
99654   h = (*xHash)(pKey,nKey);
99655   assert( (pH->htsize & (pH->htsize-1))==0 );
99656   elem = fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
99657   return elem ? elem->data : 0;
99658 }
99659
99660 /* Insert an element into the hash table pH.  The key is pKey,nKey
99661 ** and the data is "data".
99662 **
99663 ** If no element exists with a matching key, then a new
99664 ** element is created.  A copy of the key is made if the copyKey
99665 ** flag is set.  NULL is returned.
99666 **
99667 ** If another element already exists with the same key, then the
99668 ** new data replaces the old data and the old data is returned.
99669 ** The key is not copied in this instance.  If a malloc fails, then
99670 ** the new data is returned and the hash table is unchanged.
99671 **
99672 ** If the "data" parameter to this function is NULL, then the
99673 ** element corresponding to "key" is removed from the hash table.
99674 */
99675 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
99676   fts3Hash *pH,        /* The hash table to insert into */
99677   const void *pKey,    /* The key */
99678   int nKey,            /* Number of bytes in the key */
99679   void *data           /* The data */
99680 ){
99681   int hraw;                 /* Raw hash value of the key */
99682   int h;                    /* the hash of the key modulo hash table size */
99683   fts3HashElem *elem;       /* Used to loop thru the element list */
99684   fts3HashElem *new_elem;   /* New element added to the pH */
99685   int (*xHash)(const void*,int);  /* The hash function */
99686
99687   assert( pH!=0 );
99688   xHash = ftsHashFunction(pH->keyClass);
99689   assert( xHash!=0 );
99690   hraw = (*xHash)(pKey, nKey);
99691   assert( (pH->htsize & (pH->htsize-1))==0 );
99692   h = hraw & (pH->htsize-1);
99693   elem = fts3FindElementByHash(pH,pKey,nKey,h);
99694   if( elem ){
99695     void *old_data = elem->data;
99696     if( data==0 ){
99697       fts3RemoveElementByHash(pH,elem,h);
99698     }else{
99699       elem->data = data;
99700     }
99701     return old_data;
99702   }
99703   if( data==0 ) return 0;
99704   if( pH->htsize==0 ){
99705     fts3Rehash(pH,8);
99706     if( pH->htsize==0 ){
99707       pH->count = 0;
99708       return data;
99709     }
99710   }
99711   new_elem = (fts3HashElem*)fts3HashMalloc( sizeof(fts3HashElem) );
99712   if( new_elem==0 ) return data;
99713   if( pH->copyKey && pKey!=0 ){
99714     new_elem->pKey = fts3HashMalloc( nKey );
99715     if( new_elem->pKey==0 ){
99716       fts3HashFree(new_elem);
99717       return data;
99718     }
99719     memcpy((void*)new_elem->pKey, pKey, nKey);
99720   }else{
99721     new_elem->pKey = (void*)pKey;
99722   }
99723   new_elem->nKey = nKey;
99724   pH->count++;
99725   if( pH->count > pH->htsize ){
99726     fts3Rehash(pH,pH->htsize*2);
99727   }
99728   assert( pH->htsize>0 );
99729   assert( (pH->htsize & (pH->htsize-1))==0 );
99730   h = hraw & (pH->htsize-1);
99731   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
99732   new_elem->data = data;
99733   return 0;
99734 }
99735
99736 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
99737
99738 /************** End of fts3_hash.c *******************************************/
99739 /************** Begin file fts3_porter.c *************************************/
99740 /*
99741 ** 2006 September 30
99742 **
99743 ** The author disclaims copyright to this source code.  In place of
99744 ** a legal notice, here is a blessing:
99745 **
99746 **    May you do good and not evil.
99747 **    May you find forgiveness for yourself and forgive others.
99748 **    May you share freely, never taking more than you give.
99749 **
99750 *************************************************************************
99751 ** Implementation of the full-text-search tokenizer that implements
99752 ** a Porter stemmer.
99753 */
99754
99755 /*
99756 ** The code in this file is only compiled if:
99757 **
99758 **     * The FTS3 module is being built as an extension
99759 **       (in which case SQLITE_CORE is not defined), or
99760 **
99761 **     * The FTS3 module is being built into the core of
99762 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
99763 */
99764 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
99765
99766
99767
99768
99769 /*
99770 ** Class derived from sqlite3_tokenizer
99771 */
99772 typedef struct porter_tokenizer {
99773   sqlite3_tokenizer base;      /* Base class */
99774 } porter_tokenizer;
99775
99776 /*
99777 ** Class derived from sqlit3_tokenizer_cursor
99778 */
99779 typedef struct porter_tokenizer_cursor {
99780   sqlite3_tokenizer_cursor base;
99781   const char *zInput;          /* input we are tokenizing */
99782   int nInput;                  /* size of the input */
99783   int iOffset;                 /* current position in zInput */
99784   int iToken;                  /* index of next token to be returned */
99785   char *zToken;                /* storage for current token */
99786   int nAllocated;              /* space allocated to zToken buffer */
99787 } porter_tokenizer_cursor;
99788
99789
99790 /* Forward declaration */
99791 static const sqlite3_tokenizer_module porterTokenizerModule;
99792
99793
99794 /*
99795 ** Create a new tokenizer instance.
99796 */
99797 static int porterCreate(
99798   int argc, const char * const *argv,
99799   sqlite3_tokenizer **ppTokenizer
99800 ){
99801   porter_tokenizer *t;
99802   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
99803   if( t==NULL ) return SQLITE_NOMEM;
99804   memset(t, 0, sizeof(*t));
99805   *ppTokenizer = &t->base;
99806   return SQLITE_OK;
99807 }
99808
99809 /*
99810 ** Destroy a tokenizer
99811 */
99812 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
99813   sqlite3_free(pTokenizer);
99814   return SQLITE_OK;
99815 }
99816
99817 /*
99818 ** Prepare to begin tokenizing a particular string.  The input
99819 ** string to be tokenized is zInput[0..nInput-1].  A cursor
99820 ** used to incrementally tokenize this string is returned in 
99821 ** *ppCursor.
99822 */
99823 static int porterOpen(
99824   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
99825   const char *zInput, int nInput,        /* String to be tokenized */
99826   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
99827 ){
99828   porter_tokenizer_cursor *c;
99829
99830   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
99831   if( c==NULL ) return SQLITE_NOMEM;
99832
99833   c->zInput = zInput;
99834   if( zInput==0 ){
99835     c->nInput = 0;
99836   }else if( nInput<0 ){
99837     c->nInput = (int)strlen(zInput);
99838   }else{
99839     c->nInput = nInput;
99840   }
99841   c->iOffset = 0;                 /* start tokenizing at the beginning */
99842   c->iToken = 0;
99843   c->zToken = NULL;               /* no space allocated, yet. */
99844   c->nAllocated = 0;
99845
99846   *ppCursor = &c->base;
99847   return SQLITE_OK;
99848 }
99849
99850 /*
99851 ** Close a tokenization cursor previously opened by a call to
99852 ** porterOpen() above.
99853 */
99854 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
99855   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
99856   sqlite3_free(c->zToken);
99857   sqlite3_free(c);
99858   return SQLITE_OK;
99859 }
99860 /*
99861 ** Vowel or consonant
99862 */
99863 static const char cType[] = {
99864    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
99865    1, 1, 1, 2, 1
99866 };
99867
99868 /*
99869 ** isConsonant() and isVowel() determine if their first character in
99870 ** the string they point to is a consonant or a vowel, according
99871 ** to Porter ruls.  
99872 **
99873 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
99874 ** 'Y' is a consonant unless it follows another consonant,
99875 ** in which case it is a vowel.
99876 **
99877 ** In these routine, the letters are in reverse order.  So the 'y' rule
99878 ** is that 'y' is a consonant unless it is followed by another
99879 ** consonent.
99880 */
99881 static int isVowel(const char*);
99882 static int isConsonant(const char *z){
99883   int j;
99884   char x = *z;
99885   if( x==0 ) return 0;
99886   assert( x>='a' && x<='z' );
99887   j = cType[x-'a'];
99888   if( j<2 ) return j;
99889   return z[1]==0 || isVowel(z + 1);
99890 }
99891 static int isVowel(const char *z){
99892   int j;
99893   char x = *z;
99894   if( x==0 ) return 0;
99895   assert( x>='a' && x<='z' );
99896   j = cType[x-'a'];
99897   if( j<2 ) return 1-j;
99898   return isConsonant(z + 1);
99899 }
99900
99901 /*
99902 ** Let any sequence of one or more vowels be represented by V and let
99903 ** C be sequence of one or more consonants.  Then every word can be
99904 ** represented as:
99905 **
99906 **           [C] (VC){m} [V]
99907 **
99908 ** In prose:  A word is an optional consonant followed by zero or
99909 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
99910 ** number of vowel consonant pairs.  This routine computes the value
99911 ** of m for the first i bytes of a word.
99912 **
99913 ** Return true if the m-value for z is 1 or more.  In other words,
99914 ** return true if z contains at least one vowel that is followed
99915 ** by a consonant.
99916 **
99917 ** In this routine z[] is in reverse order.  So we are really looking
99918 ** for an instance of of a consonant followed by a vowel.
99919 */
99920 static int m_gt_0(const char *z){
99921   while( isVowel(z) ){ z++; }
99922   if( *z==0 ) return 0;
99923   while( isConsonant(z) ){ z++; }
99924   return *z!=0;
99925 }
99926
99927 /* Like mgt0 above except we are looking for a value of m which is
99928 ** exactly 1
99929 */
99930 static int m_eq_1(const char *z){
99931   while( isVowel(z) ){ z++; }
99932   if( *z==0 ) return 0;
99933   while( isConsonant(z) ){ z++; }
99934   if( *z==0 ) return 0;
99935   while( isVowel(z) ){ z++; }
99936   if( *z==0 ) return 1;
99937   while( isConsonant(z) ){ z++; }
99938   return *z==0;
99939 }
99940
99941 /* Like mgt0 above except we are looking for a value of m>1 instead
99942 ** or m>0
99943 */
99944 static int m_gt_1(const char *z){
99945   while( isVowel(z) ){ z++; }
99946   if( *z==0 ) return 0;
99947   while( isConsonant(z) ){ z++; }
99948   if( *z==0 ) return 0;
99949   while( isVowel(z) ){ z++; }
99950   if( *z==0 ) return 0;
99951   while( isConsonant(z) ){ z++; }
99952   return *z!=0;
99953 }
99954
99955 /*
99956 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
99957 */
99958 static int hasVowel(const char *z){
99959   while( isConsonant(z) ){ z++; }
99960   return *z!=0;
99961 }
99962
99963 /*
99964 ** Return TRUE if the word ends in a double consonant.
99965 **
99966 ** The text is reversed here. So we are really looking at
99967 ** the first two characters of z[].
99968 */
99969 static int doubleConsonant(const char *z){
99970   return isConsonant(z) && z[0]==z[1] && isConsonant(z+1);
99971 }
99972
99973 /*
99974 ** Return TRUE if the word ends with three letters which
99975 ** are consonant-vowel-consonent and where the final consonant
99976 ** is not 'w', 'x', or 'y'.
99977 **
99978 ** The word is reversed here.  So we are really checking the
99979 ** first three letters and the first one cannot be in [wxy].
99980 */
99981 static int star_oh(const char *z){
99982   return
99983     z[0]!=0 && isConsonant(z) &&
99984     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
99985     z[1]!=0 && isVowel(z+1) &&
99986     z[2]!=0 && isConsonant(z+2);
99987 }
99988
99989 /*
99990 ** If the word ends with zFrom and xCond() is true for the stem
99991 ** of the word that preceeds the zFrom ending, then change the 
99992 ** ending to zTo.
99993 **
99994 ** The input word *pz and zFrom are both in reverse order.  zTo
99995 ** is in normal order. 
99996 **
99997 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
99998 ** match.  Not that TRUE is returned even if xCond() fails and
99999 ** no substitution occurs.
100000 */
100001 static int stem(
100002   char **pz,             /* The word being stemmed (Reversed) */
100003   const char *zFrom,     /* If the ending matches this... (Reversed) */
100004   const char *zTo,       /* ... change the ending to this (not reversed) */
100005   int (*xCond)(const char*)   /* Condition that must be true */
100006 ){
100007   char *z = *pz;
100008   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
100009   if( *zFrom!=0 ) return 0;
100010   if( xCond && !xCond(z) ) return 1;
100011   while( *zTo ){
100012     *(--z) = *(zTo++);
100013   }
100014   *pz = z;
100015   return 1;
100016 }
100017
100018 /*
100019 ** This is the fallback stemmer used when the porter stemmer is
100020 ** inappropriate.  The input word is copied into the output with
100021 ** US-ASCII case folding.  If the input word is too long (more
100022 ** than 20 bytes if it contains no digits or more than 6 bytes if
100023 ** it contains digits) then word is truncated to 20 or 6 bytes
100024 ** by taking 10 or 3 bytes from the beginning and end.
100025 */
100026 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
100027   int i, mx, j;
100028   int hasDigit = 0;
100029   for(i=0; i<nIn; i++){
100030     int c = zIn[i];
100031     if( c>='A' && c<='Z' ){
100032       zOut[i] = c - 'A' + 'a';
100033     }else{
100034       if( c>='0' && c<='9' ) hasDigit = 1;
100035       zOut[i] = c;
100036     }
100037   }
100038   mx = hasDigit ? 3 : 10;
100039   if( nIn>mx*2 ){
100040     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
100041       zOut[j] = zOut[i];
100042     }
100043     i = j;
100044   }
100045   zOut[i] = 0;
100046   *pnOut = i;
100047 }
100048
100049
100050 /*
100051 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
100052 ** zOut is at least big enough to hold nIn bytes.  Write the actual
100053 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
100054 **
100055 ** Any upper-case characters in the US-ASCII character set ([A-Z])
100056 ** are converted to lower case.  Upper-case UTF characters are
100057 ** unchanged.
100058 **
100059 ** Words that are longer than about 20 bytes are stemmed by retaining
100060 ** a few bytes from the beginning and the end of the word.  If the
100061 ** word contains digits, 3 bytes are taken from the beginning and
100062 ** 3 bytes from the end.  For long words without digits, 10 bytes
100063 ** are taken from each end.  US-ASCII case folding still applies.
100064 ** 
100065 ** If the input word contains not digits but does characters not 
100066 ** in [a-zA-Z] then no stemming is attempted and this routine just 
100067 ** copies the input into the input into the output with US-ASCII
100068 ** case folding.
100069 **
100070 ** Stemming never increases the length of the word.  So there is
100071 ** no chance of overflowing the zOut buffer.
100072 */
100073 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
100074   int i, j, c;
100075   char zReverse[28];
100076   char *z, *z2;
100077   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
100078     /* The word is too big or too small for the porter stemmer.
100079     ** Fallback to the copy stemmer */
100080     copy_stemmer(zIn, nIn, zOut, pnOut);
100081     return;
100082   }
100083   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
100084     c = zIn[i];
100085     if( c>='A' && c<='Z' ){
100086       zReverse[j] = c + 'a' - 'A';
100087     }else if( c>='a' && c<='z' ){
100088       zReverse[j] = c;
100089     }else{
100090       /* The use of a character not in [a-zA-Z] means that we fallback
100091       ** to the copy stemmer */
100092       copy_stemmer(zIn, nIn, zOut, pnOut);
100093       return;
100094     }
100095   }
100096   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
100097   z = &zReverse[j+1];
100098
100099
100100   /* Step 1a */
100101   if( z[0]=='s' ){
100102     if(
100103      !stem(&z, "sess", "ss", 0) &&
100104      !stem(&z, "sei", "i", 0)  &&
100105      !stem(&z, "ss", "ss", 0)
100106     ){
100107       z++;
100108     }
100109   }
100110
100111   /* Step 1b */  
100112   z2 = z;
100113   if( stem(&z, "dee", "ee", m_gt_0) ){
100114     /* Do nothing.  The work was all in the test */
100115   }else if( 
100116      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
100117       && z!=z2
100118   ){
100119      if( stem(&z, "ta", "ate", 0) ||
100120          stem(&z, "lb", "ble", 0) ||
100121          stem(&z, "zi", "ize", 0) ){
100122        /* Do nothing.  The work was all in the test */
100123      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
100124        z++;
100125      }else if( m_eq_1(z) && star_oh(z) ){
100126        *(--z) = 'e';
100127      }
100128   }
100129
100130   /* Step 1c */
100131   if( z[0]=='y' && hasVowel(z+1) ){
100132     z[0] = 'i';
100133   }
100134
100135   /* Step 2 */
100136   switch( z[1] ){
100137    case 'a':
100138      stem(&z, "lanoita", "ate", m_gt_0) ||
100139      stem(&z, "lanoit", "tion", m_gt_0);
100140      break;
100141    case 'c':
100142      stem(&z, "icne", "ence", m_gt_0) ||
100143      stem(&z, "icna", "ance", m_gt_0);
100144      break;
100145    case 'e':
100146      stem(&z, "rezi", "ize", m_gt_0);
100147      break;
100148    case 'g':
100149      stem(&z, "igol", "log", m_gt_0);
100150      break;
100151    case 'l':
100152      stem(&z, "ilb", "ble", m_gt_0) ||
100153      stem(&z, "illa", "al", m_gt_0) ||
100154      stem(&z, "iltne", "ent", m_gt_0) ||
100155      stem(&z, "ile", "e", m_gt_0) ||
100156      stem(&z, "ilsuo", "ous", m_gt_0);
100157      break;
100158    case 'o':
100159      stem(&z, "noitazi", "ize", m_gt_0) ||
100160      stem(&z, "noita", "ate", m_gt_0) ||
100161      stem(&z, "rota", "ate", m_gt_0);
100162      break;
100163    case 's':
100164      stem(&z, "msila", "al", m_gt_0) ||
100165      stem(&z, "ssenevi", "ive", m_gt_0) ||
100166      stem(&z, "ssenluf", "ful", m_gt_0) ||
100167      stem(&z, "ssensuo", "ous", m_gt_0);
100168      break;
100169    case 't':
100170      stem(&z, "itila", "al", m_gt_0) ||
100171      stem(&z, "itivi", "ive", m_gt_0) ||
100172      stem(&z, "itilib", "ble", m_gt_0);
100173      break;
100174   }
100175
100176   /* Step 3 */
100177   switch( z[0] ){
100178    case 'e':
100179      stem(&z, "etaci", "ic", m_gt_0) ||
100180      stem(&z, "evita", "", m_gt_0)   ||
100181      stem(&z, "ezila", "al", m_gt_0);
100182      break;
100183    case 'i':
100184      stem(&z, "itici", "ic", m_gt_0);
100185      break;
100186    case 'l':
100187      stem(&z, "laci", "ic", m_gt_0) ||
100188      stem(&z, "luf", "", m_gt_0);
100189      break;
100190    case 's':
100191      stem(&z, "ssen", "", m_gt_0);
100192      break;
100193   }
100194
100195   /* Step 4 */
100196   switch( z[1] ){
100197    case 'a':
100198      if( z[0]=='l' && m_gt_1(z+2) ){
100199        z += 2;
100200      }
100201      break;
100202    case 'c':
100203      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
100204        z += 4;
100205      }
100206      break;
100207    case 'e':
100208      if( z[0]=='r' && m_gt_1(z+2) ){
100209        z += 2;
100210      }
100211      break;
100212    case 'i':
100213      if( z[0]=='c' && m_gt_1(z+2) ){
100214        z += 2;
100215      }
100216      break;
100217    case 'l':
100218      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
100219        z += 4;
100220      }
100221      break;
100222    case 'n':
100223      if( z[0]=='t' ){
100224        if( z[2]=='a' ){
100225          if( m_gt_1(z+3) ){
100226            z += 3;
100227          }
100228        }else if( z[2]=='e' ){
100229          stem(&z, "tneme", "", m_gt_1) ||
100230          stem(&z, "tnem", "", m_gt_1) ||
100231          stem(&z, "tne", "", m_gt_1);
100232        }
100233      }
100234      break;
100235    case 'o':
100236      if( z[0]=='u' ){
100237        if( m_gt_1(z+2) ){
100238          z += 2;
100239        }
100240      }else if( z[3]=='s' || z[3]=='t' ){
100241        stem(&z, "noi", "", m_gt_1);
100242      }
100243      break;
100244    case 's':
100245      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
100246        z += 3;
100247      }
100248      break;
100249    case 't':
100250      stem(&z, "eta", "", m_gt_1) ||
100251      stem(&z, "iti", "", m_gt_1);
100252      break;
100253    case 'u':
100254      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
100255        z += 3;
100256      }
100257      break;
100258    case 'v':
100259    case 'z':
100260      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
100261        z += 3;
100262      }
100263      break;
100264   }
100265
100266   /* Step 5a */
100267   if( z[0]=='e' ){
100268     if( m_gt_1(z+1) ){
100269       z++;
100270     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
100271       z++;
100272     }
100273   }
100274
100275   /* Step 5b */
100276   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
100277     z++;
100278   }
100279
100280   /* z[] is now the stemmed word in reverse order.  Flip it back
100281   ** around into forward order and return.
100282   */
100283   *pnOut = i = strlen(z);
100284   zOut[i] = 0;
100285   while( *z ){
100286     zOut[--i] = *(z++);
100287   }
100288 }
100289
100290 /*
100291 ** Characters that can be part of a token.  We assume any character
100292 ** whose value is greater than 0x80 (any UTF character) can be
100293 ** part of a token.  In other words, delimiters all must have
100294 ** values of 0x7f or lower.
100295 */
100296 static const char porterIdChar[] = {
100297 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
100298     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
100299     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
100300     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
100301     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
100302     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
100303 };
100304 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
100305
100306 /*
100307 ** Extract the next token from a tokenization cursor.  The cursor must
100308 ** have been opened by a prior call to porterOpen().
100309 */
100310 static int porterNext(
100311   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
100312   const char **pzToken,               /* OUT: *pzToken is the token text */
100313   int *pnBytes,                       /* OUT: Number of bytes in token */
100314   int *piStartOffset,                 /* OUT: Starting offset of token */
100315   int *piEndOffset,                   /* OUT: Ending offset of token */
100316   int *piPosition                     /* OUT: Position integer of token */
100317 ){
100318   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
100319   const char *z = c->zInput;
100320
100321   while( c->iOffset<c->nInput ){
100322     int iStartOffset, ch;
100323
100324     /* Scan past delimiter characters */
100325     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
100326       c->iOffset++;
100327     }
100328
100329     /* Count non-delimiter characters. */
100330     iStartOffset = c->iOffset;
100331     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
100332       c->iOffset++;
100333     }
100334
100335     if( c->iOffset>iStartOffset ){
100336       int n = c->iOffset-iStartOffset;
100337       if( n>c->nAllocated ){
100338         c->nAllocated = n+20;
100339         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
100340         if( c->zToken==NULL ) return SQLITE_NOMEM;
100341       }
100342       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
100343       *pzToken = c->zToken;
100344       *piStartOffset = iStartOffset;
100345       *piEndOffset = c->iOffset;
100346       *piPosition = c->iToken++;
100347       return SQLITE_OK;
100348     }
100349   }
100350   return SQLITE_DONE;
100351 }
100352
100353 /*
100354 ** The set of routines that implement the porter-stemmer tokenizer
100355 */
100356 static const sqlite3_tokenizer_module porterTokenizerModule = {
100357   0,
100358   porterCreate,
100359   porterDestroy,
100360   porterOpen,
100361   porterClose,
100362   porterNext,
100363 };
100364
100365 /*
100366 ** Allocate a new porter tokenizer.  Return a pointer to the new
100367 ** tokenizer in *ppModule
100368 */
100369 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
100370   sqlite3_tokenizer_module const**ppModule
100371 ){
100372   *ppModule = &porterTokenizerModule;
100373 }
100374
100375 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
100376
100377 /************** End of fts3_porter.c *****************************************/
100378 /************** Begin file fts3_tokenizer.c **********************************/
100379 /*
100380 ** 2007 June 22
100381 **
100382 ** The author disclaims copyright to this source code.  In place of
100383 ** a legal notice, here is a blessing:
100384 **
100385 **    May you do good and not evil.
100386 **    May you find forgiveness for yourself and forgive others.
100387 **    May you share freely, never taking more than you give.
100388 **
100389 ******************************************************************************
100390 **
100391 ** This is part of an SQLite module implementing full-text search.
100392 ** This particular file implements the generic tokenizer interface.
100393 */
100394
100395 /*
100396 ** The code in this file is only compiled if:
100397 **
100398 **     * The FTS3 module is being built as an extension
100399 **       (in which case SQLITE_CORE is not defined), or
100400 **
100401 **     * The FTS3 module is being built into the core of
100402 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
100403 */
100404 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
100405
100406 #ifndef SQLITE_CORE
100407   SQLITE_EXTENSION_INIT1
100408 #endif
100409
100410
100411 /*
100412 ** Implementation of the SQL scalar function for accessing the underlying 
100413 ** hash table. This function may be called as follows:
100414 **
100415 **   SELECT <function-name>(<key-name>);
100416 **   SELECT <function-name>(<key-name>, <pointer>);
100417 **
100418 ** where <function-name> is the name passed as the second argument
100419 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
100420 **
100421 ** If the <pointer> argument is specified, it must be a blob value
100422 ** containing a pointer to be stored as the hash data corresponding
100423 ** to the string <key-name>. If <pointer> is not specified, then
100424 ** the string <key-name> must already exist in the has table. Otherwise,
100425 ** an error is returned.
100426 **
100427 ** Whether or not the <pointer> argument is specified, the value returned
100428 ** is a blob containing the pointer stored as the hash data corresponding
100429 ** to string <key-name> (after the hash-table is updated, if applicable).
100430 */
100431 static void scalarFunc(
100432   sqlite3_context *context,
100433   int argc,
100434   sqlite3_value **argv
100435 ){
100436   fts3Hash *pHash;
100437   void *pPtr = 0;
100438   const unsigned char *zName;
100439   int nName;
100440
100441   assert( argc==1 || argc==2 );
100442
100443   pHash = (fts3Hash *)sqlite3_user_data(context);
100444
100445   zName = sqlite3_value_text(argv[0]);
100446   nName = sqlite3_value_bytes(argv[0])+1;
100447
100448   if( argc==2 ){
100449     void *pOld;
100450     int n = sqlite3_value_bytes(argv[1]);
100451     if( n!=sizeof(pPtr) ){
100452       sqlite3_result_error(context, "argument type mismatch", -1);
100453       return;
100454     }
100455     pPtr = *(void **)sqlite3_value_blob(argv[1]);
100456     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
100457     if( pOld==pPtr ){
100458       sqlite3_result_error(context, "out of memory", -1);
100459       return;
100460     }
100461   }else{
100462     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
100463     if( !pPtr ){
100464       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
100465       sqlite3_result_error(context, zErr, -1);
100466       sqlite3_free(zErr);
100467       return;
100468     }
100469   }
100470
100471   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
100472 }
100473
100474 #ifdef SQLITE_TEST
100475
100476
100477 /*
100478 ** Implementation of a special SQL scalar function for testing tokenizers 
100479 ** designed to be used in concert with the Tcl testing framework. This
100480 ** function must be called with two arguments:
100481 **
100482 **   SELECT <function-name>(<key-name>, <input-string>);
100483 **   SELECT <function-name>(<key-name>, <pointer>);
100484 **
100485 ** where <function-name> is the name passed as the second argument
100486 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
100487 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
100488 **
100489 ** The return value is a string that may be interpreted as a Tcl
100490 ** list. For each token in the <input-string>, three elements are
100491 ** added to the returned list. The first is the token position, the 
100492 ** second is the token text (folded, stemmed, etc.) and the third is the
100493 ** substring of <input-string> associated with the token. For example, 
100494 ** using the built-in "simple" tokenizer:
100495 **
100496 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
100497 **
100498 ** will return the string:
100499 **
100500 **   "{0 i I 1 dont don't 2 see see 3 how how}"
100501 **   
100502 */
100503 static void testFunc(
100504   sqlite3_context *context,
100505   int argc,
100506   sqlite3_value **argv
100507 ){
100508   fts3Hash *pHash;
100509   sqlite3_tokenizer_module *p;
100510   sqlite3_tokenizer *pTokenizer = 0;
100511   sqlite3_tokenizer_cursor *pCsr = 0;
100512
100513   const char *zErr = 0;
100514
100515   const char *zName;
100516   int nName;
100517   const char *zInput;
100518   int nInput;
100519
100520   const char *zArg = 0;
100521
100522   const char *zToken;
100523   int nToken;
100524   int iStart;
100525   int iEnd;
100526   int iPos;
100527
100528   Tcl_Obj *pRet;
100529
100530   assert( argc==2 || argc==3 );
100531
100532   nName = sqlite3_value_bytes(argv[0]);
100533   zName = (const char *)sqlite3_value_text(argv[0]);
100534   nInput = sqlite3_value_bytes(argv[argc-1]);
100535   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
100536
100537   if( argc==3 ){
100538     zArg = (const char *)sqlite3_value_text(argv[1]);
100539   }
100540
100541   pHash = (fts3Hash *)sqlite3_user_data(context);
100542   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
100543
100544   if( !p ){
100545     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
100546     sqlite3_result_error(context, zErr, -1);
100547     sqlite3_free(zErr);
100548     return;
100549   }
100550
100551   pRet = Tcl_NewObj();
100552   Tcl_IncrRefCount(pRet);
100553
100554   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
100555     zErr = "error in xCreate()";
100556     goto finish;
100557   }
100558   pTokenizer->pModule = p;
100559   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
100560     zErr = "error in xOpen()";
100561     goto finish;
100562   }
100563   pCsr->pTokenizer = pTokenizer;
100564
100565   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
100566     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
100567     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
100568     zToken = &zInput[iStart];
100569     nToken = iEnd-iStart;
100570     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
100571   }
100572
100573   if( SQLITE_OK!=p->xClose(pCsr) ){
100574     zErr = "error in xClose()";
100575     goto finish;
100576   }
100577   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
100578     zErr = "error in xDestroy()";
100579     goto finish;
100580   }
100581
100582 finish:
100583   if( zErr ){
100584     sqlite3_result_error(context, zErr, -1);
100585   }else{
100586     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
100587   }
100588   Tcl_DecrRefCount(pRet);
100589 }
100590
100591 static
100592 int registerTokenizer(
100593   sqlite3 *db, 
100594   char *zName, 
100595   const sqlite3_tokenizer_module *p
100596 ){
100597   int rc;
100598   sqlite3_stmt *pStmt;
100599   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
100600
100601   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
100602   if( rc!=SQLITE_OK ){
100603     return rc;
100604   }
100605
100606   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
100607   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
100608   sqlite3_step(pStmt);
100609
100610   return sqlite3_finalize(pStmt);
100611 }
100612
100613 static
100614 int queryTokenizer(
100615   sqlite3 *db, 
100616   char *zName,  
100617   const sqlite3_tokenizer_module **pp
100618 ){
100619   int rc;
100620   sqlite3_stmt *pStmt;
100621   const char zSql[] = "SELECT fts3_tokenizer(?)";
100622
100623   *pp = 0;
100624   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
100625   if( rc!=SQLITE_OK ){
100626     return rc;
100627   }
100628
100629   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
100630   if( SQLITE_ROW==sqlite3_step(pStmt) ){
100631     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
100632       memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
100633     }
100634   }
100635
100636   return sqlite3_finalize(pStmt);
100637 }
100638
100639 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100640
100641 /*
100642 ** Implementation of the scalar function fts3_tokenizer_internal_test().
100643 ** This function is used for testing only, it is not included in the
100644 ** build unless SQLITE_TEST is defined.
100645 **
100646 ** The purpose of this is to test that the fts3_tokenizer() function
100647 ** can be used as designed by the C-code in the queryTokenizer and
100648 ** registerTokenizer() functions above. These two functions are repeated
100649 ** in the README.tokenizer file as an example, so it is important to
100650 ** test them.
100651 **
100652 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
100653 ** function with no arguments. An assert() will fail if a problem is
100654 ** detected. i.e.:
100655 **
100656 **     SELECT fts3_tokenizer_internal_test();
100657 **
100658 */
100659 static void intTestFunc(
100660   sqlite3_context *context,
100661   int argc,
100662   sqlite3_value **argv
100663 ){
100664   int rc;
100665   const sqlite3_tokenizer_module *p1;
100666   const sqlite3_tokenizer_module *p2;
100667   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
100668
100669   /* Test the query function */
100670   sqlite3Fts3SimpleTokenizerModule(&p1);
100671   rc = queryTokenizer(db, "simple", &p2);
100672   assert( rc==SQLITE_OK );
100673   assert( p1==p2 );
100674   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
100675   assert( rc==SQLITE_ERROR );
100676   assert( p2==0 );
100677   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
100678
100679   /* Test the storage function */
100680   rc = registerTokenizer(db, "nosuchtokenizer", p1);
100681   assert( rc==SQLITE_OK );
100682   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
100683   assert( rc==SQLITE_OK );
100684   assert( p2==p1 );
100685
100686   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
100687 }
100688
100689 #endif
100690
100691 /*
100692 ** Set up SQL objects in database db used to access the contents of
100693 ** the hash table pointed to by argument pHash. The hash table must
100694 ** been initialised to use string keys, and to take a private copy 
100695 ** of the key when a value is inserted. i.e. by a call similar to:
100696 **
100697 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
100698 **
100699 ** This function adds a scalar function (see header comment above
100700 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
100701 ** defined at compilation time, a temporary virtual table (see header 
100702 ** comment above struct HashTableVtab) to the database schema. Both 
100703 ** provide read/write access to the contents of *pHash.
100704 **
100705 ** The third argument to this function, zName, is used as the name
100706 ** of both the scalar and, if created, the virtual table.
100707 */
100708 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
100709   sqlite3 *db, 
100710   fts3Hash *pHash, 
100711   const char *zName
100712 ){
100713   int rc = SQLITE_OK;
100714   void *p = (void *)pHash;
100715   const int any = SQLITE_ANY;
100716   char *zTest = 0;
100717   char *zTest2 = 0;
100718
100719 #ifdef SQLITE_TEST
100720   void *pdb = (void *)db;
100721   zTest = sqlite3_mprintf("%s_test", zName);
100722   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
100723   if( !zTest || !zTest2 ){
100724     rc = SQLITE_NOMEM;
100725   }
100726 #endif
100727
100728   if( rc!=SQLITE_OK
100729    || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
100730    || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
100731 #ifdef SQLITE_TEST
100732    || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
100733    || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
100734    || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
100735 #endif
100736   );
100737
100738   sqlite3_free(zTest);
100739   sqlite3_free(zTest2);
100740   return rc;
100741 }
100742
100743 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
100744
100745 /************** End of fts3_tokenizer.c **************************************/
100746 /************** Begin file fts3_tokenizer1.c *********************************/
100747 /*
100748 ** 2006 Oct 10
100749 **
100750 ** The author disclaims copyright to this source code.  In place of
100751 ** a legal notice, here is a blessing:
100752 **
100753 **    May you do good and not evil.
100754 **    May you find forgiveness for yourself and forgive others.
100755 **    May you share freely, never taking more than you give.
100756 **
100757 ******************************************************************************
100758 **
100759 ** Implementation of the "simple" full-text-search tokenizer.
100760 */
100761
100762 /*
100763 ** The code in this file is only compiled if:
100764 **
100765 **     * The FTS3 module is being built as an extension
100766 **       (in which case SQLITE_CORE is not defined), or
100767 **
100768 **     * The FTS3 module is being built into the core of
100769 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
100770 */
100771 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
100772
100773
100774
100775
100776 typedef struct simple_tokenizer {
100777   sqlite3_tokenizer base;
100778   char delim[128];             /* flag ASCII delimiters */
100779 } simple_tokenizer;
100780
100781 typedef struct simple_tokenizer_cursor {
100782   sqlite3_tokenizer_cursor base;
100783   const char *pInput;          /* input we are tokenizing */
100784   int nBytes;                  /* size of the input */
100785   int iOffset;                 /* current position in pInput */
100786   int iToken;                  /* index of next token to be returned */
100787   char *pToken;                /* storage for current token */
100788   int nTokenAllocated;         /* space allocated to zToken buffer */
100789 } simple_tokenizer_cursor;
100790
100791
100792 /* Forward declaration */
100793 static const sqlite3_tokenizer_module simpleTokenizerModule;
100794
100795 static int simpleDelim(simple_tokenizer *t, unsigned char c){
100796   return c<0x80 && t->delim[c];
100797 }
100798
100799 /*
100800 ** Create a new tokenizer instance.
100801 */
100802 static int simpleCreate(
100803   int argc, const char * const *argv,
100804   sqlite3_tokenizer **ppTokenizer
100805 ){
100806   simple_tokenizer *t;
100807
100808   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
100809   if( t==NULL ) return SQLITE_NOMEM;
100810   memset(t, 0, sizeof(*t));
100811
100812   /* TODO(shess) Delimiters need to remain the same from run to run,
100813   ** else we need to reindex.  One solution would be a meta-table to
100814   ** track such information in the database, then we'd only want this
100815   ** information on the initial create.
100816   */
100817   if( argc>1 ){
100818     int i, n = strlen(argv[1]);
100819     for(i=0; i<n; i++){
100820       unsigned char ch = argv[1][i];
100821       /* We explicitly don't support UTF-8 delimiters for now. */
100822       if( ch>=0x80 ){
100823         sqlite3_free(t);
100824         return SQLITE_ERROR;
100825       }
100826       t->delim[ch] = 1;
100827     }
100828   } else {
100829     /* Mark non-alphanumeric ASCII characters as delimiters */
100830     int i;
100831     for(i=1; i<0x80; i++){
100832       t->delim[i] = !isalnum(i);
100833     }
100834   }
100835
100836   *ppTokenizer = &t->base;
100837   return SQLITE_OK;
100838 }
100839
100840 /*
100841 ** Destroy a tokenizer
100842 */
100843 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
100844   sqlite3_free(pTokenizer);
100845   return SQLITE_OK;
100846 }
100847
100848 /*
100849 ** Prepare to begin tokenizing a particular string.  The input
100850 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
100851 ** used to incrementally tokenize this string is returned in 
100852 ** *ppCursor.
100853 */
100854 static int simpleOpen(
100855   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
100856   const char *pInput, int nBytes,        /* String to be tokenized */
100857   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
100858 ){
100859   simple_tokenizer_cursor *c;
100860
100861   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
100862   if( c==NULL ) return SQLITE_NOMEM;
100863
100864   c->pInput = pInput;
100865   if( pInput==0 ){
100866     c->nBytes = 0;
100867   }else if( nBytes<0 ){
100868     c->nBytes = (int)strlen(pInput);
100869   }else{
100870     c->nBytes = nBytes;
100871   }
100872   c->iOffset = 0;                 /* start tokenizing at the beginning */
100873   c->iToken = 0;
100874   c->pToken = NULL;               /* no space allocated, yet. */
100875   c->nTokenAllocated = 0;
100876
100877   *ppCursor = &c->base;
100878   return SQLITE_OK;
100879 }
100880
100881 /*
100882 ** Close a tokenization cursor previously opened by a call to
100883 ** simpleOpen() above.
100884 */
100885 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
100886   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
100887   sqlite3_free(c->pToken);
100888   sqlite3_free(c);
100889   return SQLITE_OK;
100890 }
100891
100892 /*
100893 ** Extract the next token from a tokenization cursor.  The cursor must
100894 ** have been opened by a prior call to simpleOpen().
100895 */
100896 static int simpleNext(
100897   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
100898   const char **ppToken,               /* OUT: *ppToken is the token text */
100899   int *pnBytes,                       /* OUT: Number of bytes in token */
100900   int *piStartOffset,                 /* OUT: Starting offset of token */
100901   int *piEndOffset,                   /* OUT: Ending offset of token */
100902   int *piPosition                     /* OUT: Position integer of token */
100903 ){
100904   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
100905   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
100906   unsigned char *p = (unsigned char *)c->pInput;
100907
100908   while( c->iOffset<c->nBytes ){
100909     int iStartOffset;
100910
100911     /* Scan past delimiter characters */
100912     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
100913       c->iOffset++;
100914     }
100915
100916     /* Count non-delimiter characters. */
100917     iStartOffset = c->iOffset;
100918     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
100919       c->iOffset++;
100920     }
100921
100922     if( c->iOffset>iStartOffset ){
100923       int i, n = c->iOffset-iStartOffset;
100924       if( n>c->nTokenAllocated ){
100925         c->nTokenAllocated = n+20;
100926         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
100927         if( c->pToken==NULL ) return SQLITE_NOMEM;
100928       }
100929       for(i=0; i<n; i++){
100930         /* TODO(shess) This needs expansion to handle UTF-8
100931         ** case-insensitivity.
100932         */
100933         unsigned char ch = p[iStartOffset+i];
100934         c->pToken[i] = ch<0x80 ? tolower(ch) : ch;
100935       }
100936       *ppToken = c->pToken;
100937       *pnBytes = n;
100938       *piStartOffset = iStartOffset;
100939       *piEndOffset = c->iOffset;
100940       *piPosition = c->iToken++;
100941
100942       return SQLITE_OK;
100943     }
100944   }
100945   return SQLITE_DONE;
100946 }
100947
100948 /*
100949 ** The set of routines that implement the simple tokenizer
100950 */
100951 static const sqlite3_tokenizer_module simpleTokenizerModule = {
100952   0,
100953   simpleCreate,
100954   simpleDestroy,
100955   simpleOpen,
100956   simpleClose,
100957   simpleNext,
100958 };
100959
100960 /*
100961 ** Allocate a new simple tokenizer.  Return a pointer to the new
100962 ** tokenizer in *ppModule
100963 */
100964 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
100965   sqlite3_tokenizer_module const**ppModule
100966 ){
100967   *ppModule = &simpleTokenizerModule;
100968 }
100969
100970 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
100971
100972 /************** End of fts3_tokenizer1.c *************************************/
100973 /************** Begin file rtree.c *******************************************/
100974 /*
100975 ** 2001 September 15
100976 **
100977 ** The author disclaims copyright to this source code.  In place of
100978 ** a legal notice, here is a blessing:
100979 **
100980 **    May you do good and not evil.
100981 **    May you find forgiveness for yourself and forgive others.
100982 **    May you share freely, never taking more than you give.
100983 **
100984 *************************************************************************
100985 ** This file contains code for implementations of the r-tree and r*-tree
100986 ** algorithms packaged as an SQLite virtual table module.
100987 **
100988 ** $Id: rtree.c,v 1.12 2008/12/22 15:04:32 danielk1977 Exp $
100989 */
100990
100991 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
100992
100993 /*
100994 ** This file contains an implementation of a couple of different variants
100995 ** of the r-tree algorithm. See the README file for further details. The 
100996 ** same data-structure is used for all, but the algorithms for insert and
100997 ** delete operations vary. The variants used are selected at compile time 
100998 ** by defining the following symbols:
100999 */
101000
101001 /* Either, both or none of the following may be set to activate 
101002 ** r*tree variant algorithms.
101003 */
101004 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
101005 #define VARIANT_RSTARTREE_REINSERT      1
101006
101007 /* 
101008 ** Exactly one of the following must be set to 1.
101009 */
101010 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
101011 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
101012 #define VARIANT_RSTARTREE_SPLIT         1
101013
101014 #define VARIANT_GUTTMAN_SPLIT \
101015         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
101016
101017 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
101018   #define PickNext QuadraticPickNext
101019   #define PickSeeds QuadraticPickSeeds
101020   #define AssignCells splitNodeGuttman
101021 #endif
101022 #if VARIANT_GUTTMAN_LINEAR_SPLIT
101023   #define PickNext LinearPickNext
101024   #define PickSeeds LinearPickSeeds
101025   #define AssignCells splitNodeGuttman
101026 #endif
101027 #if VARIANT_RSTARTREE_SPLIT
101028   #define AssignCells splitNodeStartree
101029 #endif
101030
101031
101032 #ifndef SQLITE_CORE
101033   SQLITE_EXTENSION_INIT1
101034 #else
101035 #endif
101036
101037
101038 #ifndef SQLITE_AMALGAMATION
101039 typedef sqlite3_int64 i64;
101040 typedef unsigned char u8;
101041 typedef unsigned int u32;
101042 #endif
101043
101044 typedef struct Rtree Rtree;
101045 typedef struct RtreeCursor RtreeCursor;
101046 typedef struct RtreeNode RtreeNode;
101047 typedef struct RtreeCell RtreeCell;
101048 typedef struct RtreeConstraint RtreeConstraint;
101049 typedef union RtreeCoord RtreeCoord;
101050
101051 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
101052 #define RTREE_MAX_DIMENSIONS 5
101053
101054 /* Size of hash table Rtree.aHash. This hash table is not expected to
101055 ** ever contain very many entries, so a fixed number of buckets is 
101056 ** used.
101057 */
101058 #define HASHSIZE 128
101059
101060 /* 
101061 ** An rtree virtual-table object.
101062 */
101063 struct Rtree {
101064   sqlite3_vtab base;
101065   sqlite3 *db;                /* Host database connection */
101066   int iNodeSize;              /* Size in bytes of each node in the node table */
101067   int nDim;                   /* Number of dimensions */
101068   int nBytesPerCell;          /* Bytes consumed per cell */
101069   int iDepth;                 /* Current depth of the r-tree structure */
101070   char *zDb;                  /* Name of database containing r-tree table */
101071   char *zName;                /* Name of r-tree table */ 
101072   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
101073   int nBusy;                  /* Current number of users of this structure */
101074
101075   /* List of nodes removed during a CondenseTree operation. List is
101076   ** linked together via the pointer normally used for hash chains -
101077   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
101078   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
101079   */
101080   RtreeNode *pDeleted;
101081   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
101082
101083   /* Statements to read/write/delete a record from xxx_node */
101084   sqlite3_stmt *pReadNode;
101085   sqlite3_stmt *pWriteNode;
101086   sqlite3_stmt *pDeleteNode;
101087
101088   /* Statements to read/write/delete a record from xxx_rowid */
101089   sqlite3_stmt *pReadRowid;
101090   sqlite3_stmt *pWriteRowid;
101091   sqlite3_stmt *pDeleteRowid;
101092
101093   /* Statements to read/write/delete a record from xxx_parent */
101094   sqlite3_stmt *pReadParent;
101095   sqlite3_stmt *pWriteParent;
101096   sqlite3_stmt *pDeleteParent;
101097
101098   int eCoordType;
101099 };
101100
101101 /* Possible values for eCoordType: */
101102 #define RTREE_COORD_REAL32 0
101103 #define RTREE_COORD_INT32  1
101104
101105 /*
101106 ** The minimum number of cells allowed for a node is a third of the 
101107 ** maximum. In Gutman's notation:
101108 **
101109 **     m = M/3
101110 **
101111 ** If an R*-tree "Reinsert" operation is required, the same number of
101112 ** cells are removed from the overfull node and reinserted into the tree.
101113 */
101114 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
101115 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
101116 #define RTREE_MAXCELLS 51
101117
101118 /* 
101119 ** An rtree cursor object.
101120 */
101121 struct RtreeCursor {
101122   sqlite3_vtab_cursor base;
101123   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
101124   int iCell;                        /* Index of current cell in pNode */
101125   int iStrategy;                    /* Copy of idxNum search parameter */
101126   int nConstraint;                  /* Number of entries in aConstraint */
101127   RtreeConstraint *aConstraint;     /* Search constraints. */
101128 };
101129
101130 union RtreeCoord {
101131   float f;
101132   int i;
101133 };
101134
101135 /*
101136 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
101137 ** formatted as a double. This macro assumes that local variable pRtree points
101138 ** to the Rtree structure associated with the RtreeCoord.
101139 */
101140 #define DCOORD(coord) (                           \
101141   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
101142     ((double)coord.f) :                           \
101143     ((double)coord.i)                             \
101144 )
101145
101146 /*
101147 ** A search constraint.
101148 */
101149 struct RtreeConstraint {
101150   int iCoord;                       /* Index of constrained coordinate */
101151   int op;                           /* Constraining operation */
101152   double rValue;                    /* Constraint value. */
101153 };
101154
101155 /* Possible values for RtreeConstraint.op */
101156 #define RTREE_EQ 0x41
101157 #define RTREE_LE 0x42
101158 #define RTREE_LT 0x43
101159 #define RTREE_GE 0x44
101160 #define RTREE_GT 0x45
101161
101162 /* 
101163 ** An rtree structure node.
101164 **
101165 ** Data format (RtreeNode.zData):
101166 **
101167 **   1. If the node is the root node (node 1), then the first 2 bytes
101168 **      of the node contain the tree depth as a big-endian integer.
101169 **      For non-root nodes, the first 2 bytes are left unused.
101170 **
101171 **   2. The next 2 bytes contain the number of entries currently 
101172 **      stored in the node.
101173 **
101174 **   3. The remainder of the node contains the node entries. Each entry
101175 **      consists of a single 8-byte integer followed by an even number
101176 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
101177 **      of a record. For internal nodes it is the node number of a
101178 **      child page.
101179 */
101180 struct RtreeNode {
101181   RtreeNode *pParent;               /* Parent node */
101182   i64 iNode;
101183   int nRef;
101184   int isDirty;
101185   u8 *zData;
101186   RtreeNode *pNext;                 /* Next node in this hash chain */
101187 };
101188 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
101189
101190 /* 
101191 ** Structure to store a deserialized rtree record.
101192 */
101193 struct RtreeCell {
101194   i64 iRowid;
101195   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
101196 };
101197
101198 #ifndef MAX
101199 # define MAX(x,y) ((x) < (y) ? (y) : (x))
101200 #endif
101201 #ifndef MIN
101202 # define MIN(x,y) ((x) > (y) ? (y) : (x))
101203 #endif
101204
101205 /*
101206 ** Functions to deserialize a 16 bit integer, 32 bit real number and
101207 ** 64 bit integer. The deserialized value is returned.
101208 */
101209 static int readInt16(u8 *p){
101210   return (p[0]<<8) + p[1];
101211 }
101212 static void readCoord(u8 *p, RtreeCoord *pCoord){
101213   u32 i = (
101214     (((u32)p[0]) << 24) + 
101215     (((u32)p[1]) << 16) + 
101216     (((u32)p[2]) <<  8) + 
101217     (((u32)p[3]) <<  0)
101218   );
101219   *(u32 *)pCoord = i;
101220 }
101221 static i64 readInt64(u8 *p){
101222   return (
101223     (((i64)p[0]) << 56) + 
101224     (((i64)p[1]) << 48) + 
101225     (((i64)p[2]) << 40) + 
101226     (((i64)p[3]) << 32) + 
101227     (((i64)p[4]) << 24) + 
101228     (((i64)p[5]) << 16) + 
101229     (((i64)p[6]) <<  8) + 
101230     (((i64)p[7]) <<  0)
101231   );
101232 }
101233
101234 /*
101235 ** Functions to serialize a 16 bit integer, 32 bit real number and
101236 ** 64 bit integer. The value returned is the number of bytes written
101237 ** to the argument buffer (always 2, 4 and 8 respectively).
101238 */
101239 static int writeInt16(u8 *p, int i){
101240   p[0] = (i>> 8)&0xFF;
101241   p[1] = (i>> 0)&0xFF;
101242   return 2;
101243 }
101244 static int writeCoord(u8 *p, RtreeCoord *pCoord){
101245   u32 i;
101246   assert( sizeof(RtreeCoord)==4 );
101247   assert( sizeof(u32)==4 );
101248   i = *(u32 *)pCoord;
101249   p[0] = (i>>24)&0xFF;
101250   p[1] = (i>>16)&0xFF;
101251   p[2] = (i>> 8)&0xFF;
101252   p[3] = (i>> 0)&0xFF;
101253   return 4;
101254 }
101255 static int writeInt64(u8 *p, i64 i){
101256   p[0] = (i>>56)&0xFF;
101257   p[1] = (i>>48)&0xFF;
101258   p[2] = (i>>40)&0xFF;
101259   p[3] = (i>>32)&0xFF;
101260   p[4] = (i>>24)&0xFF;
101261   p[5] = (i>>16)&0xFF;
101262   p[6] = (i>> 8)&0xFF;
101263   p[7] = (i>> 0)&0xFF;
101264   return 8;
101265 }
101266
101267 /*
101268 ** Increment the reference count of node p.
101269 */
101270 static void nodeReference(RtreeNode *p){
101271   if( p ){
101272     p->nRef++;
101273   }
101274 }
101275
101276 /*
101277 ** Clear the content of node p (set all bytes to 0x00).
101278 */
101279 static void nodeZero(Rtree *pRtree, RtreeNode *p){
101280   if( p ){
101281     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
101282     p->isDirty = 1;
101283   }
101284 }
101285
101286 /*
101287 ** Given a node number iNode, return the corresponding key to use
101288 ** in the Rtree.aHash table.
101289 */
101290 static int nodeHash(i64 iNode){
101291   return (
101292     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
101293     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
101294   ) % HASHSIZE;
101295 }
101296
101297 /*
101298 ** Search the node hash table for node iNode. If found, return a pointer
101299 ** to it. Otherwise, return 0.
101300 */
101301 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
101302   RtreeNode *p;
101303   assert( iNode!=0 );
101304   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
101305   return p;
101306 }
101307
101308 /*
101309 ** Add node pNode to the node hash table.
101310 */
101311 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
101312   if( pNode ){
101313     int iHash;
101314     assert( pNode->pNext==0 );
101315     iHash = nodeHash(pNode->iNode);
101316     pNode->pNext = pRtree->aHash[iHash];
101317     pRtree->aHash[iHash] = pNode;
101318   }
101319 }
101320
101321 /*
101322 ** Remove node pNode from the node hash table.
101323 */
101324 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
101325   RtreeNode **pp;
101326   if( pNode->iNode!=0 ){
101327     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
101328     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
101329     *pp = pNode->pNext;
101330     pNode->pNext = 0;
101331   }
101332 }
101333
101334 /*
101335 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
101336 ** indicating that node has not yet been assigned a node number. It is
101337 ** assigned a node number when nodeWrite() is called to write the
101338 ** node contents out to the database.
101339 */
101340 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
101341   RtreeNode *pNode;
101342   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
101343   if( pNode ){
101344     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
101345     pNode->zData = (u8 *)&pNode[1];
101346     pNode->nRef = 1;
101347     pNode->pParent = pParent;
101348     pNode->isDirty = 1;
101349     nodeReference(pParent);
101350   }
101351   return pNode;
101352 }
101353
101354 /*
101355 ** Obtain a reference to an r-tree node.
101356 */
101357 static int
101358 nodeAcquire(
101359   Rtree *pRtree,             /* R-tree structure */
101360   i64 iNode,                 /* Node number to load */
101361   RtreeNode *pParent,        /* Either the parent node or NULL */
101362   RtreeNode **ppNode         /* OUT: Acquired node */
101363 ){
101364   int rc;
101365   RtreeNode *pNode;
101366
101367   /* Check if the requested node is already in the hash table. If so,
101368   ** increase its reference count and return it.
101369   */
101370   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
101371     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
101372     if( pParent && !pNode->pParent ){
101373       nodeReference(pParent);
101374       pNode->pParent = pParent;
101375     }
101376     pNode->nRef++;
101377     *ppNode = pNode;
101378     return SQLITE_OK;
101379   }
101380
101381   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
101382   if( !pNode ){
101383     *ppNode = 0;
101384     return SQLITE_NOMEM;
101385   }
101386   pNode->pParent = pParent;
101387   pNode->zData = (u8 *)&pNode[1];
101388   pNode->nRef = 1;
101389   pNode->iNode = iNode;
101390   pNode->isDirty = 0;
101391   pNode->pNext = 0;
101392
101393   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
101394   rc = sqlite3_step(pRtree->pReadNode);
101395   if( rc==SQLITE_ROW ){
101396     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
101397     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
101398     nodeReference(pParent);
101399   }else{
101400     sqlite3_free(pNode);
101401     pNode = 0;
101402   }
101403
101404   *ppNode = pNode;
101405   rc = sqlite3_reset(pRtree->pReadNode);
101406
101407   if( rc==SQLITE_OK && iNode==1 ){
101408     pRtree->iDepth = readInt16(pNode->zData);
101409   }
101410
101411   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
101412   nodeHashInsert(pRtree, pNode);
101413
101414   return rc;
101415 }
101416
101417 /*
101418 ** Overwrite cell iCell of node pNode with the contents of pCell.
101419 */
101420 static void nodeOverwriteCell(
101421   Rtree *pRtree, 
101422   RtreeNode *pNode,  
101423   RtreeCell *pCell, 
101424   int iCell
101425 ){
101426   int ii;
101427   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
101428   p += writeInt64(p, pCell->iRowid);
101429   for(ii=0; ii<(pRtree->nDim*2); ii++){
101430     p += writeCoord(p, &pCell->aCoord[ii]);
101431   }
101432   pNode->isDirty = 1;
101433 }
101434
101435 /*
101436 ** Remove cell the cell with index iCell from node pNode.
101437 */
101438 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
101439   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
101440   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
101441   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
101442   memmove(pDst, pSrc, nByte);
101443   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
101444   pNode->isDirty = 1;
101445 }
101446
101447 /*
101448 ** Insert the contents of cell pCell into node pNode. If the insert
101449 ** is successful, return SQLITE_OK.
101450 **
101451 ** If there is not enough free space in pNode, return SQLITE_FULL.
101452 */
101453 static int
101454 nodeInsertCell(
101455   Rtree *pRtree, 
101456   RtreeNode *pNode, 
101457   RtreeCell *pCell 
101458 ){
101459   int nCell;                    /* Current number of cells in pNode */
101460   int nMaxCell;                 /* Maximum number of cells for pNode */
101461
101462   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
101463   nCell = NCELL(pNode);
101464
101465   assert(nCell<=nMaxCell);
101466
101467   if( nCell<nMaxCell ){
101468     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
101469     writeInt16(&pNode->zData[2], nCell+1);
101470     pNode->isDirty = 1;
101471   }
101472
101473   return (nCell==nMaxCell);
101474 }
101475
101476 /*
101477 ** If the node is dirty, write it out to the database.
101478 */
101479 static int
101480 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
101481   int rc = SQLITE_OK;
101482   if( pNode->isDirty ){
101483     sqlite3_stmt *p = pRtree->pWriteNode;
101484     if( pNode->iNode ){
101485       sqlite3_bind_int64(p, 1, pNode->iNode);
101486     }else{
101487       sqlite3_bind_null(p, 1);
101488     }
101489     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
101490     sqlite3_step(p);
101491     pNode->isDirty = 0;
101492     rc = sqlite3_reset(p);
101493     if( pNode->iNode==0 && rc==SQLITE_OK ){
101494       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
101495       nodeHashInsert(pRtree, pNode);
101496     }
101497   }
101498   return rc;
101499 }
101500
101501 /*
101502 ** Release a reference to a node. If the node is dirty and the reference
101503 ** count drops to zero, the node data is written to the database.
101504 */
101505 static int
101506 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
101507   int rc = SQLITE_OK;
101508   if( pNode ){
101509     assert( pNode->nRef>0 );
101510     pNode->nRef--;
101511     if( pNode->nRef==0 ){
101512       if( pNode->iNode==1 ){
101513         pRtree->iDepth = -1;
101514       }
101515       if( pNode->pParent ){
101516         rc = nodeRelease(pRtree, pNode->pParent);
101517       }
101518       if( rc==SQLITE_OK ){
101519         rc = nodeWrite(pRtree, pNode);
101520       }
101521       nodeHashDelete(pRtree, pNode);
101522       sqlite3_free(pNode);
101523     }
101524   }
101525   return rc;
101526 }
101527
101528 /*
101529 ** Return the 64-bit integer value associated with cell iCell of
101530 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
101531 ** an internal node, then the 64-bit integer is a child page number.
101532 */
101533 static i64 nodeGetRowid(
101534   Rtree *pRtree, 
101535   RtreeNode *pNode, 
101536   int iCell
101537 ){
101538   assert( iCell<NCELL(pNode) );
101539   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
101540 }
101541
101542 /*
101543 ** Return coordinate iCoord from cell iCell in node pNode.
101544 */
101545 static void nodeGetCoord(
101546   Rtree *pRtree, 
101547   RtreeNode *pNode, 
101548   int iCell,
101549   int iCoord,
101550   RtreeCoord *pCoord           /* Space to write result to */
101551 ){
101552   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
101553 }
101554
101555 /*
101556 ** Deserialize cell iCell of node pNode. Populate the structure pointed
101557 ** to by pCell with the results.
101558 */
101559 static void nodeGetCell(
101560   Rtree *pRtree, 
101561   RtreeNode *pNode, 
101562   int iCell,
101563   RtreeCell *pCell
101564 ){
101565   int ii;
101566   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
101567   for(ii=0; ii<pRtree->nDim*2; ii++){
101568     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
101569   }
101570 }
101571
101572
101573 /* Forward declaration for the function that does the work of
101574 ** the virtual table module xCreate() and xConnect() methods.
101575 */
101576 static int rtreeInit(
101577   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
101578 );
101579
101580 /* 
101581 ** Rtree virtual table module xCreate method.
101582 */
101583 static int rtreeCreate(
101584   sqlite3 *db,
101585   void *pAux,
101586   int argc, const char *const*argv,
101587   sqlite3_vtab **ppVtab,
101588   char **pzErr
101589 ){
101590   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
101591 }
101592
101593 /* 
101594 ** Rtree virtual table module xConnect method.
101595 */
101596 static int rtreeConnect(
101597   sqlite3 *db,
101598   void *pAux,
101599   int argc, const char *const*argv,
101600   sqlite3_vtab **ppVtab,
101601   char **pzErr
101602 ){
101603   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
101604 }
101605
101606 /*
101607 ** Increment the r-tree reference count.
101608 */
101609 static void rtreeReference(Rtree *pRtree){
101610   pRtree->nBusy++;
101611 }
101612
101613 /*
101614 ** Decrement the r-tree reference count. When the reference count reaches
101615 ** zero the structure is deleted.
101616 */
101617 static void rtreeRelease(Rtree *pRtree){
101618   pRtree->nBusy--;
101619   if( pRtree->nBusy==0 ){
101620     sqlite3_finalize(pRtree->pReadNode);
101621     sqlite3_finalize(pRtree->pWriteNode);
101622     sqlite3_finalize(pRtree->pDeleteNode);
101623     sqlite3_finalize(pRtree->pReadRowid);
101624     sqlite3_finalize(pRtree->pWriteRowid);
101625     sqlite3_finalize(pRtree->pDeleteRowid);
101626     sqlite3_finalize(pRtree->pReadParent);
101627     sqlite3_finalize(pRtree->pWriteParent);
101628     sqlite3_finalize(pRtree->pDeleteParent);
101629     sqlite3_free(pRtree);
101630   }
101631 }
101632
101633 /* 
101634 ** Rtree virtual table module xDisconnect method.
101635 */
101636 static int rtreeDisconnect(sqlite3_vtab *pVtab){
101637   rtreeRelease((Rtree *)pVtab);
101638   return SQLITE_OK;
101639 }
101640
101641 /* 
101642 ** Rtree virtual table module xDestroy method.
101643 */
101644 static int rtreeDestroy(sqlite3_vtab *pVtab){
101645   Rtree *pRtree = (Rtree *)pVtab;
101646   int rc;
101647   char *zCreate = sqlite3_mprintf(
101648     "DROP TABLE '%q'.'%q_node';"
101649     "DROP TABLE '%q'.'%q_rowid';"
101650     "DROP TABLE '%q'.'%q_parent';",
101651     pRtree->zDb, pRtree->zName, 
101652     pRtree->zDb, pRtree->zName,
101653     pRtree->zDb, pRtree->zName
101654   );
101655   if( !zCreate ){
101656     rc = SQLITE_NOMEM;
101657   }else{
101658     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
101659     sqlite3_free(zCreate);
101660   }
101661   if( rc==SQLITE_OK ){
101662     rtreeRelease(pRtree);
101663   }
101664
101665   return rc;
101666 }
101667
101668 /* 
101669 ** Rtree virtual table module xOpen method.
101670 */
101671 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
101672   int rc = SQLITE_NOMEM;
101673   RtreeCursor *pCsr;
101674
101675   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
101676   if( pCsr ){
101677     memset(pCsr, 0, sizeof(RtreeCursor));
101678     pCsr->base.pVtab = pVTab;
101679     rc = SQLITE_OK;
101680   }
101681   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
101682
101683   return rc;
101684 }
101685
101686 /* 
101687 ** Rtree virtual table module xClose method.
101688 */
101689 static int rtreeClose(sqlite3_vtab_cursor *cur){
101690   Rtree *pRtree = (Rtree *)(cur->pVtab);
101691   int rc;
101692   RtreeCursor *pCsr = (RtreeCursor *)cur;
101693   sqlite3_free(pCsr->aConstraint);
101694   rc = nodeRelease(pRtree, pCsr->pNode);
101695   sqlite3_free(pCsr);
101696   return rc;
101697 }
101698
101699 /*
101700 ** Rtree virtual table module xEof method.
101701 **
101702 ** Return non-zero if the cursor does not currently point to a valid 
101703 ** record (i.e if the scan has finished), or zero otherwise.
101704 */
101705 static int rtreeEof(sqlite3_vtab_cursor *cur){
101706   RtreeCursor *pCsr = (RtreeCursor *)cur;
101707   return (pCsr->pNode==0);
101708 }
101709
101710 /* 
101711 ** Cursor pCursor currently points to a cell in a non-leaf page.
101712 ** Return true if the sub-tree headed by the cell is filtered
101713 ** (excluded) by the constraints in the pCursor->aConstraint[] 
101714 ** array, or false otherwise.
101715 */
101716 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
101717   RtreeCell cell;
101718   int ii;
101719   int bRes = 0;
101720
101721   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
101722   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
101723     RtreeConstraint *p = &pCursor->aConstraint[ii];
101724     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
101725     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
101726
101727     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
101728         || p->op==RTREE_GT || p->op==RTREE_EQ
101729     );
101730
101731     switch( p->op ){
101732       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
101733       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
101734       case RTREE_EQ: 
101735         bRes = (p->rValue>cell_max || p->rValue<cell_min);
101736         break;
101737     }
101738   }
101739
101740   return bRes;
101741 }
101742
101743 /* 
101744 ** Return true if the cell that cursor pCursor currently points to
101745 ** would be filtered (excluded) by the constraints in the 
101746 ** pCursor->aConstraint[] array, or false otherwise.
101747 **
101748 ** This function assumes that the cell is part of a leaf node.
101749 */
101750 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
101751   RtreeCell cell;
101752   int ii;
101753
101754   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
101755   for(ii=0; ii<pCursor->nConstraint; ii++){
101756     RtreeConstraint *p = &pCursor->aConstraint[ii];
101757     double coord = DCOORD(cell.aCoord[p->iCoord]);
101758     int res;
101759     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
101760         || p->op==RTREE_GT || p->op==RTREE_EQ
101761     );
101762     switch( p->op ){
101763       case RTREE_LE: res = (coord<=p->rValue); break;
101764       case RTREE_LT: res = (coord<p->rValue);  break;
101765       case RTREE_GE: res = (coord>=p->rValue); break;
101766       case RTREE_GT: res = (coord>p->rValue);  break;
101767       case RTREE_EQ: res = (coord==p->rValue); break;
101768     }
101769
101770     if( !res ) return 1;
101771   }
101772
101773   return 0;
101774 }
101775
101776 /*
101777 ** Cursor pCursor currently points at a node that heads a sub-tree of
101778 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
101779 ** to point to the left-most cell of the sub-tree that matches the 
101780 ** configured constraints.
101781 */
101782 static int descendToCell(
101783   Rtree *pRtree, 
101784   RtreeCursor *pCursor, 
101785   int iHeight,
101786   int *pEof                 /* OUT: Set to true if cannot descend */
101787 ){
101788   int isEof;
101789   int rc;
101790   int ii;
101791   RtreeNode *pChild;
101792   sqlite3_int64 iRowid;
101793
101794   RtreeNode *pSavedNode = pCursor->pNode;
101795   int iSavedCell = pCursor->iCell;
101796
101797   assert( iHeight>=0 );
101798
101799   if( iHeight==0 ){
101800     isEof = testRtreeEntry(pRtree, pCursor);
101801   }else{
101802     isEof = testRtreeCell(pRtree, pCursor);
101803   }
101804   if( isEof || iHeight==0 ){
101805     *pEof = isEof;
101806     return SQLITE_OK;
101807   }
101808
101809   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
101810   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
101811   if( rc!=SQLITE_OK ){
101812     return rc;
101813   }
101814
101815   nodeRelease(pRtree, pCursor->pNode);
101816   pCursor->pNode = pChild;
101817   isEof = 1;
101818   for(ii=0; isEof && ii<NCELL(pChild); ii++){
101819     pCursor->iCell = ii;
101820     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
101821     if( rc!=SQLITE_OK ){
101822       return rc;
101823     }
101824   }
101825
101826   if( isEof ){
101827     assert( pCursor->pNode==pChild );
101828     nodeReference(pSavedNode);
101829     nodeRelease(pRtree, pChild);
101830     pCursor->pNode = pSavedNode;
101831     pCursor->iCell = iSavedCell;
101832   }
101833
101834   *pEof = isEof;
101835   return SQLITE_OK;
101836 }
101837
101838 /*
101839 ** One of the cells in node pNode is guaranteed to have a 64-bit 
101840 ** integer value equal to iRowid. Return the index of this cell.
101841 */
101842 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
101843   int ii;
101844   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
101845     assert( ii<(NCELL(pNode)-1) );
101846   }
101847   return ii;
101848 }
101849
101850 /*
101851 ** Return the index of the cell containing a pointer to node pNode
101852 ** in its parent. If pNode is the root node, return -1.
101853 */
101854 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
101855   RtreeNode *pParent = pNode->pParent;
101856   if( pParent ){
101857     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
101858   }
101859   return -1;
101860 }
101861
101862 /* 
101863 ** Rtree virtual table module xNext method.
101864 */
101865 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
101866   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
101867   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
101868   int rc = SQLITE_OK;
101869
101870   if( pCsr->iStrategy==1 ){
101871     /* This "scan" is a direct lookup by rowid. There is no next entry. */
101872     nodeRelease(pRtree, pCsr->pNode);
101873     pCsr->pNode = 0;
101874   }
101875
101876   else if( pCsr->pNode ){
101877     /* Move to the next entry that matches the configured constraints. */
101878     int iHeight = 0;
101879     while( pCsr->pNode ){
101880       RtreeNode *pNode = pCsr->pNode;
101881       int nCell = NCELL(pNode);
101882       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
101883         int isEof;
101884         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
101885         if( rc!=SQLITE_OK || !isEof ){
101886           return rc;
101887         }
101888       }
101889       pCsr->pNode = pNode->pParent;
101890       pCsr->iCell = nodeParentIndex(pRtree, pNode);
101891       nodeReference(pCsr->pNode);
101892       nodeRelease(pRtree, pNode);
101893       iHeight++;
101894     }
101895   }
101896
101897   return rc;
101898 }
101899
101900 /* 
101901 ** Rtree virtual table module xRowid method.
101902 */
101903 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
101904   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
101905   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
101906
101907   assert(pCsr->pNode);
101908   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
101909
101910   return SQLITE_OK;
101911 }
101912
101913 /* 
101914 ** Rtree virtual table module xColumn method.
101915 */
101916 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
101917   Rtree *pRtree = (Rtree *)cur->pVtab;
101918   RtreeCursor *pCsr = (RtreeCursor *)cur;
101919
101920   if( i==0 ){
101921     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
101922     sqlite3_result_int64(ctx, iRowid);
101923   }else{
101924     RtreeCoord c;
101925     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
101926     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
101927       sqlite3_result_double(ctx, c.f);
101928     }else{
101929       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
101930       sqlite3_result_int(ctx, c.i);
101931     }
101932   }
101933
101934   return SQLITE_OK;
101935 }
101936
101937 /* 
101938 ** Use nodeAcquire() to obtain the leaf node containing the record with 
101939 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
101940 ** return SQLITE_OK. If there is no such record in the table, set
101941 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
101942 ** to zero and return an SQLite error code.
101943 */
101944 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
101945   int rc;
101946   *ppLeaf = 0;
101947   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
101948   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
101949     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
101950     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
101951     sqlite3_reset(pRtree->pReadRowid);
101952   }else{
101953     rc = sqlite3_reset(pRtree->pReadRowid);
101954   }
101955   return rc;
101956 }
101957
101958
101959 /* 
101960 ** Rtree virtual table module xFilter method.
101961 */
101962 static int rtreeFilter(
101963   sqlite3_vtab_cursor *pVtabCursor, 
101964   int idxNum, const char *idxStr,
101965   int argc, sqlite3_value **argv
101966 ){
101967   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
101968   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
101969
101970   RtreeNode *pRoot = 0;
101971   int ii;
101972   int rc = SQLITE_OK;
101973
101974   rtreeReference(pRtree);
101975
101976   sqlite3_free(pCsr->aConstraint);
101977   pCsr->aConstraint = 0;
101978   pCsr->iStrategy = idxNum;
101979
101980   if( idxNum==1 ){
101981     /* Special case - lookup by rowid. */
101982     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
101983     i64 iRowid = sqlite3_value_int64(argv[0]);
101984     rc = findLeafNode(pRtree, iRowid, &pLeaf);
101985     pCsr->pNode = pLeaf; 
101986     if( pLeaf && rc==SQLITE_OK ){
101987       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
101988     }
101989   }else{
101990     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
101991     ** with the configured constraints. 
101992     */
101993     if( argc>0 ){
101994       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
101995       pCsr->nConstraint = argc;
101996       if( !pCsr->aConstraint ){
101997         rc = SQLITE_NOMEM;
101998       }else{
101999         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
102000         for(ii=0; ii<argc; ii++){
102001           RtreeConstraint *p = &pCsr->aConstraint[ii];
102002           p->op = idxStr[ii*2];
102003           p->iCoord = idxStr[ii*2+1]-'a';
102004           p->rValue = sqlite3_value_double(argv[ii]);
102005         }
102006       }
102007     }
102008   
102009     if( rc==SQLITE_OK ){
102010       pCsr->pNode = 0;
102011       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
102012     }
102013     if( rc==SQLITE_OK ){
102014       int isEof = 1;
102015       int nCell = NCELL(pRoot);
102016       pCsr->pNode = pRoot;
102017       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
102018         assert( pCsr->pNode==pRoot );
102019         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
102020         if( !isEof ){
102021           break;
102022         }
102023       }
102024       if( rc==SQLITE_OK && isEof ){
102025         assert( pCsr->pNode==pRoot );
102026         nodeRelease(pRtree, pRoot);
102027         pCsr->pNode = 0;
102028       }
102029       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
102030     }
102031   }
102032
102033   rtreeRelease(pRtree);
102034   return rc;
102035 }
102036
102037 /*
102038 ** Rtree virtual table module xBestIndex method. There are three
102039 ** table scan strategies to choose from (in order from most to 
102040 ** least desirable):
102041 **
102042 **   idxNum     idxStr        Strategy
102043 **   ------------------------------------------------
102044 **     1        Unused        Direct lookup by rowid.
102045 **     2        See below     R-tree query.
102046 **     3        Unused        Full table scan.
102047 **   ------------------------------------------------
102048 **
102049 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
102050 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
102051 ** constraint used. The first two bytes of idxStr correspond to 
102052 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
102053 ** (argvIndex==1) etc.
102054 **
102055 ** The first of each pair of bytes in idxStr identifies the constraint
102056 ** operator as follows:
102057 **
102058 **   Operator    Byte Value
102059 **   ----------------------
102060 **      =        0x41 ('A')
102061 **     <=        0x42 ('B')
102062 **      <        0x43 ('C')
102063 **     >=        0x44 ('D')
102064 **      >        0x45 ('E')
102065 **   ----------------------
102066 **
102067 ** The second of each pair of bytes identifies the coordinate column
102068 ** to which the constraint applies. The leftmost coordinate column
102069 ** is 'a', the second from the left 'b' etc.
102070 */
102071 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
102072   int rc = SQLITE_OK;
102073   int ii, cCol;
102074
102075   int iIdx = 0;
102076   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
102077   memset(zIdxStr, 0, sizeof(zIdxStr));
102078
102079   assert( pIdxInfo->idxStr==0 );
102080   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
102081     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
102082
102083     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
102084       /* We have an equality constraint on the rowid. Use strategy 1. */
102085       int jj;
102086       for(jj=0; jj<ii; jj++){
102087         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
102088         pIdxInfo->aConstraintUsage[jj].omit = 0;
102089       }
102090       pIdxInfo->idxNum = 1;
102091       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
102092       pIdxInfo->aConstraintUsage[jj].omit = 1;
102093
102094       /* This strategy involves a two rowid lookups on an B-Tree structures
102095       ** and then a linear search of an R-Tree node. This should be 
102096       ** considered almost as quick as a direct rowid lookup (for which 
102097       ** sqlite uses an internal cost of 0.0).
102098       */ 
102099       pIdxInfo->estimatedCost = 10.0;
102100       return SQLITE_OK;
102101     }
102102
102103     if( p->usable && p->iColumn>0 ){
102104       u8 op = 0;
102105       switch( p->op ){
102106         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
102107         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
102108         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
102109         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
102110         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
102111       }
102112       if( op ){
102113         /* Make sure this particular constraint has not been used before.
102114         ** If it has been used before, ignore it.
102115         **
102116         ** A <= or < can be used if there is a prior >= or >.
102117         ** A >= or > can be used if there is a prior < or <=.
102118         ** A <= or < is disqualified if there is a prior <=, <, or ==.
102119         ** A >= or > is disqualified if there is a prior >=, >, or ==.
102120         ** A == is disqualifed if there is any prior constraint.
102121         */
102122         int j, opmsk;
102123         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
102124         assert( compatible[RTREE_EQ & 7]==0 );
102125         assert( compatible[RTREE_LT & 7]==1 );
102126         assert( compatible[RTREE_LE & 7]==1 );
102127         assert( compatible[RTREE_GT & 7]==2 );
102128         assert( compatible[RTREE_GE & 7]==2 );
102129         cCol = p->iColumn - 1 + 'a';
102130         opmsk = compatible[op & 7];
102131         for(j=0; j<iIdx; j+=2){
102132           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
102133             op = 0;
102134             break;
102135           }
102136         }
102137       }
102138       if( op ){
102139         assert( iIdx<sizeof(zIdxStr)-1 );
102140         zIdxStr[iIdx++] = op;
102141         zIdxStr[iIdx++] = cCol;
102142         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
102143         pIdxInfo->aConstraintUsage[ii].omit = 1;
102144       }
102145     }
102146   }
102147
102148   pIdxInfo->idxNum = 2;
102149   pIdxInfo->needToFreeIdxStr = 1;
102150   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
102151     return SQLITE_NOMEM;
102152   }
102153   assert( iIdx>=0 );
102154   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
102155   return rc;
102156 }
102157
102158 /*
102159 ** Return the N-dimensional volumn of the cell stored in *p.
102160 */
102161 static float cellArea(Rtree *pRtree, RtreeCell *p){
102162   float area = 1.0;
102163   int ii;
102164   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
102165     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
102166   }
102167   return area;
102168 }
102169
102170 /*
102171 ** Return the margin length of cell p. The margin length is the sum
102172 ** of the objects size in each dimension.
102173 */
102174 static float cellMargin(Rtree *pRtree, RtreeCell *p){
102175   float margin = 0.0;
102176   int ii;
102177   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
102178     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
102179   }
102180   return margin;
102181 }
102182
102183 /*
102184 ** Store the union of cells p1 and p2 in p1.
102185 */
102186 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
102187   int ii;
102188   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
102189     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
102190       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
102191       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
102192     }
102193   }else{
102194     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
102195       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
102196       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
102197     }
102198   }
102199 }
102200
102201 /*
102202 ** Return true if the area covered by p2 is a subset of the area covered
102203 ** by p1. False otherwise.
102204 */
102205 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
102206   int ii;
102207   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
102208   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
102209     RtreeCoord *a1 = &p1->aCoord[ii];
102210     RtreeCoord *a2 = &p2->aCoord[ii];
102211     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
102212      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
102213     ){
102214       return 0;
102215     }
102216   }
102217   return 1;
102218 }
102219
102220 /*
102221 ** Return the amount cell p would grow by if it were unioned with pCell.
102222 */
102223 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
102224   float area;
102225   RtreeCell cell;
102226   memcpy(&cell, p, sizeof(RtreeCell));
102227   area = cellArea(pRtree, &cell);
102228   cellUnion(pRtree, &cell, pCell);
102229   return (cellArea(pRtree, &cell)-area);
102230 }
102231
102232 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
102233 static float cellOverlap(
102234   Rtree *pRtree, 
102235   RtreeCell *p, 
102236   RtreeCell *aCell, 
102237   int nCell, 
102238   int iExclude
102239 ){
102240   int ii;
102241   float overlap = 0.0;
102242   for(ii=0; ii<nCell; ii++){
102243     if( ii!=iExclude ){
102244       int jj;
102245       float o = 1.0;
102246       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
102247         double x1;
102248         double x2;
102249
102250         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
102251         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
102252
102253         if( x2<x1 ){
102254           o = 0.0;
102255           break;
102256         }else{
102257           o = o * (x2-x1);
102258         }
102259       }
102260       overlap += o;
102261     }
102262   }
102263   return overlap;
102264 }
102265 #endif
102266
102267 #if VARIANT_RSTARTREE_CHOOSESUBTREE
102268 static float cellOverlapEnlargement(
102269   Rtree *pRtree, 
102270   RtreeCell *p, 
102271   RtreeCell *pInsert, 
102272   RtreeCell *aCell, 
102273   int nCell, 
102274   int iExclude
102275 ){
102276   float before;
102277   float after;
102278   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
102279   cellUnion(pRtree, p, pInsert);
102280   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
102281   return after-before;
102282 }
102283 #endif
102284
102285
102286 /*
102287 ** This function implements the ChooseLeaf algorithm from Gutman[84].
102288 ** ChooseSubTree in r*tree terminology.
102289 */
102290 static int ChooseLeaf(
102291   Rtree *pRtree,               /* Rtree table */
102292   RtreeCell *pCell,            /* Cell to insert into rtree */
102293   int iHeight,                 /* Height of sub-tree rooted at pCell */
102294   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
102295 ){
102296   int rc;
102297   int ii;
102298   RtreeNode *pNode;
102299   rc = nodeAcquire(pRtree, 1, 0, &pNode);
102300
102301   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
102302     int iCell;
102303     sqlite3_int64 iBest;
102304
102305     float fMinGrowth;
102306     float fMinArea;
102307     float fMinOverlap;
102308
102309     int nCell = NCELL(pNode);
102310     RtreeCell cell;
102311     RtreeNode *pChild;
102312
102313     RtreeCell *aCell = 0;
102314
102315 #if VARIANT_RSTARTREE_CHOOSESUBTREE
102316     if( ii==(pRtree->iDepth-1) ){
102317       int jj;
102318       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
102319       if( !aCell ){
102320         rc = SQLITE_NOMEM;
102321         nodeRelease(pRtree, pNode);
102322         pNode = 0;
102323         continue;
102324       }
102325       for(jj=0; jj<nCell; jj++){
102326         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
102327       }
102328     }
102329 #endif
102330
102331     /* Select the child node which will be enlarged the least if pCell
102332     ** is inserted into it. Resolve ties by choosing the entry with
102333     ** the smallest area.
102334     */
102335     for(iCell=0; iCell<nCell; iCell++){
102336       float growth;
102337       float area;
102338       float overlap = 0.0;
102339       nodeGetCell(pRtree, pNode, iCell, &cell);
102340       growth = cellGrowth(pRtree, &cell, pCell);
102341       area = cellArea(pRtree, &cell);
102342 #if VARIANT_RSTARTREE_CHOOSESUBTREE
102343       if( ii==(pRtree->iDepth-1) ){
102344         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
102345       }
102346 #endif
102347       if( (iCell==0) 
102348        || (overlap<fMinOverlap) 
102349        || (overlap==fMinOverlap && growth<fMinGrowth)
102350        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
102351       ){
102352         fMinOverlap = overlap;
102353         fMinGrowth = growth;
102354         fMinArea = area;
102355         iBest = cell.iRowid;
102356       }
102357     }
102358
102359     sqlite3_free(aCell);
102360     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
102361     nodeRelease(pRtree, pNode);
102362     pNode = pChild;
102363   }
102364
102365   *ppLeaf = pNode;
102366   return rc;
102367 }
102368
102369 /*
102370 ** A cell with the same content as pCell has just been inserted into
102371 ** the node pNode. This function updates the bounding box cells in
102372 ** all ancestor elements.
102373 */
102374 static void AdjustTree(
102375   Rtree *pRtree,                    /* Rtree table */
102376   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
102377   RtreeCell *pCell                  /* This cell was just inserted */
102378 ){
102379   RtreeNode *p = pNode;
102380   while( p->pParent ){
102381     RtreeCell cell;
102382     RtreeNode *pParent = p->pParent;
102383     int iCell = nodeParentIndex(pRtree, p);
102384
102385     nodeGetCell(pRtree, pParent, iCell, &cell);
102386     if( !cellContains(pRtree, &cell, pCell) ){
102387       cellUnion(pRtree, &cell, pCell);
102388       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
102389     }
102390  
102391     p = pParent;
102392   }
102393 }
102394
102395 /*
102396 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
102397 */
102398 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
102399   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
102400   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
102401   sqlite3_step(pRtree->pWriteRowid);
102402   return sqlite3_reset(pRtree->pWriteRowid);
102403 }
102404
102405 /*
102406 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
102407 */
102408 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
102409   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
102410   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
102411   sqlite3_step(pRtree->pWriteParent);
102412   return sqlite3_reset(pRtree->pWriteParent);
102413 }
102414
102415 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
102416
102417 #if VARIANT_GUTTMAN_LINEAR_SPLIT
102418 /*
102419 ** Implementation of the linear variant of the PickNext() function from
102420 ** Guttman[84].
102421 */
102422 static RtreeCell *LinearPickNext(
102423   Rtree *pRtree,
102424   RtreeCell *aCell, 
102425   int nCell, 
102426   RtreeCell *pLeftBox, 
102427   RtreeCell *pRightBox,
102428   int *aiUsed
102429 ){
102430   int ii;
102431   for(ii=0; aiUsed[ii]; ii++);
102432   aiUsed[ii] = 1;
102433   return &aCell[ii];
102434 }
102435
102436 /*
102437 ** Implementation of the linear variant of the PickSeeds() function from
102438 ** Guttman[84].
102439 */
102440 static void LinearPickSeeds(
102441   Rtree *pRtree,
102442   RtreeCell *aCell, 
102443   int nCell, 
102444   int *piLeftSeed, 
102445   int *piRightSeed
102446 ){
102447   int i;
102448   int iLeftSeed = 0;
102449   int iRightSeed = 1;
102450   float maxNormalInnerWidth = 0.0;
102451
102452   /* Pick two "seed" cells from the array of cells. The algorithm used
102453   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
102454   ** indices of the two seed cells in the array are stored in local
102455   ** variables iLeftSeek and iRightSeed.
102456   */
102457   for(i=0; i<pRtree->nDim; i++){
102458     float x1 = aCell[0].aCoord[i*2];
102459     float x2 = aCell[0].aCoord[i*2+1];
102460     float x3 = x1;
102461     float x4 = x2;
102462     int jj;
102463
102464     int iCellLeft = 0;
102465     int iCellRight = 0;
102466
102467     for(jj=1; jj<nCell; jj++){
102468       float left = aCell[jj].aCoord[i*2];
102469       float right = aCell[jj].aCoord[i*2+1];
102470
102471       if( left<x1 ) x1 = left;
102472       if( right>x4 ) x4 = right;
102473       if( left>x3 ){
102474         x3 = left;
102475         iCellRight = jj;
102476       }
102477       if( right<x2 ){
102478         x2 = right;
102479         iCellLeft = jj;
102480       }
102481     }
102482
102483     if( x4!=x1 ){
102484       float normalwidth = (x3 - x2) / (x4 - x1);
102485       if( normalwidth>maxNormalInnerWidth ){
102486         iLeftSeed = iCellLeft;
102487         iRightSeed = iCellRight;
102488       }
102489     }
102490   }
102491
102492   *piLeftSeed = iLeftSeed;
102493   *piRightSeed = iRightSeed;
102494 }
102495 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
102496
102497 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
102498 /*
102499 ** Implementation of the quadratic variant of the PickNext() function from
102500 ** Guttman[84].
102501 */
102502 static RtreeCell *QuadraticPickNext(
102503   Rtree *pRtree,
102504   RtreeCell *aCell, 
102505   int nCell, 
102506   RtreeCell *pLeftBox, 
102507   RtreeCell *pRightBox,
102508   int *aiUsed
102509 ){
102510   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
102511
102512   int iSelect = -1;
102513   float fDiff;
102514   int ii;
102515   for(ii=0; ii<nCell; ii++){
102516     if( aiUsed[ii]==0 ){
102517       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
102518       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
102519       float diff = FABS(right-left);
102520       if( iSelect<0 || diff>fDiff ){
102521         fDiff = diff;
102522         iSelect = ii;
102523       }
102524     }
102525   }
102526   aiUsed[iSelect] = 1;
102527   return &aCell[iSelect];
102528 }
102529
102530 /*
102531 ** Implementation of the quadratic variant of the PickSeeds() function from
102532 ** Guttman[84].
102533 */
102534 static void QuadraticPickSeeds(
102535   Rtree *pRtree,
102536   RtreeCell *aCell, 
102537   int nCell, 
102538   int *piLeftSeed, 
102539   int *piRightSeed
102540 ){
102541   int ii;
102542   int jj;
102543
102544   int iLeftSeed = 0;
102545   int iRightSeed = 1;
102546   float fWaste = 0.0;
102547
102548   for(ii=0; ii<nCell; ii++){
102549     for(jj=ii+1; jj<nCell; jj++){
102550       float right = cellArea(pRtree, &aCell[jj]);
102551       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
102552       float waste = growth - right;
102553
102554       if( waste>fWaste ){
102555         iLeftSeed = ii;
102556         iRightSeed = jj;
102557         fWaste = waste;
102558       }
102559     }
102560   }
102561
102562   *piLeftSeed = iLeftSeed;
102563   *piRightSeed = iRightSeed;
102564 }
102565 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
102566
102567 /*
102568 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
102569 ** nIdx. The aIdx array contains the set of integers from 0 to 
102570 ** (nIdx-1) in no particular order. This function sorts the values
102571 ** in aIdx according to the indexed values in aDistance. For
102572 ** example, assuming the inputs:
102573 **
102574 **   aIdx      = { 0,   1,   2,   3 }
102575 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
102576 **
102577 ** this function sets the aIdx array to contain:
102578 **
102579 **   aIdx      = { 0,   1,   2,   3 }
102580 **
102581 ** The aSpare array is used as temporary working space by the
102582 ** sorting algorithm.
102583 */
102584 static void SortByDistance(
102585   int *aIdx, 
102586   int nIdx, 
102587   float *aDistance, 
102588   int *aSpare
102589 ){
102590   if( nIdx>1 ){
102591     int iLeft = 0;
102592     int iRight = 0;
102593
102594     int nLeft = nIdx/2;
102595     int nRight = nIdx-nLeft;
102596     int *aLeft = aIdx;
102597     int *aRight = &aIdx[nLeft];
102598
102599     SortByDistance(aLeft, nLeft, aDistance, aSpare);
102600     SortByDistance(aRight, nRight, aDistance, aSpare);
102601
102602     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
102603     aLeft = aSpare;
102604
102605     while( iLeft<nLeft || iRight<nRight ){
102606       if( iLeft==nLeft ){
102607         aIdx[iLeft+iRight] = aRight[iRight];
102608         iRight++;
102609       }else if( iRight==nRight ){
102610         aIdx[iLeft+iRight] = aLeft[iLeft];
102611         iLeft++;
102612       }else{
102613         float fLeft = aDistance[aLeft[iLeft]];
102614         float fRight = aDistance[aRight[iRight]];
102615         if( fLeft<fRight ){
102616           aIdx[iLeft+iRight] = aLeft[iLeft];
102617           iLeft++;
102618         }else{
102619           aIdx[iLeft+iRight] = aRight[iRight];
102620           iRight++;
102621         }
102622       }
102623     }
102624
102625 #if 0
102626     /* Check that the sort worked */
102627     {
102628       int jj;
102629       for(jj=1; jj<nIdx; jj++){
102630         float left = aDistance[aIdx[jj-1]];
102631         float right = aDistance[aIdx[jj]];
102632         assert( left<=right );
102633       }
102634     }
102635 #endif
102636   }
102637 }
102638
102639 /*
102640 ** Arguments aIdx, aCell and aSpare all point to arrays of size
102641 ** nIdx. The aIdx array contains the set of integers from 0 to 
102642 ** (nIdx-1) in no particular order. This function sorts the values
102643 ** in aIdx according to dimension iDim of the cells in aCell. The
102644 ** minimum value of dimension iDim is considered first, the
102645 ** maximum used to break ties.
102646 **
102647 ** The aSpare array is used as temporary working space by the
102648 ** sorting algorithm.
102649 */
102650 static void SortByDimension(
102651   Rtree *pRtree,
102652   int *aIdx, 
102653   int nIdx, 
102654   int iDim, 
102655   RtreeCell *aCell, 
102656   int *aSpare
102657 ){
102658   if( nIdx>1 ){
102659
102660     int iLeft = 0;
102661     int iRight = 0;
102662
102663     int nLeft = nIdx/2;
102664     int nRight = nIdx-nLeft;
102665     int *aLeft = aIdx;
102666     int *aRight = &aIdx[nLeft];
102667
102668     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
102669     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
102670
102671     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
102672     aLeft = aSpare;
102673     while( iLeft<nLeft || iRight<nRight ){
102674       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
102675       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
102676       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
102677       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
102678       if( (iLeft!=nLeft) && ((iRight==nRight)
102679        || (xleft1<xright1)
102680        || (xleft1==xright1 && xleft2<xright2)
102681       )){
102682         aIdx[iLeft+iRight] = aLeft[iLeft];
102683         iLeft++;
102684       }else{
102685         aIdx[iLeft+iRight] = aRight[iRight];
102686         iRight++;
102687       }
102688     }
102689
102690 #if 0
102691     /* Check that the sort worked */
102692     {
102693       int jj;
102694       for(jj=1; jj<nIdx; jj++){
102695         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
102696         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
102697         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
102698         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
102699         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
102700       }
102701     }
102702 #endif
102703   }
102704 }
102705
102706 #if VARIANT_RSTARTREE_SPLIT
102707 /*
102708 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
102709 */
102710 static int splitNodeStartree(
102711   Rtree *pRtree,
102712   RtreeCell *aCell,
102713   int nCell,
102714   RtreeNode *pLeft,
102715   RtreeNode *pRight,
102716   RtreeCell *pBboxLeft,
102717   RtreeCell *pBboxRight
102718 ){
102719   int **aaSorted;
102720   int *aSpare;
102721   int ii;
102722
102723   int iBestDim;
102724   int iBestSplit;
102725   float fBestMargin;
102726
102727   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
102728
102729   aaSorted = (int **)sqlite3_malloc(nByte);
102730   if( !aaSorted ){
102731     return SQLITE_NOMEM;
102732   }
102733
102734   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
102735   memset(aaSorted, 0, nByte);
102736   for(ii=0; ii<pRtree->nDim; ii++){
102737     int jj;
102738     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
102739     for(jj=0; jj<nCell; jj++){
102740       aaSorted[ii][jj] = jj;
102741     }
102742     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
102743   }
102744
102745   for(ii=0; ii<pRtree->nDim; ii++){
102746     float margin = 0.0;
102747     float fBestOverlap;
102748     float fBestArea;
102749     int iBestLeft;
102750     int nLeft;
102751
102752     for(
102753       nLeft=RTREE_MINCELLS(pRtree); 
102754       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
102755       nLeft++
102756     ){
102757       RtreeCell left;
102758       RtreeCell right;
102759       int kk;
102760       float overlap;
102761       float area;
102762
102763       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
102764       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
102765       for(kk=1; kk<(nCell-1); kk++){
102766         if( kk<nLeft ){
102767           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
102768         }else{
102769           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
102770         }
102771       }
102772       margin += cellMargin(pRtree, &left);
102773       margin += cellMargin(pRtree, &right);
102774       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
102775       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
102776       if( (nLeft==RTREE_MINCELLS(pRtree))
102777        || (overlap<fBestOverlap)
102778        || (overlap==fBestOverlap && area<fBestArea)
102779       ){
102780         iBestLeft = nLeft;
102781         fBestOverlap = overlap;
102782         fBestArea = area;
102783       }
102784     }
102785
102786     if( ii==0 || margin<fBestMargin ){
102787       iBestDim = ii;
102788       fBestMargin = margin;
102789       iBestSplit = iBestLeft;
102790     }
102791   }
102792
102793   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
102794   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
102795   for(ii=0; ii<nCell; ii++){
102796     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
102797     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
102798     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
102799     nodeInsertCell(pRtree, pTarget, pCell);
102800     cellUnion(pRtree, pBbox, pCell);
102801   }
102802
102803   sqlite3_free(aaSorted);
102804   return SQLITE_OK;
102805 }
102806 #endif
102807
102808 #if VARIANT_GUTTMAN_SPLIT
102809 /*
102810 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
102811 */
102812 static int splitNodeGuttman(
102813   Rtree *pRtree,
102814   RtreeCell *aCell,
102815   int nCell,
102816   RtreeNode *pLeft,
102817   RtreeNode *pRight,
102818   RtreeCell *pBboxLeft,
102819   RtreeCell *pBboxRight
102820 ){
102821   int iLeftSeed = 0;
102822   int iRightSeed = 1;
102823   int *aiUsed;
102824   int i;
102825
102826   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
102827   memset(aiUsed, 0, sizeof(int)*nCell);
102828
102829   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
102830
102831   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
102832   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
102833   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
102834   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
102835   aiUsed[iLeftSeed] = 1;
102836   aiUsed[iRightSeed] = 1;
102837
102838   for(i=nCell-2; i>0; i--){
102839     RtreeCell *pNext;
102840     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
102841     float diff =  
102842       cellGrowth(pRtree, pBboxLeft, pNext) - 
102843       cellGrowth(pRtree, pBboxRight, pNext)
102844     ;
102845     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
102846      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
102847     ){
102848       nodeInsertCell(pRtree, pRight, pNext);
102849       cellUnion(pRtree, pBboxRight, pNext);
102850     }else{
102851       nodeInsertCell(pRtree, pLeft, pNext);
102852       cellUnion(pRtree, pBboxLeft, pNext);
102853     }
102854   }
102855
102856   sqlite3_free(aiUsed);
102857   return SQLITE_OK;
102858 }
102859 #endif
102860
102861 static int updateMapping(
102862   Rtree *pRtree, 
102863   i64 iRowid, 
102864   RtreeNode *pNode, 
102865   int iHeight
102866 ){
102867   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
102868   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
102869   if( iHeight>0 ){
102870     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
102871     if( pChild ){
102872       nodeRelease(pRtree, pChild->pParent);
102873       nodeReference(pNode);
102874       pChild->pParent = pNode;
102875     }
102876   }
102877   return xSetMapping(pRtree, iRowid, pNode->iNode);
102878 }
102879
102880 static int SplitNode(
102881   Rtree *pRtree,
102882   RtreeNode *pNode,
102883   RtreeCell *pCell,
102884   int iHeight
102885 ){
102886   int i;
102887   int newCellIsRight = 0;
102888
102889   int rc = SQLITE_OK;
102890   int nCell = NCELL(pNode);
102891   RtreeCell *aCell;
102892   int *aiUsed;
102893
102894   RtreeNode *pLeft = 0;
102895   RtreeNode *pRight = 0;
102896
102897   RtreeCell leftbbox;
102898   RtreeCell rightbbox;
102899
102900   /* Allocate an array and populate it with a copy of pCell and 
102901   ** all cells from node pLeft. Then zero the original node.
102902   */
102903   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
102904   if( !aCell ){
102905     rc = SQLITE_NOMEM;
102906     goto splitnode_out;
102907   }
102908   aiUsed = (int *)&aCell[nCell+1];
102909   memset(aiUsed, 0, sizeof(int)*(nCell+1));
102910   for(i=0; i<nCell; i++){
102911     nodeGetCell(pRtree, pNode, i, &aCell[i]);
102912   }
102913   nodeZero(pRtree, pNode);
102914   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
102915   nCell++;
102916
102917   if( pNode->iNode==1 ){
102918     pRight = nodeNew(pRtree, pNode, 1);
102919     pLeft = nodeNew(pRtree, pNode, 1);
102920     pRtree->iDepth++;
102921     pNode->isDirty = 1;
102922     writeInt16(pNode->zData, pRtree->iDepth);
102923   }else{
102924     pLeft = pNode;
102925     pRight = nodeNew(pRtree, pLeft->pParent, 1);
102926     nodeReference(pLeft);
102927   }
102928
102929   if( !pLeft || !pRight ){
102930     rc = SQLITE_NOMEM;
102931     goto splitnode_out;
102932   }
102933
102934   memset(pLeft->zData, 0, pRtree->iNodeSize);
102935   memset(pRight->zData, 0, pRtree->iNodeSize);
102936
102937   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
102938   if( rc!=SQLITE_OK ){
102939     goto splitnode_out;
102940   }
102941
102942   /* Ensure both child nodes have node numbers assigned to them. */
102943   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
102944    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
102945   ){
102946     goto splitnode_out;
102947   }
102948
102949   rightbbox.iRowid = pRight->iNode;
102950   leftbbox.iRowid = pLeft->iNode;
102951
102952   if( pNode->iNode==1 ){
102953     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
102954     if( rc!=SQLITE_OK ){
102955       goto splitnode_out;
102956     }
102957   }else{
102958     RtreeNode *pParent = pLeft->pParent;
102959     int iCell = nodeParentIndex(pRtree, pLeft);
102960     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
102961     AdjustTree(pRtree, pParent, &leftbbox);
102962   }
102963   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
102964     goto splitnode_out;
102965   }
102966
102967   for(i=0; i<NCELL(pRight); i++){
102968     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
102969     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
102970     if( iRowid==pCell->iRowid ){
102971       newCellIsRight = 1;
102972     }
102973     if( rc!=SQLITE_OK ){
102974       goto splitnode_out;
102975     }
102976   }
102977   if( pNode->iNode==1 ){
102978     for(i=0; i<NCELL(pLeft); i++){
102979       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
102980       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
102981       if( rc!=SQLITE_OK ){
102982         goto splitnode_out;
102983       }
102984     }
102985   }else if( newCellIsRight==0 ){
102986     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
102987   }
102988
102989   if( rc==SQLITE_OK ){
102990     rc = nodeRelease(pRtree, pRight);
102991     pRight = 0;
102992   }
102993   if( rc==SQLITE_OK ){
102994     rc = nodeRelease(pRtree, pLeft);
102995     pLeft = 0;
102996   }
102997
102998 splitnode_out:
102999   nodeRelease(pRtree, pRight);
103000   nodeRelease(pRtree, pLeft);
103001   sqlite3_free(aCell);
103002   return rc;
103003 }
103004
103005 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
103006   int rc = SQLITE_OK;
103007   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
103008     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
103009     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
103010       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
103011       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
103012     }else{
103013       rc = SQLITE_ERROR;
103014     }
103015     sqlite3_reset(pRtree->pReadParent);
103016     if( rc==SQLITE_OK ){
103017       rc = fixLeafParent(pRtree, pLeaf->pParent);
103018     }
103019   }
103020   return rc;
103021 }
103022
103023 static int deleteCell(Rtree *, RtreeNode *, int, int);
103024
103025 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
103026   int rc;
103027   RtreeNode *pParent;
103028   int iCell;
103029
103030   assert( pNode->nRef==1 );
103031
103032   /* Remove the entry in the parent cell. */
103033   iCell = nodeParentIndex(pRtree, pNode);
103034   pParent = pNode->pParent;
103035   pNode->pParent = 0;
103036   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
103037    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
103038   ){
103039     return rc;
103040   }
103041
103042   /* Remove the xxx_node entry. */
103043   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
103044   sqlite3_step(pRtree->pDeleteNode);
103045   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
103046     return rc;
103047   }
103048
103049   /* Remove the xxx_parent entry. */
103050   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
103051   sqlite3_step(pRtree->pDeleteParent);
103052   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
103053     return rc;
103054   }
103055   
103056   /* Remove the node from the in-memory hash table and link it into
103057   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
103058   */
103059   nodeHashDelete(pRtree, pNode);
103060   pNode->iNode = iHeight;
103061   pNode->pNext = pRtree->pDeleted;
103062   pNode->nRef++;
103063   pRtree->pDeleted = pNode;
103064
103065   return SQLITE_OK;
103066 }
103067
103068 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
103069   RtreeNode *pParent = pNode->pParent;
103070   if( pParent ){
103071     int ii; 
103072     int nCell = NCELL(pNode);
103073     RtreeCell box;                            /* Bounding box for pNode */
103074     nodeGetCell(pRtree, pNode, 0, &box);
103075     for(ii=1; ii<nCell; ii++){
103076       RtreeCell cell;
103077       nodeGetCell(pRtree, pNode, ii, &cell);
103078       cellUnion(pRtree, &box, &cell);
103079     }
103080     box.iRowid = pNode->iNode;
103081     ii = nodeParentIndex(pRtree, pNode);
103082     nodeOverwriteCell(pRtree, pParent, &box, ii);
103083     fixBoundingBox(pRtree, pParent);
103084   }
103085 }
103086
103087 /*
103088 ** Delete the cell at index iCell of node pNode. After removing the
103089 ** cell, adjust the r-tree data structure if required.
103090 */
103091 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
103092   int rc;
103093
103094   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
103095     return rc;
103096   }
103097
103098   /* Remove the cell from the node. This call just moves bytes around
103099   ** the in-memory node image, so it cannot fail.
103100   */
103101   nodeDeleteCell(pRtree, pNode, iCell);
103102
103103   /* If the node is not the tree root and now has less than the minimum
103104   ** number of cells, remove it from the tree. Otherwise, update the
103105   ** cell in the parent node so that it tightly contains the updated
103106   ** node.
103107   */
103108   if( pNode->iNode!=1 ){
103109     RtreeNode *pParent = pNode->pParent;
103110     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
103111      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
103112     ){
103113       rc = removeNode(pRtree, pNode, iHeight);
103114     }else{
103115       fixBoundingBox(pRtree, pNode);
103116     }
103117   }
103118
103119   return rc;
103120 }
103121
103122 static int Reinsert(
103123   Rtree *pRtree, 
103124   RtreeNode *pNode, 
103125   RtreeCell *pCell, 
103126   int iHeight
103127 ){
103128   int *aOrder;
103129   int *aSpare;
103130   RtreeCell *aCell;
103131   float *aDistance;
103132   int nCell;
103133   float aCenterCoord[RTREE_MAX_DIMENSIONS];
103134   int iDim;
103135   int ii;
103136   int rc = SQLITE_OK;
103137
103138   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
103139
103140   nCell = NCELL(pNode)+1;
103141
103142   /* Allocate the buffers used by this operation. The allocation is
103143   ** relinquished before this function returns.
103144   */
103145   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
103146     sizeof(RtreeCell) +         /* aCell array */
103147     sizeof(int)       +         /* aOrder array */
103148     sizeof(int)       +         /* aSpare array */
103149     sizeof(float)               /* aDistance array */
103150   ));
103151   if( !aCell ){
103152     return SQLITE_NOMEM;
103153   }
103154   aOrder    = (int *)&aCell[nCell];
103155   aSpare    = (int *)&aOrder[nCell];
103156   aDistance = (float *)&aSpare[nCell];
103157
103158   for(ii=0; ii<nCell; ii++){
103159     if( ii==(nCell-1) ){
103160       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
103161     }else{
103162       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
103163     }
103164     aOrder[ii] = ii;
103165     for(iDim=0; iDim<pRtree->nDim; iDim++){
103166       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
103167       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
103168     }
103169   }
103170   for(iDim=0; iDim<pRtree->nDim; iDim++){
103171     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
103172   }
103173
103174   for(ii=0; ii<nCell; ii++){
103175     aDistance[ii] = 0.0;
103176     for(iDim=0; iDim<pRtree->nDim; iDim++){
103177       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
103178           DCOORD(aCell[ii].aCoord[iDim*2]);
103179       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
103180     }
103181   }
103182
103183   SortByDistance(aOrder, nCell, aDistance, aSpare);
103184   nodeZero(pRtree, pNode);
103185
103186   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
103187     RtreeCell *p = &aCell[aOrder[ii]];
103188     nodeInsertCell(pRtree, pNode, p);
103189     if( p->iRowid==pCell->iRowid ){
103190       if( iHeight==0 ){
103191         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
103192       }else{
103193         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
103194       }
103195     }
103196   }
103197   if( rc==SQLITE_OK ){
103198     fixBoundingBox(pRtree, pNode);
103199   }
103200   for(; rc==SQLITE_OK && ii<nCell; ii++){
103201     /* Find a node to store this cell in. pNode->iNode currently contains
103202     ** the height of the sub-tree headed by the cell.
103203     */
103204     RtreeNode *pInsert;
103205     RtreeCell *p = &aCell[aOrder[ii]];
103206     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
103207     if( rc==SQLITE_OK ){
103208       int rc2;
103209       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
103210       rc2 = nodeRelease(pRtree, pInsert);
103211       if( rc==SQLITE_OK ){
103212         rc = rc2;
103213       }
103214     }
103215   }
103216
103217   sqlite3_free(aCell);
103218   return rc;
103219 }
103220
103221 /*
103222 ** Insert cell pCell into node pNode. Node pNode is the head of a 
103223 ** subtree iHeight high (leaf nodes have iHeight==0).
103224 */
103225 static int rtreeInsertCell(
103226   Rtree *pRtree,
103227   RtreeNode *pNode,
103228   RtreeCell *pCell,
103229   int iHeight
103230 ){
103231   int rc = SQLITE_OK;
103232   if( iHeight>0 ){
103233     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
103234     if( pChild ){
103235       nodeRelease(pRtree, pChild->pParent);
103236       nodeReference(pNode);
103237       pChild->pParent = pNode;
103238     }
103239   }
103240   if( nodeInsertCell(pRtree, pNode, pCell) ){
103241 #if VARIANT_RSTARTREE_REINSERT
103242     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
103243       rc = SplitNode(pRtree, pNode, pCell, iHeight);
103244     }else{
103245       pRtree->iReinsertHeight = iHeight;
103246       rc = Reinsert(pRtree, pNode, pCell, iHeight);
103247     }
103248 #else
103249     rc = SplitNode(pRtree, pNode, pCell, iHeight);
103250 #endif
103251   }else{
103252     AdjustTree(pRtree, pNode, pCell);
103253     if( iHeight==0 ){
103254       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
103255     }else{
103256       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
103257     }
103258   }
103259   return rc;
103260 }
103261
103262 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
103263   int ii;
103264   int rc = SQLITE_OK;
103265   int nCell = NCELL(pNode);
103266
103267   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
103268     RtreeNode *pInsert;
103269     RtreeCell cell;
103270     nodeGetCell(pRtree, pNode, ii, &cell);
103271
103272     /* Find a node to store this cell in. pNode->iNode currently contains
103273     ** the height of the sub-tree headed by the cell.
103274     */
103275     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
103276     if( rc==SQLITE_OK ){
103277       int rc2;
103278       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
103279       rc2 = nodeRelease(pRtree, pInsert);
103280       if( rc==SQLITE_OK ){
103281         rc = rc2;
103282       }
103283     }
103284   }
103285   return rc;
103286 }
103287
103288 /*
103289 ** Select a currently unused rowid for a new r-tree record.
103290 */
103291 static int newRowid(Rtree *pRtree, i64 *piRowid){
103292   int rc;
103293   sqlite3_bind_null(pRtree->pWriteRowid, 1);
103294   sqlite3_bind_null(pRtree->pWriteRowid, 2);
103295   sqlite3_step(pRtree->pWriteRowid);
103296   rc = sqlite3_reset(pRtree->pWriteRowid);
103297   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
103298   return rc;
103299 }
103300
103301 #ifndef NDEBUG
103302 static int hashIsEmpty(Rtree *pRtree){
103303   int ii;
103304   for(ii=0; ii<HASHSIZE; ii++){
103305     assert( !pRtree->aHash[ii] );
103306   }
103307   return 1;
103308 }
103309 #endif
103310
103311 /*
103312 ** The xUpdate method for rtree module virtual tables.
103313 */
103314 int rtreeUpdate(
103315   sqlite3_vtab *pVtab, 
103316   int nData, 
103317   sqlite3_value **azData, 
103318   sqlite_int64 *pRowid
103319 ){
103320   Rtree *pRtree = (Rtree *)pVtab;
103321   int rc = SQLITE_OK;
103322
103323   rtreeReference(pRtree);
103324
103325   assert(nData>=1);
103326   assert(hashIsEmpty(pRtree));
103327
103328   /* If azData[0] is not an SQL NULL value, it is the rowid of a
103329   ** record to delete from the r-tree table. The following block does
103330   ** just that.
103331   */
103332   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
103333     i64 iDelete;                /* The rowid to delete */
103334     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
103335     int iCell;                  /* Index of iDelete cell in pLeaf */
103336     RtreeNode *pRoot;
103337
103338     /* Obtain a reference to the root node to initialise Rtree.iDepth */
103339     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
103340
103341     /* Obtain a reference to the leaf node that contains the entry 
103342     ** about to be deleted. 
103343     */
103344     if( rc==SQLITE_OK ){
103345       iDelete = sqlite3_value_int64(azData[0]);
103346       rc = findLeafNode(pRtree, iDelete, &pLeaf);
103347     }
103348
103349     /* Delete the cell in question from the leaf node. */
103350     if( rc==SQLITE_OK ){
103351       int rc2;
103352       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
103353       rc = deleteCell(pRtree, pLeaf, iCell, 0);
103354       rc2 = nodeRelease(pRtree, pLeaf);
103355       if( rc==SQLITE_OK ){
103356         rc = rc2;
103357       }
103358     }
103359
103360     /* Delete the corresponding entry in the <rtree>_rowid table. */
103361     if( rc==SQLITE_OK ){
103362       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
103363       sqlite3_step(pRtree->pDeleteRowid);
103364       rc = sqlite3_reset(pRtree->pDeleteRowid);
103365     }
103366
103367     /* Check if the root node now has exactly one child. If so, remove
103368     ** it, schedule the contents of the child for reinsertion and 
103369     ** reduce the tree height by one.
103370     **
103371     ** This is equivalent to copying the contents of the child into
103372     ** the root node (the operation that Gutman's paper says to perform 
103373     ** in this scenario).
103374     */
103375     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
103376       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
103377         RtreeNode *pChild;
103378         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
103379         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
103380         if( rc==SQLITE_OK ){
103381           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
103382         }
103383         if( rc==SQLITE_OK ){
103384           pRtree->iDepth--;
103385           writeInt16(pRoot->zData, pRtree->iDepth);
103386           pRoot->isDirty = 1;
103387         }
103388       }
103389     }
103390
103391     /* Re-insert the contents of any underfull nodes removed from the tree. */
103392     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
103393       if( rc==SQLITE_OK ){
103394         rc = reinsertNodeContent(pRtree, pLeaf);
103395       }
103396       pRtree->pDeleted = pLeaf->pNext;
103397       sqlite3_free(pLeaf);
103398     }
103399
103400     /* Release the reference to the root node. */
103401     if( rc==SQLITE_OK ){
103402       rc = nodeRelease(pRtree, pRoot);
103403     }else{
103404       nodeRelease(pRtree, pRoot);
103405     }
103406   }
103407
103408   /* If the azData[] array contains more than one element, elements
103409   ** (azData[2]..azData[argc-1]) contain a new record to insert into
103410   ** the r-tree structure.
103411   */
103412   if( rc==SQLITE_OK && nData>1 ){
103413     /* Insert a new record into the r-tree */
103414     RtreeCell cell;
103415     int ii;
103416     RtreeNode *pLeaf;
103417
103418     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
103419     assert( nData==(pRtree->nDim*2 + 3) );
103420     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
103421       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
103422         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
103423         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
103424         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
103425           rc = SQLITE_CONSTRAINT;
103426           goto constraint;
103427         }
103428       }
103429     }else{
103430       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
103431         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
103432         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
103433         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
103434           rc = SQLITE_CONSTRAINT;
103435           goto constraint;
103436         }
103437       }
103438     }
103439
103440     /* Figure out the rowid of the new row. */
103441     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
103442       rc = newRowid(pRtree, &cell.iRowid);
103443     }else{
103444       cell.iRowid = sqlite3_value_int64(azData[2]);
103445       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
103446       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
103447         sqlite3_reset(pRtree->pReadRowid);
103448         rc = SQLITE_CONSTRAINT;
103449         goto constraint;
103450       }
103451       rc = sqlite3_reset(pRtree->pReadRowid);
103452     }
103453
103454     if( rc==SQLITE_OK ){
103455       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
103456     }
103457     if( rc==SQLITE_OK ){
103458       int rc2;
103459       pRtree->iReinsertHeight = -1;
103460       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
103461       rc2 = nodeRelease(pRtree, pLeaf);
103462       if( rc==SQLITE_OK ){
103463         rc = rc2;
103464       }
103465     }
103466   }
103467
103468 constraint:
103469   rtreeRelease(pRtree);
103470   return rc;
103471 }
103472
103473 /*
103474 ** The xRename method for rtree module virtual tables.
103475 */
103476 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
103477   Rtree *pRtree = (Rtree *)pVtab;
103478   int rc = SQLITE_NOMEM;
103479   char *zSql = sqlite3_mprintf(
103480     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
103481     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
103482     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
103483     , pRtree->zDb, pRtree->zName, zNewName 
103484     , pRtree->zDb, pRtree->zName, zNewName 
103485     , pRtree->zDb, pRtree->zName, zNewName
103486   );
103487   if( zSql ){
103488     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
103489     sqlite3_free(zSql);
103490   }
103491   return rc;
103492 }
103493
103494 static sqlite3_module rtreeModule = {
103495   0,                         /* iVersion */
103496   rtreeCreate,                /* xCreate - create a table */
103497   rtreeConnect,               /* xConnect - connect to an existing table */
103498   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
103499   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
103500   rtreeDestroy,               /* xDestroy - Drop a table */
103501   rtreeOpen,                  /* xOpen - open a cursor */
103502   rtreeClose,                 /* xClose - close a cursor */
103503   rtreeFilter,                /* xFilter - configure scan constraints */
103504   rtreeNext,                  /* xNext - advance a cursor */
103505   rtreeEof,                   /* xEof */
103506   rtreeColumn,                /* xColumn - read data */
103507   rtreeRowid,                 /* xRowid - read data */
103508   rtreeUpdate,                /* xUpdate - write data */
103509   0,                          /* xBegin - begin transaction */
103510   0,                          /* xSync - sync transaction */
103511   0,                          /* xCommit - commit transaction */
103512   0,                          /* xRollback - rollback transaction */
103513   0,                          /* xFindFunction - function overloading */
103514   rtreeRename                 /* xRename - rename the table */
103515 };
103516
103517 static int rtreeSqlInit(
103518   Rtree *pRtree, 
103519   sqlite3 *db, 
103520   const char *zDb, 
103521   const char *zPrefix, 
103522   int isCreate
103523 ){
103524   int rc = SQLITE_OK;
103525
103526   #define N_STATEMENT 9
103527   static const char *azSql[N_STATEMENT] = {
103528     /* Read and write the xxx_node table */
103529     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
103530     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
103531     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
103532
103533     /* Read and write the xxx_rowid table */
103534     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
103535     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
103536     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
103537
103538     /* Read and write the xxx_parent table */
103539     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
103540     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
103541     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
103542   };
103543   sqlite3_stmt **appStmt[N_STATEMENT];
103544   int i;
103545
103546   pRtree->db = db;
103547
103548   if( isCreate ){
103549     char *zCreate = sqlite3_mprintf(
103550 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
103551 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
103552 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
103553 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
103554       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
103555     );
103556     if( !zCreate ){
103557       return SQLITE_NOMEM;
103558     }
103559     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
103560     sqlite3_free(zCreate);
103561     if( rc!=SQLITE_OK ){
103562       return rc;
103563     }
103564   }
103565
103566   appStmt[0] = &pRtree->pReadNode;
103567   appStmt[1] = &pRtree->pWriteNode;
103568   appStmt[2] = &pRtree->pDeleteNode;
103569   appStmt[3] = &pRtree->pReadRowid;
103570   appStmt[4] = &pRtree->pWriteRowid;
103571   appStmt[5] = &pRtree->pDeleteRowid;
103572   appStmt[6] = &pRtree->pReadParent;
103573   appStmt[7] = &pRtree->pWriteParent;
103574   appStmt[8] = &pRtree->pDeleteParent;
103575
103576   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
103577     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
103578     if( zSql ){
103579       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
103580     }else{
103581       rc = SQLITE_NOMEM;
103582     }
103583     sqlite3_free(zSql);
103584   }
103585
103586   return rc;
103587 }
103588
103589 /*
103590 ** This routine queries database handle db for the page-size used by
103591 ** database zDb. If successful, the page-size in bytes is written to
103592 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
103593 ** code is returned.
103594 */
103595 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
103596   int rc = SQLITE_NOMEM;
103597   char *zSql;
103598   sqlite3_stmt *pStmt = 0;
103599
103600   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
103601   if( !zSql ){
103602     return SQLITE_NOMEM;
103603   }
103604
103605   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103606   sqlite3_free(zSql);
103607   if( rc!=SQLITE_OK ){
103608     return rc;
103609   }
103610
103611   if( SQLITE_ROW==sqlite3_step(pStmt) ){
103612     *piPageSize = sqlite3_column_int(pStmt, 0);
103613   }
103614   return sqlite3_finalize(pStmt);
103615 }
103616
103617 /* 
103618 ** This function is the implementation of both the xConnect and xCreate
103619 ** methods of the r-tree virtual table.
103620 **
103621 **   argv[0]   -> module name
103622 **   argv[1]   -> database name
103623 **   argv[2]   -> table name
103624 **   argv[...] -> column names...
103625 */
103626 static int rtreeInit(
103627   sqlite3 *db,                        /* Database connection */
103628   void *pAux,                         /* One of the RTREE_COORD_* constants */
103629   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
103630   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
103631   char **pzErr,                       /* OUT: Error message, if any */
103632   int isCreate                        /* True for xCreate, false for xConnect */
103633 ){
103634   int rc = SQLITE_OK;
103635   int iPageSize = 0;
103636   Rtree *pRtree;
103637   int nDb;              /* Length of string argv[1] */
103638   int nName;            /* Length of string argv[2] */
103639   int eCoordType = (int)pAux;
103640
103641   const char *aErrMsg[] = {
103642     0,                                                    /* 0 */
103643     "Wrong number of columns for an rtree table",         /* 1 */
103644     "Too few columns for an rtree table",                 /* 2 */
103645     "Too many columns for an rtree table"                 /* 3 */
103646   };
103647
103648   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
103649   if( aErrMsg[iErr] ){
103650     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
103651     return SQLITE_ERROR;
103652   }
103653
103654   rc = getPageSize(db, argv[1], &iPageSize);
103655   if( rc!=SQLITE_OK ){
103656     return rc;
103657   }
103658
103659   /* Allocate the sqlite3_vtab structure */
103660   nDb = strlen(argv[1]);
103661   nName = strlen(argv[2]);
103662   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
103663   if( !pRtree ){
103664     return SQLITE_NOMEM;
103665   }
103666   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
103667   pRtree->nBusy = 1;
103668   pRtree->base.pModule = &rtreeModule;
103669   pRtree->zDb = (char *)&pRtree[1];
103670   pRtree->zName = &pRtree->zDb[nDb+1];
103671   pRtree->nDim = (argc-4)/2;
103672   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
103673   pRtree->eCoordType = eCoordType;
103674   memcpy(pRtree->zDb, argv[1], nDb);
103675   memcpy(pRtree->zName, argv[2], nName);
103676
103677   /* Figure out the node size to use. By default, use 64 bytes less than
103678   ** the database page-size. This ensures that each node is stored on
103679   ** a single database page.
103680   **
103681   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
103682   ** entries would fit in a single node, use a smaller node-size.
103683   */
103684   pRtree->iNodeSize = iPageSize-64;
103685   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
103686     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
103687   }
103688
103689   /* Create/Connect to the underlying relational database schema. If
103690   ** that is successful, call sqlite3_declare_vtab() to configure
103691   ** the r-tree table schema.
103692   */
103693   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
103694     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
103695   }else{
103696     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
103697     char *zTmp;
103698     int ii;
103699     for(ii=4; zSql && ii<argc; ii++){
103700       zTmp = zSql;
103701       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
103702       sqlite3_free(zTmp);
103703     }
103704     if( zSql ){
103705       zTmp = zSql;
103706       zSql = sqlite3_mprintf("%s);", zTmp);
103707       sqlite3_free(zTmp);
103708     }
103709     if( !zSql || sqlite3_declare_vtab(db, zSql) ){
103710       rc = SQLITE_NOMEM;
103711     }
103712     sqlite3_free(zSql);
103713   }
103714
103715   if( rc==SQLITE_OK ){
103716     *ppVtab = (sqlite3_vtab *)pRtree;
103717   }else{
103718     rtreeRelease(pRtree);
103719   }
103720   return rc;
103721 }
103722
103723
103724 /*
103725 ** Implementation of a scalar function that decodes r-tree nodes to
103726 ** human readable strings. This can be used for debugging and analysis.
103727 **
103728 ** The scalar function takes two arguments, a blob of data containing
103729 ** an r-tree node, and the number of dimensions the r-tree indexes.
103730 ** For a two-dimensional r-tree structure called "rt", to deserialize
103731 ** all nodes, a statement like:
103732 **
103733 **   SELECT rtreenode(2, data) FROM rt_node;
103734 **
103735 ** The human readable string takes the form of a Tcl list with one
103736 ** entry for each cell in the r-tree node. Each entry is itself a
103737 ** list, containing the 8-byte rowid/pageno followed by the 
103738 ** <num-dimension>*2 coordinates.
103739 */
103740 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
103741   char *zText = 0;
103742   RtreeNode node;
103743   Rtree tree;
103744   int ii;
103745
103746   memset(&node, 0, sizeof(RtreeNode));
103747   memset(&tree, 0, sizeof(Rtree));
103748   tree.nDim = sqlite3_value_int(apArg[0]);
103749   tree.nBytesPerCell = 8 + 8 * tree.nDim;
103750   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
103751
103752   for(ii=0; ii<NCELL(&node); ii++){
103753     char zCell[512];
103754     int nCell = 0;
103755     RtreeCell cell;
103756     int jj;
103757
103758     nodeGetCell(&tree, &node, ii, &cell);
103759     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
103760     nCell = strlen(zCell);
103761     for(jj=0; jj<tree.nDim*2; jj++){
103762       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
103763       nCell = strlen(zCell);
103764     }
103765
103766     if( zText ){
103767       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
103768       sqlite3_free(zText);
103769       zText = zTextNew;
103770     }else{
103771       zText = sqlite3_mprintf("{%s}", zCell);
103772     }
103773   }
103774   
103775   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
103776 }
103777
103778 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
103779   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
103780    || sqlite3_value_bytes(apArg[0])<2
103781   ){
103782     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
103783   }else{
103784     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
103785     sqlite3_result_int(ctx, readInt16(zBlob));
103786   }
103787 }
103788
103789 /*
103790 ** Register the r-tree module with database handle db. This creates the
103791 ** virtual table module "rtree" and the debugging/analysis scalar 
103792 ** function "rtreenode".
103793 */
103794 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
103795   int rc = SQLITE_OK;
103796
103797   if( rc==SQLITE_OK ){
103798     int utf8 = SQLITE_UTF8;
103799     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
103800   }
103801   if( rc==SQLITE_OK ){
103802     int utf8 = SQLITE_UTF8;
103803     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
103804   }
103805   if( rc==SQLITE_OK ){
103806     void *c = (void *)RTREE_COORD_REAL32;
103807     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
103808   }
103809   if( rc==SQLITE_OK ){
103810     void *c = (void *)RTREE_COORD_INT32;
103811     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
103812   }
103813
103814   return rc;
103815 }
103816
103817 #if !SQLITE_CORE
103818 SQLITE_API int sqlite3_extension_init(
103819   sqlite3 *db,
103820   char **pzErrMsg,
103821   const sqlite3_api_routines *pApi
103822 ){
103823   SQLITE_EXTENSION_INIT2(pApi)
103824   return sqlite3RtreeInit(db);
103825 }
103826 #endif
103827
103828 #endif
103829
103830 /************** End of rtree.c ***********************************************/
103831 /************** Begin file icu.c *********************************************/
103832 /*
103833 ** 2007 May 6
103834 **
103835 ** The author disclaims copyright to this source code.  In place of
103836 ** a legal notice, here is a blessing:
103837 **
103838 **    May you do good and not evil.
103839 **    May you find forgiveness for yourself and forgive others.
103840 **    May you share freely, never taking more than you give.
103841 **
103842 *************************************************************************
103843 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
103844 **
103845 ** This file implements an integration between the ICU library 
103846 ** ("International Components for Unicode", an open-source library 
103847 ** for handling unicode data) and SQLite. The integration uses 
103848 ** ICU to provide the following to SQLite:
103849 **
103850 **   * An implementation of the SQL regexp() function (and hence REGEXP
103851 **     operator) using the ICU uregex_XX() APIs.
103852 **
103853 **   * Implementations of the SQL scalar upper() and lower() functions
103854 **     for case mapping.
103855 **
103856 **   * Integration of ICU and SQLite collation seqences.
103857 **
103858 **   * An implementation of the LIKE operator that uses ICU to 
103859 **     provide case-independent matching.
103860 */
103861
103862 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
103863
103864 /* Include ICU headers */
103865 #include <unicode/utypes.h>
103866 #include <unicode/uregex.h>
103867 #include <unicode/ustring.h>
103868 #include <unicode/ucol.h>
103869
103870
103871 #ifndef SQLITE_CORE
103872   SQLITE_EXTENSION_INIT1
103873 #else
103874 #endif
103875
103876 /*
103877 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
103878 ** operator.
103879 */
103880 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
103881 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
103882 #endif
103883
103884 /*
103885 ** Version of sqlite3_free() that is always a function, never a macro.
103886 */
103887 static void xFree(void *p){
103888   sqlite3_free(p);
103889 }
103890
103891 /*
103892 ** Compare two UTF-8 strings for equality where the first string is
103893 ** a "LIKE" expression. Return true (1) if they are the same and 
103894 ** false (0) if they are different.
103895 */
103896 static int icuLikeCompare(
103897   const uint8_t *zPattern,   /* LIKE pattern */
103898   const uint8_t *zString,    /* The UTF-8 string to compare against */
103899   const UChar32 uEsc         /* The escape character */
103900 ){
103901   static const int MATCH_ONE = (UChar32)'_';
103902   static const int MATCH_ALL = (UChar32)'%';
103903
103904   int iPattern = 0;       /* Current byte index in zPattern */
103905   int iString = 0;        /* Current byte index in zString */
103906
103907   int prevEscape = 0;     /* True if the previous character was uEsc */
103908
103909   while( zPattern[iPattern]!=0 ){
103910
103911     /* Read (and consume) the next character from the input pattern. */
103912     UChar32 uPattern;
103913     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
103914     assert(uPattern!=0);
103915
103916     /* There are now 4 possibilities:
103917     **
103918     **     1. uPattern is an unescaped match-all character "%",
103919     **     2. uPattern is an unescaped match-one character "_",
103920     **     3. uPattern is an unescaped escape character, or
103921     **     4. uPattern is to be handled as an ordinary character
103922     */
103923     if( !prevEscape && uPattern==MATCH_ALL ){
103924       /* Case 1. */
103925       uint8_t c;
103926
103927       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
103928       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
103929       ** test string.
103930       */
103931       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
103932         if( c==MATCH_ONE ){
103933           if( zString[iString]==0 ) return 0;
103934           U8_FWD_1_UNSAFE(zString, iString);
103935         }
103936         iPattern++;
103937       }
103938
103939       if( zPattern[iPattern]==0 ) return 1;
103940
103941       while( zString[iString] ){
103942         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
103943           return 1;
103944         }
103945         U8_FWD_1_UNSAFE(zString, iString);
103946       }
103947       return 0;
103948
103949     }else if( !prevEscape && uPattern==MATCH_ONE ){
103950       /* Case 2. */
103951       if( zString[iString]==0 ) return 0;
103952       U8_FWD_1_UNSAFE(zString, iString);
103953
103954     }else if( !prevEscape && uPattern==uEsc){
103955       /* Case 3. */
103956       prevEscape = 1;
103957
103958     }else{
103959       /* Case 4. */
103960       UChar32 uString;
103961       U8_NEXT_UNSAFE(zString, iString, uString);
103962       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
103963       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
103964       if( uString!=uPattern ){
103965         return 0;
103966       }
103967       prevEscape = 0;
103968     }
103969   }
103970
103971   return zString[iString]==0;
103972 }
103973
103974 /*
103975 ** Implementation of the like() SQL function.  This function implements
103976 ** the build-in LIKE operator.  The first argument to the function is the
103977 ** pattern and the second argument is the string.  So, the SQL statements:
103978 **
103979 **       A LIKE B
103980 **
103981 ** is implemented as like(B, A). If there is an escape character E, 
103982 **
103983 **       A LIKE B ESCAPE E
103984 **
103985 ** is mapped to like(B, A, E).
103986 */
103987 static void icuLikeFunc(
103988   sqlite3_context *context, 
103989   int argc, 
103990   sqlite3_value **argv
103991 ){
103992   const unsigned char *zA = sqlite3_value_text(argv[0]);
103993   const unsigned char *zB = sqlite3_value_text(argv[1]);
103994   UChar32 uEsc = 0;
103995
103996   /* Limit the length of the LIKE or GLOB pattern to avoid problems
103997   ** of deep recursion and N*N behavior in patternCompare().
103998   */
103999   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
104000     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104001     return;
104002   }
104003
104004
104005   if( argc==3 ){
104006     /* The escape character string must consist of a single UTF-8 character.
104007     ** Otherwise, return an error.
104008     */
104009     int nE= sqlite3_value_bytes(argv[2]);
104010     const unsigned char *zE = sqlite3_value_text(argv[2]);
104011     int i = 0;
104012     if( zE==0 ) return;
104013     U8_NEXT(zE, i, nE, uEsc);
104014     if( i!=nE){
104015       sqlite3_result_error(context, 
104016           "ESCAPE expression must be a single character", -1);
104017       return;
104018     }
104019   }
104020
104021   if( zA && zB ){
104022     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
104023   }
104024 }
104025
104026 /*
104027 ** This function is called when an ICU function called from within
104028 ** the implementation of an SQL scalar function returns an error.
104029 **
104030 ** The scalar function context passed as the first argument is 
104031 ** loaded with an error message based on the following two args.
104032 */
104033 static void icuFunctionError(
104034   sqlite3_context *pCtx,       /* SQLite scalar function context */
104035   const char *zName,           /* Name of ICU function that failed */
104036   UErrorCode e                 /* Error code returned by ICU function */
104037 ){
104038   char zBuf[128];
104039   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
104040   zBuf[127] = '\0';
104041   sqlite3_result_error(pCtx, zBuf, -1);
104042 }
104043
104044 /*
104045 ** Function to delete compiled regexp objects. Registered as
104046 ** a destructor function with sqlite3_set_auxdata().
104047 */
104048 static void icuRegexpDelete(void *p){
104049   URegularExpression *pExpr = (URegularExpression *)p;
104050   uregex_close(pExpr);
104051 }
104052
104053 /*
104054 ** Implementation of SQLite REGEXP operator. This scalar function takes
104055 ** two arguments. The first is a regular expression pattern to compile
104056 ** the second is a string to match against that pattern. If either 
104057 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
104058 ** is 1 if the string matches the pattern, or 0 otherwise.
104059 **
104060 ** SQLite maps the regexp() function to the regexp() operator such
104061 ** that the following two are equivalent:
104062 **
104063 **     zString REGEXP zPattern
104064 **     regexp(zPattern, zString)
104065 **
104066 ** Uses the following ICU regexp APIs:
104067 **
104068 **     uregex_open()
104069 **     uregex_matches()
104070 **     uregex_close()
104071 */
104072 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
104073   UErrorCode status = U_ZERO_ERROR;
104074   URegularExpression *pExpr;
104075   UBool res;
104076   const UChar *zString = sqlite3_value_text16(apArg[1]);
104077
104078   /* If the left hand side of the regexp operator is NULL, 
104079   ** then the result is also NULL. 
104080   */
104081   if( !zString ){
104082     return;
104083   }
104084
104085   pExpr = sqlite3_get_auxdata(p, 0);
104086   if( !pExpr ){
104087     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
104088     if( !zPattern ){
104089       return;
104090     }
104091     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
104092
104093     if( U_SUCCESS(status) ){
104094       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
104095     }else{
104096       assert(!pExpr);
104097       icuFunctionError(p, "uregex_open", status);
104098       return;
104099     }
104100   }
104101
104102   /* Configure the text that the regular expression operates on. */
104103   uregex_setText(pExpr, zString, -1, &status);
104104   if( !U_SUCCESS(status) ){
104105     icuFunctionError(p, "uregex_setText", status);
104106     return;
104107   }
104108
104109   /* Attempt the match */
104110   res = uregex_matches(pExpr, 0, &status);
104111   if( !U_SUCCESS(status) ){
104112     icuFunctionError(p, "uregex_matches", status);
104113     return;
104114   }
104115
104116   /* Set the text that the regular expression operates on to a NULL
104117   ** pointer. This is not really necessary, but it is tidier than 
104118   ** leaving the regular expression object configured with an invalid
104119   ** pointer after this function returns.
104120   */
104121   uregex_setText(pExpr, 0, 0, &status);
104122
104123   /* Return 1 or 0. */
104124   sqlite3_result_int(p, res ? 1 : 0);
104125 }
104126
104127 /*
104128 ** Implementations of scalar functions for case mapping - upper() and 
104129 ** lower(). Function upper() converts its input to upper-case (ABC).
104130 ** Function lower() converts to lower-case (abc).
104131 **
104132 ** ICU provides two types of case mapping, "general" case mapping and
104133 ** "language specific". Refer to ICU documentation for the differences
104134 ** between the two.
104135 **
104136 ** To utilise "general" case mapping, the upper() or lower() scalar 
104137 ** functions are invoked with one argument:
104138 **
104139 **     upper('ABC') -> 'abc'
104140 **     lower('abc') -> 'ABC'
104141 **
104142 ** To access ICU "language specific" case mapping, upper() or lower()
104143 ** should be invoked with two arguments. The second argument is the name
104144 ** of the locale to use. Passing an empty string ("") or SQL NULL value
104145 ** as the second argument is the same as invoking the 1 argument version
104146 ** of upper() or lower().
104147 **
104148 **     lower('I', 'en_us') -> 'i'
104149 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
104150 **
104151 ** http://www.icu-project.org/userguide/posix.html#case_mappings
104152 */
104153 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
104154   const UChar *zInput;
104155   UChar *zOutput;
104156   int nInput;
104157   int nOutput;
104158
104159   UErrorCode status = U_ZERO_ERROR;
104160   const char *zLocale = 0;
104161
104162   assert(nArg==1 || nArg==2);
104163   if( nArg==2 ){
104164     zLocale = (const char *)sqlite3_value_text(apArg[1]);
104165   }
104166
104167   zInput = sqlite3_value_text16(apArg[0]);
104168   if( !zInput ){
104169     return;
104170   }
104171   nInput = sqlite3_value_bytes16(apArg[0]);
104172
104173   nOutput = nInput * 2 + 2;
104174   zOutput = sqlite3_malloc(nOutput);
104175   if( !zOutput ){
104176     return;
104177   }
104178
104179   if( sqlite3_user_data(p) ){
104180     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
104181   }else{
104182     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
104183   }
104184
104185   if( !U_SUCCESS(status) ){
104186     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
104187     return;
104188   }
104189
104190   sqlite3_result_text16(p, zOutput, -1, xFree);
104191 }
104192
104193 /*
104194 ** Collation sequence destructor function. The pCtx argument points to
104195 ** a UCollator structure previously allocated using ucol_open().
104196 */
104197 static void icuCollationDel(void *pCtx){
104198   UCollator *p = (UCollator *)pCtx;
104199   ucol_close(p);
104200 }
104201
104202 /*
104203 ** Collation sequence comparison function. The pCtx argument points to
104204 ** a UCollator structure previously allocated using ucol_open().
104205 */
104206 static int icuCollationColl(
104207   void *pCtx,
104208   int nLeft,
104209   const void *zLeft,
104210   int nRight,
104211   const void *zRight
104212 ){
104213   UCollationResult res;
104214   UCollator *p = (UCollator *)pCtx;
104215   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
104216   switch( res ){
104217     case UCOL_LESS:    return -1;
104218     case UCOL_GREATER: return +1;
104219     case UCOL_EQUAL:   return 0;
104220   }
104221   assert(!"Unexpected return value from ucol_strcoll()");
104222   return 0;
104223 }
104224
104225 /*
104226 ** Implementation of the scalar function icu_load_collation().
104227 **
104228 ** This scalar function is used to add ICU collation based collation 
104229 ** types to an SQLite database connection. It is intended to be called
104230 ** as follows:
104231 **
104232 **     SELECT icu_load_collation(<locale>, <collation-name>);
104233 **
104234 ** Where <locale> is a string containing an ICU locale identifier (i.e.
104235 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
104236 ** collation sequence to create.
104237 */
104238 static void icuLoadCollation(
104239   sqlite3_context *p, 
104240   int nArg, 
104241   sqlite3_value **apArg
104242 ){
104243   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
104244   UErrorCode status = U_ZERO_ERROR;
104245   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
104246   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
104247   UCollator *pUCollator;    /* ICU library collation object */
104248   int rc;                   /* Return code from sqlite3_create_collation_x() */
104249
104250   assert(nArg==2);
104251   zLocale = (const char *)sqlite3_value_text(apArg[0]);
104252   zName = (const char *)sqlite3_value_text(apArg[1]);
104253
104254   if( !zLocale || !zName ){
104255     return;
104256   }
104257
104258   pUCollator = ucol_open(zLocale, &status);
104259   if( !U_SUCCESS(status) ){
104260     icuFunctionError(p, "ucol_open", status);
104261     return;
104262   }
104263   assert(p);
104264
104265   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
104266       icuCollationColl, icuCollationDel
104267   );
104268   if( rc!=SQLITE_OK ){
104269     ucol_close(pUCollator);
104270     sqlite3_result_error(p, "Error registering collation function", -1);
104271   }
104272 }
104273
104274 /*
104275 ** Register the ICU extension functions with database db.
104276 */
104277 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
104278   struct IcuScalar {
104279     const char *zName;                        /* Function name */
104280     int nArg;                                 /* Number of arguments */
104281     int enc;                                  /* Optimal text encoding */
104282     void *pContext;                           /* sqlite3_user_data() context */
104283     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
104284   } scalars[] = {
104285     {"regexp",-1, SQLITE_ANY,          0, icuRegexpFunc},
104286
104287     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
104288     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
104289     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
104290     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
104291
104292     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
104293     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
104294     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
104295     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
104296
104297     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
104298     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
104299
104300     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
104301   };
104302
104303   int rc = SQLITE_OK;
104304   int i;
104305
104306   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
104307     struct IcuScalar *p = &scalars[i];
104308     rc = sqlite3_create_function(
104309         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
104310     );
104311   }
104312
104313   return rc;
104314 }
104315
104316 #if !SQLITE_CORE
104317 SQLITE_API int sqlite3_extension_init(
104318   sqlite3 *db, 
104319   char **pzErrMsg,
104320   const sqlite3_api_routines *pApi
104321 ){
104322   SQLITE_EXTENSION_INIT2(pApi)
104323   return sqlite3IcuInit(db);
104324 }
104325 #endif
104326
104327 #endif
104328
104329 /************** End of icu.c *************************************************/
104330 /************** Begin file fts3_icu.c ****************************************/
104331 /*
104332 ** 2007 June 22
104333 **
104334 ** The author disclaims copyright to this source code.  In place of
104335 ** a legal notice, here is a blessing:
104336 **
104337 **    May you do good and not evil.
104338 **    May you find forgiveness for yourself and forgive others.
104339 **    May you share freely, never taking more than you give.
104340 **
104341 *************************************************************************
104342 ** This file implements a tokenizer for fts3 based on the ICU library.
104343 ** 
104344 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
104345 */
104346
104347 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
104348 #ifdef SQLITE_ENABLE_ICU
104349
104350
104351 #include <unicode/ubrk.h>
104352 #include <unicode/utf16.h>
104353
104354 typedef struct IcuTokenizer IcuTokenizer;
104355 typedef struct IcuCursor IcuCursor;
104356
104357 struct IcuTokenizer {
104358   sqlite3_tokenizer base;
104359   char *zLocale;
104360 };
104361
104362 struct IcuCursor {
104363   sqlite3_tokenizer_cursor base;
104364
104365   UBreakIterator *pIter;      /* ICU break-iterator object */
104366   int nChar;                  /* Number of UChar elements in pInput */
104367   UChar *aChar;               /* Copy of input using utf-16 encoding */
104368   int *aOffset;               /* Offsets of each character in utf-8 input */
104369
104370   int nBuffer;
104371   char *zBuffer;
104372
104373   int iToken;
104374 };
104375
104376 /*
104377 ** Create a new tokenizer instance.
104378 */
104379 static int icuCreate(
104380   int argc,                            /* Number of entries in argv[] */
104381   const char * const *argv,            /* Tokenizer creation arguments */
104382   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
104383 ){
104384   IcuTokenizer *p;
104385   int n = 0;
104386
104387   if( argc>0 ){
104388     n = strlen(argv[0])+1;
104389   }
104390   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
104391   if( !p ){
104392     return SQLITE_NOMEM;
104393   }
104394   memset(p, 0, sizeof(IcuTokenizer));
104395
104396   if( n ){
104397     p->zLocale = (char *)&p[1];
104398     memcpy(p->zLocale, argv[0], n);
104399   }
104400
104401   *ppTokenizer = (sqlite3_tokenizer *)p;
104402
104403   return SQLITE_OK;
104404 }
104405
104406 /*
104407 ** Destroy a tokenizer
104408 */
104409 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
104410   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
104411   sqlite3_free(p);
104412   return SQLITE_OK;
104413 }
104414
104415 /*
104416 ** Prepare to begin tokenizing a particular string.  The input
104417 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
104418 ** used to incrementally tokenize this string is returned in 
104419 ** *ppCursor.
104420 */
104421 static int icuOpen(
104422   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
104423   const char *zInput,                    /* Input string */
104424   int nInput,                            /* Length of zInput in bytes */
104425   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
104426 ){
104427   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
104428   IcuCursor *pCsr;
104429
104430   const int32_t opt = U_FOLD_CASE_DEFAULT;
104431   UErrorCode status = U_ZERO_ERROR;
104432   int nChar;
104433
104434   UChar32 c;
104435   int iInput = 0;
104436   int iOut = 0;
104437
104438   *ppCursor = 0;
104439
104440   if( nInput<0 ){
104441     nInput = strlen(zInput);
104442   }
104443   nChar = nInput+1;
104444   pCsr = (IcuCursor *)sqlite3_malloc(
104445       sizeof(IcuCursor) +                /* IcuCursor */
104446       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
104447       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
104448   );
104449   if( !pCsr ){
104450     return SQLITE_NOMEM;
104451   }
104452   memset(pCsr, 0, sizeof(IcuCursor));
104453   pCsr->aChar = (UChar *)&pCsr[1];
104454   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
104455
104456   pCsr->aOffset[iOut] = iInput;
104457   U8_NEXT(zInput, iInput, nInput, c); 
104458   while( c>0 ){
104459     int isError = 0;
104460     c = u_foldCase(c, opt);
104461     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
104462     if( isError ){
104463       sqlite3_free(pCsr);
104464       return SQLITE_ERROR;
104465     }
104466     pCsr->aOffset[iOut] = iInput;
104467
104468     if( iInput<nInput ){
104469       U8_NEXT(zInput, iInput, nInput, c);
104470     }else{
104471       c = 0;
104472     }
104473   }
104474
104475   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
104476   if( !U_SUCCESS(status) ){
104477     sqlite3_free(pCsr);
104478     return SQLITE_ERROR;
104479   }
104480   pCsr->nChar = iOut;
104481
104482   ubrk_first(pCsr->pIter);
104483   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
104484   return SQLITE_OK;
104485 }
104486
104487 /*
104488 ** Close a tokenization cursor previously opened by a call to icuOpen().
104489 */
104490 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
104491   IcuCursor *pCsr = (IcuCursor *)pCursor;
104492   ubrk_close(pCsr->pIter);
104493   sqlite3_free(pCsr->zBuffer);
104494   sqlite3_free(pCsr);
104495   return SQLITE_OK;
104496 }
104497
104498 /*
104499 ** Extract the next token from a tokenization cursor.
104500 */
104501 static int icuNext(
104502   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
104503   const char **ppToken,               /* OUT: *ppToken is the token text */
104504   int *pnBytes,                       /* OUT: Number of bytes in token */
104505   int *piStartOffset,                 /* OUT: Starting offset of token */
104506   int *piEndOffset,                   /* OUT: Ending offset of token */
104507   int *piPosition                     /* OUT: Position integer of token */
104508 ){
104509   IcuCursor *pCsr = (IcuCursor *)pCursor;
104510
104511   int iStart = 0;
104512   int iEnd = 0;
104513   int nByte = 0;
104514
104515   while( iStart==iEnd ){
104516     UChar32 c;
104517
104518     iStart = ubrk_current(pCsr->pIter);
104519     iEnd = ubrk_next(pCsr->pIter);
104520     if( iEnd==UBRK_DONE ){
104521       return SQLITE_DONE;
104522     }
104523
104524     while( iStart<iEnd ){
104525       int iWhite = iStart;
104526       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
104527       if( u_isspace(c) ){
104528         iStart = iWhite;
104529       }else{
104530         break;
104531       }
104532     }
104533     assert(iStart<=iEnd);
104534   }
104535
104536   do {
104537     UErrorCode status = U_ZERO_ERROR;
104538     if( nByte ){
104539       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
104540       if( !zNew ){
104541         return SQLITE_NOMEM;
104542       }
104543       pCsr->zBuffer = zNew;
104544       pCsr->nBuffer = nByte;
104545     }
104546
104547     u_strToUTF8(
104548         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
104549         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
104550         &status                                  /* Output success/failure */
104551     );
104552   } while( nByte>pCsr->nBuffer );
104553
104554   *ppToken = pCsr->zBuffer;
104555   *pnBytes = nByte;
104556   *piStartOffset = pCsr->aOffset[iStart];
104557   *piEndOffset = pCsr->aOffset[iEnd];
104558   *piPosition = pCsr->iToken++;
104559
104560   return SQLITE_OK;
104561 }
104562
104563 /*
104564 ** The set of routines that implement the simple tokenizer
104565 */
104566 static const sqlite3_tokenizer_module icuTokenizerModule = {
104567   0,                           /* iVersion */
104568   icuCreate,                   /* xCreate  */
104569   icuDestroy,                  /* xCreate  */
104570   icuOpen,                     /* xOpen    */
104571   icuClose,                    /* xClose   */
104572   icuNext,                     /* xNext    */
104573 };
104574
104575 /*
104576 ** Set *ppModule to point at the implementation of the ICU tokenizer.
104577 */
104578 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
104579   sqlite3_tokenizer_module const**ppModule
104580 ){
104581   *ppModule = &icuTokenizerModule;
104582 }
104583
104584 #endif /* defined(SQLITE_ENABLE_ICU) */
104585 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
104586
104587 /************** End of fts3_icu.c ********************************************/